1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};414243export enum Pallets {44 Inflation = 'inflation',45 RmrkCore = 'rmrkcore',46 RmrkEquip = 'rmrkequip',47 ReFungible = 'refungible',48 Fungible = 'fungible',49 NFT = 'nonfungible',50 Scheduler = 'scheduler',51}5253export async function isUnique(): Promise<boolean> {54 return usingApi(async api => {55 const chain = await api.rpc.system.chain();5657 return chain.eq('UNIQUE');58 });59}6061export async function isQuartz(): Promise<boolean> {62 return usingApi(async api => {63 const chain = await api.rpc.system.chain();64 65 return chain.eq('QUARTZ');66 });67}6869let modulesNames: any;70export function getModuleNames(api: ApiPromise): string[] {71 if (typeof modulesNames === 'undefined') 72 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());73 return modulesNames;74}7576export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {77 return await usingApi(async api => {78 const pallets = getModuleNames(api);7980 return requiredPallets.filter(p => !pallets.includes(p));81 });82}8384export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {85 return (await missingRequiredPallets(requiredPallets)).length == 0;86}8788export async function requirePallets(mocha: Context, requiredPallets: string[]) {89 const missingPallets = await missingRequiredPallets(requiredPallets);9091 if (missingPallets.length > 0) {92 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;93 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;94 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9596 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798 mocha.skip();99 }100}101102export function bigIntToSub(api: ApiPromise, number: bigint) {103 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();104}105106export function 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 138 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 214 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 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 456 const collectionCountBefore = await getCreatedCollectionCount(api);457458 459 const alicePrivateKey = privateKeyWrapper('//Alice');460461 const result = await createCollection(api, alicePrivateKey, params);462463 464 const collectionCountAfter = await getCreatedCollectionCount(api);465466 467 const collection = await queryCollectionExpectSuccess(api, result.collectionId);468469 470 471 expect(result.success).to.be.true;472 expect(result.collectionId).to.be.equal(collectionCountAfter);473 474 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 493 const collectionCountBefore = await getCreatedCollectionCount(api);494495 496 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 512 const collectionCountAfter = await getCreatedCollectionCount(api);513514 515 const collection = await queryCollectionExpectSuccess(api, result.collectionId);516517 518 519 expect(result.success).to.be.true;520 expect(result.collectionId).to.be.equal(collectionCountAfter);521 522 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 541 const collectionCountBefore = await getCreatedCollectionCount(api);542543 544 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 560 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 580 const collectionCountBefore = await getCreatedCollectionCount(api);581582 583 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 588 const collectionCountAfter = await getCreatedCollectionCount(api);589590 591 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 633 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 642 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 649 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 687 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 693 const collection = await queryCollectionExpectSuccess(api, collectionId);694695 696 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 707 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 713 const collection = await queryCollectionExpectSuccess(api, collectionId);714715 716 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 725 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 735 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 745 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 754 const tx = api.tx.unique.confirmSponsorship(collectionId);755 const events = await submitTransactionAsync(sender, tx);756 const result = getGenericResult(events);757758 759 const collection = await queryCollectionExpectSuccess(api, collectionId);760761 762 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 774 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 926 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 942 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 1058 expect(result.success).to.be.false;1059 });1060}106110621063export 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( 1135 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( 1162 scheduledId,1163 expectedBlockNumber, 1164 repetitions <= 1 ? null : [period, repetitions], 1165 0, 1166 {Value: operationTx as any},1167 );11681169 1170 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1171 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 1191 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 1309 1310 1311 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 1326 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 1475 1476 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 1536 1537 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 1577 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1578 const events = await submitTransactionAsync(sender, tx);1579 const result = getGenericResult(events);15801581 1582 const collection = await queryCollectionExpectSuccess(api, collectionId);15831584 1585 1586 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 1598 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 1603 1604 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 1624 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 1630 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 1643 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 1647 expect(result.success).to.be.false;1648 });1649}16501651export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1652 await usingApi(async (api) => {1653 1654 const tx = api.tx.unique.setChainLimits(limits);1655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1656 const result = getCreateCollectionResult(events);1657 1658 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 1671 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 1686 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 1699 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 1704 1705 expect(result.success).to.be.false;1706 });1707}17081709export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1710 await usingApi(async (api) => {1711 1712 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1713 const events = await submitTransactionAsync(sender, tx);1714 const result = getGenericResult(events);17151716 1717 1718 expect(result.success).to.be.true;1719 });1720}17211722export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1723 await usingApi(async (api) => {1724 1725 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1726 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1727 const result = getGenericResult(events);17281729 1730 1731 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 1742 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}