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}5152export async function isUnique(): Promise<boolean> {53 return usingApi(async api => {54 const chain = await api.rpc.system.chain();5556 return chain.eq('UNIQUE');57 });58}5960export async function isQuartz(): Promise<boolean> {61 return usingApi(async api => {62 const chain = await api.rpc.system.chain();63 64 return chain.eq('QUARTZ');65 });66}6768let modulesNames: any;69export function getModuleNames(api: ApiPromise): string[] {70 if (typeof modulesNames === 'undefined') 71 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());72 return modulesNames;73}7475export function requirePallets(mocha: Context, api: ApiPromise, requiredPallets: string[]) {76 const pallets = getModuleNames(api);7778 const isAllPalletsPresent = requiredPallets.every(p => pallets.includes(p));7980 if (!isAllPalletsPresent) {81 mocha.skip();82 }83}8485export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {86 if (typeof input === 'string') {87 if (input.length >= 47) {88 return {Substrate: input};89 } else if (input.length === 42 && input.startsWith('0x')) {90 return {Ethereum: input.toLowerCase()};91 } else if (input.length === 40 && !input.startsWith('0x')) {92 return {Ethereum: '0x' + input.toLowerCase()};93 } else {94 throw new Error(`Unknown address format: "${input}"`);95 }96 }97 if ('address' in input) {98 return {Substrate: input.address};99 }100 if ('Ethereum' in input) {101 return {102 Ethereum: input.Ethereum.toLowerCase(),103 };104 } else if ('ethereum' in input) {105 return {106 Ethereum: (input as any).ethereum.toLowerCase(),107 };108 } else if ('Substrate' in input) {109 return input;110 } else if ('substrate' in input) {111 return {112 Substrate: (input as any).substrate,113 };114 }115116 117 return {Substrate: input.toString()};118}119export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {120 input = normalizeAccountId(input);121 if ('Substrate' in input) {122 return input.Substrate;123 } else {124 return evmToAddress(input.Ethereum);125 }126}127128export const U128_MAX = (1n << 128n) - 1n;129130const MICROUNIQUE = 1_000_000_000_000n;131const MILLIUNIQUE = 1_000n * MICROUNIQUE;132const CENTIUNIQUE = 10n * MILLIUNIQUE;133export const UNIQUE = 100n * CENTIUNIQUE;134135interface GenericResult<T> {136 success: boolean;137 data: T | null;138}139140interface CreateCollectionResult {141 success: boolean;142 collectionId: number;143}144145interface CreateItemResult {146 success: boolean;147 collectionId: number;148 itemId: number;149 recipient?: CrossAccountId;150 amount?: number;151}152153interface DestroyItemResult {154 success: boolean;155 collectionId: number;156 itemId: number;157 owner: CrossAccountId;158 amount: number;159}160161interface TransferResult {162 collectionId: number;163 itemId: number;164 sender?: CrossAccountId;165 recipient?: CrossAccountId;166 value: bigint;167}168169interface IReFungibleOwner {170 fraction: BN;171 owner: number[];172}173174interface IGetMessage {175 checkMsgUnqMethod: string;176 checkMsgTrsMethod: string;177 checkMsgSysMethod: string;178}179180export interface IFungibleTokenDataType {181 value: number;182}183184export interface IChainLimits {185 collectionNumbersLimit: number;186 accountTokenOwnershipLimit: number;187 collectionsAdminsLimit: number;188 customDataLimit: number;189 nftSponsorTransferTimeout: number;190 fungibleSponsorTransferTimeout: number;191 refungibleSponsorTransferTimeout: number;192 193 194}195196export interface IReFungibleTokenDataType {197 owner: IReFungibleOwner[];198}199200export function uniqueEventMessage(events: EventRecord[]): IGetMessage {201 let checkMsgUnqMethod = '';202 let checkMsgTrsMethod = '';203 let checkMsgSysMethod = '';204 events.forEach(({event: {method, section}}) => {205 if (section === 'common') {206 checkMsgUnqMethod = method;207 } else if (section === 'treasury') {208 checkMsgTrsMethod = method;209 } else if (section === 'system') {210 checkMsgSysMethod = method;211 } else { return null; }212 });213 const result: IGetMessage = {214 checkMsgUnqMethod,215 checkMsgTrsMethod,216 checkMsgSysMethod,217 };218 return result;219}220221export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {222 const event = events.find(r => check(r.event));223 if (!event) return;224 return event.event as T;225}226227export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;228export function getGenericResult<T>(229 events: EventRecord[],230 expectSection: string,231 expectMethod: string,232 extractAction: (data: GenericEventData) => T233): GenericResult<T>;234235export function getGenericResult<T>(236 events: EventRecord[],237 expectSection?: string,238 expectMethod?: string,239 extractAction?: (data: GenericEventData) => T,240): GenericResult<T> {241 let success = false;242 let successData = null;243244 events.forEach(({event: {data, method, section}}) => {245 246 if (method === 'ExtrinsicSuccess') {247 success = true;248 } else if ((expectSection == section) && (expectMethod == method)) {249 successData = extractAction!(data as any);250 }251 });252253 const result: GenericResult<T> = {254 success,255 data: successData,256 };257 return result;258}259260export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {261 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));262 const result: CreateCollectionResult = {263 success: genericResult.success,264 collectionId: genericResult.data ?? 0,265 };266 return result;267}268269export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {270 const results: CreateItemResult[] = [];271 272 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {273 const collectionId = parseInt(data[0].toString(), 10);274 const itemId = parseInt(data[1].toString(), 10);275 const recipient = normalizeAccountId(data[2].toJSON() as any);276 const amount = parseInt(data[3].toString(), 10);277278 const itemRes: CreateItemResult = {279 success: true,280 collectionId,281 itemId,282 recipient,283 amount,284 };285286 results.push(itemRes);287 return results;288 });289290 if (!genericResult.success) return [];291 return results;292}293294export function getCreateItemResult(events: EventRecord[]): CreateItemResult {295 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));296 297 if (genericResult.data == null) 298 return {299 success: genericResult.success,300 collectionId: 0,301 itemId: 0,302 amount: 0,303 };304 else 305 return {306 success: genericResult.success,307 collectionId: genericResult.data[0] as number,308 itemId: genericResult.data[1] as number,309 recipient: normalizeAccountId(genericResult.data![2] as any),310 amount: genericResult.data[3] as number,311 };312}313314export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {315 const results: DestroyItemResult[] = [];316 317 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {318 const collectionId = parseInt(data[0].toString(), 10);319 const itemId = parseInt(data[1].toString(), 10);320 const owner = normalizeAccountId(data[2].toJSON() as any);321 const amount = parseInt(data[3].toString(), 10);322323 const itemRes: DestroyItemResult = {324 success: true,325 collectionId,326 itemId,327 owner,328 amount,329 };330331 results.push(itemRes);332 return results;333 });334335 if (!genericResult.success) return [];336 return results;337}338339export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {340 for (const {event} of events) {341 if (api.events.common.Transfer.is(event)) {342 const [collection, token, sender, recipient, value] = event.data;343 return {344 collectionId: collection.toNumber(),345 itemId: token.toNumber(),346 sender: normalizeAccountId(sender.toJSON() as any),347 recipient: normalizeAccountId(recipient.toJSON() as any),348 value: value.toBigInt(),349 };350 }351 }352 throw new Error('no transfer event');353}354355interface Nft {356 type: 'NFT';357}358359interface Fungible {360 type: 'Fungible';361 decimalPoints: number;362}363364interface ReFungible {365 type: 'ReFungible';366}367368export type CollectionMode = Nft | Fungible | ReFungible;369370export type Property = {371 key: any,372 value: any,373};374375type Permission = {376 mutable: boolean;377 collectionAdmin: boolean;378 tokenOwner: boolean;379}380381type PropertyPermission = {382 key: any;383 permission: Permission;384}385386export type CreateCollectionParams = {387 mode: CollectionMode,388 name: string,389 description: string,390 tokenPrefix: string,391 properties?: Array<Property>,392 propPerm?: Array<PropertyPermission>393};394395const defaultCreateCollectionParams: CreateCollectionParams = {396 description: 'description',397 mode: {type: 'NFT'},398 name: 'name',399 tokenPrefix: 'prefix',400};401402export async function403createCollection(404 api: ApiPromise,405 sender: IKeyringPair,406 params: Partial<CreateCollectionParams> = {},407): Promise<CreateCollectionResult> {408 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};409410 let modeprm = {};411 if (mode.type === 'NFT') {412 modeprm = {nft: null};413 } else if (mode.type === 'Fungible') {414 modeprm = {fungible: mode.decimalPoints};415 } else if (mode.type === 'ReFungible') {416 modeprm = {refungible: null};417 }418419 const tx = api.tx.unique.createCollectionEx({420 name: strToUTF16(name),421 description: strToUTF16(description),422 tokenPrefix: strToUTF16(tokenPrefix),423 mode: modeprm as any,424 });425 const events = await submitTransactionAsync(sender, tx);426 return getCreateCollectionResult(events);427}428429export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {430 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432 let collectionId = 0;433 await usingApi(async (api, privateKeyWrapper) => {434 435 const collectionCountBefore = await getCreatedCollectionCount(api);436437 438 const alicePrivateKey = privateKeyWrapper('//Alice');439440 const result = await createCollection(api, alicePrivateKey, params);441442 443 const collectionCountAfter = await getCreatedCollectionCount(api);444445 446 const collection = await queryCollectionExpectSuccess(api, result.collectionId);447448 449 450 expect(result.success).to.be.true;451 expect(result.collectionId).to.be.equal(collectionCountAfter);452 453 expect(collection).to.be.not.null;454 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');455 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));456 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);457 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);458 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);459460 collectionId = result.collectionId;461 });462463 return collectionId;464}465466export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {467 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};468469 let collectionId = 0;470 await usingApi(async (api, privateKeyWrapper) => {471 472 const collectionCountBefore = await getCreatedCollectionCount(api);473474 475 const alicePrivateKey = privateKeyWrapper('//Alice');476477 let modeprm = {};478 if (mode.type === 'NFT') {479 modeprm = {nft: null};480 } else if (mode.type === 'Fungible') {481 modeprm = {fungible: mode.decimalPoints};482 } else if (mode.type === 'ReFungible') {483 modeprm = {refungible: null};484 }485486 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});487 const events = await submitTransactionAsync(alicePrivateKey, tx);488 const result = getCreateCollectionResult(events);489490 491 const collectionCountAfter = await getCreatedCollectionCount(api);492493 494 const collection = await queryCollectionExpectSuccess(api, result.collectionId);495496 497 498 expect(result.success).to.be.true;499 expect(result.collectionId).to.be.equal(collectionCountAfter);500 501 expect(collection).to.be.not.null;502 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');503 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));504 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);505 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);506 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);507508509 collectionId = result.collectionId;510 });511512 return collectionId;513}514515export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {516 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};517518 await usingApi(async (api, privateKeyWrapper) => {519 520 const collectionCountBefore = await getCreatedCollectionCount(api);521522 523 const alicePrivateKey = privateKeyWrapper('//Alice');524525 let modeprm = {};526 if (mode.type === 'NFT') {527 modeprm = {nft: null};528 } else if (mode.type === 'Fungible') {529 modeprm = {fungible: mode.decimalPoints};530 } else if (mode.type === 'ReFungible') {531 modeprm = {refungible: null};532 }533534 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});535 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;536537538 539 const collectionCountAfter = await getCreatedCollectionCount(api);540541 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');542 });543}544545export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {546 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};547548 let modeprm = {};549 if (mode.type === 'NFT') {550 modeprm = {nft: null};551 } else if (mode.type === 'Fungible') {552 modeprm = {fungible: mode.decimalPoints};553 } else if (mode.type === 'ReFungible') {554 modeprm = {refungible: null};555 }556557 await usingApi(async (api, privateKeyWrapper) => {558 559 const collectionCountBefore = await getCreatedCollectionCount(api);560561 562 const alicePrivateKey = privateKeyWrapper('//Alice');563 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});564 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;565566 567 const collectionCountAfter = await getCreatedCollectionCount(api);568569 570 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');571 });572}573574export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {575 let bal = 0n;576 let unused;577 do {578 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;579 unused = privateKeyWrapper(`//${randomSeed}`);580 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();581 } while (bal !== 0n);582 return unused;583}584585export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {586 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();587}588589export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {590 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));591}592593export async function findNotExistingCollection(api: ApiPromise): Promise<number> {594 const totalNumber = await getCreatedCollectionCount(api);595 const newCollection: number = totalNumber + 1;596 return newCollection;597}598599function getDestroyResult(events: EventRecord[]): boolean {600 let success = false;601 events.forEach(({event: {method}}) => {602 if (method == 'ExtrinsicSuccess') {603 success = true;604 }605 });606 return success;607}608609export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {610 await usingApi(async (api, privateKeyWrapper) => {611 612 const alicePrivateKey = privateKeyWrapper(senderSeed);613 const tx = api.tx.unique.destroyCollection(collectionId);614 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;615 });616}617618export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {619 await usingApi(async (api, privateKeyWrapper) => {620 621 const alicePrivateKey = privateKeyWrapper(senderSeed);622 const tx = api.tx.unique.destroyCollection(collectionId);623 const events = await submitTransactionAsync(alicePrivateKey, tx);624 const result = getDestroyResult(events);625 expect(result).to.be.true;626627 628 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;629 });630}631632export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {633 await usingApi(async (api) => {634 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);635 const events = await submitTransactionAsync(sender, tx);636 const result = getGenericResult(events);637638 expect(result.success).to.be.true;639 });640}641642export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {643 await usingApi(async(api) => {644 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);645 const events = await submitTransactionAsync(sender, tx);646 const result = getGenericResult(events);647648 expect(result.success).to.be.true;649 });650};651652export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {653 await usingApi(async (api) => {654 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656 const result = getGenericResult(events);657658 expect(result.success).to.be.false;659 });660}661662export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {663 await usingApi(async (api, privateKeyWrapper) => {664665 666 const senderPrivateKey = privateKeyWrapper(sender);667 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);668 const events = await submitTransactionAsync(senderPrivateKey, tx);669 const result = getGenericResult(events);670671 672 const collection = await queryCollectionExpectSuccess(api, collectionId);673674 675 expect(result.success).to.be.true;676 expect(collection.sponsorship.toJSON()).to.deep.equal({677 unconfirmed: sponsor,678 });679 });680}681682export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {683 await usingApi(async (api, privateKeyWrapper) => {684685 686 const alicePrivateKey = privateKeyWrapper(sender);687 const tx = api.tx.unique.removeCollectionSponsor(collectionId);688 const events = await submitTransactionAsync(alicePrivateKey, tx);689 const result = getGenericResult(events);690691 692 const collection = await queryCollectionExpectSuccess(api, collectionId);693694 695 expect(result.success).to.be.true;696 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});697 });698}699700export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {701 await usingApi(async (api, privateKeyWrapper) => {702703 704 const alicePrivateKey = privateKeyWrapper(senderSeed);705 const tx = api.tx.unique.removeCollectionSponsor(collectionId);706 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;707 });708}709710export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {711 await usingApi(async (api, privateKeyWrapper) => {712713 714 const alicePrivateKey = privateKeyWrapper(senderSeed);715 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);716 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;717 });718}719720export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {721 await usingApi(async (api, privateKeyWrapper) => {722723 724 const sender = privateKeyWrapper(senderSeed);725 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);726 });727}728729export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {730 await usingApi(async (api, privateKeyWrapper) => {731732 733 const tx = api.tx.unique.confirmSponsorship(collectionId);734 const events = await submitTransactionAsync(sender, tx);735 const result = getGenericResult(events);736737 738 const collection = await queryCollectionExpectSuccess(api, collectionId);739740 741 expect(result.success).to.be.true;742 expect(collection.sponsorship.toJSON()).to.be.deep.equal({743 confirmed: sender.address,744 });745 });746}747748749export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {750 await usingApi(async (api, privateKeyWrapper) => {751752 753 const sender = privateKeyWrapper(senderSeed);754 const tx = api.tx.unique.confirmSponsorship(collectionId);755 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;756 });757}758759export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {760 await usingApi(async (api) => {761 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);762 const events = await submitTransactionAsync(sender, tx);763 const result = getGenericResult(events);764765 expect(result.success).to.be.true;766 });767}768769export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {770 await usingApi(async (api) => {771 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);772 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773 const result = getGenericResult(events);774775 expect(result.success).to.be.false;776 });777}778779export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {780781 await usingApi(async (api) => {782783 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);784 const events = await submitTransactionAsync(sender, tx);785 const result = getGenericResult(events);786787 expect(result.success).to.be.true;788 });789}790791export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {792793 await usingApi(async (api) => {794795 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);796 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;797 const result = getGenericResult(events);798799 expect(result.success).to.be.false;800 });801}802803export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {804 await usingApi(async (api) => {805 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);806 const events = await submitTransactionAsync(sender, tx);807 const result = getGenericResult(events);808809 expect(result.success).to.be.true;810 });811}812813export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {814 await usingApi(async (api) => {815 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);816 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;817 const result = getGenericResult(events);818819 expect(result.success).to.be.false;820 });821}822823export async function getNextSponsored(824 api: ApiPromise,825 collectionId: number,826 account: string | CrossAccountId,827 tokenId: number,828): Promise<number> {829 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));830}831832export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {833 await usingApi(async (api) => {834 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);835 const events = await submitTransactionAsync(sender, tx);836 const result = getGenericResult(events);837838 expect(result.success).to.be.true;839 });840}841842export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {843 let allowlisted = false;844 await usingApi(async (api) => {845 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;846 });847 return allowlisted;848}849850export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {851 await usingApi(async (api) => {852 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());853 const events = await submitTransactionAsync(sender, tx);854 const result = getGenericResult(events);855856 expect(result.success).to.be.true;857 });858}859860export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {861 await usingApi(async (api) => {862 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());863 const events = await submitTransactionAsync(sender, tx);864 const result = getGenericResult(events);865866 expect(result.success).to.be.true;867 });868}869870export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {871 await usingApi(async (api) => {872 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());873 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;874 const result = getGenericResult(events);875876 expect(result.success).to.be.false;877 });878}879880export interface CreateFungibleData {881 readonly Value: bigint;882}883884export interface CreateReFungibleData { }885export interface CreateNftData { }886887export type CreateItemData = {888 NFT: CreateNftData;889} | {890 Fungible: CreateFungibleData;891} | {892 ReFungible: CreateReFungibleData;893};894895export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {896 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);897 const events = await submitTransactionAsync(sender, tx);898 return getGenericResult(events).success;899}900901export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {902 await usingApi(async (api) => {903 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);904 905 expect(balanceBefore >= BigInt(value)).to.be.true;906907 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;908909 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);910 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);911 });912}913914export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {915 await usingApi(async (api) => {916 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);917918 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;919 const result = getCreateCollectionResult(events);920 921 expect(result.success).to.be.false;922 });923}924925export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {926 await usingApi(async (api) => {927 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);928 const events = await submitTransactionAsync(sender, tx);929 return getGenericResult(events).success;930 });931}932933export async function934approve(935 api: ApiPromise,936 collectionId: number,937 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,938) {939 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);940 const events = await submitTransactionAsync(owner, approveUniqueTx);941 return getGenericResult(events).success;942}943944export async function945approveExpectSuccess(946 collectionId: number,947 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,948) {949 await usingApi(async (api: ApiPromise) => {950 const result = await approve(api, collectionId, tokenId, owner, approved, amount);951 expect(result).to.be.true;952953 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));954 });955}956957export async function adminApproveFromExpectSuccess(958 collectionId: number,959 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,960) {961 await usingApi(async (api: ApiPromise) => {962 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963 const events = await submitTransactionAsync(admin, approveUniqueTx);964 const result = getGenericResult(events);965 expect(result.success).to.be.true;966967 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));968 });969}970971export async function972transferFrom(973 api: ApiPromise,974 collectionId: number,975 tokenId: number,976 accountApproved: IKeyringPair,977 accountFrom: IKeyringPair | CrossAccountId,978 accountTo: IKeyringPair | CrossAccountId,979 value: number | bigint,980) {981 const from = normalizeAccountId(accountFrom);982 const to = normalizeAccountId(accountTo);983 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);984 const events = await submitTransactionAsync(accountApproved, transferFromTx);985 return getGenericResult(events).success;986}987988export async function989transferFromExpectSuccess(990 collectionId: number,991 tokenId: number,992 accountApproved: IKeyringPair,993 accountFrom: IKeyringPair | CrossAccountId,994 accountTo: IKeyringPair | CrossAccountId,995 value: number | bigint = 1,996 type = 'NFT',997) {998 await usingApi(async (api: ApiPromise) => {999 const from = normalizeAccountId(accountFrom);1000 const to = normalizeAccountId(accountTo);1001 let balanceBefore = 0n;1002 if (type === 'Fungible' || type === 'ReFungible') {1003 balanceBefore = await getBalance(api, collectionId, to, tokenId);1004 }1005 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1006 if (type === 'NFT') {1007 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1008 }1009 if (type === 'Fungible') {1010 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1011 if (JSON.stringify(to) !== JSON.stringify(from)) {1012 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1013 } else {1014 expect(balanceAfter).to.be.equal(balanceBefore);1015 }1016 }1017 if (type === 'ReFungible') {1018 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1019 }1020 });1021}10221023export async function1024transferFromExpectFail(1025 collectionId: number,1026 tokenId: number,1027 accountApproved: IKeyringPair,1028 accountFrom: IKeyringPair,1029 accountTo: IKeyringPair,1030 value: number | bigint = 1,1031) {1032 await usingApi(async (api: ApiPromise) => {1033 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1034 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1035 const result = getCreateCollectionResult(events);1036 1037 expect(result.success).to.be.false;1038 });1039}104010411042export async function getBlockNumber(api: ApiPromise): Promise<number> {1043 return new Promise<number>(async (resolve) => {1044 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1045 unsubscribe();1046 resolve(head.number.toNumber());1047 });1048 });1049}10501051export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1052 await usingApi(async (api) => {1053 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1054 const events = await submitTransactionAsync(sender, changeAdminTx);1055 const result = getCreateCollectionResult(events);1056 expect(result.success).to.be.true;1057 });1058}10591060export async function adminApproveFromExpectFail(1061 collectionId: number,1062 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1063) {1064 await usingApi(async (api: ApiPromise) => {1065 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1066 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1067 const result = getGenericResult(events);1068 expect(result.success).to.be.false;1069 });1070}10711072export async function1073getFreeBalance(account: IKeyringPair): Promise<bigint> {1074 let balance = 0n;1075 await usingApi(async (api) => {1076 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1077 });10781079 return balance;1080}10811082export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1083 const tx = api.tx.balances.transfer(target, amount);1084 const events = await submitTransactionAsync(source, tx);1085 const result = getGenericResult(events);1086 expect(result.success).to.be.true;1087}10881089export async function1090scheduleExpectSuccess(1091 operationTx: any,1092 sender: IKeyringPair,1093 blockSchedule: number,1094 scheduledId: string,1095 period = 1,1096 repetitions = 1,1097) {1098 await usingApi(async (api: ApiPromise) => {1099 const blockNumber: number | undefined = await getBlockNumber(api);1100 const expectedBlockNumber = blockNumber + blockSchedule;11011102 expect(blockNumber).to.be.greaterThan(0);1103 const scheduleTx = api.tx.scheduler.scheduleNamed( 1104 scheduledId,1105 expectedBlockNumber, 1106 repetitions > 1 ? [period, repetitions] : null, 1107 0, 1108 {Value: operationTx as any},1109 );11101111 const events = await submitTransactionAsync(sender, scheduleTx);1112 expect(getGenericResult(events).success).to.be.true;1113 });1114}11151116export async function1117scheduleExpectFailure(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 ? null : [period, repetitions], 1134 0, 1135 {Value: operationTx as any},1136 );11371138 1139 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1140 1141 });1142}11431144export async function1145scheduleTransferAndWaitExpectSuccess(1146 collectionId: number,1147 tokenId: number,1148 sender: IKeyringPair,1149 recipient: IKeyringPair,1150 value: number | bigint = 1,1151 blockSchedule: number,1152 scheduledId: string,1153) {1154 await usingApi(async (api: ApiPromise) => {1155 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11561157 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11581159 1160 await waitNewBlocks(blockSchedule + 1);11611162 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11631164 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1165 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1166 });1167}11681169export async function1170scheduleTransferExpectSuccess(1171 collectionId: number,1172 tokenId: number,1173 sender: IKeyringPair,1174 recipient: IKeyringPair,1175 value: number | bigint = 1,1176 blockSchedule: number,1177 scheduledId: string,1178) {1179 await usingApi(async (api: ApiPromise) => {1180 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11811182 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11831184 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1185 });1186}11871188export async function1189scheduleTransferFundsPeriodicExpectSuccess(1190 amount: bigint,1191 sender: IKeyringPair,1192 recipient: IKeyringPair,1193 blockSchedule: number,1194 scheduledId: string,1195 period: number,1196 repetitions: number,1197) {1198 await usingApi(async (api: ApiPromise) => {1199 const transferTx = api.tx.balances.transfer(recipient.address, amount);12001201 const balanceBefore = await getFreeBalance(recipient);1202 1203 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12041205 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1206 });1207}12081209export async function1210transfer(1211 api: ApiPromise,1212 collectionId: number,1213 tokenId: number,1214 sender: IKeyringPair,1215 recipient: IKeyringPair | CrossAccountId,1216 value: number | bigint,1217) : Promise<boolean> {1218 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1219 const events = await executeTransaction(api, sender, transferTx);1220 return getGenericResult(events).success;1221}12221223export async function1224transferExpectSuccess(1225 collectionId: number,1226 tokenId: number,1227 sender: IKeyringPair,1228 recipient: IKeyringPair | CrossAccountId,1229 value: number | bigint = 1,1230 type = 'NFT',1231) {1232 await usingApi(async (api: ApiPromise) => {1233 const from = normalizeAccountId(sender);1234 const to = normalizeAccountId(recipient);12351236 let balanceBefore = 0n;1237 if (type === 'Fungible' || type === 'ReFungible') {1238 balanceBefore = await getBalance(api, collectionId, to, tokenId);1239 }12401241 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242 const events = await executeTransaction(api, sender, transferTx);1243 const result = getTransferResult(api, events);12441245 expect(result.collectionId).to.be.equal(collectionId);1246 expect(result.itemId).to.be.equal(tokenId);1247 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1248 expect(result.recipient).to.be.deep.equal(to);1249 expect(result.value).to.be.equal(BigInt(value));12501251 if (type === 'NFT') {1252 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1253 }1254 if (type === 'Fungible' || type === 'ReFungible') {1255 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1256 if (JSON.stringify(to) !== JSON.stringify(from)) {1257 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1258 } else {1259 expect(balanceAfter).to.be.equal(balanceBefore);1260 }1261 }1262 });1263}12641265export async function1266transferExpectFailure(1267 collectionId: number,1268 tokenId: number,1269 sender: IKeyringPair,1270 recipient: IKeyringPair | CrossAccountId,1271 value: number | bigint = 1,1272) {1273 await usingApi(async (api: ApiPromise) => {1274 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1275 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1276 const result = getGenericResult(events);1277 1278 1279 1280 expect(result.success).to.be.false;1281 1282 });1283}12841285export async function1286approveExpectFail(1287 collectionId: number,1288 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1289) {1290 await usingApi(async (api: ApiPromise) => {1291 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1292 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1293 const result = getCreateCollectionResult(events);1294 1295 expect(result.success).to.be.false;1296 });1297}12981299export async function getBalance(1300 api: ApiPromise,1301 collectionId: number,1302 owner: string | CrossAccountId | IKeyringPair,1303 token: number,1304): Promise<bigint> {1305 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1306}1307export async function getTokenOwner(1308 api: ApiPromise,1309 collectionId: number,1310 token: number,1311): Promise<CrossAccountId> {1312 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1313 if (owner == null) throw new Error('owner == null');1314 return normalizeAccountId(owner);1315}1316export async function getTopmostTokenOwner(1317 api: ApiPromise,1318 collectionId: number,1319 token: number,1320): Promise<CrossAccountId> {1321 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1322 if (owner == null) throw new Error('owner == null');1323 return normalizeAccountId(owner);1324}1325export async function getTokenChildren(1326 api: ApiPromise,1327 collectionId: number,1328 tokenId: number,1329): Promise<UpDataStructsTokenChild[]> {1330 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1331}1332export async function isTokenExists(1333 api: ApiPromise,1334 collectionId: number,1335 token: number,1336): Promise<boolean> {1337 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1338}1339export async function getLastTokenId(1340 api: ApiPromise,1341 collectionId: number,1342): Promise<number> {1343 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1344}1345export async function getAdminList(1346 api: ApiPromise,1347 collectionId: number,1348): Promise<string[]> {1349 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1350}1351export async function getTokenProperties(1352 api: ApiPromise,1353 collectionId: number,1354 tokenId: number,1355 propertyKeys: string[],1356): Promise<UpDataStructsProperty[]> {1357 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1358}13591360export async function createFungibleItemExpectSuccess(1361 sender: IKeyringPair,1362 collectionId: number,1363 data: CreateFungibleData,1364 owner: CrossAccountId | string = sender.address,1365) {1366 return await usingApi(async (api) => {1367 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13681369 const events = await submitTransactionAsync(sender, tx);1370 const result = getCreateItemResult(events);13711372 expect(result.success).to.be.true;1373 return result.itemId;1374 });1375}13761377export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1378 await usingApi(async (api) => {1379 const to = normalizeAccountId(owner);1380 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13811382 const events = await submitTransactionAsync(sender, tx);1383 expect(getGenericResult(events).success).to.be.true;1384 });1385}13861387export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1388 await usingApi(async (api) => {1389 const to = normalizeAccountId(owner);1390 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13911392 const events = await submitTransactionAsync(sender, tx);1393 const result = getCreateItemsResult(events);13941395 for (const res of result) {1396 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1397 }1398 });1399}14001401export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1402 await usingApi(async (api) => {1403 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14041405 const events = await submitTransactionAsync(sender, tx);1406 const result = getCreateItemsResult(events);14071408 for (const res of result) {1409 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1410 }1411 });1412}14131414export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1415 let newItemId = 0;1416 await usingApi(async (api) => {1417 const to = normalizeAccountId(owner);1418 const itemCountBefore = await getLastTokenId(api, collectionId);1419 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14201421 let tx;1422 if (createMode === 'Fungible') {1423 const createData = {fungible: {value: 10}};1424 tx = api.tx.unique.createItem(collectionId, to, createData as any);1425 } else if (createMode === 'ReFungible') {1426 const createData = {refungible: {pieces: 100}};1427 tx = api.tx.unique.createItem(collectionId, to, createData as any);1428 } else {1429 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1430 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1431 }14321433 const events = await submitTransactionAsync(sender, tx);1434 const result = getCreateItemResult(events);14351436 const itemCountAfter = await getLastTokenId(api, collectionId);1437 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14381439 if (createMode === 'NFT') {1440 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1441 }14421443 1444 1445 expect(result.success).to.be.true;1446 if (createMode === 'Fungible') {1447 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1448 } else {1449 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1450 }1451 expect(collectionId).to.be.equal(result.collectionId);1452 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1453 expect(to).to.be.deep.equal(result.recipient);1454 newItemId = result.itemId;1455 });1456 return newItemId;1457}14581459export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1460 await usingApi(async (api) => {14611462 let tx;1463 if (createMode === 'NFT') {1464 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1465 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1466 } else {1467 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1468 }146914701471 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1472 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1473 const result = getCreateItemResult(events);14741475 expect(result.success).to.be.false;1476 });1477}14781479export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1480 let newItemId = 0;1481 await usingApi(async (api) => {1482 const to = normalizeAccountId(owner);1483 const itemCountBefore = await getLastTokenId(api, collectionId);1484 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14851486 let tx;1487 if (createMode === 'Fungible') {1488 const createData = {fungible: {value: 10}};1489 tx = api.tx.unique.createItem(collectionId, to, createData as any);1490 } else if (createMode === 'ReFungible') {1491 const createData = {refungible: {pieces: 100}};1492 tx = api.tx.unique.createItem(collectionId, to, createData as any);1493 } else {1494 const createData = {nft: {}};1495 tx = api.tx.unique.createItem(collectionId, to, createData as any);1496 }14971498 const events = await executeTransaction(api, sender, tx);1499 const result = getCreateItemResult(events);15001501 const itemCountAfter = await getLastTokenId(api, collectionId);1502 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15031504 1505 1506 expect(result.success).to.be.true;1507 if (createMode === 'Fungible') {1508 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1509 } else {1510 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1511 }1512 expect(collectionId).to.be.equal(result.collectionId);1513 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1514 expect(to).to.be.deep.equal(result.recipient);1515 newItemId = result.itemId;1516 });1517 return newItemId;1518}15191520export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1521 const createData = {refungible: {pieces: amount}};1522 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15231524 const events = await submitTransactionAsync(sender, tx);1525 return getCreateItemResult(events);1526}15271528export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529 await usingApi(async (api) => {1530 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15311532 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1533 const result = getCreateItemResult(events);15341535 expect(result.success).to.be.false;1536 });1537}15381539export async function setPublicAccessModeExpectSuccess(1540 sender: IKeyringPair, collectionId: number,1541 accessMode: 'Normal' | 'AllowList',1542) {1543 await usingApi(async (api) => {15441545 1546 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1547 const events = await submitTransactionAsync(sender, tx);1548 const result = getGenericResult(events);15491550 1551 const collection = await queryCollectionExpectSuccess(api, collectionId);15521553 1554 1555 expect(result.success).to.be.true;1556 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1557 });1558}15591560export async function setPublicAccessModeExpectFail(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 expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1569 const result = getGenericResult(events);15701571 1572 1573 expect(result.success).to.be.false;1574 });1575}15761577export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1578 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1579}15801581export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1582 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1583}15841585export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1586 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1587}15881589export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1590 await usingApi(async (api) => {15911592 1593 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1594 const events = await submitTransactionAsync(sender, tx);1595 const result = getGenericResult(events);1596 expect(result.success).to.be.true;15971598 1599 const collection = await queryCollectionExpectSuccess(api, collectionId);16001601 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1602 });1603}16041605export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1606 await setMintPermissionExpectSuccess(sender, collectionId, true);1607}16081609export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1610 await usingApi(async (api) => {1611 1612 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1613 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1614 const result = getCreateCollectionResult(events);1615 1616 expect(result.success).to.be.false;1617 });1618}16191620export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1621 await usingApi(async (api) => {1622 1623 const tx = api.tx.unique.setChainLimits(limits);1624 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1625 const result = getCreateCollectionResult(events);1626 1627 expect(result.success).to.be.false;1628 });1629}16301631export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1632 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1633}16341635export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1636 await usingApi(async (api) => {1637 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16381639 1640 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1641 const events = await submitTransactionAsync(sender, tx);1642 const result = getGenericResult(events);1643 expect(result.success).to.be.true;16441645 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1646 });1647}16481649export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1650 await usingApi(async (api) => {16511652 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16531654 1655 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1656 const events = await submitTransactionAsync(sender, tx);1657 const result = getGenericResult(events);1658 expect(result.success).to.be.true;16591660 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1661 });1662}16631664export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1665 await usingApi(async (api) => {16661667 1668 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1669 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1670 const result = getGenericResult(events);16711672 1673 1674 expect(result.success).to.be.false;1675 });1676}16771678export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1679 await usingApi(async (api) => {1680 1681 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1682 const events = await submitTransactionAsync(sender, tx);1683 const result = getGenericResult(events);16841685 1686 1687 expect(result.success).to.be.true;1688 });1689}16901691export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1692 await usingApi(async (api) => {1693 1694 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1695 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1696 const result = getGenericResult(events);16971698 1699 1700 expect(result.success).to.be.false;1701 });1702}17031704export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1705 : Promise<UpDataStructsRpcCollection | null> => {1706 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1707};17081709export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1710 1711 return (await api.rpc.unique.collectionStats()).created.toNumber();1712};17131714export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1715 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1716}17171718export async function waitNewBlocks(blocksCount = 1): Promise<void> {1719 await usingApi(async (api) => {1720 const promise = new Promise<void>(async (resolve) => {1721 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1722 if (blocksCount > 0) {1723 blocksCount--;1724 } else {1725 unsubscribe();1726 resolve();1727 }1728 });1729 });1730 return promise;1731 });1732}17331734export async function repartitionRFT(1735 api: ApiPromise,1736 collectionId: number,1737 sender: IKeyringPair,1738 tokenId: number,1739 amount: bigint,1740): Promise<boolean> {1741 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1742 const events = await submitTransactionAsync(sender, tx);1743 const result = getGenericResult(events);17441745 return result.success;1746}17471748export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1749 let i: any = it;1750 if (opts.only) i = i.only;1751 else if (opts.skip) i = i.skip;1752 i(name, async () => {1753 await usingApi(async (api, privateKeyWrapper) => {1754 await cb({api, privateKeyWrapper});1755 });1756 });1757}17581759itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1760itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});