difftreelog
fix parse bitint to decimals
in: master
4 files changed
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../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 normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {107 if (typeof input === 'string') {108 if (input.length >= 47) {109 return {Substrate: input};110 } else if (input.length === 42 && input.startsWith('0x')) {111 return {Ethereum: input.toLowerCase()};112 } else if (input.length === 40 && !input.startsWith('0x')) {113 return {Ethereum: '0x' + input.toLowerCase()};114 } else {115 throw new Error(`Unknown address format: "${input}"`);116 }117 }118 if ('address' in input) {119 return {Substrate: input.address};120 }121 if ('Ethereum' in input) {122 return {123 Ethereum: input.Ethereum.toLowerCase(),124 };125 } else if ('ethereum' in input) {126 return {127 Ethereum: (input as any).ethereum.toLowerCase(),128 };129 } else if ('Substrate' in input) {130 return input;131 } else if ('substrate' in input) {132 return {133 Substrate: (input as any).substrate,134 };135 }136137 // AccountId138 return {Substrate: input.toString()};139}140export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {141 input = normalizeAccountId(input);142 if ('Substrate' in input) {143 return input.Substrate;144 } else {145 return evmToAddress(input.Ethereum);146 }147}148149export const U128_MAX = (1n << 128n) - 1n;150151const MICROUNIQUE = 1_000_000_000_000n;152const MILLIUNIQUE = 1_000n * MICROUNIQUE;153const CENTIUNIQUE = 10n * MILLIUNIQUE;154export const UNIQUE = 100n * CENTIUNIQUE;155156interface GenericResult<T> {157 success: boolean;158 data: T | null;159}160161interface CreateCollectionResult {162 success: boolean;163 collectionId: number;164}165166interface CreateItemResult {167 success: boolean;168 collectionId: number;169 itemId: number;170 recipient?: CrossAccountId;171 amount?: number;172}173174interface DestroyItemResult {175 success: boolean;176 collectionId: number;177 itemId: number;178 owner: CrossAccountId;179 amount: number;180}181182interface TransferResult {183 collectionId: number;184 itemId: number;185 sender?: CrossAccountId;186 recipient?: CrossAccountId;187 value: bigint;188}189190interface IReFungibleOwner {191 fraction: BN;192 owner: number[];193}194195interface IGetMessage {196 checkMsgUnqMethod: string;197 checkMsgTrsMethod: string;198 checkMsgSysMethod: string;199}200201export interface IFungibleTokenDataType {202 value: number;203}204205export interface IChainLimits {206 collectionNumbersLimit: number;207 accountTokenOwnershipLimit: number;208 collectionsAdminsLimit: number;209 customDataLimit: number;210 nftSponsorTransferTimeout: number;211 fungibleSponsorTransferTimeout: number;212 refungibleSponsorTransferTimeout: number;213 //offchainSchemaLimit: number;214 //constOnChainSchemaLimit: number;215}216217export interface IReFungibleTokenDataType {218 owner: IReFungibleOwner[];219}220221export function uniqueEventMessage(events: EventRecord[]): IGetMessage {222 let checkMsgUnqMethod = '';223 let checkMsgTrsMethod = '';224 let checkMsgSysMethod = '';225 events.forEach(({event: {method, section}}) => {226 if (section === 'common') {227 checkMsgUnqMethod = method;228 } else if (section === 'treasury') {229 checkMsgTrsMethod = method;230 } else if (section === 'system') {231 checkMsgSysMethod = method;232 } else { return null; }233 });234 const result: IGetMessage = {235 checkMsgUnqMethod,236 checkMsgTrsMethod,237 checkMsgSysMethod,238 };239 return result;240}241242export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {243 const event = events.find(r => check(r.event));244 if (!event) return;245 return event.event as T;246}247248export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;249export function getGenericResult<T>(250 events: EventRecord[],251 expectSection: string,252 expectMethod: string,253 extractAction: (data: GenericEventData) => T254): GenericResult<T>;255256export function getGenericResult<T>(257 events: EventRecord[],258 expectSection?: string,259 expectMethod?: string,260 extractAction?: (data: GenericEventData) => T,261): GenericResult<T> {262 let success = false;263 let successData = null;264265 events.forEach(({event: {data, method, section}}) => {266 // console.log(` ${phase}: ${section}.${method}:: ${data}`);267 if (method === 'ExtrinsicSuccess') {268 success = true;269 } else if ((expectSection == section) && (expectMethod == method)) {270 successData = extractAction!(data as any);271 }272 });273274 const result: GenericResult<T> = {275 success,276 data: successData,277 };278 return result;279}280281export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {282 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));283 const result: CreateCollectionResult = {284 success: genericResult.success,285 collectionId: genericResult.data ?? 0,286 };287 return result;288}289290export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {291 const results: CreateItemResult[] = [];292 293 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {294 const collectionId = parseInt(data[0].toString(), 10);295 const itemId = parseInt(data[1].toString(), 10);296 const recipient = normalizeAccountId(data[2].toJSON() as any);297 const amount = parseInt(data[3].toString(), 10);298299 const itemRes: CreateItemResult = {300 success: true,301 collectionId,302 itemId,303 recipient,304 amount,305 };306307 results.push(itemRes);308 return results;309 });310311 if (!genericResult.success) return [];312 return results;313}314315export function getCreateItemResult(events: EventRecord[]): CreateItemResult {316 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));317 318 if (genericResult.data == null) 319 return {320 success: genericResult.success,321 collectionId: 0,322 itemId: 0,323 amount: 0,324 };325 else 326 return {327 success: genericResult.success,328 collectionId: genericResult.data[0] as number,329 itemId: genericResult.data[1] as number,330 recipient: normalizeAccountId(genericResult.data![2] as any),331 amount: genericResult.data[3] as number,332 };333}334335export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {336 const results: DestroyItemResult[] = [];337 338 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {339 const collectionId = parseInt(data[0].toString(), 10);340 const itemId = parseInt(data[1].toString(), 10);341 const owner = normalizeAccountId(data[2].toJSON() as any);342 const amount = parseInt(data[3].toString(), 10);343344 const itemRes: DestroyItemResult = {345 success: true,346 collectionId,347 itemId,348 owner,349 amount,350 };351352 results.push(itemRes);353 return results;354 });355356 if (!genericResult.success) return [];357 return results;358}359360export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {361 for (const {event} of events) {362 if (api.events.common.Transfer.is(event)) {363 const [collection, token, sender, recipient, value] = event.data;364 return {365 collectionId: collection.toNumber(),366 itemId: token.toNumber(),367 sender: normalizeAccountId(sender.toJSON() as any),368 recipient: normalizeAccountId(recipient.toJSON() as any),369 value: value.toBigInt(),370 };371 }372 }373 throw new Error('no transfer event');374}375376interface Nft {377 type: 'NFT';378}379380interface Fungible {381 type: 'Fungible';382 decimalPoints: number;383}384385interface ReFungible {386 type: 'ReFungible';387}388389export type CollectionMode = Nft | Fungible | ReFungible;390391export type Property = {392 key: any,393 value: any,394};395396type Permission = {397 mutable: boolean;398 collectionAdmin: boolean;399 tokenOwner: boolean;400}401402type PropertyPermission = {403 key: any;404 permission: Permission;405}406407export type CreateCollectionParams = {408 mode: CollectionMode,409 name: string,410 description: string,411 tokenPrefix: string,412 properties?: Array<Property>,413 propPerm?: Array<PropertyPermission>414};415416const defaultCreateCollectionParams: CreateCollectionParams = {417 description: 'description',418 mode: {type: 'NFT'},419 name: 'name',420 tokenPrefix: 'prefix',421};422423export async function424createCollection(425 api: ApiPromise,426 sender: IKeyringPair,427 params: Partial<CreateCollectionParams> = {},428): Promise<CreateCollectionResult> {429 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431 let modeprm = {};432 if (mode.type === 'NFT') {433 modeprm = {nft: null};434 } else if (mode.type === 'Fungible') {435 modeprm = {fungible: mode.decimalPoints};436 } else if (mode.type === 'ReFungible') {437 modeprm = {refungible: null};438 }439440 const tx = api.tx.unique.createCollectionEx({441 name: strToUTF16(name),442 description: strToUTF16(description),443 tokenPrefix: strToUTF16(tokenPrefix),444 mode: modeprm as any,445 });446 const events = await executeTransaction(api, sender, tx);447 return getCreateCollectionResult(events);448}449450export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {451 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};452453 let collectionId = 0;454 await usingApi(async (api, privateKeyWrapper) => {455 // Get number of collections before the transaction456 const collectionCountBefore = await getCreatedCollectionCount(api);457458 // Run the CreateCollection transaction459 const alicePrivateKey = privateKeyWrapper('//Alice');460461 const result = await createCollection(api, alicePrivateKey, params);462463 // Get number of collections after the transaction464 const collectionCountAfter = await getCreatedCollectionCount(api);465466 // Get the collection467 const collection = await queryCollectionExpectSuccess(api, result.collectionId);468469 // What to expect470 // tslint:disable-next-line:no-unused-expression471 expect(result.success).to.be.true;472 expect(result.collectionId).to.be.equal(collectionCountAfter);473 // tslint:disable-next-line:no-unused-expression474 expect(collection).to.be.not.null;475 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');476 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));477 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);478 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);479 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);480481 collectionId = result.collectionId;482 });483484 return collectionId;485}486487export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {488 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};489490 let collectionId = 0;491 await usingApi(async (api, privateKeyWrapper) => {492 // Get number of collections before the transaction493 const collectionCountBefore = await getCreatedCollectionCount(api);494495 // Run the CreateCollection transaction496 const alicePrivateKey = privateKeyWrapper('//Alice');497498 let modeprm = {};499 if (mode.type === 'NFT') {500 modeprm = {nft: null};501 } else if (mode.type === 'Fungible') {502 modeprm = {fungible: mode.decimalPoints};503 } else if (mode.type === 'ReFungible') {504 modeprm = {refungible: null};505 }506507 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});508 const events = await submitTransactionAsync(alicePrivateKey, tx);509 const result = getCreateCollectionResult(events);510511 // Get number of collections after the transaction512 const collectionCountAfter = await getCreatedCollectionCount(api);513514 // Get the collection515 const collection = await queryCollectionExpectSuccess(api, result.collectionId);516517 // What to expect518 // tslint:disable-next-line:no-unused-expression519 expect(result.success).to.be.true;520 expect(result.collectionId).to.be.equal(collectionCountAfter);521 // tslint:disable-next-line:no-unused-expression522 expect(collection).to.be.not.null;523 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');524 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));525 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);526 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);527 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);528529530 collectionId = result.collectionId;531 });532533 return collectionId;534}535536export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {537 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};538539 await usingApi(async (api, privateKeyWrapper) => {540 // Get number of collections before the transaction541 const collectionCountBefore = await getCreatedCollectionCount(api);542543 // Run the CreateCollection transaction544 const alicePrivateKey = privateKeyWrapper('//Alice');545546 let modeprm = {};547 if (mode.type === 'NFT') {548 modeprm = {nft: null};549 } else if (mode.type === 'Fungible') {550 modeprm = {fungible: mode.decimalPoints};551 } else if (mode.type === 'ReFungible') {552 modeprm = {refungible: null};553 }554555 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});556 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;557558559 // Get number of collections after the transaction560 const collectionCountAfter = await getCreatedCollectionCount(api);561562 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');563 });564}565566export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {567 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};568569 let modeprm = {};570 if (mode.type === 'NFT') {571 modeprm = {nft: null};572 } else if (mode.type === 'Fungible') {573 modeprm = {fungible: mode.decimalPoints};574 } else if (mode.type === 'ReFungible') {575 modeprm = {refungible: null};576 }577578 await usingApi(async (api, privateKeyWrapper) => {579 // Get number of collections before the transaction580 const collectionCountBefore = await getCreatedCollectionCount(api);581582 // Run the CreateCollection transaction583 const alicePrivateKey = privateKeyWrapper('//Alice');584 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});585 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;586587 // Get number of collections after the transaction588 const collectionCountAfter = await getCreatedCollectionCount(api);589590 // What to expect591 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');592 });593}594595export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {596 let bal = 0n;597 let unused;598 do {599 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;600 unused = privateKeyWrapper(`//${randomSeed}`);601 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();602 } while (bal !== 0n);603 return unused;604}605606export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {607 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();608}609610export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {611 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));612}613614export async function findNotExistingCollection(api: ApiPromise): Promise<number> {615 const totalNumber = await getCreatedCollectionCount(api);616 const newCollection: number = totalNumber + 1;617 return newCollection;618}619620function getDestroyResult(events: EventRecord[]): boolean {621 let success = false;622 events.forEach(({event: {method}}) => {623 if (method == 'ExtrinsicSuccess') {624 success = true;625 }626 });627 return success;628}629630export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {631 await usingApi(async (api, privateKeyWrapper) => {632 // Run the DestroyCollection transaction633 const alicePrivateKey = privateKeyWrapper(senderSeed);634 const tx = api.tx.unique.destroyCollection(collectionId);635 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;636 });637}638639export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {640 await usingApi(async (api, privateKeyWrapper) => {641 // Run the DestroyCollection transaction642 const alicePrivateKey = privateKeyWrapper(senderSeed);643 const tx = api.tx.unique.destroyCollection(collectionId);644 const events = await submitTransactionAsync(alicePrivateKey, tx);645 const result = getDestroyResult(events);646 expect(result).to.be.true;647648 // What to expect649 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;650 });651}652653export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {654 await usingApi(async (api) => {655 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);656 const events = await submitTransactionAsync(sender, tx);657 const result = getGenericResult(events);658659 expect(result.success).to.be.true;660 });661}662663export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {664 await usingApi(async(api) => {665 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);666 const events = await submitTransactionAsync(sender, tx);667 const result = getGenericResult(events);668669 expect(result.success).to.be.true;670 });671};672673export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {674 await usingApi(async (api) => {675 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);676 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 const result = getGenericResult(events);678679 expect(result.success).to.be.false;680 });681}682683export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {684 await usingApi(async (api, privateKeyWrapper) => {685686 // Run the transaction687 const senderPrivateKey = privateKeyWrapper(sender);688 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);689 const events = await submitTransactionAsync(senderPrivateKey, tx);690 const result = getGenericResult(events);691692 // Get the collection693 const collection = await queryCollectionExpectSuccess(api, collectionId);694695 // What to expect696 expect(result.success).to.be.true;697 expect(collection.sponsorship.toJSON()).to.deep.equal({698 unconfirmed: sponsor,699 });700 });701}702703export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {704 await usingApi(async (api, privateKeyWrapper) => {705706 // Run the transaction707 const alicePrivateKey = privateKeyWrapper(sender);708 const tx = api.tx.unique.removeCollectionSponsor(collectionId);709 const events = await submitTransactionAsync(alicePrivateKey, tx);710 const result = getGenericResult(events);711712 // Get the collection713 const collection = await queryCollectionExpectSuccess(api, collectionId);714715 // What to expect716 expect(result.success).to.be.true;717 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});718 });719}720721export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {722 await usingApi(async (api, privateKeyWrapper) => {723724 // Run the transaction725 const alicePrivateKey = privateKeyWrapper(senderSeed);726 const tx = api.tx.unique.removeCollectionSponsor(collectionId);727 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;728 });729}730731export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {732 await usingApi(async (api, privateKeyWrapper) => {733734 // Run the transaction735 const alicePrivateKey = privateKeyWrapper(senderSeed);736 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);737 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;738 });739}740741export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {742 await usingApi(async (api, privateKeyWrapper) => {743744 // Run the transaction745 const sender = privateKeyWrapper(senderSeed);746 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);747 });748}749750export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {751 await usingApi(async (api, privateKeyWrapper) => {752753 // Run the transaction754 const tx = api.tx.unique.confirmSponsorship(collectionId);755 const events = await submitTransactionAsync(sender, tx);756 const result = getGenericResult(events);757758 // Get the collection759 const collection = await queryCollectionExpectSuccess(api, collectionId);760761 // What to expect762 expect(result.success).to.be.true;763 expect(collection.sponsorship.toJSON()).to.be.deep.equal({764 confirmed: sender.address,765 });766 });767}768769770export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {771 await usingApi(async (api, privateKeyWrapper) => {772773 // Run the transaction774 const sender = privateKeyWrapper(senderSeed);775 const tx = api.tx.unique.confirmSponsorship(collectionId);776 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;777 });778}779780export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {781 await usingApi(async (api) => {782 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);783 const events = await submitTransactionAsync(sender, tx);784 const result = getGenericResult(events);785786 expect(result.success).to.be.true;787 });788}789790export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {791 await usingApi(async (api) => {792 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);793 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;794 const result = getGenericResult(events);795796 expect(result.success).to.be.false;797 });798}799800export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {801802 await usingApi(async (api) => {803804 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);805 const events = await submitTransactionAsync(sender, tx);806 const result = getGenericResult(events);807808 expect(result.success).to.be.true;809 });810}811812export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {813814 await usingApi(async (api) => {815816 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);817 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;818 const result = getGenericResult(events);819820 expect(result.success).to.be.false;821 });822}823824export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {825 await usingApi(async (api) => {826 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);827 const events = await submitTransactionAsync(sender, tx);828 const result = getGenericResult(events);829830 expect(result.success).to.be.true;831 });832}833834export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {835 await usingApi(async (api) => {836 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);837 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;838 const result = getGenericResult(events);839840 expect(result.success).to.be.false;841 });842}843844export async function getNextSponsored(845 api: ApiPromise,846 collectionId: number,847 account: string | CrossAccountId,848 tokenId: number,849): Promise<number> {850 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));851}852853export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {854 await usingApi(async (api) => {855 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);856 const events = await submitTransactionAsync(sender, tx);857 const result = getGenericResult(events);858859 expect(result.success).to.be.true;860 });861}862863export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {864 let allowlisted = false;865 await usingApi(async (api) => {866 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;867 });868 return allowlisted;869}870871export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {872 await usingApi(async (api) => {873 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());874 const events = await submitTransactionAsync(sender, tx);875 const result = getGenericResult(events);876877 expect(result.success).to.be.true;878 });879}880881export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {882 await usingApi(async (api) => {883 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());884 const events = await submitTransactionAsync(sender, tx);885 const result = getGenericResult(events);886887 expect(result.success).to.be.true;888 });889}890891export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {892 await usingApi(async (api) => {893 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());894 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;895 const result = getGenericResult(events);896897 expect(result.success).to.be.false;898 });899}900901export interface CreateFungibleData {902 readonly Value: bigint;903}904905export interface CreateReFungibleData { }906export interface CreateNftData { }907908export type CreateItemData = {909 NFT: CreateNftData;910} | {911 Fungible: CreateFungibleData;912} | {913 ReFungible: CreateReFungibleData;914};915916export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {917 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);918 const events = await submitTransactionAsync(sender, tx);919 return getGenericResult(events).success;920}921922export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {923 await usingApi(async (api) => {924 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);925 // if burning token by admin - use adminButnItemExpectSuccess926 expect(balanceBefore >= BigInt(value)).to.be.true;927928 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;929930 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);931 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);932 });933}934935export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {936 await usingApi(async (api) => {937 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);938939 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;940 const result = getCreateCollectionResult(events);941 // tslint:disable-next-line:no-unused-expression942 expect(result.success).to.be.false;943 });944}945946export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {947 await usingApi(async (api) => {948 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);949 const events = await submitTransactionAsync(sender, tx);950 return getGenericResult(events).success;951 });952}953954export async function955approve(956 api: ApiPromise,957 collectionId: number,958 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,959) {960 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);961 const events = await submitTransactionAsync(owner, approveUniqueTx);962 return getGenericResult(events).success;963}964965export async function966approveExpectSuccess(967 collectionId: number,968 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,969) {970 await usingApi(async (api: ApiPromise) => {971 const result = await approve(api, collectionId, tokenId, owner, approved, amount);972 expect(result).to.be.true;973974 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));975 });976}977978export async function adminApproveFromExpectSuccess(979 collectionId: number,980 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,981) {982 await usingApi(async (api: ApiPromise) => {983 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);984 const events = await submitTransactionAsync(admin, approveUniqueTx);985 const result = getGenericResult(events);986 expect(result.success).to.be.true;987988 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));989 });990}991992export async function993transferFrom(994 api: ApiPromise,995 collectionId: number,996 tokenId: number,997 accountApproved: IKeyringPair,998 accountFrom: IKeyringPair | CrossAccountId,999 accountTo: IKeyringPair | CrossAccountId,1000 value: number | bigint,1001) {1002 const from = normalizeAccountId(accountFrom);1003 const to = normalizeAccountId(accountTo);1004 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1005 const events = await submitTransactionAsync(accountApproved, transferFromTx);1006 return getGenericResult(events).success;1007}10081009export async function1010transferFromExpectSuccess(1011 collectionId: number,1012 tokenId: number,1013 accountApproved: IKeyringPair,1014 accountFrom: IKeyringPair | CrossAccountId,1015 accountTo: IKeyringPair | CrossAccountId,1016 value: number | bigint = 1,1017 type = 'NFT',1018) {1019 await usingApi(async (api: ApiPromise) => {1020 const from = normalizeAccountId(accountFrom);1021 const to = normalizeAccountId(accountTo);1022 let balanceBefore = 0n;1023 if (type === 'Fungible' || type === 'ReFungible') {1024 balanceBefore = await getBalance(api, collectionId, to, tokenId);1025 }1026 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1027 if (type === 'NFT') {1028 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1029 }1030 if (type === 'Fungible') {1031 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1032 if (JSON.stringify(to) !== JSON.stringify(from)) {1033 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1034 } else {1035 expect(balanceAfter).to.be.equal(balanceBefore);1036 }1037 }1038 if (type === 'ReFungible') {1039 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1040 }1041 });1042}10431044export async function1045transferFromExpectFail(1046 collectionId: number,1047 tokenId: number,1048 accountApproved: IKeyringPair,1049 accountFrom: IKeyringPair,1050 accountTo: IKeyringPair,1051 value: number | bigint = 1,1052) {1053 await usingApi(async (api: ApiPromise) => {1054 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1055 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1056 const result = getCreateCollectionResult(events);1057 // tslint:disable-next-line:no-unused-expression1058 expect(result.success).to.be.false;1059 });1060}10611062/* eslint no-async-promise-executor: "off" */1063export async function getBlockNumber(api: ApiPromise): Promise<number> {1064 return new Promise<number>(async (resolve) => {1065 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1066 unsubscribe();1067 resolve(head.number.toNumber());1068 });1069 });1070}10711072export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1073 await usingApi(async (api) => {1074 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1075 const events = await submitTransactionAsync(sender, changeAdminTx);1076 const result = getCreateCollectionResult(events);1077 expect(result.success).to.be.true;1078 });1079}10801081export async function adminApproveFromExpectFail(1082 collectionId: number,1083 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1084) {1085 await usingApi(async (api: ApiPromise) => {1086 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1087 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1088 const result = getGenericResult(events);1089 expect(result.success).to.be.false;1090 });1091}10921093export async function1094getFreeBalance(account: IKeyringPair): Promise<bigint> {1095 let balance = 0n;1096 await usingApi(async (api) => {1097 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1098 });10991100 return balance;1101}11021103export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1104 return usingApi(async api => {1105 const siblingPrefix = '0x7369626c';1106 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1107 const suffix = '000000000000000000000000000000000000000000000000';11081109 return siblingPrefix + encodedParaId + suffix;1110 });1111}11121113export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1114 const tx = api.tx.balances.transfer(target, amount);1115 const events = await submitTransactionAsync(source, tx);1116 const result = getGenericResult(events);1117 expect(result.success).to.be.true;1118}11191120export async function1121scheduleExpectSuccess(1122 operationTx: any,1123 sender: IKeyringPair,1124 blockSchedule: number,1125 scheduledId: string,1126 period = 1,1127 repetitions = 1,1128) {1129 await usingApi(async (api: ApiPromise) => {1130 const blockNumber: number | undefined = await getBlockNumber(api);1131 const expectedBlockNumber = blockNumber + blockSchedule;11321133 expect(blockNumber).to.be.greaterThan(0);1134 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1135 scheduledId,1136 expectedBlockNumber, 1137 repetitions > 1 ? [period, repetitions] : null, 1138 0, 1139 {Value: operationTx as any},1140 );11411142 const events = await submitTransactionAsync(sender, scheduleTx);1143 expect(getGenericResult(events).success).to.be.true;1144 });1145}11461147export async function1148scheduleExpectFailure(1149 operationTx: any,1150 sender: IKeyringPair,1151 blockSchedule: number,1152 scheduledId: string,1153 period = 1,1154 repetitions = 1,1155) {1156 await usingApi(async (api: ApiPromise) => {1157 const blockNumber: number | undefined = await getBlockNumber(api);1158 const expectedBlockNumber = blockNumber + blockSchedule;11591160 expect(blockNumber).to.be.greaterThan(0);1161 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1162 scheduledId,1163 expectedBlockNumber, 1164 repetitions <= 1 ? null : [period, repetitions], 1165 0, 1166 {Value: operationTx as any},1167 );11681169 //const events = 1170 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1171 //expect(getGenericResult(events).success).to.be.false;1172 });1173}11741175export async function1176scheduleTransferAndWaitExpectSuccess(1177 collectionId: number,1178 tokenId: number,1179 sender: IKeyringPair,1180 recipient: IKeyringPair,1181 value: number | bigint = 1,1182 blockSchedule: number,1183 scheduledId: string,1184) {1185 await usingApi(async (api: ApiPromise) => {1186 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11871188 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11891190 // sleep for n + 1 blocks1191 await waitNewBlocks(blockSchedule + 1);11921193 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11941195 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1196 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1197 });1198}11991200export async function1201scheduleTransferExpectSuccess(1202 collectionId: number,1203 tokenId: number,1204 sender: IKeyringPair,1205 recipient: IKeyringPair,1206 value: number | bigint = 1,1207 blockSchedule: number,1208 scheduledId: string,1209) {1210 await usingApi(async (api: ApiPromise) => {1211 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12121213 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12141215 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1216 });1217}12181219export async function1220scheduleTransferFundsPeriodicExpectSuccess(1221 amount: bigint,1222 sender: IKeyringPair,1223 recipient: IKeyringPair,1224 blockSchedule: number,1225 scheduledId: string,1226 period: number,1227 repetitions: number,1228) {1229 await usingApi(async (api: ApiPromise) => {1230 const transferTx = api.tx.balances.transfer(recipient.address, amount);12311232 const balanceBefore = await getFreeBalance(recipient);1233 1234 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12351236 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1237 });1238}12391240export async function1241transfer(1242 api: ApiPromise,1243 collectionId: number,1244 tokenId: number,1245 sender: IKeyringPair,1246 recipient: IKeyringPair | CrossAccountId,1247 value: number | bigint,1248) : Promise<boolean> {1249 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1250 const events = await executeTransaction(api, sender, transferTx);1251 return getGenericResult(events).success;1252}12531254export async function1255transferExpectSuccess(1256 collectionId: number,1257 tokenId: number,1258 sender: IKeyringPair,1259 recipient: IKeyringPair | CrossAccountId,1260 value: number | bigint = 1,1261 type = 'NFT',1262) {1263 await usingApi(async (api: ApiPromise) => {1264 const from = normalizeAccountId(sender);1265 const to = normalizeAccountId(recipient);12661267 let balanceBefore = 0n;1268 if (type === 'Fungible' || type === 'ReFungible') {1269 balanceBefore = await getBalance(api, collectionId, to, tokenId);1270 }12711272 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1273 const events = await executeTransaction(api, sender, transferTx);1274 const result = getTransferResult(api, events);12751276 expect(result.collectionId).to.be.equal(collectionId);1277 expect(result.itemId).to.be.equal(tokenId);1278 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1279 expect(result.recipient).to.be.deep.equal(to);1280 expect(result.value).to.be.equal(BigInt(value));12811282 if (type === 'NFT') {1283 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1284 }1285 if (type === 'Fungible' || type === 'ReFungible') {1286 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1287 if (JSON.stringify(to) !== JSON.stringify(from)) {1288 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1289 } else {1290 expect(balanceAfter).to.be.equal(balanceBefore);1291 }1292 }1293 });1294}12951296export async function1297transferExpectFailure(1298 collectionId: number,1299 tokenId: number,1300 sender: IKeyringPair,1301 recipient: IKeyringPair | CrossAccountId,1302 value: number | bigint = 1,1303) {1304 await usingApi(async (api: ApiPromise) => {1305 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1306 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1307 const result = getGenericResult(events);1308 // if (events && Array.isArray(events)) {1309 // const result = getCreateCollectionResult(events);1310 // tslint:disable-next-line:no-unused-expression1311 expect(result.success).to.be.false;1312 //}1313 });1314}13151316export async function1317approveExpectFail(1318 collectionId: number,1319 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1320) {1321 await usingApi(async (api: ApiPromise) => {1322 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1323 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1324 const result = getCreateCollectionResult(events);1325 // tslint:disable-next-line:no-unused-expression1326 expect(result.success).to.be.false;1327 });1328}13291330export async function getBalance(1331 api: ApiPromise,1332 collectionId: number,1333 owner: string | CrossAccountId | IKeyringPair,1334 token: number,1335): Promise<bigint> {1336 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1337}1338export async function getTokenOwner(1339 api: ApiPromise,1340 collectionId: number,1341 token: number,1342): Promise<CrossAccountId> {1343 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1344 if (owner == null) throw new Error('owner == null');1345 return normalizeAccountId(owner);1346}1347export async function getTopmostTokenOwner(1348 api: ApiPromise,1349 collectionId: number,1350 token: number,1351): Promise<CrossAccountId> {1352 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1353 if (owner == null) throw new Error('owner == null');1354 return normalizeAccountId(owner);1355}1356export async function getTokenChildren(1357 api: ApiPromise,1358 collectionId: number,1359 tokenId: number,1360): Promise<UpDataStructsTokenChild[]> {1361 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1362}1363export async function isTokenExists(1364 api: ApiPromise,1365 collectionId: number,1366 token: number,1367): Promise<boolean> {1368 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1369}1370export async function getLastTokenId(1371 api: ApiPromise,1372 collectionId: number,1373): Promise<number> {1374 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1375}1376export async function getAdminList(1377 api: ApiPromise,1378 collectionId: number,1379): Promise<string[]> {1380 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1381}1382export async function getTokenProperties(1383 api: ApiPromise,1384 collectionId: number,1385 tokenId: number,1386 propertyKeys: string[],1387): Promise<UpDataStructsProperty[]> {1388 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1389}13901391export async function createFungibleItemExpectSuccess(1392 sender: IKeyringPair,1393 collectionId: number,1394 data: CreateFungibleData,1395 owner: CrossAccountId | string = sender.address,1396) {1397 return await usingApi(async (api) => {1398 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13991400 const events = await submitTransactionAsync(sender, tx);1401 const result = getCreateItemResult(events);14021403 expect(result.success).to.be.true;1404 return result.itemId;1405 });1406}14071408export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1409 await usingApi(async (api) => {1410 const to = normalizeAccountId(owner);1411 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14121413 const events = await submitTransactionAsync(sender, tx);1414 expect(getGenericResult(events).success).to.be.true;1415 });1416}14171418export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1419 await usingApi(async (api) => {1420 const to = normalizeAccountId(owner);1421 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14221423 const events = await submitTransactionAsync(sender, tx);1424 const result = getCreateItemsResult(events);14251426 for (const res of result) {1427 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1428 }1429 });1430}14311432export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1433 await usingApi(async (api) => {1434 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14351436 const events = await submitTransactionAsync(sender, tx);1437 const result = getCreateItemsResult(events);14381439 for (const res of result) {1440 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1441 }1442 });1443}14441445export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1446 let newItemId = 0;1447 await usingApi(async (api) => {1448 const to = normalizeAccountId(owner);1449 const itemCountBefore = await getLastTokenId(api, collectionId);1450 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14511452 let tx;1453 if (createMode === 'Fungible') {1454 const createData = {fungible: {value: 10}};1455 tx = api.tx.unique.createItem(collectionId, to, createData as any);1456 } else if (createMode === 'ReFungible') {1457 const createData = {refungible: {pieces: 100}};1458 tx = api.tx.unique.createItem(collectionId, to, createData as any);1459 } else {1460 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1461 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1462 }14631464 const events = await submitTransactionAsync(sender, tx);1465 const result = getCreateItemResult(events);14661467 const itemCountAfter = await getLastTokenId(api, collectionId);1468 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14691470 if (createMode === 'NFT') {1471 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1472 }14731474 // What to expect1475 // tslint:disable-next-line:no-unused-expression1476 expect(result.success).to.be.true;1477 if (createMode === 'Fungible') {1478 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1479 } else {1480 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1481 }1482 expect(collectionId).to.be.equal(result.collectionId);1483 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1484 expect(to).to.be.deep.equal(result.recipient);1485 newItemId = result.itemId;1486 });1487 return newItemId;1488}14891490export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1491 await usingApi(async (api) => {14921493 let tx;1494 if (createMode === 'NFT') {1495 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1496 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1497 } else {1498 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1499 }150015011502 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1503 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1504 const result = getCreateItemResult(events);15051506 expect(result.success).to.be.false;1507 });1508}15091510export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1511 let newItemId = 0;1512 await usingApi(async (api) => {1513 const to = normalizeAccountId(owner);1514 const itemCountBefore = await getLastTokenId(api, collectionId);1515 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15161517 let tx;1518 if (createMode === 'Fungible') {1519 const createData = {fungible: {value: 10}};1520 tx = api.tx.unique.createItem(collectionId, to, createData as any);1521 } else if (createMode === 'ReFungible') {1522 const createData = {refungible: {pieces: 100}};1523 tx = api.tx.unique.createItem(collectionId, to, createData as any);1524 } else {1525 const createData = {nft: {}};1526 tx = api.tx.unique.createItem(collectionId, to, createData as any);1527 }15281529 const events = await executeTransaction(api, sender, tx);1530 const result = getCreateItemResult(events);15311532 const itemCountAfter = await getLastTokenId(api, collectionId);1533 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15341535 // What to expect1536 // tslint:disable-next-line:no-unused-expression1537 expect(result.success).to.be.true;1538 if (createMode === 'Fungible') {1539 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1540 } else {1541 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1542 }1543 expect(collectionId).to.be.equal(result.collectionId);1544 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1545 expect(to).to.be.deep.equal(result.recipient);1546 newItemId = result.itemId;1547 });1548 return newItemId;1549}15501551export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1552 const createData = {refungible: {pieces: amount}};1553 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15541555 const events = await submitTransactionAsync(sender, tx);1556 return getCreateItemResult(events);1557}15581559export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1560 await usingApi(async (api) => {1561 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15621563 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1564 const result = getCreateItemResult(events);15651566 expect(result.success).to.be.false;1567 });1568}15691570export async function setPublicAccessModeExpectSuccess(1571 sender: IKeyringPair, collectionId: number,1572 accessMode: 'Normal' | 'AllowList',1573) {1574 await usingApi(async (api) => {15751576 // Run the transaction1577 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1578 const events = await submitTransactionAsync(sender, tx);1579 const result = getGenericResult(events);15801581 // Get the collection1582 const collection = await queryCollectionExpectSuccess(api, collectionId);15831584 // What to expect1585 // tslint:disable-next-line:no-unused-expression1586 expect(result.success).to.be.true;1587 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1588 });1589}15901591export async function setPublicAccessModeExpectFail(1592 sender: IKeyringPair, collectionId: number,1593 accessMode: 'Normal' | 'AllowList',1594) {1595 await usingApi(async (api) => {15961597 // Run the transaction1598 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1599 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1600 const result = getGenericResult(events);16011602 // What to expect1603 // tslint:disable-next-line:no-unused-expression1604 expect(result.success).to.be.false;1605 });1606}16071608export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1610}16111612export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1613 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1614}16151616export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1617 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1618}16191620export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1621 await usingApi(async (api) => {16221623 // Run the transaction1624 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1625 const events = await submitTransactionAsync(sender, tx);1626 const result = getGenericResult(events);1627 expect(result.success).to.be.true;16281629 // Get the collection1630 const collection = await queryCollectionExpectSuccess(api, collectionId);16311632 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1633 });1634}16351636export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1637 await setMintPermissionExpectSuccess(sender, collectionId, true);1638}16391640export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1641 await usingApi(async (api) => {1642 // Run the transaction1643 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1644 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1645 const result = getCreateCollectionResult(events);1646 // tslint:disable-next-line:no-unused-expression1647 expect(result.success).to.be.false;1648 });1649}16501651export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1652 await usingApi(async (api) => {1653 // Run the transaction1654 const tx = api.tx.unique.setChainLimits(limits);1655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1656 const result = getCreateCollectionResult(events);1657 // tslint:disable-next-line:no-unused-expression1658 expect(result.success).to.be.false;1659 });1660}16611662export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1663 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1664}16651666export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1667 await usingApi(async (api) => {1668 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16691670 // Run the transaction1671 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1672 const events = await submitTransactionAsync(sender, tx);1673 const result = getGenericResult(events);1674 expect(result.success).to.be.true;16751676 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1677 });1678}16791680export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1681 await usingApi(async (api) => {16821683 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16841685 // Run the transaction1686 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1687 const events = await submitTransactionAsync(sender, tx);1688 const result = getGenericResult(events);1689 expect(result.success).to.be.true;16901691 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1692 });1693}16941695export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1696 await usingApi(async (api) => {16971698 // Run the transaction1699 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1700 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1701 const result = getGenericResult(events);17021703 // What to expect1704 // tslint:disable-next-line:no-unused-expression1705 expect(result.success).to.be.false;1706 });1707}17081709export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1710 await usingApi(async (api) => {1711 // Run the transaction1712 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1713 const events = await submitTransactionAsync(sender, tx);1714 const result = getGenericResult(events);17151716 // What to expect1717 // tslint:disable-next-line:no-unused-expression1718 expect(result.success).to.be.true;1719 });1720}17211722export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1723 await usingApi(async (api) => {1724 // Run the transaction1725 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1726 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1727 const result = getGenericResult(events);17281729 // What to expect1730 // tslint:disable-next-line:no-unused-expression1731 expect(result.success).to.be.false;1732 });1733}17341735export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1736 : Promise<UpDataStructsRpcCollection | null> => {1737 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1738};17391740export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1741 // set global object - collectionsCount1742 return (await api.rpc.unique.collectionStats()).created.toNumber();1743};17441745export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1746 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1747}17481749export const describe_xcm = (1750 process.env.RUN_XCM_TESTS1751 ? describe1752 : describe.skip1753);17541755export async function waitNewBlocks(blocksCount = 1): Promise<void> {1756 await usingApi(async (api) => {1757 const promise = new Promise<void>(async (resolve) => {1758 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1759 if (blocksCount > 0) {1760 blocksCount--;1761 } else {1762 unsubscribe();1763 resolve();1764 }1765 });1766 });1767 return promise;1768 });1769}17701771export async function waitEvent(1772 api: ApiPromise,1773 maxBlocksToWait: number,1774 eventSection: string,1775 eventMethod: string,1776): Promise<EventRecord | null> {17771778 const promise = new Promise<EventRecord | null>(async (resolve) => {1779 const unsubscribe = await api.query.system.events(eventRecords => {1780 const neededEvent = eventRecords.find(r => {1781 return r.event.section == eventSection && r.event.method == eventMethod;1782 });17831784 if (neededEvent) {1785 unsubscribe();1786 resolve(neededEvent);1787 }17881789 if (maxBlocksToWait > 0) {1790 maxBlocksToWait--;1791 } else {1792 unsubscribe();1793 resolve(null);1794 }1795 });1796 });1797 return promise;1798}17991800export async function repartitionRFT(1801 api: ApiPromise,1802 collectionId: number,1803 sender: IKeyringPair,1804 tokenId: number,1805 amount: bigint,1806): Promise<boolean> {1807 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1808 const events = await submitTransactionAsync(sender, tx);1809 const result = getGenericResult(events);18101811 return result.success;1812}18131814export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1815 let i: any = it;1816 if (opts.only) i = i.only;1817 else if (opts.skip) i = i.skip;1818 i(name, async () => {1819 await usingApi(async (api, privateKeyWrapper) => {1820 await cb({api, privateKeyWrapper});1821 });1822 });1823}18241825itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1826itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18271828let accountSeed = 10000;18291830const keyringEth = new Keyring({type: 'ethereum'});1831const keyringEd25519 = new Keyring({type: 'ed25519'});1832const keyringSr25519 = new Keyring({type: 'sr25519'});18331834export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1835 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56,'0')}`;1836 if (type == 'sr25519') {1837 return keyringSr25519.addFromUri(privateKey);1838 } else if (type == 'ed25519') {1839 return keyringEd25519.addFromUri(privateKey);1840 }1841 return keyringEth.addFromUri(privateKey);1842}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../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 let numberStr = number.toString();108 console.log('[0] str = ', numberStr);109110 // Get rid of `n` at the end111 numberStr = numberStr.substring(0, numberStr.length - 1);112 console.log('[1] str = ', numberStr);113114 const dotPos = numberStr.length - decimals;115 if (dotPos <= 0) {116 return '0.' + numberStr;117 } else {118 const intPart = numberStr.substring(0, dotPos);119 const fractPart = numberStr.substring(dotPos);120 return intPart + '.' + fractPart;121 }122}123124export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {125 if (typeof input === 'string') {126 if (input.length >= 47) {127 return {Substrate: input};128 } else if (input.length === 42 && input.startsWith('0x')) {129 return {Ethereum: input.toLowerCase()};130 } else if (input.length === 40 && !input.startsWith('0x')) {131 return {Ethereum: '0x' + input.toLowerCase()};132 } else {133 throw new Error(`Unknown address format: "${input}"`);134 }135 }136 if ('address' in input) {137 return {Substrate: input.address};138 }139 if ('Ethereum' in input) {140 return {141 Ethereum: input.Ethereum.toLowerCase(),142 };143 } else if ('ethereum' in input) {144 return {145 Ethereum: (input as any).ethereum.toLowerCase(),146 };147 } else if ('Substrate' in input) {148 return input;149 } else if ('substrate' in input) {150 return {151 Substrate: (input as any).substrate,152 };153 }154155 // AccountId156 return {Substrate: input.toString()};157}158export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {159 input = normalizeAccountId(input);160 if ('Substrate' in input) {161 return input.Substrate;162 } else {163 return evmToAddress(input.Ethereum);164 }165}166167export const U128_MAX = (1n << 128n) - 1n;168169const MICROUNIQUE = 1_000_000_000_000n;170const MILLIUNIQUE = 1_000n * MICROUNIQUE;171const CENTIUNIQUE = 10n * MILLIUNIQUE;172export const UNIQUE = 100n * CENTIUNIQUE;173174interface GenericResult<T> {175 success: boolean;176 data: T | null;177}178179interface CreateCollectionResult {180 success: boolean;181 collectionId: number;182}183184interface CreateItemResult {185 success: boolean;186 collectionId: number;187 itemId: number;188 recipient?: CrossAccountId;189 amount?: number;190}191192interface DestroyItemResult {193 success: boolean;194 collectionId: number;195 itemId: number;196 owner: CrossAccountId;197 amount: number;198}199200interface TransferResult {201 collectionId: number;202 itemId: number;203 sender?: CrossAccountId;204 recipient?: CrossAccountId;205 value: bigint;206}207208interface IReFungibleOwner {209 fraction: BN;210 owner: number[];211}212213interface IGetMessage {214 checkMsgUnqMethod: string;215 checkMsgTrsMethod: string;216 checkMsgSysMethod: string;217}218219export interface IFungibleTokenDataType {220 value: number;221}222223export interface IChainLimits {224 collectionNumbersLimit: number;225 accountTokenOwnershipLimit: number;226 collectionsAdminsLimit: number;227 customDataLimit: number;228 nftSponsorTransferTimeout: number;229 fungibleSponsorTransferTimeout: number;230 refungibleSponsorTransferTimeout: number;231 //offchainSchemaLimit: number;232 //constOnChainSchemaLimit: number;233}234235export interface IReFungibleTokenDataType {236 owner: IReFungibleOwner[];237}238239export function uniqueEventMessage(events: EventRecord[]): IGetMessage {240 let checkMsgUnqMethod = '';241 let checkMsgTrsMethod = '';242 let checkMsgSysMethod = '';243 events.forEach(({event: {method, section}}) => {244 if (section === 'common') {245 checkMsgUnqMethod = method;246 } else if (section === 'treasury') {247 checkMsgTrsMethod = method;248 } else if (section === 'system') {249 checkMsgSysMethod = method;250 } else { return null; }251 });252 const result: IGetMessage = {253 checkMsgUnqMethod,254 checkMsgTrsMethod,255 checkMsgSysMethod,256 };257 return result;258}259260export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {261 const event = events.find(r => check(r.event));262 if (!event) return;263 return event.event as T;264}265266export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;267export function getGenericResult<T>(268 events: EventRecord[],269 expectSection: string,270 expectMethod: string,271 extractAction: (data: GenericEventData) => T272): GenericResult<T>;273274export function getGenericResult<T>(275 events: EventRecord[],276 expectSection?: string,277 expectMethod?: string,278 extractAction?: (data: GenericEventData) => T,279): GenericResult<T> {280 let success = false;281 let successData = null;282283 events.forEach(({event: {data, method, section}}) => {284 // console.log(` ${phase}: ${section}.${method}:: ${data}`);285 if (method === 'ExtrinsicSuccess') {286 success = true;287 } else if ((expectSection == section) && (expectMethod == method)) {288 successData = extractAction!(data as any);289 }290 });291292 const result: GenericResult<T> = {293 success,294 data: successData,295 };296 return result;297}298299export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {300 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));301 const result: CreateCollectionResult = {302 success: genericResult.success,303 collectionId: genericResult.data ?? 0,304 };305 return result;306}307308export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {309 const results: CreateItemResult[] = [];310 311 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {312 const collectionId = parseInt(data[0].toString(), 10);313 const itemId = parseInt(data[1].toString(), 10);314 const recipient = normalizeAccountId(data[2].toJSON() as any);315 const amount = parseInt(data[3].toString(), 10);316317 const itemRes: CreateItemResult = {318 success: true,319 collectionId,320 itemId,321 recipient,322 amount,323 };324325 results.push(itemRes);326 return results;327 });328329 if (!genericResult.success) return [];330 return results;331}332333export function getCreateItemResult(events: EventRecord[]): CreateItemResult {334 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));335 336 if (genericResult.data == null) 337 return {338 success: genericResult.success,339 collectionId: 0,340 itemId: 0,341 amount: 0,342 };343 else 344 return {345 success: genericResult.success,346 collectionId: genericResult.data[0] as number,347 itemId: genericResult.data[1] as number,348 recipient: normalizeAccountId(genericResult.data![2] as any),349 amount: genericResult.data[3] as number,350 };351}352353export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {354 const results: DestroyItemResult[] = [];355 356 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {357 const collectionId = parseInt(data[0].toString(), 10);358 const itemId = parseInt(data[1].toString(), 10);359 const owner = normalizeAccountId(data[2].toJSON() as any);360 const amount = parseInt(data[3].toString(), 10);361362 const itemRes: DestroyItemResult = {363 success: true,364 collectionId,365 itemId,366 owner,367 amount,368 };369370 results.push(itemRes);371 return results;372 });373374 if (!genericResult.success) return [];375 return results;376}377378export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {379 for (const {event} of events) {380 if (api.events.common.Transfer.is(event)) {381 const [collection, token, sender, recipient, value] = event.data;382 return {383 collectionId: collection.toNumber(),384 itemId: token.toNumber(),385 sender: normalizeAccountId(sender.toJSON() as any),386 recipient: normalizeAccountId(recipient.toJSON() as any),387 value: value.toBigInt(),388 };389 }390 }391 throw new Error('no transfer event');392}393394interface Nft {395 type: 'NFT';396}397398interface Fungible {399 type: 'Fungible';400 decimalPoints: number;401}402403interface ReFungible {404 type: 'ReFungible';405}406407export type CollectionMode = Nft | Fungible | ReFungible;408409export type Property = {410 key: any,411 value: any,412};413414type Permission = {415 mutable: boolean;416 collectionAdmin: boolean;417 tokenOwner: boolean;418}419420type PropertyPermission = {421 key: any;422 permission: Permission;423}424425export type CreateCollectionParams = {426 mode: CollectionMode,427 name: string,428 description: string,429 tokenPrefix: string,430 properties?: Array<Property>,431 propPerm?: Array<PropertyPermission>432};433434const defaultCreateCollectionParams: CreateCollectionParams = {435 description: 'description',436 mode: {type: 'NFT'},437 name: 'name',438 tokenPrefix: 'prefix',439};440441export async function442createCollection(443 api: ApiPromise,444 sender: IKeyringPair,445 params: Partial<CreateCollectionParams> = {},446): Promise<CreateCollectionResult> {447 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};448449 let modeprm = {};450 if (mode.type === 'NFT') {451 modeprm = {nft: null};452 } else if (mode.type === 'Fungible') {453 modeprm = {fungible: mode.decimalPoints};454 } else if (mode.type === 'ReFungible') {455 modeprm = {refungible: null};456 }457458 const tx = api.tx.unique.createCollectionEx({459 name: strToUTF16(name),460 description: strToUTF16(description),461 tokenPrefix: strToUTF16(tokenPrefix),462 mode: modeprm as any,463 });464 const events = await executeTransaction(api, sender, tx);465 return getCreateCollectionResult(events);466}467468export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {469 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};470471 let collectionId = 0;472 await usingApi(async (api, privateKeyWrapper) => {473 // Get number of collections before the transaction474 const collectionCountBefore = await getCreatedCollectionCount(api);475476 // Run the CreateCollection transaction477 const alicePrivateKey = privateKeyWrapper('//Alice');478479 const result = await createCollection(api, alicePrivateKey, params);480481 // Get number of collections after the transaction482 const collectionCountAfter = await getCreatedCollectionCount(api);483484 // Get the collection485 const collection = await queryCollectionExpectSuccess(api, result.collectionId);486487 // What to expect488 // tslint:disable-next-line:no-unused-expression489 expect(result.success).to.be.true;490 expect(result.collectionId).to.be.equal(collectionCountAfter);491 // tslint:disable-next-line:no-unused-expression492 expect(collection).to.be.not.null;493 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');494 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));495 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);496 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);497 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);498499 collectionId = result.collectionId;500 });501502 return collectionId;503}504505export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {506 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};507508 let collectionId = 0;509 await usingApi(async (api, privateKeyWrapper) => {510 // Get number of collections before the transaction511 const collectionCountBefore = await getCreatedCollectionCount(api);512513 // Run the CreateCollection transaction514 const alicePrivateKey = privateKeyWrapper('//Alice');515516 let modeprm = {};517 if (mode.type === 'NFT') {518 modeprm = {nft: null};519 } else if (mode.type === 'Fungible') {520 modeprm = {fungible: mode.decimalPoints};521 } else if (mode.type === 'ReFungible') {522 modeprm = {refungible: null};523 }524525 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});526 const events = await submitTransactionAsync(alicePrivateKey, tx);527 const result = getCreateCollectionResult(events);528529 // Get number of collections after the transaction530 const collectionCountAfter = await getCreatedCollectionCount(api);531532 // Get the collection533 const collection = await queryCollectionExpectSuccess(api, result.collectionId);534535 // What to expect536 // tslint:disable-next-line:no-unused-expression537 expect(result.success).to.be.true;538 expect(result.collectionId).to.be.equal(collectionCountAfter);539 // tslint:disable-next-line:no-unused-expression540 expect(collection).to.be.not.null;541 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');542 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));543 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);544 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);545 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);546547548 collectionId = result.collectionId;549 });550551 return collectionId;552}553554export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {555 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};556557 await usingApi(async (api, privateKeyWrapper) => {558 // Get number of collections before the transaction559 const collectionCountBefore = await getCreatedCollectionCount(api);560561 // Run the CreateCollection transaction562 const alicePrivateKey = privateKeyWrapper('//Alice');563564 let modeprm = {};565 if (mode.type === 'NFT') {566 modeprm = {nft: null};567 } else if (mode.type === 'Fungible') {568 modeprm = {fungible: mode.decimalPoints};569 } else if (mode.type === 'ReFungible') {570 modeprm = {refungible: null};571 }572573 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});574 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;575576577 // Get number of collections after the transaction578 const collectionCountAfter = await getCreatedCollectionCount(api);579580 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');581 });582}583584export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {585 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};586587 let modeprm = {};588 if (mode.type === 'NFT') {589 modeprm = {nft: null};590 } else if (mode.type === 'Fungible') {591 modeprm = {fungible: mode.decimalPoints};592 } else if (mode.type === 'ReFungible') {593 modeprm = {refungible: null};594 }595596 await usingApi(async (api, privateKeyWrapper) => {597 // Get number of collections before the transaction598 const collectionCountBefore = await getCreatedCollectionCount(api);599600 // Run the CreateCollection transaction601 const alicePrivateKey = privateKeyWrapper('//Alice');602 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});603 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;604605 // Get number of collections after the transaction606 const collectionCountAfter = await getCreatedCollectionCount(api);607608 // What to expect609 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');610 });611}612613export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {614 let bal = 0n;615 let unused;616 do {617 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;618 unused = privateKeyWrapper(`//${randomSeed}`);619 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();620 } while (bal !== 0n);621 return unused;622}623624export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {625 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();626}627628export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {629 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));630}631632export async function findNotExistingCollection(api: ApiPromise): Promise<number> {633 const totalNumber = await getCreatedCollectionCount(api);634 const newCollection: number = totalNumber + 1;635 return newCollection;636}637638function getDestroyResult(events: EventRecord[]): boolean {639 let success = false;640 events.forEach(({event: {method}}) => {641 if (method == 'ExtrinsicSuccess') {642 success = true;643 }644 });645 return success;646}647648export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {649 await usingApi(async (api, privateKeyWrapper) => {650 // Run the DestroyCollection transaction651 const alicePrivateKey = privateKeyWrapper(senderSeed);652 const tx = api.tx.unique.destroyCollection(collectionId);653 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;654 });655}656657export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {658 await usingApi(async (api, privateKeyWrapper) => {659 // Run the DestroyCollection transaction660 const alicePrivateKey = privateKeyWrapper(senderSeed);661 const tx = api.tx.unique.destroyCollection(collectionId);662 const events = await submitTransactionAsync(alicePrivateKey, tx);663 const result = getDestroyResult(events);664 expect(result).to.be.true;665666 // What to expect667 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;668 });669}670671export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {672 await usingApi(async (api) => {673 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);674 const events = await submitTransactionAsync(sender, tx);675 const result = getGenericResult(events);676677 expect(result.success).to.be.true;678 });679}680681export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {682 await usingApi(async(api) => {683 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);684 const events = await submitTransactionAsync(sender, tx);685 const result = getGenericResult(events);686687 expect(result.success).to.be.true;688 });689};690691export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {692 await usingApi(async (api) => {693 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);694 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;695 const result = getGenericResult(events);696697 expect(result.success).to.be.false;698 });699}700701export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {702 await usingApi(async (api, privateKeyWrapper) => {703704 // Run the transaction705 const senderPrivateKey = privateKeyWrapper(sender);706 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);707 const events = await submitTransactionAsync(senderPrivateKey, tx);708 const result = getGenericResult(events);709710 // Get the collection711 const collection = await queryCollectionExpectSuccess(api, collectionId);712713 // What to expect714 expect(result.success).to.be.true;715 expect(collection.sponsorship.toJSON()).to.deep.equal({716 unconfirmed: sponsor,717 });718 });719}720721export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {722 await usingApi(async (api, privateKeyWrapper) => {723724 // Run the transaction725 const alicePrivateKey = privateKeyWrapper(sender);726 const tx = api.tx.unique.removeCollectionSponsor(collectionId);727 const events = await submitTransactionAsync(alicePrivateKey, tx);728 const result = getGenericResult(events);729730 // Get the collection731 const collection = await queryCollectionExpectSuccess(api, collectionId);732733 // What to expect734 expect(result.success).to.be.true;735 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});736 });737}738739export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {740 await usingApi(async (api, privateKeyWrapper) => {741742 // Run the transaction743 const alicePrivateKey = privateKeyWrapper(senderSeed);744 const tx = api.tx.unique.removeCollectionSponsor(collectionId);745 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;746 });747}748749export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {750 await usingApi(async (api, privateKeyWrapper) => {751752 // Run the transaction753 const alicePrivateKey = privateKeyWrapper(senderSeed);754 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);755 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;756 });757}758759export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {760 await usingApi(async (api, privateKeyWrapper) => {761762 // Run the transaction763 const sender = privateKeyWrapper(senderSeed);764 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);765 });766}767768export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {769 await usingApi(async (api, privateKeyWrapper) => {770771 // Run the transaction772 const tx = api.tx.unique.confirmSponsorship(collectionId);773 const events = await submitTransactionAsync(sender, tx);774 const result = getGenericResult(events);775776 // Get the collection777 const collection = await queryCollectionExpectSuccess(api, collectionId);778779 // What to expect780 expect(result.success).to.be.true;781 expect(collection.sponsorship.toJSON()).to.be.deep.equal({782 confirmed: sender.address,783 });784 });785}786787788export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {789 await usingApi(async (api, privateKeyWrapper) => {790791 // Run the transaction792 const sender = privateKeyWrapper(senderSeed);793 const tx = api.tx.unique.confirmSponsorship(collectionId);794 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795 });796}797798export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {799 await usingApi(async (api) => {800 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);801 const events = await submitTransactionAsync(sender, tx);802 const result = getGenericResult(events);803804 expect(result.success).to.be.true;805 });806}807808export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {809 await usingApi(async (api) => {810 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);811 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;812 const result = getGenericResult(events);813814 expect(result.success).to.be.false;815 });816}817818export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {819820 await usingApi(async (api) => {821822 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);823 const events = await submitTransactionAsync(sender, tx);824 const result = getGenericResult(events);825826 expect(result.success).to.be.true;827 });828}829830export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {831832 await usingApi(async (api) => {833834 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);835 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;836 const result = getGenericResult(events);837838 expect(result.success).to.be.false;839 });840}841842export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {843 await usingApi(async (api) => {844 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);845 const events = await submitTransactionAsync(sender, tx);846 const result = getGenericResult(events);847848 expect(result.success).to.be.true;849 });850}851852export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {853 await usingApi(async (api) => {854 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);855 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;856 const result = getGenericResult(events);857858 expect(result.success).to.be.false;859 });860}861862export async function getNextSponsored(863 api: ApiPromise,864 collectionId: number,865 account: string | CrossAccountId,866 tokenId: number,867): Promise<number> {868 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));869}870871export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {872 await usingApi(async (api) => {873 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);874 const events = await submitTransactionAsync(sender, tx);875 const result = getGenericResult(events);876877 expect(result.success).to.be.true;878 });879}880881export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {882 let allowlisted = false;883 await usingApi(async (api) => {884 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;885 });886 return allowlisted;887}888889export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {890 await usingApi(async (api) => {891 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());892 const events = await submitTransactionAsync(sender, tx);893 const result = getGenericResult(events);894895 expect(result.success).to.be.true;896 });897}898899export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {900 await usingApi(async (api) => {901 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());902 const events = await submitTransactionAsync(sender, tx);903 const result = getGenericResult(events);904905 expect(result.success).to.be.true;906 });907}908909export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {910 await usingApi(async (api) => {911 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());912 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;913 const result = getGenericResult(events);914915 expect(result.success).to.be.false;916 });917}918919export interface CreateFungibleData {920 readonly Value: bigint;921}922923export interface CreateReFungibleData { }924export interface CreateNftData { }925926export type CreateItemData = {927 NFT: CreateNftData;928} | {929 Fungible: CreateFungibleData;930} | {931 ReFungible: CreateReFungibleData;932};933934export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {935 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);936 const events = await submitTransactionAsync(sender, tx);937 return getGenericResult(events).success;938}939940export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {941 await usingApi(async (api) => {942 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);943 // if burning token by admin - use adminButnItemExpectSuccess944 expect(balanceBefore >= BigInt(value)).to.be.true;945946 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;947948 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);949 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);950 });951}952953export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {954 await usingApi(async (api) => {955 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);956957 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;958 const result = getCreateCollectionResult(events);959 // tslint:disable-next-line:no-unused-expression960 expect(result.success).to.be.false;961 });962}963964export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {965 await usingApi(async (api) => {966 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);967 const events = await submitTransactionAsync(sender, tx);968 return getGenericResult(events).success;969 });970}971972export async function973approve(974 api: ApiPromise,975 collectionId: number,976 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,977) {978 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);979 const events = await submitTransactionAsync(owner, approveUniqueTx);980 return getGenericResult(events).success;981}982983export async function984approveExpectSuccess(985 collectionId: number,986 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,987) {988 await usingApi(async (api: ApiPromise) => {989 const result = await approve(api, collectionId, tokenId, owner, approved, amount);990 expect(result).to.be.true;991992 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));993 });994}995996export async function adminApproveFromExpectSuccess(997 collectionId: number,998 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,999) {1000 await usingApi(async (api: ApiPromise) => {1001 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1002 const events = await submitTransactionAsync(admin, approveUniqueTx);1003 const result = getGenericResult(events);1004 expect(result.success).to.be.true;10051006 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1007 });1008}10091010export async function1011transferFrom(1012 api: ApiPromise,1013 collectionId: number,1014 tokenId: number,1015 accountApproved: IKeyringPair,1016 accountFrom: IKeyringPair | CrossAccountId,1017 accountTo: IKeyringPair | CrossAccountId,1018 value: number | bigint,1019) {1020 const from = normalizeAccountId(accountFrom);1021 const to = normalizeAccountId(accountTo);1022 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1023 const events = await submitTransactionAsync(accountApproved, transferFromTx);1024 return getGenericResult(events).success;1025}10261027export async function1028transferFromExpectSuccess(1029 collectionId: number,1030 tokenId: number,1031 accountApproved: IKeyringPair,1032 accountFrom: IKeyringPair | CrossAccountId,1033 accountTo: IKeyringPair | CrossAccountId,1034 value: number | bigint = 1,1035 type = 'NFT',1036) {1037 await usingApi(async (api: ApiPromise) => {1038 const from = normalizeAccountId(accountFrom);1039 const to = normalizeAccountId(accountTo);1040 let balanceBefore = 0n;1041 if (type === 'Fungible' || type === 'ReFungible') {1042 balanceBefore = await getBalance(api, collectionId, to, tokenId);1043 }1044 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1045 if (type === 'NFT') {1046 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1047 }1048 if (type === 'Fungible') {1049 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1050 if (JSON.stringify(to) !== JSON.stringify(from)) {1051 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1052 } else {1053 expect(balanceAfter).to.be.equal(balanceBefore);1054 }1055 }1056 if (type === 'ReFungible') {1057 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1058 }1059 });1060}10611062export async function1063transferFromExpectFail(1064 collectionId: number,1065 tokenId: number,1066 accountApproved: IKeyringPair,1067 accountFrom: IKeyringPair,1068 accountTo: IKeyringPair,1069 value: number | bigint = 1,1070) {1071 await usingApi(async (api: ApiPromise) => {1072 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1073 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1074 const result = getCreateCollectionResult(events);1075 // tslint:disable-next-line:no-unused-expression1076 expect(result.success).to.be.false;1077 });1078}10791080/* eslint no-async-promise-executor: "off" */1081export async function getBlockNumber(api: ApiPromise): Promise<number> {1082 return new Promise<number>(async (resolve) => {1083 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1084 unsubscribe();1085 resolve(head.number.toNumber());1086 });1087 });1088}10891090export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1091 await usingApi(async (api) => {1092 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1093 const events = await submitTransactionAsync(sender, changeAdminTx);1094 const result = getCreateCollectionResult(events);1095 expect(result.success).to.be.true;1096 });1097}10981099export async function adminApproveFromExpectFail(1100 collectionId: number,1101 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1102) {1103 await usingApi(async (api: ApiPromise) => {1104 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1105 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1106 const result = getGenericResult(events);1107 expect(result.success).to.be.false;1108 });1109}11101111export async function1112getFreeBalance(account: IKeyringPair): Promise<bigint> {1113 let balance = 0n;1114 await usingApi(async (api) => {1115 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1116 });11171118 return balance;1119}11201121export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1122 return usingApi(async api => {1123 const siblingPrefix = '0x7369626c';1124 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( // schedule1153 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( // schedule1180 scheduledId,1181 expectedBlockNumber, 1182 repetitions <= 1 ? null : [period, repetitions], 1183 0, 1184 {Value: operationTx as any},1185 );11861187 //const events = 1188 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1189 //expect(getGenericResult(events).success).to.be.false;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 // sleep for n + 1 blocks1209 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);1251 1252 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 // if (events && Array.isArray(events)) {1327 // const result = getCreateCollectionResult(events);1328 // tslint:disable-next-line:no-unused-expression1329 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 // tslint:disable-next-line:no-unused-expression1344 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 // What to expect1493 // tslint:disable-next-line:no-unused-expression1494 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 // What to expect1554 // tslint:disable-next-line:no-unused-expression1555 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 // Run the transaction1595 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1596 const events = await submitTransactionAsync(sender, tx);1597 const result = getGenericResult(events);15981599 // Get the collection1600 const collection = await queryCollectionExpectSuccess(api, collectionId);16011602 // What to expect1603 // tslint:disable-next-line:no-unused-expression1604 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 // Run the transaction1616 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 // What to expect1621 // tslint:disable-next-line:no-unused-expression1622 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 // Run the transaction1642 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 // Get the collection1648 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 // Run the transaction1661 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 // tslint:disable-next-line:no-unused-expression1665 expect(result.success).to.be.false;1666 });1667}16681669export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1670 await usingApi(async (api) => {1671 // Run the transaction1672 const tx = api.tx.unique.setChainLimits(limits);1673 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1674 const result = getCreateCollectionResult(events);1675 // tslint:disable-next-line:no-unused-expression1676 expect(result.success).to.be.false;1677 });1678}16791680export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {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 // Run the transaction1689 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 // Run the transaction1704 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 // Run the transaction1717 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 // What to expect1722 // tslint:disable-next-line:no-unused-expression1723 expect(result.success).to.be.false;1724 });1725}17261727export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1728 await usingApi(async (api) => {1729 // Run the transaction1730 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1731 const events = await submitTransactionAsync(sender, tx);1732 const result = getGenericResult(events);17331734 // What to expect1735 // tslint:disable-next-line:no-unused-expression1736 expect(result.success).to.be.true;1737 });1738}17391740export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1741 await usingApi(async (api) => {1742 // Run the transaction1743 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 // What to expect1748 // tslint:disable-next-line:no-unused-expression1749 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 // set global object - collectionsCount1760 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 const describe_xcm = (1768 process.env.RUN_XCM_TESTS1769 ? describe1770 : describe.skip1771);17721773export async function waitNewBlocks(blocksCount = 1): Promise<void> {1774 await usingApi(async (api) => {1775 const promise = new Promise<void>(async (resolve) => {1776 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1777 if (blocksCount > 0) {1778 blocksCount--;1779 } else {1780 unsubscribe();1781 resolve();1782 }1783 });1784 });1785 return promise;1786 });1787}17881789export async function waitEvent(1790 api: ApiPromise,1791 maxBlocksToWait: number,1792 eventSection: string,1793 eventMethod: string,1794): Promise<EventRecord | null> {17951796 const promise = new Promise<EventRecord | null>(async (resolve) => {1797 const unsubscribe = await api.query.system.events(eventRecords => {1798 const neededEvent = eventRecords.find(r => {1799 return r.event.section == eventSection && r.event.method == eventMethod;1800 });18011802 if (neededEvent) {1803 unsubscribe();1804 resolve(neededEvent);1805 }18061807 if (maxBlocksToWait > 0) {1808 maxBlocksToWait--;1809 } else {1810 unsubscribe();1811 resolve(null);1812 }1813 });1814 });1815 return promise;1816}18171818export async function repartitionRFT(1819 api: ApiPromise,1820 collectionId: number,1821 sender: IKeyringPair,1822 tokenId: number,1823 amount: bigint,1824): Promise<boolean> {1825 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1826 const events = await submitTransactionAsync(sender, tx);1827 const result = getGenericResult(events);18281829 return result.success;1830}18311832export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1833 let i: any = it;1834 if (opts.only) i = i.only;1835 else if (opts.skip) i = i.skip;1836 i(name, async () => {1837 await usingApi(async (api, privateKeyWrapper) => {1838 await cb({api, privateKeyWrapper});1839 });1840 });1841}18421843itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1844itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18451846let accountSeed = 10000;18471848const keyringEth = new Keyring({type: 'ethereum'});1849const keyringEd25519 = new Keyring({type: 'ed25519'});1850const keyringSr25519 = new Keyring({type: 'sr25519'});18511852export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1853 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56,'0')}`;1854 if (type == 'sr25519') {1855 return keyringSr25519.addFromUri(privateKey);1856 } else if (type == 'ed25519') {1857 return keyringEd25519.addFromUri(privateKey);1858 }1859 return keyringEth.addFromUri(privateKey);1860}tests/src/xcm/xcmOpal.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmOpal.test.ts
+++ b/tests/src/xcm/xcmOpal.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from './../substrate/substrate-api';
-import {getGenericResult, paraSiblingSovereignAccount} from './../util/helpers';
+import {bigIntToDecimals, getGenericResult, paraSiblingSovereignAccount} from './../util/helpers';
import waitNewBlocks from './../substrate/wait-new-blocks';
import {normalizeAccountId} from './../util/helpers';
import getBalance from './../substrate/get-balance';
@@ -43,6 +43,8 @@
const ASSET_METADATA_DESCRIPTION = 'USDT';
const ASSET_METADATA_MINIMAL_BALANCE = 1;
+const WESTMINT_DECIMALS = 12;
+
const TRANSFER_AMOUNT = 1_000_000_000_000_000_000n;
// 10,000.00 (ten thousands) USDT
@@ -281,7 +283,10 @@
[balanceStmnAfter] = await getBalance(api, [alice.address]);
// common good parachain take commission in it native token
- console.log('Opal to Westmint transaction fees on Westmint: %s WND', balanceStmnBefore - balanceStmnAfter);
+ console.log(
+ 'Opal to Westmint transaction fees on Westmint: %s WND',
+ bigIntToDecimals(balanceStmnBefore - balanceStmnAfter, WESTMINT_DECIMALS),
+ );
expect(balanceStmnBefore > balanceStmnAfter).to.be.true;
}, statemineApiOptions);
@@ -297,10 +302,16 @@
// commission has not paid in USDT token
expect(free == TRANSFER_AMOUNT).to.be.true;
- console.log('Opal to Westmint transaction fees on Opal: %s USDT', TRANSFER_AMOUNT - free);
+ console.log(
+ 'Opal to Westmint transaction fees on Opal: %s USDT',
+ bigIntToDecimals(TRANSFER_AMOUNT - free),
+ );
// ... and parachain native token
expect(balanceOpalAfter == balanceOpalBefore).to.be.true;
- console.log('Opal to Westmint transaction fees on Opal: %s WND', balanceOpalAfter - balanceOpalBefore);
+ console.log(
+ 'Opal to Westmint transaction fees on Opal: %s WND',
+ bigIntToDecimals(balanceOpalAfter - balanceOpalBefore, WESTMINT_DECIMALS),
+ );
}, uniqueApiOptions);
@@ -451,8 +462,14 @@
[balanceBobAfter] = await getBalance(api, [bob.address]);
balanceBobRelayTokenAfter = BigInt(((await api.query.tokens.accounts(bob.addressRaw, {NativeAssetId: 'Parent'})).toJSON() as any).free);
const wndFee = balanceBobRelayTokenAfter - TRANSFER_AMOUNT_RELAY - balanceBobRelayTokenBefore;
- console.log('Relay (Westend) to Opal transaction fees: %s OPL', balanceBobAfter - balanceBobBefore);
- console.log('Relay (Westend) to Opal transaction fees: %s WND', wndFee);
+ console.log(
+ 'Relay (Westend) to Opal transaction fees: %s OPL',
+ bigIntToDecimals(balanceBobAfter - balanceBobBefore),
+ );
+ console.log(
+ 'Relay (Westend) to Opal transaction fees: %s WND',
+ bigIntToDecimals(wndFee, WESTMINT_DECIMALS),
+ );
expect(balanceBobBefore == balanceBobAfter).to.be.true;
expect(balanceBobRelayTokenBefore < balanceBobRelayTokenAfter).to.be.true;
}, uniqueApiOptions2);
@@ -504,4 +521,4 @@
}, uniqueApiOptions);
});
-});
\ No newline at end of file
+});
tests/src/xcm/xcmQuartz.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmQuartz.test.ts
+++ b/tests/src/xcm/xcmQuartz.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';
@@ -37,6 +37,8 @@
const KARURA_PORT = 9946;
const MOONRIVER_PORT = 9947;
+const KARURA_DECIMALS = 12;
+
const TRANSFER_AMOUNT = 2000000000000000000000000n;
function parachainApiOptions(port: number): ApiOptions {
@@ -182,7 +184,7 @@
[balanceQuartzTokenMiddle] = await getBalance(api, [randomAccount.address]);
const qtzFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
- console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', qtzFees);
+ console.log('[Quartz -> Karura] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
expect(qtzFees > 0n).to.be.true;
});
@@ -198,8 +200,11 @@
const karFees = balanceKaruraTokenInit - balanceKaruraTokenMiddle;
const qtzIncomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenInit;
- console.log('[Quartz -> Karura] transaction fees on Karura: %s KAR', karFees);
- console.log('[Quartz -> Karura] income %s QTZ', qtzIncomeTransfer);
+ console.log('
+ [Quartz -> Karura] transaction fees on Karura: %s KAR',
+ bigIntToDecimals(karFees, KARURA_DECIMALS),
+ );
+ console.log('[Quartz -> Karura] income %s QTZ', bigIntToDecimals(qtzIncomeTransfer));
expect(karFees == 0n).to.be.true;
expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
@@ -249,8 +254,11 @@
const karFees = balanceKaruraTokenMiddle - balanceKaruraTokenFinal;
const qtzOutcomeTransfer = balanceQuartzForeignTokenMiddle - balanceQuartzForeignTokenFinal;
- console.log('[Karura -> Quartz] transaction fees on Karura: %s KAR', karFees);
- console.log('[Karura -> Quartz] outcome %s QTZ', qtzOutcomeTransfer);
+ console.log(
+ '[Karura -> Quartz] transaction fees on Karura: %s KAR',
+ bigIntToDecimals(karFees, KARURA_DECIMALS),
+ );
+ console.log('[Karura -> Quartz] outcome %s QTZ', bigIntToDecimals(qtzOutcomeTransfer));
expect(karFees > 0).to.be.true;
expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
@@ -266,10 +274,10 @@
const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
expect(actuallyDelivered > 0).to.be.true;
- console.log('[Karura -> Quartz] actually delivered %s QTZ', actuallyDelivered);
+ console.log('[Karura -> Quartz] actually delivered %s QTZ', bigIntToDecimals(actuallyDelivered));
const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
- console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', qtzFees);
+ console.log('[Karura -> Quartz] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
expect(qtzFees == 0n).to.be.true;
});
});
@@ -581,7 +589,7 @@
expect(balanceQuartzTokenMiddle < balanceQuartzTokenInit).to.be.true;
const transactionFees = balanceQuartzTokenInit - balanceQuartzTokenMiddle - TRANSFER_AMOUNT;
- console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', transactionFees);
+ console.log('[Quartz -> Moonriver] transaction fees on Quartz: %s QTZ', bigIntToDecimals(transactionFees));
expect(transactionFees > 0).to.be.true;
});
@@ -592,7 +600,7 @@
[balanceMovrTokenMiddle] = await getBalance(api, [randomAccountMoonriver.address]);
const movrFees = balanceMovrTokenInit - balanceMovrTokenMiddle;
- console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR', movrFees);
+ console.log('[Quartz -> Moonriver] transaction fees on Moonriver: %s MOVR',bigIntToDecimals(movrFees));
expect(movrFees == 0n).to.be.true;
const qtzRandomAccountAsset = (
@@ -601,7 +609,7 @@
balanceForeignQtzTokenMiddle = BigInt(qtzRandomAccountAsset['balance']);
const qtzIncomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenInit;
- console.log('[Quartz -> Moonriver] income %s QTZ', qtzIncomeTransfer);
+ console.log('[Quartz -> Moonriver] income %s QTZ', bigIntToDecimals(qtzIncomeTransfer));
expect(qtzIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
moonriverOptions(),
@@ -647,7 +655,7 @@
[balanceMovrTokenFinal] = await getBalance(api, [randomAccountMoonriver.address]);
const movrFees = balanceMovrTokenMiddle - balanceMovrTokenFinal;
- console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', movrFees);
+ console.log('[Moonriver -> Quartz] transaction fees on Moonriver: %s MOVR', bigIntToDecimals(movrFees));
expect(movrFees > 0).to.be.true;
const qtzRandomAccountAsset = (
@@ -659,7 +667,7 @@
balanceForeignQtzTokenFinal = 0n;
const qtzOutcomeTransfer = balanceForeignQtzTokenMiddle - balanceForeignQtzTokenFinal;
- console.log('[Quartz -> Moonriver] outcome %s QTZ', qtzOutcomeTransfer);
+ console.log('[Quartz -> Moonriver] outcome %s QTZ', bigIntToDecimals(qtzOutcomeTransfer));
expect(qtzOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
moonriverOptions(),
@@ -672,10 +680,10 @@
const actuallyDelivered = balanceQuartzTokenFinal - balanceQuartzTokenMiddle;
expect(actuallyDelivered > 0).to.be.true;
- console.log('[Moonriver -> Quartz] actually delivered %s QTZ', actuallyDelivered);
+ console.log('[Moonriver -> Quartz] actually delivered %s QTZ', bigIntToDecimals(actuallyDelivered));
const qtzFees = TRANSFER_AMOUNT - actuallyDelivered;
- console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', qtzFees);
+ console.log('[Moonriver -> Quartz] transaction fees on Quartz: %s QTZ', bigIntToDecimals(qtzFees));
expect(qtzFees == 0n).to.be.true;
});
});
tests/src/xcm/xcmUnique.test.tsdiffbeforeafterboth--- a/tests/src/xcm/xcmUnique.test.ts
+++ b/tests/src/xcm/xcmUnique.test.ts
@@ -21,7 +21,7 @@
import {ApiOptions} from '@polkadot/api/types';
import {IKeyringPair} from '@polkadot/types/types';
import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
-import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm} from '../util/helpers';
+import {getGenericResult, generateKeyringPair, waitEvent, describe_xcm, bigIntToDecimals} from '../util/helpers';
import {MultiLocation} from '@polkadot/types/interfaces';
import {blake2AsHex} from '@polkadot/util-crypto';
import waitNewBlocks from '../substrate/wait-new-blocks';
@@ -37,6 +37,8 @@
const ACALA_PORT = 9946;
const MOONBEAM_PORT = 9947;
+const ACALA_DECIMALS = 12;
+
const TRANSFER_AMOUNT = 2000000000000000000000000n;
function parachainApiOptions(port: number): ApiOptions {
@@ -182,7 +184,7 @@
[balanceUniqueTokenMiddle] = await getBalance(api, [randomAccount.address]);
const unqFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
- console.log('[Unique -> Acala] transaction fees on Unique: %s UNQ', unqFees);
+ console.log('[Unique -> Acala] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
expect(unqFees > 0n).to.be.true;
});
@@ -198,8 +200,11 @@
const acaFees = balanceAcalaTokenInit - balanceAcalaTokenMiddle;
const unqIncomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenInit;
- console.log('[Unique -> Acala] transaction fees on Acala: %s ACA', acaFees);
- console.log('[Unique -> Acala] income %s UNQ', unqIncomeTransfer);
+ console.log(
+ '[Unique -> Acala] transaction fees on Acala: %s ACA',
+ bigIntToDecimals(acaFees, ACALA_DECIMALS),
+ );
+ console.log('[Unique -> Acala] income %s UNQ', bigIntToDecimals(unqIncomeTransfer));
expect(acaFees == 0n).to.be.true;
expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
@@ -249,8 +254,11 @@
const acaFees = balanceAcalaTokenMiddle - balanceAcalaTokenFinal;
const unqOutcomeTransfer = balanceUniqueForeignTokenMiddle - balanceUniqueForeignTokenFinal;
- console.log('[Acala -> Unique] transaction fees on Acala: %s ACA', acaFees);
- console.log('[Acala -> Unique] outcome %s UNQ', unqOutcomeTransfer);
+ console.log(
+ '[Acala -> Unique] transaction fees on Acala: %s ACA',
+ bigIntToDecimals(acaFees, ACALA_DECIMALS),
+ );
+ console.log('[Acala -> Unique] outcome %s UNQ', bigIntToDecimals(unqOutcomeTransfer));
expect(acaFees > 0).to.be.true;
expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
@@ -266,10 +274,10 @@
const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
expect(actuallyDelivered > 0).to.be.true;
- console.log('[Acala -> Unique] actually delivered %s UNQ', actuallyDelivered);
+ console.log('[Acala -> Unique] actually delivered %s UNQ', bigIntToDecimals(actuallyDelivered));
const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
- console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', unqFees);
+ console.log('[Acala -> Unique] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
expect(unqFees == 0n).to.be.true;
});
});
@@ -581,7 +589,7 @@
expect(balanceUniqueTokenMiddle < balanceUniqueTokenInit).to.be.true;
const transactionFees = balanceUniqueTokenInit - balanceUniqueTokenMiddle - TRANSFER_AMOUNT;
- console.log('[Unique -> Moonbeam] transaction fees on Unique: %s UNQ', transactionFees);
+ console.log('[Unique -> Moonbeam] transaction fees on Unique: %s UNQ', bigIntToDecimals(transactionFees));
expect(transactionFees > 0).to.be.true;
});
@@ -592,7 +600,7 @@
[balanceGlmrTokenMiddle] = await getBalance(api, [randomAccountMoonbeam.address]);
const glmrFees = balanceGlmrTokenInit - balanceGlmrTokenMiddle;
- console.log('[Unique -> Moonbeam] transaction fees on Moonbeam: %s GLMR', glmrFees);
+ console.log('[Unique -> Moonbeam] transaction fees on Moonbeam: %s GLMR', bigIntToDecimals(glmrFees));
expect(glmrFees == 0n).to.be.true;
const unqRandomAccountAsset = (
@@ -601,7 +609,7 @@
balanceForeignUnqTokenMiddle = BigInt(unqRandomAccountAsset['balance']);
const unqIncomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenInit;
- console.log('[Unique -> Moonbeam] income %s UNQ', unqIncomeTransfer);
+ console.log('[Unique -> Moonbeam] income %s UNQ', bigIntToDecimals(unqIncomeTransfer));
expect(unqIncomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
moonbeamOptions(),
@@ -647,7 +655,7 @@
[balanceGlmrTokenFinal] = await getBalance(api, [randomAccountMoonbeam.address]);
const glmrFees = balanceGlmrTokenMiddle - balanceGlmrTokenFinal;
- console.log('[Moonbeam -> Unique] transaction fees on Moonbeam: %s GLMR', glmrFees);
+ console.log('[Moonbeam -> Unique] transaction fees on Moonbeam: %s GLMR', bigIntToDecimals(glmrFees));
expect(glmrFees > 0).to.be.true;
const unqRandomAccountAsset = (
@@ -659,7 +667,7 @@
balanceForeignUnqTokenFinal = 0n;
const unqOutcomeTransfer = balanceForeignUnqTokenMiddle - balanceForeignUnqTokenFinal;
- console.log('[Unique -> Moonbeam] outcome %s UNQ', unqOutcomeTransfer);
+ console.log('[Unique -> Moonbeam] outcome %s UNQ', bigIntToDecimals(unqOutcomeTransfer));
expect(unqOutcomeTransfer == TRANSFER_AMOUNT).to.be.true;
},
moonbeamOptions(),
@@ -672,10 +680,10 @@
const actuallyDelivered = balanceUniqueTokenFinal - balanceUniqueTokenMiddle;
expect(actuallyDelivered > 0).to.be.true;
- console.log('[Moonbeam -> Unique] actually delivered %s UNQ', actuallyDelivered);
+ console.log('[Moonbeam -> Unique] actually delivered %s UNQ', bigIntToDecimals(actuallyDelivered));
const unqFees = TRANSFER_AMOUNT - actuallyDelivered;
- console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', unqFees);
+ console.log('[Moonbeam -> Unique] transaction fees on Unique: %s UNQ', bigIntToDecimals(unqFees));
expect(unqFees == 0n).to.be.true;
});
});