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 {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 collectionId: number;109 itemId: number;110 sender?: CrossAccountId;111 recipient?: CrossAccountId;112 value: bigint;113}114115interface IReFungibleOwner {116 fraction: BN;117 owner: number[];118}119120interface IGetMessage {121 checkMsgUnqMethod: string;122 checkMsgTrsMethod: string;123 checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127 value: number;128}129130export interface IChainLimits {131 collectionNumbersLimit: number;132 accountTokenOwnershipLimit: number;133 collectionsAdminsLimit: number;134 customDataLimit: number;135 nftSponsorTransferTimeout: number;136 fungibleSponsorTransferTimeout: number;137 refungibleSponsorTransferTimeout: number;138 offchainSchemaLimit: number;139 constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143 owner: IReFungibleOwner[];144 constData: number[];145 variableData: number[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult(events: EventRecord[]): GenericResult {176 const result: GenericResult = {177 success: false,178 };179 events.forEach(({event: {method}}) => {180 181 if (method === 'ExtrinsicSuccess') {182 result.success = true;183 }184 });185 return result;186}187188189190export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {191 let success = false;192 let collectionId = 0;193 events.forEach(({event: {data, method, section}}) => {194 195 if (method == 'ExtrinsicSuccess') {196 success = true;197 } else if ((section == 'common') && (method == 'CollectionCreated')) {198 collectionId = parseInt(data[0].toString(), 10);199 }200 });201 const result: CreateCollectionResult = {202 success,203 collectionId,204 };205 return result;206}207208export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {209 let success = false;210 let collectionId = 0;211 let itemId = 0;212 let recipient;213214 const results : CreateItemResult[] = [];215216 events.forEach(({event: {data, method, section}}) => {217 218 if (method == 'ExtrinsicSuccess') {219 success = true;220 } else if ((section == 'common') && (method == 'ItemCreated')) {221 collectionId = parseInt(data[0].toString(), 10);222 itemId = parseInt(data[1].toString(), 10);223 recipient = normalizeAccountId(data[2].toJSON() as any);224225 const itemRes: CreateItemResult = {226 success,227 collectionId,228 itemId,229 recipient,230 };231232 results.push(itemRes);233 }234 });235236 return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240 let success = false;241 let collectionId = 0;242 let itemId = 0;243 let recipient;244 events.forEach(({event: {data, method, section}}) => {245 246 if (method == 'ExtrinsicSuccess') {247 success = true;248 } else if ((section == 'common') && (method == 'ItemCreated')) {249 collectionId = parseInt(data[0].toString(), 10);250 itemId = parseInt(data[1].toString(), 10);251 recipient = normalizeAccountId(data[2].toJSON() as any);252 }253 });254 const result: CreateItemResult = {255 success,256 collectionId,257 itemId,258 recipient,259 };260 return result;261}262263export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {264 for (const {event} of events) {265 if (api.events.common.Transfer.is(event)) {266 const [collection, token, sender, recipient, value] = event.data;267 return {268 collectionId: collection.toNumber(),269 itemId: token.toNumber(),270 sender: normalizeAccountId(sender.toJSON() as any),271 recipient: normalizeAccountId(recipient.toJSON() as any),272 value: value.toBigInt(),273 };274 }275 }276 throw new Error('no transfer event');277}278279interface Nft {280 type: 'NFT';281}282283interface Fungible {284 type: 'Fungible';285 decimalPoints: number;286}287288interface ReFungible {289 type: 'ReFungible';290}291292type CollectionMode = Nft | Fungible | ReFungible;293294export type Property = {295 key: any,296 value: any,297};298299type PropertyPermission = {300 key: any,301 mutable: boolean;302 collectionAdmin: boolean;303 tokenOwner: boolean;304}305306export type CreateCollectionParams = {307 mode: CollectionMode,308 name: string,309 description: string,310 tokenPrefix: string,311 schemaVersion: string,312 properties?: Array<Property>,313 propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317 description: 'description',318 mode: {type: 'NFT'},319 name: 'name',320 tokenPrefix: 'prefix',321 schemaVersion: 'ImageURL',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api) => {329 330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 333 const alicePrivateKey = privateKey('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 schemaVersion: schemaVersion,350 });351 const events = await submitTransactionAsync(alicePrivateKey, tx);352 const result = getCreateCollectionResult(events);353354 355 const collectionCountAfter = await getCreatedCollectionCount(api);356357 358 const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360 361 362 expect(result.success).to.be.true;363 expect(result.collectionId).to.be.equal(collectionCountAfter);364 365 expect(collection).to.be.not.null;366 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372 collectionId = result.collectionId;373 });374375 return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381 let collectionId = 0;382 await usingApi(async (api) => {383 384 const collectionCountBefore = await getCreatedCollectionCount(api);385386 387 const alicePrivateKey = privateKey('//Alice');388389 let modeprm = {};390 if (mode.type === 'NFT') {391 modeprm = {nft: null};392 } else if (mode.type === 'Fungible') {393 modeprm = {fungible: mode.decimalPoints};394 } else if (mode.type === 'ReFungible') {395 modeprm = {refungible: null};396 }397398 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});399 const events = await submitTransactionAsync(alicePrivateKey, tx);400 const result = getCreateCollectionResult(events);401402 403 const collectionCountAfter = await getCreatedCollectionCount(api);404405 406 const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408 409 410 expect(result.success).to.be.true;411 expect(result.collectionId).to.be.equal(collectionCountAfter);412 413 expect(collection).to.be.not.null;414 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421 collectionId = result.collectionId;422 });423424 return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430 const collectionId = 0;431 await usingApi(async (api) => {432 433 const collectionCountBefore = await getCreatedCollectionCount(api);434435 436 const alicePrivateKey = privateKey('//Alice');437438 let modeprm = {};439 if (mode.type === 'NFT') {440 modeprm = {nft: null};441 } else if (mode.type === 'Fungible') {442 modeprm = {fungible: mode.decimalPoints};443 } else if (mode.type === 'ReFungible') {444 modeprm = {refungible: null};445 }446447 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});448 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449450451 452 const collectionCountAfter = await getCreatedCollectionCount(api);453454 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');455 });456}457458export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {459 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};460461 let modeprm = {};462 if (mode.type === 'NFT') {463 modeprm = {nft: null};464 } else if (mode.type === 'Fungible') {465 modeprm = {fungible: mode.decimalPoints};466 } else if (mode.type === 'ReFungible') {467 modeprm = {refungible: null};468 }469470 await usingApi(async (api) => {471 472 const collectionCountBefore = await getCreatedCollectionCount(api);473474 475 const alicePrivateKey = privateKey('//Alice');476 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});477 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;478479 480 const collectionCountAfter = await getCreatedCollectionCount(api);481482 483 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');484 });485}486487export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {488 let bal = 0n;489 let unused;490 do {491 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;492 const keyring = new Keyring({type: 'sr25519'});493 unused = keyring.addFromUri(`//${randomSeed}`);494 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();495 } while (bal !== 0n);496 return unused;497}498499export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {500 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();501}502503export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {504 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));505}506507export async function findNotExistingCollection(api: ApiPromise): Promise<number> {508 const totalNumber = await getCreatedCollectionCount(api);509 const newCollection: number = totalNumber + 1;510 return newCollection;511}512513function getDestroyResult(events: EventRecord[]): boolean {514 let success = false;515 events.forEach(({event: {method}}) => {516 if (method == 'ExtrinsicSuccess') {517 success = true;518 }519 });520 return success;521}522523export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {524 await usingApi(async (api) => {525 526 const alicePrivateKey = privateKey(senderSeed);527 const tx = api.tx.unique.destroyCollection(collectionId);528 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;529 });530}531532export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {533 await usingApi(async (api) => {534 535 const alicePrivateKey = privateKey(senderSeed);536 const tx = api.tx.unique.destroyCollection(collectionId);537 const events = await submitTransactionAsync(alicePrivateKey, tx);538 const result = getDestroyResult(events);539 expect(result).to.be.true;540541 542 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;543 });544}545546export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {547 await usingApi(async (api) => {548 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);549 const events = await submitTransactionAsync(sender, tx);550 const result = getGenericResult(events);551552 expect(result.success).to.be.true;553 });554}555556export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {557 await usingApi(async (api) => {558 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);559 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;560 const result = getGenericResult(events);561562 expect(result.success).to.be.false;563 });564}565566export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {567 await usingApi(async (api) => {568569 570 const senderPrivateKey = privateKey(sender);571 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);572 const events = await submitTransactionAsync(senderPrivateKey, tx);573 const result = getGenericResult(events);574575 576 const collection = await queryCollectionExpectSuccess(api, collectionId);577578 579 expect(result.success).to.be.true;580 expect(collection.sponsorship.toJSON()).to.deep.equal({581 unconfirmed: sponsor,582 });583 });584}585586export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {587 await usingApi(async (api) => {588589 590 const alicePrivateKey = privateKey(sender);591 const tx = api.tx.unique.removeCollectionSponsor(collectionId);592 const events = await submitTransactionAsync(alicePrivateKey, tx);593 const result = getGenericResult(events);594595 596 const collection = await queryCollectionExpectSuccess(api, collectionId);597598 599 expect(result.success).to.be.true;600 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});601 });602}603604export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {605 await usingApi(async (api) => {606607 608 const alicePrivateKey = privateKey(senderSeed);609 const tx = api.tx.unique.removeCollectionSponsor(collectionId);610 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;611 });612}613614export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {615 await usingApi(async (api) => {616617 618 const alicePrivateKey = privateKey(senderSeed);619 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);620 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;621 });622}623624export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {625 await usingApi(async (api) => {626627 628 const sender = privateKey(senderSeed);629 const tx = api.tx.unique.confirmSponsorship(collectionId);630 const events = await submitTransactionAsync(sender, tx);631 const result = getGenericResult(events);632633 634 const collection = await queryCollectionExpectSuccess(api, collectionId);635636 637 expect(result.success).to.be.true;638 expect(collection.sponsorship.toJSON()).to.be.deep.equal({639 confirmed: sender.address,640 });641 });642}643644645export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {646 await usingApi(async (api) => {647648 649 const sender = privateKey(senderSeed);650 const tx = api.tx.unique.confirmSponsorship(collectionId);651 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;652 });653}654655export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {656657 await usingApi(async (api) => {658 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);659 const events = await submitTransactionAsync(sender, tx);660 const result = getGenericResult(events);661662 expect(result.success).to.be.true;663 });664}665666export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {667668 await usingApi(async (api) => {669 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);670 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671 const result = getGenericResult(events);672673 expect(result.success).to.be.false;674 });675}676677export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {678 await usingApi(async (api) => {679 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);680 const events = await submitTransactionAsync(sender, tx);681 const result = getGenericResult(events);682683 expect(result.success).to.be.true;684 });685}686687export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {688 await usingApi(async (api) => {689 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);690 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;691 const result = getGenericResult(events);692693 expect(result.success).to.be.false;694 });695}696697export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {698699 await usingApi(async (api) => {700701 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);702 const events = await submitTransactionAsync(sender, tx);703 const result = getGenericResult(events);704705 expect(result.success).to.be.true;706 });707}708709export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {710711 await usingApi(async (api) => {712713 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);714 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;715 const result = getGenericResult(events);716717 expect(result.success).to.be.false;718 });719}720721export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {722 await usingApi(async (api) => {723 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);724 const events = await submitTransactionAsync(sender, tx);725 const result = getGenericResult(events);726727 expect(result.success).to.be.true;728 });729}730731export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {732 await usingApi(async (api) => {733 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);734 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;735 const result = getGenericResult(events);736737 expect(result.success).to.be.false;738 });739}740741export async function getNextSponsored(742 api: ApiPromise,743 collectionId: number,744 account: string | CrossAccountId,745 tokenId: number,746): Promise<number> {747 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));748}749750export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {751 await usingApi(async (api) => {752 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);753 const events = await submitTransactionAsync(sender, tx);754 const result = getGenericResult(events);755756 expect(result.success).to.be.true;757 });758}759760export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {761 let allowlisted = false;762 await usingApi(async (api) => {763 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;764 });765 return allowlisted;766}767768export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769 await usingApi(async (api) => {770 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());771 const events = await submitTransactionAsync(sender, tx);772 const result = getGenericResult(events);773774 expect(result.success).to.be.true;775 });776}777778export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {779 await usingApi(async (api) => {780 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());781 const events = await submitTransactionAsync(sender, tx);782 const result = getGenericResult(events);783784 expect(result.success).to.be.true;785 });786}787788export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {789 await usingApi(async (api) => {790 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());791 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792 const result = getGenericResult(events);793794 expect(result.success).to.be.false;795 });796}797798export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {799 await usingApi(async (api) => {800 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));801 const events = await submitTransactionAsync(sender, tx);802 const result = getGenericResult(events);803804 expect(result.success).to.be.true;805 });806}807808export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {809 await usingApi(async (api) => {810 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));811 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;812 });813}814815export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {816 await usingApi(async (api) => {817 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));818 const events = await submitTransactionAsync(sender, tx);819 const result = getGenericResult(events);820821 expect(result.success).to.be.true;822 });823}824825export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {826 await usingApi(async (api) => {827 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));828 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;829 });830}831832export interface CreateFungibleData {833 readonly Value: bigint;834}835836export interface CreateReFungibleData { }837export interface CreateNftData { }838839export type CreateItemData = {840 NFT: CreateNftData;841} | {842 Fungible: CreateFungibleData;843} | {844 ReFungible: CreateReFungibleData;845};846847export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {848 await usingApi(async (api) => {849 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);850 851 expect(balanceBefore >= BigInt(value)).to.be.true;852853 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);854 const events = await submitTransactionAsync(sender, tx);855 const result = getGenericResult(events);856 expect(result.success).to.be.true;857858 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);859 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);860 });861}862863export async function864approveExpectSuccess(865 collectionId: number,866 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,867) {868 await usingApi(async (api: ApiPromise) => {869 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);870 const events = await submitTransactionAsync(owner, approveUniqueTx);871 const result = getGenericResult(events);872 expect(result.success).to.be.true;873874 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));875 });876}877878export async function adminApproveFromExpectSuccess(879 collectionId: number,880 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,881) {882 await usingApi(async (api: ApiPromise) => {883 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);884 const events = await submitTransactionAsync(admin, approveUniqueTx);885 const result = getGenericResult(events);886 expect(result.success).to.be.true;887888 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));889 });890}891892export async function893transferFromExpectSuccess(894 collectionId: number,895 tokenId: number,896 accountApproved: IKeyringPair,897 accountFrom: IKeyringPair | CrossAccountId,898 accountTo: IKeyringPair | CrossAccountId,899 value: number | bigint = 1,900 type = 'NFT',901) {902 await usingApi(async (api: ApiPromise) => {903 const from = normalizeAccountId(accountFrom);904 const to = normalizeAccountId(accountTo);905 let balanceBefore = 0n;906 if (type === 'Fungible' || type === 'ReFungible') {907 balanceBefore = await getBalance(api, collectionId, to, tokenId);908 }909 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);910 const events = await submitTransactionAsync(accountApproved, transferFromTx);911 const result = getCreateItemResult(events);912 913 expect(result.success).to.be.true;914 if (type === 'NFT') {915 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);916 }917 if (type === 'Fungible') {918 const balanceAfter = await getBalance(api, collectionId, to, tokenId);919 if (JSON.stringify(to) !== JSON.stringify(from)) {920 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));921 } else {922 expect(balanceAfter).to.be.equal(balanceBefore);923 }924 }925 if (type === 'ReFungible') {926 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));927 }928 });929}930931export async function932transferFromExpectFail(933 collectionId: number,934 tokenId: number,935 accountApproved: IKeyringPair,936 accountFrom: IKeyringPair,937 accountTo: IKeyringPair,938 value: number | bigint = 1,939) {940 await usingApi(async (api: ApiPromise) => {941 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);942 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;943 const result = getCreateCollectionResult(events);944 945 expect(result.success).to.be.false;946 });947}948949950async function getBlockNumber(api: ApiPromise): Promise<number> {951 return new Promise<number>(async (resolve) => {952 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {953 unsubscribe();954 resolve(head.number.toNumber());955 });956 });957}958959export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {960 await usingApi(async (api) => {961 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));962 const events = await submitTransactionAsync(sender, changeAdminTx);963 const result = getCreateCollectionResult(events);964 expect(result.success).to.be.true;965 });966}967968export async function969getFreeBalance(account: IKeyringPair): Promise<bigint> {970 let balance = 0n;971 await usingApi(async (api) => {972 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());973 });974975 return balance;976}977978export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {979 const tx = api.tx.balances.transfer(target, amount);980 const events = await submitTransactionAsync(source, tx);981 const result = getGenericResult(events);982 expect(result.success).to.be.true;983}984985export async function986scheduleTransferExpectSuccess(987 collectionId: number,988 tokenId: number,989 sender: IKeyringPair,990 recipient: IKeyringPair,991 value: number | bigint = 1,992 blockSchedule: number,993) {994 await usingApi(async (api: ApiPromise) => {995 const blockNumber: number | undefined = await getBlockNumber(api);996 const expectedBlockNumber = blockNumber + blockSchedule;997998 expect(blockNumber).to.be.greaterThan(0);999 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1000 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10011002 await submitTransactionAsync(sender, scheduleTx);10031004 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10051006 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10071008 1009 await waitNewBlocks(blockSchedule + 1);10101011 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1014 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1015 });1016}101710181019export async function1020transferExpectSuccess(1021 collectionId: number,1022 tokenId: number,1023 sender: IKeyringPair,1024 recipient: IKeyringPair | CrossAccountId,1025 value: number | bigint = 1,1026 type = 'NFT',1027) {1028 await usingApi(async (api: ApiPromise) => {1029 const from = normalizeAccountId(sender);1030 const to = normalizeAccountId(recipient);10311032 let balanceBefore = 0n;1033 if (type === 'Fungible') {1034 balanceBefore = await getBalance(api, collectionId, to, tokenId);1035 }1036 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1037 const events = await executeTransaction(api, sender, transferTx);10381039 const result = getTransferResult(api, events);1040 expect(result.collectionId).to.be.equal(collectionId);1041 expect(result.itemId).to.be.equal(tokenId);1042 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1043 expect(result.recipient).to.be.deep.equal(to);1044 expect(result.value).to.be.equal(BigInt(value));10451046 if (type === 'NFT') {1047 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1048 }1049 if (type === 'Fungible') {1050 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1051 if (JSON.stringify(to) !== JSON.stringify(from)) {1052 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1053 } else {1054 expect(balanceAfter).to.be.equal(balanceBefore);1055 }1056 }1057 if (type === 'ReFungible') {1058 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1059 }1060 });1061}10621063export async function1064transferExpectFailure(1065 collectionId: number,1066 tokenId: number,1067 sender: IKeyringPair,1068 recipient: IKeyringPair | CrossAccountId,1069 value: number | bigint = 1,1070) {1071 await usingApi(async (api: ApiPromise) => {1072 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1073 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1074 const result = getGenericResult(events);1075 1076 1077 1078 expect(result.success).to.be.false;1079 1080 });1081}10821083export async function1084approveExpectFail(1085 collectionId: number,1086 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1087) {1088 await usingApi(async (api: ApiPromise) => {1089 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1090 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1091 const result = getCreateCollectionResult(events);1092 1093 expect(result.success).to.be.false;1094 });1095}10961097export async function getBalance(1098 api: ApiPromise,1099 collectionId: number,1100 owner: string | CrossAccountId,1101 token: number,1102): Promise<bigint> {1103 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1104}1105export async function getTokenOwner(1106 api: ApiPromise,1107 collectionId: number,1108 token: number,1109): Promise<CrossAccountId> {1110 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1111 if (owner == null) throw new Error('owner == null');1112 return normalizeAccountId(owner);1113}1114export async function getTopmostTokenOwner(1115 api: ApiPromise,1116 collectionId: number,1117 token: number,1118): Promise<CrossAccountId> {1119 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1120 if (owner == null) throw new Error('owner == null');1121 return normalizeAccountId(owner);1122}1123export async function isTokenExists(1124 api: ApiPromise,1125 collectionId: number,1126 token: number,1127): Promise<boolean> {1128 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1129}1130export async function getLastTokenId(1131 api: ApiPromise,1132 collectionId: number,1133): Promise<number> {1134 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1135}1136export async function getAdminList(1137 api: ApiPromise,1138 collectionId: number,1139): Promise<string[]> {1140 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1141}1142export async function getVariableMetadata(1143 api: ApiPromise,1144 collectionId: number,1145 tokenId: number,1146): Promise<number[]> {1147 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1148}1149export async function getConstMetadata(1150 api: ApiPromise,1151 collectionId: number,1152 tokenId: number,1153): Promise<number[]> {1154 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1155}11561157export async function createFungibleItemExpectSuccess(1158 sender: IKeyringPair,1159 collectionId: number,1160 data: CreateFungibleData,1161 owner: CrossAccountId | string = sender.address,1162) {1163 return await usingApi(async (api) => {1164 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11651166 const events = await submitTransactionAsync(sender, tx);1167 const result = getCreateItemResult(events);11681169 expect(result.success).to.be.true;1170 return result.itemId;1171 });1172}11731174export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1175 let newItemId = 0;1176 await usingApi(async (api) => {1177 const to = normalizeAccountId(owner);1178 const itemCountBefore = await getLastTokenId(api, collectionId);1179 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11801181 let tx;1182 if (createMode === 'Fungible') {1183 const createData = {fungible: {value: 10}};1184 tx = api.tx.unique.createItem(collectionId, to, createData as any);1185 } else if (createMode === 'ReFungible') {1186 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1187 tx = api.tx.unique.createItem(collectionId, to, createData as any);1188 } else {1189 const createData = {nft: {const_data: [], variable_data: []}};1190 tx = api.tx.unique.createItem(collectionId, to, createData as any);1191 }11921193 const events = await submitTransactionAsync(sender, tx);1194 const result = getCreateItemResult(events);11951196 const itemCountAfter = await getLastTokenId(api, collectionId);1197 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11981199 1200 1201 expect(result.success).to.be.true;1202 if (createMode === 'Fungible') {1203 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1204 } else {1205 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1206 }1207 expect(collectionId).to.be.equal(result.collectionId);1208 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1209 expect(to).to.be.deep.equal(result.recipient);1210 newItemId = result.itemId;1211 });1212 return newItemId;1213}12141215export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1216 await usingApi(async (api) => {1217 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12181219 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1220 const result = getCreateItemResult(events);12211222 expect(result.success).to.be.false;1223 });1224}12251226export async function setPublicAccessModeExpectSuccess(1227 sender: IKeyringPair, collectionId: number,1228 accessMode: 'Normal' | 'AllowList',1229) {1230 await usingApi(async (api) => {12311232 1233 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1234 const events = await submitTransactionAsync(sender, tx);1235 const result = getGenericResult(events);12361237 1238 const collection = await queryCollectionExpectSuccess(api, collectionId);12391240 1241 1242 expect(result.success).to.be.true;1243 expect(collection.access.toHuman()).to.be.equal(accessMode);1244 });1245}12461247export async function setPublicAccessModeExpectFail(1248 sender: IKeyringPair, collectionId: number,1249 accessMode: 'Normal' | 'AllowList',1250) {1251 await usingApi(async (api) => {12521253 1254 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1255 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1256 const result = getGenericResult(events);12571258 1259 1260 expect(result.success).to.be.false;1261 });1262}12631264export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1265 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1266}12671268export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1269 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1270}12711272export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1273 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1274}12751276export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1277 await usingApi(async (api) => {12781279 1280 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1281 const events = await submitTransactionAsync(sender, tx);1282 const result = getGenericResult(events);1283 expect(result.success).to.be.true;12841285 1286 const collection = await queryCollectionExpectSuccess(api, collectionId);12871288 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1289 });1290}12911292export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1293 await setMintPermissionExpectSuccess(sender, collectionId, true);1294}12951296export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1297 await usingApi(async (api) => {1298 1299 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1300 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1301 const result = getCreateCollectionResult(events);1302 1303 expect(result.success).to.be.false;1304 });1305}13061307export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1308 await usingApi(async (api) => {1309 1310 const tx = api.tx.unique.setChainLimits(limits);1311 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1312 const result = getCreateCollectionResult(events);1313 1314 expect(result.success).to.be.false;1315 });1316}13171318export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1319 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1320}13211322export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1323 await usingApi(async (api) => {1324 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13251326 1327 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1328 const events = await submitTransactionAsync(sender, tx);1329 const result = getGenericResult(events);1330 expect(result.success).to.be.true;13311332 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1333 });1334}13351336export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1337 await usingApi(async (api) => {13381339 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13401341 1342 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1343 const events = await submitTransactionAsync(sender, tx);1344 const result = getGenericResult(events);1345 expect(result.success).to.be.true;13461347 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1348 });1349}13501351export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1352 await usingApi(async (api) => {13531354 1355 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1356 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357 const result = getGenericResult(events);13581359 1360 1361 expect(result.success).to.be.false;1362 });1363}13641365export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1366 await usingApi(async (api) => {1367 1368 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1369 const events = await submitTransactionAsync(sender, tx);1370 const result = getGenericResult(events);13711372 1373 1374 expect(result.success).to.be.true;1375 });1376}13771378export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1379 await usingApi(async (api) => {1380 1381 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1382 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1383 const result = getGenericResult(events);13841385 1386 1387 expect(result.success).to.be.false;1388 });1389}13901391export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1392 : Promise<UpDataStructsRpcCollection | null> => {1393 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1394};13951396export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1397 1398 return (await api.rpc.unique.collectionStats()).created.toNumber();1399};14001401export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1402 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1403}14041405export async function waitNewBlocks(blocksCount = 1): Promise<void> {1406 await usingApi(async (api) => {1407 const promise = new Promise<void>(async (resolve) => {1408 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1409 if (blocksCount > 0) {1410 blocksCount--;1411 } else {1412 unsubscribe();1413 resolve();1414 }1415 });1416 });1417 return promise;1418 });1419}