1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} 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 transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1104 const tx = api.tx.balances.transfer(target, amount);1105 const events = await submitTransactionAsync(source, tx);1106 const result = getGenericResult(events);1107 expect(result.success).to.be.true;1108}11091110export async function1111scheduleExpectSuccess(1112 operationTx: any,1113 sender: IKeyringPair,1114 blockSchedule: number,1115 scheduledId: string,1116 period = 1,1117 repetitions = 1,1118) {1119 await usingApi(async (api: ApiPromise) => {1120 const blockNumber: number | undefined = await getBlockNumber(api);1121 const expectedBlockNumber = blockNumber + blockSchedule;11221123 expect(blockNumber).to.be.greaterThan(0);1124 const scheduleTx = api.tx.scheduler.scheduleNamed( 1125 scheduledId,1126 expectedBlockNumber, 1127 repetitions > 1 ? [period, repetitions] : null, 1128 0, 1129 {Value: operationTx as any},1130 );11311132 const events = await submitTransactionAsync(sender, scheduleTx);1133 expect(getGenericResult(events).success).to.be.true;1134 });1135}11361137export async function1138scheduleExpectFailure(1139 operationTx: any,1140 sender: IKeyringPair,1141 blockSchedule: number,1142 scheduledId: string,1143 period = 1,1144 repetitions = 1,1145) {1146 await usingApi(async (api: ApiPromise) => {1147 const blockNumber: number | undefined = await getBlockNumber(api);1148 const expectedBlockNumber = blockNumber + blockSchedule;11491150 expect(blockNumber).to.be.greaterThan(0);1151 const scheduleTx = api.tx.scheduler.scheduleNamed( 1152 scheduledId,1153 expectedBlockNumber, 1154 repetitions <= 1 ? null : [period, repetitions], 1155 0, 1156 {Value: operationTx as any},1157 );11581159 1160 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1161 1162 });1163}11641165export async function1166scheduleTransferAndWaitExpectSuccess(1167 collectionId: number,1168 tokenId: number,1169 sender: IKeyringPair,1170 recipient: IKeyringPair,1171 value: number | bigint = 1,1172 blockSchedule: number,1173 scheduledId: string,1174) {1175 await usingApi(async (api: ApiPromise) => {1176 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11771178 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11791180 1181 await waitNewBlocks(blockSchedule + 1);11821183 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11841185 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1186 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1187 });1188}11891190export async function1191scheduleTransferExpectSuccess(1192 collectionId: number,1193 tokenId: number,1194 sender: IKeyringPair,1195 recipient: IKeyringPair,1196 value: number | bigint = 1,1197 blockSchedule: number,1198 scheduledId: string,1199) {1200 await usingApi(async (api: ApiPromise) => {1201 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12021203 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12041205 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1206 });1207}12081209export async function1210scheduleTransferFundsPeriodicExpectSuccess(1211 amount: bigint,1212 sender: IKeyringPair,1213 recipient: IKeyringPair,1214 blockSchedule: number,1215 scheduledId: string,1216 period: number,1217 repetitions: number,1218) {1219 await usingApi(async (api: ApiPromise) => {1220 const transferTx = api.tx.balances.transfer(recipient.address, amount);12211222 const balanceBefore = await getFreeBalance(recipient);1223 1224 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12251226 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1227 });1228}12291230export async function1231transfer(1232 api: ApiPromise,1233 collectionId: number,1234 tokenId: number,1235 sender: IKeyringPair,1236 recipient: IKeyringPair | CrossAccountId,1237 value: number | bigint,1238) : Promise<boolean> {1239 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1240 const events = await executeTransaction(api, sender, transferTx);1241 return getGenericResult(events).success;1242}12431244export async function1245transferExpectSuccess(1246 collectionId: number,1247 tokenId: number,1248 sender: IKeyringPair,1249 recipient: IKeyringPair | CrossAccountId,1250 value: number | bigint = 1,1251 type = 'NFT',1252) {1253 await usingApi(async (api: ApiPromise) => {1254 const from = normalizeAccountId(sender);1255 const to = normalizeAccountId(recipient);12561257 let balanceBefore = 0n;1258 if (type === 'Fungible' || type === 'ReFungible') {1259 balanceBefore = await getBalance(api, collectionId, to, tokenId);1260 }12611262 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1263 const events = await executeTransaction(api, sender, transferTx);1264 const result = getTransferResult(api, events);12651266 expect(result.collectionId).to.be.equal(collectionId);1267 expect(result.itemId).to.be.equal(tokenId);1268 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1269 expect(result.recipient).to.be.deep.equal(to);1270 expect(result.value).to.be.equal(BigInt(value));12711272 if (type === 'NFT') {1273 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1274 }1275 if (type === 'Fungible' || type === 'ReFungible') {1276 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1277 if (JSON.stringify(to) !== JSON.stringify(from)) {1278 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1279 } else {1280 expect(balanceAfter).to.be.equal(balanceBefore);1281 }1282 }1283 });1284}12851286export async function1287transferExpectFailure(1288 collectionId: number,1289 tokenId: number,1290 sender: IKeyringPair,1291 recipient: IKeyringPair | CrossAccountId,1292 value: number | bigint = 1,1293) {1294 await usingApi(async (api: ApiPromise) => {1295 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1296 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1297 const result = getGenericResult(events);1298 1299 1300 1301 expect(result.success).to.be.false;1302 1303 });1304}13051306export async function1307approveExpectFail(1308 collectionId: number,1309 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1310) {1311 await usingApi(async (api: ApiPromise) => {1312 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1313 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1314 const result = getCreateCollectionResult(events);1315 1316 expect(result.success).to.be.false;1317 });1318}13191320export async function getBalance(1321 api: ApiPromise,1322 collectionId: number,1323 owner: string | CrossAccountId | IKeyringPair,1324 token: number,1325): Promise<bigint> {1326 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1327}1328export async function getTokenOwner(1329 api: ApiPromise,1330 collectionId: number,1331 token: number,1332): Promise<CrossAccountId> {1333 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1334 if (owner == null) throw new Error('owner == null');1335 return normalizeAccountId(owner);1336}1337export async function getTopmostTokenOwner(1338 api: ApiPromise,1339 collectionId: number,1340 token: number,1341): Promise<CrossAccountId> {1342 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1343 if (owner == null) throw new Error('owner == null');1344 return normalizeAccountId(owner);1345}1346export async function getTokenChildren(1347 api: ApiPromise,1348 collectionId: number,1349 tokenId: number,1350): Promise<UpDataStructsTokenChild[]> {1351 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1352}1353export async function isTokenExists(1354 api: ApiPromise,1355 collectionId: number,1356 token: number,1357): Promise<boolean> {1358 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1359}1360export async function getLastTokenId(1361 api: ApiPromise,1362 collectionId: number,1363): Promise<number> {1364 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1365}1366export async function getAdminList(1367 api: ApiPromise,1368 collectionId: number,1369): Promise<string[]> {1370 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1371}1372export async function getTokenProperties(1373 api: ApiPromise,1374 collectionId: number,1375 tokenId: number,1376 propertyKeys: string[],1377): Promise<UpDataStructsProperty[]> {1378 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1379}13801381export async function createFungibleItemExpectSuccess(1382 sender: IKeyringPair,1383 collectionId: number,1384 data: CreateFungibleData,1385 owner: CrossAccountId | string = sender.address,1386) {1387 return await usingApi(async (api) => {1388 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13891390 const events = await submitTransactionAsync(sender, tx);1391 const result = getCreateItemResult(events);13921393 expect(result.success).to.be.true;1394 return result.itemId;1395 });1396}13971398export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1399 await usingApi(async (api) => {1400 const to = normalizeAccountId(owner);1401 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14021403 const events = await submitTransactionAsync(sender, tx);1404 expect(getGenericResult(events).success).to.be.true;1405 });1406}14071408export async function createMultipleItemsWithPropsExpectSuccess(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 const result = getCreateItemsResult(events);14151416 for (const res of result) {1417 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1418 }1419 });1420}14211422export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1423 await usingApi(async (api) => {1424 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14251426 const events = await submitTransactionAsync(sender, tx);1427 const result = getCreateItemsResult(events);14281429 for (const res of result) {1430 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1431 }1432 });1433}14341435export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1436 let newItemId = 0;1437 await usingApi(async (api) => {1438 const to = normalizeAccountId(owner);1439 const itemCountBefore = await getLastTokenId(api, collectionId);1440 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14411442 let tx;1443 if (createMode === 'Fungible') {1444 const createData = {fungible: {value: 10}};1445 tx = api.tx.unique.createItem(collectionId, to, createData as any);1446 } else if (createMode === 'ReFungible') {1447 const createData = {refungible: {pieces: 100}};1448 tx = api.tx.unique.createItem(collectionId, to, createData as any);1449 } else {1450 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1451 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1452 }14531454 const events = await submitTransactionAsync(sender, tx);1455 const result = getCreateItemResult(events);14561457 const itemCountAfter = await getLastTokenId(api, collectionId);1458 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14591460 if (createMode === 'NFT') {1461 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1462 }14631464 1465 1466 expect(result.success).to.be.true;1467 if (createMode === 'Fungible') {1468 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1469 } else {1470 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1471 }1472 expect(collectionId).to.be.equal(result.collectionId);1473 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1474 expect(to).to.be.deep.equal(result.recipient);1475 newItemId = result.itemId;1476 });1477 return newItemId;1478}14791480export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1481 await usingApi(async (api) => {14821483 let tx;1484 if (createMode === 'NFT') {1485 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1486 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1487 } else {1488 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1489 }149014911492 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1493 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1494 const result = getCreateItemResult(events);14951496 expect(result.success).to.be.false;1497 });1498}14991500export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1501 let newItemId = 0;1502 await usingApi(async (api) => {1503 const to = normalizeAccountId(owner);1504 const itemCountBefore = await getLastTokenId(api, collectionId);1505 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15061507 let tx;1508 if (createMode === 'Fungible') {1509 const createData = {fungible: {value: 10}};1510 tx = api.tx.unique.createItem(collectionId, to, createData as any);1511 } else if (createMode === 'ReFungible') {1512 const createData = {refungible: {pieces: 100}};1513 tx = api.tx.unique.createItem(collectionId, to, createData as any);1514 } else {1515 const createData = {nft: {}};1516 tx = api.tx.unique.createItem(collectionId, to, createData as any);1517 }15181519 const events = await executeTransaction(api, sender, tx);1520 const result = getCreateItemResult(events);15211522 const itemCountAfter = await getLastTokenId(api, collectionId);1523 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15241525 1526 1527 expect(result.success).to.be.true;1528 if (createMode === 'Fungible') {1529 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1530 } else {1531 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1532 }1533 expect(collectionId).to.be.equal(result.collectionId);1534 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1535 expect(to).to.be.deep.equal(result.recipient);1536 newItemId = result.itemId;1537 });1538 return newItemId;1539}15401541export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1542 const createData = {refungible: {pieces: amount}};1543 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15441545 const events = await submitTransactionAsync(sender, tx);1546 return getCreateItemResult(events);1547}15481549export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1550 await usingApi(async (api) => {1551 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15521553 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1554 const result = getCreateItemResult(events);15551556 expect(result.success).to.be.false;1557 });1558}15591560export async function setPublicAccessModeExpectSuccess(1561 sender: IKeyringPair, collectionId: number,1562 accessMode: 'Normal' | 'AllowList',1563) {1564 await usingApi(async (api) => {15651566 1567 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1568 const events = await submitTransactionAsync(sender, tx);1569 const result = getGenericResult(events);15701571 1572 const collection = await queryCollectionExpectSuccess(api, collectionId);15731574 1575 1576 expect(result.success).to.be.true;1577 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1578 });1579}15801581export async function setPublicAccessModeExpectFail(1582 sender: IKeyringPair, collectionId: number,1583 accessMode: 'Normal' | 'AllowList',1584) {1585 await usingApi(async (api) => {15861587 1588 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1589 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1590 const result = getGenericResult(events);15911592 1593 1594 expect(result.success).to.be.false;1595 });1596}15971598export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1599 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1600}16011602export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1603 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1604}16051606export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1607 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1608}16091610export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1611 await usingApi(async (api) => {16121613 1614 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1615 const events = await submitTransactionAsync(sender, tx);1616 const result = getGenericResult(events);1617 expect(result.success).to.be.true;16181619 1620 const collection = await queryCollectionExpectSuccess(api, collectionId);16211622 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1623 });1624}16251626export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1627 await setMintPermissionExpectSuccess(sender, collectionId, true);1628}16291630export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1631 await usingApi(async (api) => {1632 1633 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1634 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1635 const result = getCreateCollectionResult(events);1636 1637 expect(result.success).to.be.false;1638 });1639}16401641export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1642 await usingApi(async (api) => {1643 1644 const tx = api.tx.unique.setChainLimits(limits);1645 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1646 const result = getCreateCollectionResult(events);1647 1648 expect(result.success).to.be.false;1649 });1650}16511652export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1653 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1654}16551656export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1657 await usingApi(async (api) => {1658 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16591660 1661 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1662 const events = await submitTransactionAsync(sender, tx);1663 const result = getGenericResult(events);1664 expect(result.success).to.be.true;16651666 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1667 });1668}16691670export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1671 await usingApi(async (api) => {16721673 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16741675 1676 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1677 const events = await submitTransactionAsync(sender, tx);1678 const result = getGenericResult(events);1679 expect(result.success).to.be.true;16801681 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1682 });1683}16841685export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1686 await usingApi(async (api) => {16871688 1689 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1690 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1691 const result = getGenericResult(events);16921693 1694 1695 expect(result.success).to.be.false;1696 });1697}16981699export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1700 await usingApi(async (api) => {1701 1702 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1703 const events = await submitTransactionAsync(sender, tx);1704 const result = getGenericResult(events);17051706 1707 1708 expect(result.success).to.be.true;1709 });1710}17111712export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1713 await usingApi(async (api) => {1714 1715 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1716 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1717 const result = getGenericResult(events);17181719 1720 1721 expect(result.success).to.be.false;1722 });1723}17241725export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1726 : Promise<UpDataStructsRpcCollection | null> => {1727 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1728};17291730export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1731 1732 return (await api.rpc.unique.collectionStats()).created.toNumber();1733};17341735export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1736 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1737}17381739export async function waitNewBlocks(blocksCount = 1): Promise<void> {1740 await usingApi(async (api) => {1741 const promise = new Promise<void>(async (resolve) => {1742 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1743 if (blocksCount > 0) {1744 blocksCount--;1745 } else {1746 unsubscribe();1747 resolve();1748 }1749 });1750 });1751 return promise;1752 });1753}17541755export async function repartitionRFT(1756 api: ApiPromise,1757 collectionId: number,1758 sender: IKeyringPair,1759 tokenId: number,1760 amount: bigint,1761): Promise<boolean> {1762 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1763 const events = await submitTransactionAsync(sender, tx);1764 const result = getGenericResult(events);17651766 return result.success;1767}17681769export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1770 let i: any = it;1771 if (opts.only) i = i.only;1772 else if (opts.skip) i = i.skip;1773 i(name, async () => {1774 await usingApi(async (api, privateKeyWrapper) => {1775 await cb({api, privateKeyWrapper});1776 });1777 });1778}17791780itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1781itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});