1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {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, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} 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 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209 events.forEach(({event: {data, method, section}}) => {210 211 if (method == 'ExtrinsicSuccess') {212 success = true;213 } else if ((section == 'common') && (method == 'ItemCreated')) {214 collectionId = parseInt(data[0].toString(), 10);215 itemId = parseInt(data[1].toString(), 10);216 recipient = normalizeAccountId(data[2].toJSON() as any);217 }218 });219 const result: CreateItemResult = {220 success,221 collectionId,222 itemId,223 recipient,224 };225 return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229 const result: TransferResult = {230 success: false,231 collectionId: 0,232 itemId: 0,233 value: 0n,234 };235236 events.forEach(({event: {data, method, section}}) => {237 if (method === 'ExtrinsicSuccess') {238 result.success = true;239 } else if (section === 'common' && method === 'Transfer') {240 result.collectionId = +data[0].toString();241 result.itemId = +data[1].toString();242 result.sender = normalizeAccountId(data[2].toJSON() as any);243 result.recipient = normalizeAccountId(data[3].toJSON() as any);244 result.value = BigInt(data[4].toString());245 }246 });247248 return result;249}250251interface Nft {252 type: 'NFT';253}254255interface Fungible {256 type: 'Fungible';257 decimalPoints: number;258}259260interface ReFungible {261 type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267 mode: CollectionMode,268 name: string,269 description: string,270 tokenPrefix: string,271 schemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275 description: 'description',276 mode: {type: 'NFT'},277 name: 'name',278 tokenPrefix: 'prefix',279 schemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};284285 let collectionId = 0;286 await usingApi(async (api) => {287 288 const collectionCountBefore = await getCreatedCollectionCount(api);289290 291 const alicePrivateKey = privateKey('//Alice');292293 let modeprm = {};294 if (mode.type === 'NFT') {295 modeprm = {nft: null};296 } else if (mode.type === 'Fungible') {297 modeprm = {fungible: mode.decimalPoints};298 } else if (mode.type === 'ReFungible') {299 modeprm = {refungible: null};300 }301302 const tx = api.tx.unique.createCollectionEx({303 name: strToUTF16(name), 304 description: strToUTF16(description), 305 tokenPrefix: strToUTF16(tokenPrefix), 306 mode: modeprm as any,307 schemaVersion: schemaVersion,308 });309 const events = await submitTransactionAsync(alicePrivateKey, tx);310 const result = getCreateCollectionResult(events);311312 313 const collectionCountAfter = await getCreatedCollectionCount(api);314315 316 const collection = await queryCollectionExpectSuccess(api, result.collectionId);317318 319 320 expect(result.success).to.be.true;321 expect(result.collectionId).to.be.equal(collectionCountAfter);322 323 expect(collection).to.be.not.null;324 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');325 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));326 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);327 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);328 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);329330 collectionId = result.collectionId;331 });332333 return collectionId;334}335336export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {337 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};338339 let modeprm = {};340 if (mode.type === 'NFT') {341 modeprm = {nft: null};342 } else if (mode.type === 'Fungible') {343 modeprm = {fungible: mode.decimalPoints};344 } else if (mode.type === 'ReFungible') {345 modeprm = {refungible: null};346 }347348 await usingApi(async (api) => {349 350 const collectionCountBefore = await getCreatedCollectionCount(api);351352 353 const alicePrivateKey = privateKey('//Alice');354 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});355 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356357 358 const collectionCountAfter = await getCreatedCollectionCount(api);359360 361 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');362 });363}364365export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {366 let bal = 0n;367 let unused;368 do {369 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;370 const keyring = new Keyring({type: 'sr25519'});371 unused = keyring.addFromUri(`//${randomSeed}`);372 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();373 } while (bal !== 0n);374 return unused;375}376377export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {378 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();379}380381export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {382 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));383}384385export async function findNotExistingCollection(api: ApiPromise): Promise<number> {386 const totalNumber = await getCreatedCollectionCount(api);387 const newCollection: number = totalNumber + 1;388 return newCollection;389}390391function getDestroyResult(events: EventRecord[]): boolean {392 let success = false;393 events.forEach(({event: {method}}) => {394 if (method == 'ExtrinsicSuccess') {395 success = true;396 }397 });398 return success;399}400401export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {402 await usingApi(async (api) => {403 404 const alicePrivateKey = privateKey(senderSeed);405 const tx = api.tx.unique.destroyCollection(collectionId);406 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;407 });408}409410export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {411 await usingApi(async (api) => {412 413 const alicePrivateKey = privateKey(senderSeed);414 const tx = api.tx.unique.destroyCollection(collectionId);415 const events = await submitTransactionAsync(alicePrivateKey, tx);416 const result = getDestroyResult(events);417 expect(result).to.be.true;418419 420 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;421 });422}423424export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {425 await usingApi(async (api) => {426 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);427 const events = await submitTransactionAsync(sender, tx);428 const result = getGenericResult(events);429430 expect(result.success).to.be.true;431 });432}433434export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {435 await usingApi(async (api) => {436 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);437 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438 const result = getGenericResult(events);439440 expect(result.success).to.be.false;441 });442}443444export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {445 await usingApi(async (api) => {446447 448 const senderPrivateKey = privateKey(sender);449 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);450 const events = await submitTransactionAsync(senderPrivateKey, tx);451 const result = getGenericResult(events);452453 454 const collection = await queryCollectionExpectSuccess(api, collectionId);455456 457 expect(result.success).to.be.true;458 expect(collection.sponsorship.toJSON()).to.deep.equal({459 unconfirmed: sponsor,460 });461 });462}463464export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {465 await usingApi(async (api) => {466467 468 const alicePrivateKey = privateKey(sender);469 const tx = api.tx.unique.removeCollectionSponsor(collectionId);470 const events = await submitTransactionAsync(alicePrivateKey, tx);471 const result = getGenericResult(events);472473 474 const collection = await queryCollectionExpectSuccess(api, collectionId);475476 477 expect(result.success).to.be.true;478 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});479 });480}481482export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {483 await usingApi(async (api) => {484485 486 const alicePrivateKey = privateKey(senderSeed);487 const tx = api.tx.unique.removeCollectionSponsor(collectionId);488 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489 });490}491492export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {493 await usingApi(async (api) => {494495 496 const alicePrivateKey = privateKey(senderSeed);497 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);498 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;499 });500}501502export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {503 await usingApi(async () => {504 const sender = privateKey(senderSeed);505 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);506 });507}508509export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {510 await usingApi(async (api) => {511512 513 const tx = api.tx.unique.confirmSponsorship(collectionId);514 const events = await submitTransactionAsync(sender, tx);515 const result = getGenericResult(events);516517 518 const collection = await queryCollectionExpectSuccess(api, collectionId);519520 521 expect(result.success).to.be.true;522 expect(collection.sponsorship.toJSON()).to.be.deep.equal({523 confirmed: sender.address,524 });525 });526}527528529export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {530 await usingApi(async (api) => {531532 533 const sender = privateKey(senderSeed);534 const tx = api.tx.unique.confirmSponsorship(collectionId);535 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536 });537}538539export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {540541 await usingApi(async (api) => {542 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);543 const events = await submitTransactionAsync(sender, tx);544 const result = getGenericResult(events);545546 expect(result.success).to.be.true;547 });548}549550export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {551552 await usingApi(async (api) => {553 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);554 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;555 const result = getGenericResult(events);556557 expect(result.success).to.be.false;558 });559}560561export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {562 await usingApi(async (api) => {563 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);564 const events = await submitTransactionAsync(sender, tx);565 const result = getGenericResult(events);566567 expect(result.success).to.be.true;568 });569}570571export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {572 await usingApi(async (api) => {573 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);574 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;575 const result = getGenericResult(events);576577 expect(result.success).to.be.false;578 });579}580581export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {582583 await usingApi(async (api) => {584585 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);586 const events = await submitTransactionAsync(sender, tx);587 const result = getGenericResult(events);588589 expect(result.success).to.be.true;590 });591}592593export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {594595 await usingApi(async (api) => {596597 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);598 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;599 const result = getGenericResult(events);600601 expect(result.success).to.be.false;602 });603}604605export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {606 await usingApi(async (api) => {607 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);608 const events = await submitTransactionAsync(sender, tx);609 const result = getGenericResult(events);610611 expect(result.success).to.be.true;612 });613}614615export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {616 await usingApi(async (api) => {617 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);618 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;619 const result = getGenericResult(events);620621 expect(result.success).to.be.false;622 });623}624625export async function getNextSponsored(626 api: ApiPromise,627 collectionId: number,628 account: string | CrossAccountId,629 tokenId: number,630): Promise<number> {631 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));632}633634export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {635 await usingApi(async (api) => {636 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);637 const events = await submitTransactionAsync(sender, tx);638 const result = getGenericResult(events);639640 expect(result.success).to.be.true;641 });642}643644export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {645 let allowlisted = false;646 await usingApi(async (api) => {647 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;648 });649 return allowlisted;650}651652export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {653 await usingApi(async (api) => {654 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());655 const events = await submitTransactionAsync(sender, tx);656 const result = getGenericResult(events);657658 expect(result.success).to.be.true;659 });660}661662export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {663 await usingApi(async (api) => {664 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());665 const events = await submitTransactionAsync(sender, tx);666 const result = getGenericResult(events);667668 expect(result.success).to.be.true;669 });670}671672export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {673 await usingApi(async (api) => {674 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());675 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;676 const result = getGenericResult(events);677678 expect(result.success).to.be.false;679 });680}681682export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {683 await usingApi(async (api) => {684 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));685 const events = await submitTransactionAsync(sender, tx);686 const result = getGenericResult(events);687688 expect(result.success).to.be.true;689 });690}691692export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {693 await usingApi(async (api) => {694 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));695 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;696 });697}698699export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {700 await usingApi(async (api) => {701 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));702 const events = await submitTransactionAsync(sender, tx);703 const result = getGenericResult(events);704705 expect(result.success).to.be.true;706 });707}708709export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {710 await usingApi(async (api) => {711 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));712 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;713 });714}715716export interface CreateFungibleData {717 readonly Value: bigint;718}719720export interface CreateReFungibleData { }721export interface CreateNftData { }722723export type CreateItemData = {724 NFT: CreateNftData;725} | {726 Fungible: CreateFungibleData;727} | {728 ReFungible: CreateReFungibleData;729};730731export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {732 await usingApi(async (api) => {733 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);734 735 expect(balanceBefore >= BigInt(value)).to.be.true;736737 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);738 const events = await submitTransactionAsync(sender, tx);739 const result = getGenericResult(events);740 expect(result.success).to.be.true;741742 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);743 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);744 });745}746747export async function748approveExpectSuccess(749 collectionId: number,750 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,751) {752 await usingApi(async (api: ApiPromise) => {753 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);754 const events = await submitTransactionAsync(owner, approveUniqueTx);755 const result = getGenericResult(events);756 expect(result.success).to.be.true;757758 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));759 });760}761762export async function adminApproveFromExpectSuccess(763 collectionId: number,764 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,765) {766 await usingApi(async (api: ApiPromise) => {767 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);768 const events = await submitTransactionAsync(admin, approveUniqueTx);769 const result = getGenericResult(events);770 expect(result.success).to.be.true;771772 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));773 });774}775776export async function777transferFromExpectSuccess(778 collectionId: number,779 tokenId: number,780 accountApproved: IKeyringPair,781 accountFrom: IKeyringPair | CrossAccountId,782 accountTo: IKeyringPair | CrossAccountId,783 value: number | bigint = 1,784 type = 'NFT',785) {786 await usingApi(async (api: ApiPromise) => {787 const from = normalizeAccountId(accountFrom);788 const to = normalizeAccountId(accountTo);789 let balanceBefore = 0n;790 if (type === 'Fungible') {791 balanceBefore = await getBalance(api, collectionId, to, tokenId);792 }793 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);794 const events = await submitTransactionAsync(accountApproved, transferFromTx);795 const result = getCreateItemResult(events);796 797 expect(result.success).to.be.true;798 if (type === 'NFT') {799 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);800 }801 if (type === 'Fungible') {802 const balanceAfter = await getBalance(api, collectionId, to, tokenId);803 if (JSON.stringify(to) !== JSON.stringify(from)) {804 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));805 } else {806 expect(balanceAfter).to.be.equal(balanceBefore);807 }808 }809 if (type === 'ReFungible') {810 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));811 }812 });813}814815export async function816transferFromExpectFail(817 collectionId: number,818 tokenId: number,819 accountApproved: IKeyringPair,820 accountFrom: IKeyringPair,821 accountTo: IKeyringPair,822 value: number | bigint = 1,823) {824 await usingApi(async (api: ApiPromise) => {825 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);826 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;827 const result = getCreateCollectionResult(events);828 829 expect(result.success).to.be.false;830 });831}832833834export async function getBlockNumber(api: ApiPromise): Promise<number> {835 return new Promise<number>(async (resolve) => {836 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {837 unsubscribe();838 resolve(head.number.toNumber());839 });840 });841}842843export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {844 await usingApi(async (api) => {845 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));846 const events = await submitTransactionAsync(sender, changeAdminTx);847 const result = getCreateCollectionResult(events);848 expect(result.success).to.be.true;849 });850}851852export async function853getFreeBalance(account: IKeyringPair): Promise<bigint> {854 let balance = 0n;855 await usingApi(async (api) => {856 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());857 });858859 return balance;860}861862export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {863 const tx = api.tx.balances.transfer(target, amount);864 const events = await submitTransactionAsync(source, tx);865 const result = getGenericResult(events);866 expect(result.success).to.be.true;867}868869export async function870scheduleExpectSuccess(871 operationTx: any,872 sender: IKeyringPair,873 blockSchedule: number,874 scheduledId: string,875 period = 1,876 repetitions = 1,877) {878 await usingApi(async (api: ApiPromise) => {879 const blockNumber: number | undefined = await getBlockNumber(api);880 const expectedBlockNumber = blockNumber + blockSchedule;881882 expect(blockNumber).to.be.greaterThan(0);883 const scheduleTx = api.tx.scheduler.scheduleNamed( 884 scheduledId,885 expectedBlockNumber, 886 repetitions > 1 ? [period, repetitions] : null, 887 0, 888 {value: operationTx as any},889 );890891 const events = await submitTransactionAsync(sender, scheduleTx);892 expect(getGenericResult(events).success).to.be.true;893 });894}895896export async function897scheduleExpectFailure(898 operationTx: any,899 sender: IKeyringPair,900 blockSchedule: number,901 scheduledId: string,902 period = 1,903 repetitions = 1,904) {905 await usingApi(async (api: ApiPromise) => {906 const blockNumber: number | undefined = await getBlockNumber(api);907 const expectedBlockNumber = blockNumber + blockSchedule;908909 expect(blockNumber).to.be.greaterThan(0);910 const scheduleTx = api.tx.scheduler.scheduleNamed( 911 scheduledId,912 expectedBlockNumber, 913 repetitions <= 1 ? null : [period, repetitions], 914 0, 915 {value: operationTx as any},916 );917918 919 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;920 921 });922}923924export async function925scheduleTransferAndWaitExpectSuccess(926 collectionId: number,927 tokenId: number,928 sender: IKeyringPair,929 recipient: IKeyringPair,930 value: number | bigint = 1,931 blockSchedule: number,932 scheduledId: string,933) {934 await usingApi(async (api: ApiPromise) => {935 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);936937 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();938939 940 await waitNewBlocks(blockSchedule + 1);941942 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();943944 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));945 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);946 });947}948949export async function950scheduleTransferExpectSuccess(951 collectionId: number,952 tokenId: number,953 sender: IKeyringPair,954 recipient: IKeyringPair,955 value: number | bigint = 1,956 blockSchedule: number,957 scheduledId: string,958) {959 await usingApi(async (api: ApiPromise) => {960 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);961962 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);963964 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));965 });966}967968export async function969scheduleTransferFundsPeriodicExpectSuccess(970 amount: bigint,971 sender: IKeyringPair,972 recipient: IKeyringPair,973 blockSchedule: number,974 scheduledId: string,975 period: number,976 repetitions: number,977) {978 await usingApi(async (api: ApiPromise) => {979 const transferTx = api.tx.balances.transfer(recipient.address, amount);980981 const balanceBefore = await getFreeBalance(recipient);982 983 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);984985 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);986 });987}988989export async function990transferExpectSuccess(991 collectionId: number,992 tokenId: number,993 sender: IKeyringPair,994 recipient: IKeyringPair | CrossAccountId,995 value: number | bigint = 1,996 type = 'NFT',997) {998 await usingApi(async (api: ApiPromise) => {999 const from = normalizeAccountId(sender);1000 const to = normalizeAccountId(recipient);10011002 let balanceBefore = 0n;1003 if (type === 'Fungible') {1004 balanceBefore = await getBalance(api, collectionId, to, tokenId);1005 }1006 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1007 const events = await submitTransactionAsync(sender, transferTx);1008 const result = getTransferResult(events);1009 1010 expect(result.success).to.be.true;1011 expect(result.collectionId).to.be.equal(collectionId);1012 expect(result.itemId).to.be.equal(tokenId);1013 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1014 expect(result.recipient).to.be.deep.equal(to);1015 expect(result.value).to.be.equal(BigInt(value));1016 if (type === 'NFT') {1017 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1018 }1019 if (type === 'Fungible') {1020 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1021 if (JSON.stringify(to) !== JSON.stringify(from)) {1022 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1023 } else {1024 expect(balanceAfter).to.be.equal(balanceBefore);1025 }1026 }1027 if (type === 'ReFungible') {1028 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1029 }1030 });1031}10321033export async function1034transferExpectFailure(1035 collectionId: number,1036 tokenId: number,1037 sender: IKeyringPair,1038 recipient: IKeyringPair,1039 value: number | bigint = 1,1040) {1041 await usingApi(async (api: ApiPromise) => {1042 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1043 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1044 const result = getGenericResult(events);1045 1046 1047 1048 expect(result.success).to.be.false;1049 1050 });1051}10521053export async function1054approveExpectFail(1055 collectionId: number,1056 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1057) {1058 await usingApi(async (api: ApiPromise) => {1059 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1060 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1061 const result = getCreateCollectionResult(events);1062 1063 expect(result.success).to.be.false;1064 });1065}10661067export async function getBalance(1068 api: ApiPromise,1069 collectionId: number,1070 owner: string | CrossAccountId,1071 token: number,1072): Promise<bigint> {1073 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1074}1075export async function getTokenOwner(1076 api: ApiPromise,1077 collectionId: number,1078 token: number,1079): Promise<CrossAccountId> {1080 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);1081}1082export async function isTokenExists(1083 api: ApiPromise,1084 collectionId: number,1085 token: number,1086): Promise<boolean> {1087 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1088}1089export async function getLastTokenId(1090 api: ApiPromise,1091 collectionId: number,1092): Promise<number> {1093 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1094}1095export async function getAdminList(1096 api: ApiPromise,1097 collectionId: number,1098): Promise<string[]> {1099 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1100}1101export async function getVariableMetadata(1102 api: ApiPromise,1103 collectionId: number,1104 tokenId: number,1105): Promise<number[]> {1106 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1107}1108export async function getConstMetadata(1109 api: ApiPromise,1110 collectionId: number,1111 tokenId: number,1112): Promise<number[]> {1113 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1114}11151116export async function createFungibleItemExpectSuccess(1117 sender: IKeyringPair,1118 collectionId: number,1119 data: CreateFungibleData,1120 owner: CrossAccountId | string = sender.address,1121) {1122 return await usingApi(async (api) => {1123 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11241125 const events = await submitTransactionAsync(sender, tx);1126 const result = getCreateItemResult(events);11271128 expect(result.success).to.be.true;1129 return result.itemId;1130 });1131}11321133export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1134 let newItemId = 0;1135 await usingApi(async (api) => {1136 const to = normalizeAccountId(owner);1137 const itemCountBefore = await getLastTokenId(api, collectionId);1138 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11391140 let tx;1141 if (createMode === 'Fungible') {1142 const createData = {fungible: {value: 10}};1143 tx = api.tx.unique.createItem(collectionId, to, createData as any);1144 } else if (createMode === 'ReFungible') {1145 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1146 tx = api.tx.unique.createItem(collectionId, to, createData as any);1147 } else {1148 const createData = {nft: {const_data: [], variable_data: []}};1149 tx = api.tx.unique.createItem(collectionId, to, createData as any);1150 }11511152 const events = await submitTransactionAsync(sender, tx);1153 const result = getCreateItemResult(events);11541155 const itemCountAfter = await getLastTokenId(api, collectionId);1156 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11571158 1159 1160 expect(result.success).to.be.true;1161 if (createMode === 'Fungible') {1162 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1163 } else {1164 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1165 }1166 expect(collectionId).to.be.equal(result.collectionId);1167 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1168 expect(to).to.be.deep.equal(result.recipient);1169 newItemId = result.itemId;1170 });1171 return newItemId;1172}11731174export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1175 await usingApi(async (api) => {1176 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11771178 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179 const result = getCreateItemResult(events);11801181 expect(result.success).to.be.false;1182 });1183}11841185export async function setPublicAccessModeExpectSuccess(1186 sender: IKeyringPair, collectionId: number,1187 accessMode: 'Normal' | 'AllowList',1188) {1189 await usingApi(async (api) => {11901191 1192 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1193 const events = await submitTransactionAsync(sender, tx);1194 const result = getGenericResult(events);11951196 1197 const collection = await queryCollectionExpectSuccess(api, collectionId);11981199 1200 1201 expect(result.success).to.be.true;1202 expect(collection.access.toHuman()).to.be.equal(accessMode);1203 });1204}12051206export async function setPublicAccessModeExpectFail(1207 sender: IKeyringPair, collectionId: number,1208 accessMode: 'Normal' | 'AllowList',1209) {1210 await usingApi(async (api) => {12111212 1213 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1214 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1215 const result = getGenericResult(events);12161217 1218 1219 expect(result.success).to.be.false;1220 });1221}12221223export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1224 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1225}12261227export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1228 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1229}12301231export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1232 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1233}12341235export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1236 await usingApi(async (api) => {12371238 1239 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1240 const events = await submitTransactionAsync(sender, tx);1241 const result = getGenericResult(events);1242 expect(result.success).to.be.true;12431244 1245 const collection = await queryCollectionExpectSuccess(api, collectionId);12461247 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1248 });1249}12501251export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1252 await setMintPermissionExpectSuccess(sender, collectionId, true);1253}12541255export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1256 await usingApi(async (api) => {1257 1258 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1259 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1260 const result = getCreateCollectionResult(events);1261 1262 expect(result.success).to.be.false;1263 });1264}12651266export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1267 await usingApi(async (api) => {1268 1269 const tx = api.tx.unique.setChainLimits(limits);1270 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1271 const result = getCreateCollectionResult(events);1272 1273 expect(result.success).to.be.false;1274 });1275}12761277export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1278 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1279}12801281export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1282 await usingApi(async (api) => {1283 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12841285 1286 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1287 const events = await submitTransactionAsync(sender, tx);1288 const result = getGenericResult(events);1289 expect(result.success).to.be.true;12901291 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1292 });1293}12941295export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1296 await usingApi(async (api) => {12971298 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12991300 1301 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1302 const events = await submitTransactionAsync(sender, tx);1303 const result = getGenericResult(events);1304 expect(result.success).to.be.true;13051306 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1307 });1308}13091310export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1311 await usingApi(async (api) => {13121313 1314 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1315 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1316 const result = getGenericResult(events);13171318 1319 1320 expect(result.success).to.be.false;1321 });1322}13231324export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1325 await usingApi(async (api) => {1326 1327 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1328 const events = await submitTransactionAsync(sender, tx);1329 const result = getGenericResult(events);13301331 1332 1333 expect(result.success).to.be.true;1334 });1335}13361337export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1338 await usingApi(async (api) => {1339 1340 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1341 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1342 const result = getGenericResult(events);13431344 1345 1346 expect(result.success).to.be.false;1347 });1348}13491350export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1351 : Promise<UpDataStructsCollection | null> => {1352 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1353};13541355export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1356 1357 return (await api.rpc.unique.collectionStats()).created.toNumber();1358};13591360export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1361 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1362}13631364export async function waitNewBlocks(blocksCount = 1): Promise<void> {1365 await usingApi(async (api) => {1366 const promise = new Promise<void>(async (resolve) => {1367 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1368 if (blocksCount > 0) {1369 blocksCount--;1370 } else {1371 unsubscribe();1372 resolve();1373 }1374 });1375 });1376 return promise;1377 });1378}