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 normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {103 if (typeof input === 'string') {104 if (input.length >= 47) {105 return {Substrate: input};106 } else if (input.length === 42 && input.startsWith('0x')) {107 return {Ethereum: input.toLowerCase()};108 } else if (input.length === 40 && !input.startsWith('0x')) {109 return {Ethereum: '0x' + input.toLowerCase()};110 } else {111 throw new Error(`Unknown address format: "${input}"`);112 }113 }114 if ('address' in input) {115 return {Substrate: input.address};116 }117 if ('Ethereum' in input) {118 return {119 Ethereum: input.Ethereum.toLowerCase(),120 };121 } else if ('ethereum' in input) {122 return {123 Ethereum: (input as any).ethereum.toLowerCase(),124 };125 } else if ('Substrate' in input) {126 return input;127 } else if ('substrate' in input) {128 return {129 Substrate: (input as any).substrate,130 };131 }132133 134 return {Substrate: input.toString()};135}136export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {137 input = normalizeAccountId(input);138 if ('Substrate' in input) {139 return input.Substrate;140 } else {141 return evmToAddress(input.Ethereum);142 }143}144145export const U128_MAX = (1n << 128n) - 1n;146147const MICROUNIQUE = 1_000_000_000_000n;148const MILLIUNIQUE = 1_000n * MICROUNIQUE;149const CENTIUNIQUE = 10n * MILLIUNIQUE;150export const UNIQUE = 100n * CENTIUNIQUE;151152interface GenericResult<T> {153 success: boolean;154 data: T | null;155}156157interface CreateCollectionResult {158 success: boolean;159 collectionId: number;160}161162interface CreateItemResult {163 success: boolean;164 collectionId: number;165 itemId: number;166 recipient?: CrossAccountId;167 amount?: number;168}169170interface DestroyItemResult {171 success: boolean;172 collectionId: number;173 itemId: number;174 owner: CrossAccountId;175 amount: number;176}177178interface TransferResult {179 collectionId: number;180 itemId: number;181 sender?: CrossAccountId;182 recipient?: CrossAccountId;183 value: bigint;184}185186interface IReFungibleOwner {187 fraction: BN;188 owner: number[];189}190191interface IGetMessage {192 checkMsgUnqMethod: string;193 checkMsgTrsMethod: string;194 checkMsgSysMethod: string;195}196197export interface IFungibleTokenDataType {198 value: number;199}200201export interface IChainLimits {202 collectionNumbersLimit: number;203 accountTokenOwnershipLimit: number;204 collectionsAdminsLimit: number;205 customDataLimit: number;206 nftSponsorTransferTimeout: number;207 fungibleSponsorTransferTimeout: number;208 refungibleSponsorTransferTimeout: number;209 210 211}212213export interface IReFungibleTokenDataType {214 owner: IReFungibleOwner[];215}216217export function uniqueEventMessage(events: EventRecord[]): IGetMessage {218 let checkMsgUnqMethod = '';219 let checkMsgTrsMethod = '';220 let checkMsgSysMethod = '';221 events.forEach(({event: {method, section}}) => {222 if (section === 'common') {223 checkMsgUnqMethod = method;224 } else if (section === 'treasury') {225 checkMsgTrsMethod = method;226 } else if (section === 'system') {227 checkMsgSysMethod = method;228 } else { return null; }229 });230 const result: IGetMessage = {231 checkMsgUnqMethod,232 checkMsgTrsMethod,233 checkMsgSysMethod,234 };235 return result;236}237238export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {239 const event = events.find(r => check(r.event));240 if (!event) return;241 return event.event as T;242}243244export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;245export function getGenericResult<T>(246 events: EventRecord[],247 expectSection: string,248 expectMethod: string,249 extractAction: (data: GenericEventData) => T250): GenericResult<T>;251252export function getGenericResult<T>(253 events: EventRecord[],254 expectSection?: string,255 expectMethod?: string,256 extractAction?: (data: GenericEventData) => T,257): GenericResult<T> {258 let success = false;259 let successData = null;260261 events.forEach(({event: {data, method, section}}) => {262 263 if (method === 'ExtrinsicSuccess') {264 success = true;265 } else if ((expectSection == section) && (expectMethod == method)) {266 successData = extractAction!(data as any);267 }268 });269270 const result: GenericResult<T> = {271 success,272 data: successData,273 };274 return result;275}276277export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {278 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));279 const result: CreateCollectionResult = {280 success: genericResult.success,281 collectionId: genericResult.data ?? 0,282 };283 return result;284}285286export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {287 const results: CreateItemResult[] = [];288 289 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {290 const collectionId = parseInt(data[0].toString(), 10);291 const itemId = parseInt(data[1].toString(), 10);292 const recipient = normalizeAccountId(data[2].toJSON() as any);293 const amount = parseInt(data[3].toString(), 10);294295 const itemRes: CreateItemResult = {296 success: true,297 collectionId,298 itemId,299 recipient,300 amount,301 };302303 results.push(itemRes);304 return results;305 });306307 if (!genericResult.success) return [];308 return results;309}310311export function getCreateItemResult(events: EventRecord[]): CreateItemResult {312 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));313 314 if (genericResult.data == null) 315 return {316 success: genericResult.success,317 collectionId: 0,318 itemId: 0,319 amount: 0,320 };321 else 322 return {323 success: genericResult.success,324 collectionId: genericResult.data[0] as number,325 itemId: genericResult.data[1] as number,326 recipient: normalizeAccountId(genericResult.data![2] as any),327 amount: genericResult.data[3] as number,328 };329}330331export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {332 const results: DestroyItemResult[] = [];333 334 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {335 const collectionId = parseInt(data[0].toString(), 10);336 const itemId = parseInt(data[1].toString(), 10);337 const owner = normalizeAccountId(data[2].toJSON() as any);338 const amount = parseInt(data[3].toString(), 10);339340 const itemRes: DestroyItemResult = {341 success: true,342 collectionId,343 itemId,344 owner,345 amount,346 };347348 results.push(itemRes);349 return results;350 });351352 if (!genericResult.success) return [];353 return results;354}355356export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {357 for (const {event} of events) {358 if (api.events.common.Transfer.is(event)) {359 const [collection, token, sender, recipient, value] = event.data;360 return {361 collectionId: collection.toNumber(),362 itemId: token.toNumber(),363 sender: normalizeAccountId(sender.toJSON() as any),364 recipient: normalizeAccountId(recipient.toJSON() as any),365 value: value.toBigInt(),366 };367 }368 }369 throw new Error('no transfer event');370}371372interface Nft {373 type: 'NFT';374}375376interface Fungible {377 type: 'Fungible';378 decimalPoints: number;379}380381interface ReFungible {382 type: 'ReFungible';383}384385export type CollectionMode = Nft | Fungible | ReFungible;386387export type Property = {388 key: any,389 value: any,390};391392type Permission = {393 mutable: boolean;394 collectionAdmin: boolean;395 tokenOwner: boolean;396}397398type PropertyPermission = {399 key: any;400 permission: Permission;401}402403export type CreateCollectionParams = {404 mode: CollectionMode,405 name: string,406 description: string,407 tokenPrefix: string,408 properties?: Array<Property>,409 propPerm?: Array<PropertyPermission>410};411412const defaultCreateCollectionParams: CreateCollectionParams = {413 description: 'description',414 mode: {type: 'NFT'},415 name: 'name',416 tokenPrefix: 'prefix',417};418419export async function420createCollection(421 api: ApiPromise,422 sender: IKeyringPair,423 params: Partial<CreateCollectionParams> = {},424): Promise<CreateCollectionResult> {425 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};426427 let modeprm = {};428 if (mode.type === 'NFT') {429 modeprm = {nft: null};430 } else if (mode.type === 'Fungible') {431 modeprm = {fungible: mode.decimalPoints};432 } else if (mode.type === 'ReFungible') {433 modeprm = {refungible: null};434 }435436 const tx = api.tx.unique.createCollectionEx({437 name: strToUTF16(name),438 description: strToUTF16(description),439 tokenPrefix: strToUTF16(tokenPrefix),440 mode: modeprm as any,441 });442 const events = await executeTransaction(api, sender, tx);443 return getCreateCollectionResult(events);444}445446export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {447 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};448449 let collectionId = 0;450 await usingApi(async (api, privateKeyWrapper) => {451 452 const collectionCountBefore = await getCreatedCollectionCount(api);453454 455 const alicePrivateKey = privateKeyWrapper('//Alice');456457 const result = await createCollection(api, alicePrivateKey, params);458459 460 const collectionCountAfter = await getCreatedCollectionCount(api);461462 463 const collection = await queryCollectionExpectSuccess(api, result.collectionId);464465 466 467 expect(result.success).to.be.true;468 expect(result.collectionId).to.be.equal(collectionCountAfter);469 470 expect(collection).to.be.not.null;471 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');472 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));473 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);474 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);475 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);476477 collectionId = result.collectionId;478 });479480 return collectionId;481}482483export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {484 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};485486 let collectionId = 0;487 await usingApi(async (api, privateKeyWrapper) => {488 489 const collectionCountBefore = await getCreatedCollectionCount(api);490491 492 const alicePrivateKey = privateKeyWrapper('//Alice');493494 let modeprm = {};495 if (mode.type === 'NFT') {496 modeprm = {nft: null};497 } else if (mode.type === 'Fungible') {498 modeprm = {fungible: mode.decimalPoints};499 } else if (mode.type === 'ReFungible') {500 modeprm = {refungible: null};501 }502503 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});504 const events = await submitTransactionAsync(alicePrivateKey, tx);505 const result = getCreateCollectionResult(events);506507 508 const collectionCountAfter = await getCreatedCollectionCount(api);509510 511 const collection = await queryCollectionExpectSuccess(api, result.collectionId);512513 514 515 expect(result.success).to.be.true;516 expect(result.collectionId).to.be.equal(collectionCountAfter);517 518 expect(collection).to.be.not.null;519 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');520 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));521 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);522 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);523 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);524525526 collectionId = result.collectionId;527 });528529 return collectionId;530}531532export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {533 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};534535 await usingApi(async (api, privateKeyWrapper) => {536 537 const collectionCountBefore = await getCreatedCollectionCount(api);538539 540 const alicePrivateKey = privateKeyWrapper('//Alice');541542 let modeprm = {};543 if (mode.type === 'NFT') {544 modeprm = {nft: null};545 } else if (mode.type === 'Fungible') {546 modeprm = {fungible: mode.decimalPoints};547 } else if (mode.type === 'ReFungible') {548 modeprm = {refungible: null};549 }550551 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});552 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;553554555 556 const collectionCountAfter = await getCreatedCollectionCount(api);557558 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');559 });560}561562export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {563 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};564565 let modeprm = {};566 if (mode.type === 'NFT') {567 modeprm = {nft: null};568 } else if (mode.type === 'Fungible') {569 modeprm = {fungible: mode.decimalPoints};570 } else if (mode.type === 'ReFungible') {571 modeprm = {refungible: null};572 }573574 await usingApi(async (api, privateKeyWrapper) => {575 576 const collectionCountBefore = await getCreatedCollectionCount(api);577578 579 const alicePrivateKey = privateKeyWrapper('//Alice');580 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});581 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;582583 584 const collectionCountAfter = await getCreatedCollectionCount(api);585586 587 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');588 });589}590591export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {592 let bal = 0n;593 let unused;594 do {595 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;596 unused = privateKeyWrapper(`//${randomSeed}`);597 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();598 } while (bal !== 0n);599 return unused;600}601602export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {603 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();604}605606export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {607 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));608}609610export async function findNotExistingCollection(api: ApiPromise): Promise<number> {611 const totalNumber = await getCreatedCollectionCount(api);612 const newCollection: number = totalNumber + 1;613 return newCollection;614}615616function getDestroyResult(events: EventRecord[]): boolean {617 let success = false;618 events.forEach(({event: {method}}) => {619 if (method == 'ExtrinsicSuccess') {620 success = true;621 }622 });623 return success;624}625626export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {627 await usingApi(async (api, privateKeyWrapper) => {628 629 const alicePrivateKey = privateKeyWrapper(senderSeed);630 const tx = api.tx.unique.destroyCollection(collectionId);631 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;632 });633}634635export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {636 await usingApi(async (api, privateKeyWrapper) => {637 638 const alicePrivateKey = privateKeyWrapper(senderSeed);639 const tx = api.tx.unique.destroyCollection(collectionId);640 const events = await submitTransactionAsync(alicePrivateKey, tx);641 const result = getDestroyResult(events);642 expect(result).to.be.true;643644 645 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;646 });647}648649export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {650 await usingApi(async (api) => {651 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);652 const events = await submitTransactionAsync(sender, tx);653 const result = getGenericResult(events);654655 expect(result.success).to.be.true;656 });657}658659export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {660 await usingApi(async(api) => {661 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);662 const events = await submitTransactionAsync(sender, tx);663 const result = getGenericResult(events);664665 expect(result.success).to.be.true;666 });667};668669export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {670 await usingApi(async (api) => {671 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);672 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;673 const result = getGenericResult(events);674675 expect(result.success).to.be.false;676 });677}678679export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {680 await usingApi(async (api, privateKeyWrapper) => {681682 683 const senderPrivateKey = privateKeyWrapper(sender);684 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);685 const events = await submitTransactionAsync(senderPrivateKey, tx);686 const result = getGenericResult(events);687688 689 const collection = await queryCollectionExpectSuccess(api, collectionId);690691 692 expect(result.success).to.be.true;693 expect(collection.sponsorship.toJSON()).to.deep.equal({694 unconfirmed: sponsor,695 });696 });697}698699export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {700 await usingApi(async (api, privateKeyWrapper) => {701702 703 const alicePrivateKey = privateKeyWrapper(sender);704 const tx = api.tx.unique.removeCollectionSponsor(collectionId);705 const events = await submitTransactionAsync(alicePrivateKey, tx);706 const result = getGenericResult(events);707708 709 const collection = await queryCollectionExpectSuccess(api, collectionId);710711 712 expect(result.success).to.be.true;713 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});714 });715}716717export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {718 await usingApi(async (api, privateKeyWrapper) => {719720 721 const alicePrivateKey = privateKeyWrapper(senderSeed);722 const tx = api.tx.unique.removeCollectionSponsor(collectionId);723 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;724 });725}726727export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {728 await usingApi(async (api, privateKeyWrapper) => {729730 731 const alicePrivateKey = privateKeyWrapper(senderSeed);732 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);733 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;734 });735}736737export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {738 await usingApi(async (api, privateKeyWrapper) => {739740 741 const sender = privateKeyWrapper(senderSeed);742 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);743 });744}745746export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {747 await usingApi(async (api, privateKeyWrapper) => {748749 750 const tx = api.tx.unique.confirmSponsorship(collectionId);751 const events = await submitTransactionAsync(sender, tx);752 const result = getGenericResult(events);753754 755 const collection = await queryCollectionExpectSuccess(api, collectionId);756757 758 expect(result.success).to.be.true;759 expect(collection.sponsorship.toJSON()).to.be.deep.equal({760 confirmed: sender.address,761 });762 });763}764765766export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {767 await usingApi(async (api, privateKeyWrapper) => {768769 770 const sender = privateKeyWrapper(senderSeed);771 const tx = api.tx.unique.confirmSponsorship(collectionId);772 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773 });774}775776export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {777 await usingApi(async (api) => {778 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);779 const events = await submitTransactionAsync(sender, tx);780 const result = getGenericResult(events);781782 expect(result.success).to.be.true;783 });784}785786export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {787 await usingApi(async (api) => {788 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);789 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790 const result = getGenericResult(events);791792 expect(result.success).to.be.false;793 });794}795796export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {797798 await usingApi(async (api) => {799800 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);801 const events = await submitTransactionAsync(sender, tx);802 const result = getGenericResult(events);803804 expect(result.success).to.be.true;805 });806}807808export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {809810 await usingApi(async (api) => {811812 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);813 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;814 const result = getGenericResult(events);815816 expect(result.success).to.be.false;817 });818}819820export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {821 await usingApi(async (api) => {822 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);823 const events = await submitTransactionAsync(sender, tx);824 const result = getGenericResult(events);825826 expect(result.success).to.be.true;827 });828}829830export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {831 await usingApi(async (api) => {832 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);833 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;834 const result = getGenericResult(events);835836 expect(result.success).to.be.false;837 });838}839840export async function getNextSponsored(841 api: ApiPromise,842 collectionId: number,843 account: string | CrossAccountId,844 tokenId: number,845): Promise<number> {846 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));847}848849export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {850 await usingApi(async (api) => {851 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);852 const events = await submitTransactionAsync(sender, tx);853 const result = getGenericResult(events);854855 expect(result.success).to.be.true;856 });857}858859export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {860 let allowlisted = false;861 await usingApi(async (api) => {862 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;863 });864 return allowlisted;865}866867export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {868 await usingApi(async (api) => {869 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());870 const events = await submitTransactionAsync(sender, tx);871 const result = getGenericResult(events);872873 expect(result.success).to.be.true;874 });875}876877export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {878 await usingApi(async (api) => {879 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());880 const events = await submitTransactionAsync(sender, tx);881 const result = getGenericResult(events);882883 expect(result.success).to.be.true;884 });885}886887export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {888 await usingApi(async (api) => {889 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());890 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;891 const result = getGenericResult(events);892893 expect(result.success).to.be.false;894 });895}896897export interface CreateFungibleData {898 readonly Value: bigint;899}900901export interface CreateReFungibleData { }902export interface CreateNftData { }903904export type CreateItemData = {905 NFT: CreateNftData;906} | {907 Fungible: CreateFungibleData;908} | {909 ReFungible: CreateReFungibleData;910};911912export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {913 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);914 const events = await submitTransactionAsync(sender, tx);915 return getGenericResult(events).success;916}917918export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {919 await usingApi(async (api) => {920 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);921 922 expect(balanceBefore >= BigInt(value)).to.be.true;923924 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;925926 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);928 });929}930931export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {932 await usingApi(async (api) => {933 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);934935 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;936 const result = getCreateCollectionResult(events);937 938 expect(result.success).to.be.false;939 });940}941942export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {943 await usingApi(async (api) => {944 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);945 const events = await submitTransactionAsync(sender, tx);946 return getGenericResult(events).success;947 });948}949950export async function951approve(952 api: ApiPromise,953 collectionId: number,954 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,955) {956 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);957 const events = await submitTransactionAsync(owner, approveUniqueTx);958 return getGenericResult(events).success;959}960961export async function962approveExpectSuccess(963 collectionId: number,964 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,965) {966 await usingApi(async (api: ApiPromise) => {967 const result = await approve(api, collectionId, tokenId, owner, approved, amount);968 expect(result).to.be.true;969970 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));971 });972}973974export async function adminApproveFromExpectSuccess(975 collectionId: number,976 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,977) {978 await usingApi(async (api: ApiPromise) => {979 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);980 const events = await submitTransactionAsync(admin, approveUniqueTx);981 const result = getGenericResult(events);982 expect(result.success).to.be.true;983984 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));985 });986}987988export async function989transferFrom(990 api: ApiPromise,991 collectionId: number,992 tokenId: number,993 accountApproved: IKeyringPair,994 accountFrom: IKeyringPair | CrossAccountId,995 accountTo: IKeyringPair | CrossAccountId,996 value: number | bigint,997) {998 const from = normalizeAccountId(accountFrom);999 const to = normalizeAccountId(accountTo);1000 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1001 const events = await submitTransactionAsync(accountApproved, transferFromTx);1002 return getGenericResult(events).success;1003}10041005export async function1006transferFromExpectSuccess(1007 collectionId: number,1008 tokenId: number,1009 accountApproved: IKeyringPair,1010 accountFrom: IKeyringPair | CrossAccountId,1011 accountTo: IKeyringPair | CrossAccountId,1012 value: number | bigint = 1,1013 type = 'NFT',1014) {1015 await usingApi(async (api: ApiPromise) => {1016 const from = normalizeAccountId(accountFrom);1017 const to = normalizeAccountId(accountTo);1018 let balanceBefore = 0n;1019 if (type === 'Fungible' || type === 'ReFungible') {1020 balanceBefore = await getBalance(api, collectionId, to, tokenId);1021 }1022 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1023 if (type === 'NFT') {1024 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1025 }1026 if (type === 'Fungible') {1027 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1028 if (JSON.stringify(to) !== JSON.stringify(from)) {1029 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1030 } else {1031 expect(balanceAfter).to.be.equal(balanceBefore);1032 }1033 }1034 if (type === 'ReFungible') {1035 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1036 }1037 });1038}10391040export async function1041transferFromExpectFail(1042 collectionId: number,1043 tokenId: number,1044 accountApproved: IKeyringPair,1045 accountFrom: IKeyringPair,1046 accountTo: IKeyringPair,1047 value: number | bigint = 1,1048) {1049 await usingApi(async (api: ApiPromise) => {1050 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1051 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1052 const result = getCreateCollectionResult(events);1053 1054 expect(result.success).to.be.false;1055 });1056}105710581059export async function getBlockNumber(api: ApiPromise): Promise<number> {1060 return new Promise<number>(async (resolve) => {1061 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1062 unsubscribe();1063 resolve(head.number.toNumber());1064 });1065 });1066}10671068export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1069 await usingApi(async (api) => {1070 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1071 const events = await submitTransactionAsync(sender, changeAdminTx);1072 const result = getCreateCollectionResult(events);1073 expect(result.success).to.be.true;1074 });1075}10761077export async function adminApproveFromExpectFail(1078 collectionId: number,1079 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1080) {1081 await usingApi(async (api: ApiPromise) => {1082 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1083 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1084 const result = getGenericResult(events);1085 expect(result.success).to.be.false;1086 });1087}10881089export async function1090getFreeBalance(account: IKeyringPair): Promise<bigint> {1091 let balance = 0n;1092 await usingApi(async (api) => {1093 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1094 });10951096 return balance;1097}10981099export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1100 return usingApi(async api => {1101 const siblingPrefix = '0x7369626c';1102 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1103 const suffix = '000000000000000000000000000000000000000000000000';11041105 return siblingPrefix + encodedParaId + suffix;1106 });1107}11081109export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1110 const tx = api.tx.balances.transfer(target, amount);1111 const events = await submitTransactionAsync(source, tx);1112 const result = getGenericResult(events);1113 expect(result.success).to.be.true;1114}11151116export async function1117scheduleExpectSuccess(1118 operationTx: any,1119 sender: IKeyringPair,1120 blockSchedule: number,1121 scheduledId: string,1122 period = 1,1123 repetitions = 1,1124) {1125 await usingApi(async (api: ApiPromise) => {1126 const blockNumber: number | undefined = await getBlockNumber(api);1127 const expectedBlockNumber = blockNumber + blockSchedule;11281129 expect(blockNumber).to.be.greaterThan(0);1130 const scheduleTx = api.tx.scheduler.scheduleNamed( 1131 scheduledId,1132 expectedBlockNumber, 1133 repetitions > 1 ? [period, repetitions] : null, 1134 0, 1135 {Value: operationTx as any},1136 );11371138 const events = await submitTransactionAsync(sender, scheduleTx);1139 expect(getGenericResult(events).success).to.be.true;1140 });1141}11421143export async function1144scheduleExpectFailure(1145 operationTx: any,1146 sender: IKeyringPair,1147 blockSchedule: number,1148 scheduledId: string,1149 period = 1,1150 repetitions = 1,1151) {1152 await usingApi(async (api: ApiPromise) => {1153 const blockNumber: number | undefined = await getBlockNumber(api);1154 const expectedBlockNumber = blockNumber + blockSchedule;11551156 expect(blockNumber).to.be.greaterThan(0);1157 const scheduleTx = api.tx.scheduler.scheduleNamed( 1158 scheduledId,1159 expectedBlockNumber, 1160 repetitions <= 1 ? null : [period, repetitions], 1161 0, 1162 {Value: operationTx as any},1163 );11641165 1166 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1167 1168 });1169}11701171export async function1172scheduleTransferAndWaitExpectSuccess(1173 collectionId: number,1174 tokenId: number,1175 sender: IKeyringPair,1176 recipient: IKeyringPair,1177 value: number | bigint = 1,1178 blockSchedule: number,1179 scheduledId: string,1180) {1181 await usingApi(async (api: ApiPromise) => {1182 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11831184 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11851186 1187 await waitNewBlocks(blockSchedule + 1);11881189 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11901191 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1192 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1193 });1194}11951196export async function1197scheduleTransferExpectSuccess(1198 collectionId: number,1199 tokenId: number,1200 sender: IKeyringPair,1201 recipient: IKeyringPair,1202 value: number | bigint = 1,1203 blockSchedule: number,1204 scheduledId: string,1205) {1206 await usingApi(async (api: ApiPromise) => {1207 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12081209 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12101211 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1212 });1213}12141215export async function1216scheduleTransferFundsPeriodicExpectSuccess(1217 amount: bigint,1218 sender: IKeyringPair,1219 recipient: IKeyringPair,1220 blockSchedule: number,1221 scheduledId: string,1222 period: number,1223 repetitions: number,1224) {1225 await usingApi(async (api: ApiPromise) => {1226 const transferTx = api.tx.balances.transfer(recipient.address, amount);12271228 const balanceBefore = await getFreeBalance(recipient);1229 1230 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12311232 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1233 });1234}12351236export async function1237transfer(1238 api: ApiPromise,1239 collectionId: number,1240 tokenId: number,1241 sender: IKeyringPair,1242 recipient: IKeyringPair | CrossAccountId,1243 value: number | bigint,1244) : Promise<boolean> {1245 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1246 const events = await executeTransaction(api, sender, transferTx);1247 return getGenericResult(events).success;1248}12491250export async function1251transferExpectSuccess(1252 collectionId: number,1253 tokenId: number,1254 sender: IKeyringPair,1255 recipient: IKeyringPair | CrossAccountId,1256 value: number | bigint = 1,1257 type = 'NFT',1258) {1259 await usingApi(async (api: ApiPromise) => {1260 const from = normalizeAccountId(sender);1261 const to = normalizeAccountId(recipient);12621263 let balanceBefore = 0n;1264 if (type === 'Fungible' || type === 'ReFungible') {1265 balanceBefore = await getBalance(api, collectionId, to, tokenId);1266 }12671268 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1269 const events = await executeTransaction(api, sender, transferTx);1270 const result = getTransferResult(api, events);12711272 expect(result.collectionId).to.be.equal(collectionId);1273 expect(result.itemId).to.be.equal(tokenId);1274 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1275 expect(result.recipient).to.be.deep.equal(to);1276 expect(result.value).to.be.equal(BigInt(value));12771278 if (type === 'NFT') {1279 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1280 }1281 if (type === 'Fungible' || type === 'ReFungible') {1282 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1283 if (JSON.stringify(to) !== JSON.stringify(from)) {1284 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1285 } else {1286 expect(balanceAfter).to.be.equal(balanceBefore);1287 }1288 }1289 });1290}12911292export async function1293transferExpectFailure(1294 collectionId: number,1295 tokenId: number,1296 sender: IKeyringPair,1297 recipient: IKeyringPair | CrossAccountId,1298 value: number | bigint = 1,1299) {1300 await usingApi(async (api: ApiPromise) => {1301 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1302 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1303 const result = getGenericResult(events);1304 1305 1306 1307 expect(result.success).to.be.false;1308 1309 });1310}13111312export async function1313approveExpectFail(1314 collectionId: number,1315 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1316) {1317 await usingApi(async (api: ApiPromise) => {1318 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1319 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1320 const result = getCreateCollectionResult(events);1321 1322 expect(result.success).to.be.false;1323 });1324}13251326export async function getBalance(1327 api: ApiPromise,1328 collectionId: number,1329 owner: string | CrossAccountId | IKeyringPair,1330 token: number,1331): Promise<bigint> {1332 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1333}1334export async function getTokenOwner(1335 api: ApiPromise,1336 collectionId: number,1337 token: number,1338): Promise<CrossAccountId> {1339 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1340 if (owner == null) throw new Error('owner == null');1341 return normalizeAccountId(owner);1342}1343export async function getTopmostTokenOwner(1344 api: ApiPromise,1345 collectionId: number,1346 token: number,1347): Promise<CrossAccountId> {1348 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1349 if (owner == null) throw new Error('owner == null');1350 return normalizeAccountId(owner);1351}1352export async function getTokenChildren(1353 api: ApiPromise,1354 collectionId: number,1355 tokenId: number,1356): Promise<UpDataStructsTokenChild[]> {1357 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1358}1359export async function isTokenExists(1360 api: ApiPromise,1361 collectionId: number,1362 token: number,1363): Promise<boolean> {1364 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1365}1366export async function getLastTokenId(1367 api: ApiPromise,1368 collectionId: number,1369): Promise<number> {1370 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1371}1372export async function getAdminList(1373 api: ApiPromise,1374 collectionId: number,1375): Promise<string[]> {1376 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1377}1378export async function getTokenProperties(1379 api: ApiPromise,1380 collectionId: number,1381 tokenId: number,1382 propertyKeys: string[],1383): Promise<UpDataStructsProperty[]> {1384 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1385}13861387export async function createFungibleItemExpectSuccess(1388 sender: IKeyringPair,1389 collectionId: number,1390 data: CreateFungibleData,1391 owner: CrossAccountId | string = sender.address,1392) {1393 return await usingApi(async (api) => {1394 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13951396 const events = await submitTransactionAsync(sender, tx);1397 const result = getCreateItemResult(events);13981399 expect(result.success).to.be.true;1400 return result.itemId;1401 });1402}14031404export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1405 await usingApi(async (api) => {1406 const to = normalizeAccountId(owner);1407 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14081409 const events = await submitTransactionAsync(sender, tx);1410 expect(getGenericResult(events).success).to.be.true;1411 });1412}14131414export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1415 await usingApi(async (api) => {1416 const to = normalizeAccountId(owner);1417 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14181419 const events = await submitTransactionAsync(sender, tx);1420 const result = getCreateItemsResult(events);14211422 for (const res of result) {1423 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1424 }1425 });1426}14271428export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1429 await usingApi(async (api) => {1430 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14311432 const events = await submitTransactionAsync(sender, tx);1433 const result = getCreateItemsResult(events);14341435 for (const res of result) {1436 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1437 }1438 });1439}14401441export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1442 let newItemId = 0;1443 await usingApi(async (api) => {1444 const to = normalizeAccountId(owner);1445 const itemCountBefore = await getLastTokenId(api, collectionId);1446 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14471448 let tx;1449 if (createMode === 'Fungible') {1450 const createData = {fungible: {value: 10}};1451 tx = api.tx.unique.createItem(collectionId, to, createData as any);1452 } else if (createMode === 'ReFungible') {1453 const createData = {refungible: {pieces: 100}};1454 tx = api.tx.unique.createItem(collectionId, to, createData as any);1455 } else {1456 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1457 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1458 }14591460 const events = await submitTransactionAsync(sender, tx);1461 const result = getCreateItemResult(events);14621463 const itemCountAfter = await getLastTokenId(api, collectionId);1464 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14651466 if (createMode === 'NFT') {1467 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1468 }14691470 1471 1472 expect(result.success).to.be.true;1473 if (createMode === 'Fungible') {1474 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1475 } else {1476 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1477 }1478 expect(collectionId).to.be.equal(result.collectionId);1479 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1480 expect(to).to.be.deep.equal(result.recipient);1481 newItemId = result.itemId;1482 });1483 return newItemId;1484}14851486export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1487 await usingApi(async (api) => {14881489 let tx;1490 if (createMode === 'NFT') {1491 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1492 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1493 } else {1494 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1495 }149614971498 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1499 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1500 const result = getCreateItemResult(events);15011502 expect(result.success).to.be.false;1503 });1504}15051506export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1507 let newItemId = 0;1508 await usingApi(async (api) => {1509 const to = normalizeAccountId(owner);1510 const itemCountBefore = await getLastTokenId(api, collectionId);1511 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15121513 let tx;1514 if (createMode === 'Fungible') {1515 const createData = {fungible: {value: 10}};1516 tx = api.tx.unique.createItem(collectionId, to, createData as any);1517 } else if (createMode === 'ReFungible') {1518 const createData = {refungible: {pieces: 100}};1519 tx = api.tx.unique.createItem(collectionId, to, createData as any);1520 } else {1521 const createData = {nft: {}};1522 tx = api.tx.unique.createItem(collectionId, to, createData as any);1523 }15241525 const events = await executeTransaction(api, sender, tx);1526 const result = getCreateItemResult(events);15271528 const itemCountAfter = await getLastTokenId(api, collectionId);1529 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15301531 1532 1533 expect(result.success).to.be.true;1534 if (createMode === 'Fungible') {1535 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1536 } else {1537 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1538 }1539 expect(collectionId).to.be.equal(result.collectionId);1540 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1541 expect(to).to.be.deep.equal(result.recipient);1542 newItemId = result.itemId;1543 });1544 return newItemId;1545}15461547export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1548 const createData = {refungible: {pieces: amount}};1549 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15501551 const events = await submitTransactionAsync(sender, tx);1552 return getCreateItemResult(events);1553}15541555export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1556 await usingApi(async (api) => {1557 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15581559 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1560 const result = getCreateItemResult(events);15611562 expect(result.success).to.be.false;1563 });1564}15651566export async function setPublicAccessModeExpectSuccess(1567 sender: IKeyringPair, collectionId: number,1568 accessMode: 'Normal' | 'AllowList',1569) {1570 await usingApi(async (api) => {15711572 1573 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1574 const events = await submitTransactionAsync(sender, tx);1575 const result = getGenericResult(events);15761577 1578 const collection = await queryCollectionExpectSuccess(api, collectionId);15791580 1581 1582 expect(result.success).to.be.true;1583 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1584 });1585}15861587export async function setPublicAccessModeExpectFail(1588 sender: IKeyringPair, collectionId: number,1589 accessMode: 'Normal' | 'AllowList',1590) {1591 await usingApi(async (api) => {15921593 1594 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1596 const result = getGenericResult(events);15971598 1599 1600 expect(result.success).to.be.false;1601 });1602}16031604export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1605 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1606}16071608export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1609 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1610}16111612export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1613 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1614}16151616export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1617 await usingApi(async (api) => {16181619 1620 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1621 const events = await submitTransactionAsync(sender, tx);1622 const result = getGenericResult(events);1623 expect(result.success).to.be.true;16241625 1626 const collection = await queryCollectionExpectSuccess(api, collectionId);16271628 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1629 });1630}16311632export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1633 await setMintPermissionExpectSuccess(sender, collectionId, true);1634}16351636export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1637 await usingApi(async (api) => {1638 1639 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1640 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1641 const result = getCreateCollectionResult(events);1642 1643 expect(result.success).to.be.false;1644 });1645}16461647export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1648 await usingApi(async (api) => {1649 1650 const tx = api.tx.unique.setChainLimits(limits);1651 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1652 const result = getCreateCollectionResult(events);1653 1654 expect(result.success).to.be.false;1655 });1656}16571658export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1659 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1660}16611662export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1663 await usingApi(async (api) => {1664 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16651666 1667 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1668 const events = await submitTransactionAsync(sender, tx);1669 const result = getGenericResult(events);1670 expect(result.success).to.be.true;16711672 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1673 });1674}16751676export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1677 await usingApi(async (api) => {16781679 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16801681 1682 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1683 const events = await submitTransactionAsync(sender, tx);1684 const result = getGenericResult(events);1685 expect(result.success).to.be.true;16861687 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1688 });1689}16901691export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1692 await usingApi(async (api) => {16931694 1695 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1696 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1697 const result = getGenericResult(events);16981699 1700 1701 expect(result.success).to.be.false;1702 });1703}17041705export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1706 await usingApi(async (api) => {1707 1708 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1709 const events = await submitTransactionAsync(sender, tx);1710 const result = getGenericResult(events);17111712 1713 1714 expect(result.success).to.be.true;1715 });1716}17171718export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1719 await usingApi(async (api) => {1720 1721 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1722 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1723 const result = getGenericResult(events);17241725 1726 1727 expect(result.success).to.be.false;1728 });1729}17301731export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1732 : Promise<UpDataStructsRpcCollection | null> => {1733 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1734};17351736export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1737 1738 return (await api.rpc.unique.collectionStats()).created.toNumber();1739};17401741export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1742 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1743}17441745export async function waitNewBlocks(blocksCount = 1): Promise<void> {1746 await usingApi(async (api) => {1747 const promise = new Promise<void>(async (resolve) => {1748 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1749 if (blocksCount > 0) {1750 blocksCount--;1751 } else {1752 unsubscribe();1753 resolve();1754 }1755 });1756 });1757 return promise;1758 });1759}17601761export async function repartitionRFT(1762 api: ApiPromise,1763 collectionId: number,1764 sender: IKeyringPair,1765 tokenId: number,1766 amount: bigint,1767): Promise<boolean> {1768 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1769 const events = await submitTransactionAsync(sender, tx);1770 const result = getGenericResult(events);17711772 return result.success;1773}17741775export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1776 let i: any = it;1777 if (opts.only) i = i.only;1778 else if (opts.skip) i = i.skip;1779 i(name, async () => {1780 await usingApi(async (api, privateKeyWrapper) => {1781 await cb({api, privateKeyWrapper});1782 });1783 });1784}17851786itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1787itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});17881789let accountSeed = 10000;17901791const keyringEth = new Keyring({type: 'ethereum'});1792const keyringEd25519 = new Keyring({type: 'ed25519'});1793const keyringSr25519 = new Keyring({type: 'sr25519'});17941795export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1796 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56, '0')}`;1797 if (type == 'sr25519') {1798 return keyringSr25519.addFromUri(privateKey);1799 } else if (type == 'ed25519') {1800 return keyringEd25519.addFromUri(privateKey);1801 }1802 return keyringEth.addFromUri(privateKey);1803}