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 variableOnChainSchemaLimit: number;140 constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144 owner: IReFungibleOwner[];145 constData: number[];146 variableData: number[];147}148149export function uniqueEventMessage(events: EventRecord[]): IGetMessage {150 let checkMsgUnqMethod = '';151 let checkMsgTrsMethod = '';152 let checkMsgSysMethod = '';153 events.forEach(({event: {method, section}}) => {154 if (section === 'common') {155 checkMsgUnqMethod = method;156 } else if (section === 'treasury') {157 checkMsgTrsMethod = method;158 } else if (section === 'system') {159 checkMsgSysMethod = method;160 } else { return null; }161 });162 const result: IGetMessage = {163 checkMsgUnqMethod,164 checkMsgTrsMethod,165 checkMsgSysMethod,166 };167 return result;168}169170export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {171 const event = events.find(r => check(r.event));172 if (!event) return;173 return event.event as T;174}175176export function getGenericResult(events: EventRecord[]): GenericResult {177 const result: GenericResult = {178 success: false,179 };180 events.forEach(({event: {method}}) => {181 182 if (method === 'ExtrinsicSuccess') {183 result.success = true;184 }185 });186 return result;187}188189190191export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {192 let success = false;193 let collectionId = 0;194 events.forEach(({event: {data, method, section}}) => {195 196 if (method == 'ExtrinsicSuccess') {197 success = true;198 } else if ((section == 'common') && (method == 'CollectionCreated')) {199 collectionId = parseInt(data[0].toString(), 10);200 }201 });202 const result: CreateCollectionResult = {203 success,204 collectionId,205 };206 return result;207}208209export function getCreateItemResult(events: EventRecord[]): CreateItemResult {210 let success = false;211 let collectionId = 0;212 let itemId = 0;213 let recipient;214 events.forEach(({event: {data, method, section}}) => {215 216 if (method == 'ExtrinsicSuccess') {217 success = true;218 } else if ((section == 'common') && (method == 'ItemCreated')) {219 collectionId = parseInt(data[0].toString(), 10);220 itemId = parseInt(data[1].toString(), 10);221 recipient = normalizeAccountId(data[2].toJSON() as any);222 }223 });224 const result: CreateItemResult = {225 success,226 collectionId,227 itemId,228 recipient,229 };230 return result;231}232233export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {234 for (const {event} of events) {235 if (api.events.common.Transfer.is(event)) {236 const [collection, token, sender, recipient, value] = event.data;237 return {238 collectionId: collection.toNumber(),239 itemId: token.toNumber(),240 sender: normalizeAccountId(sender.toJSON() as any),241 recipient: normalizeAccountId(recipient.toJSON() as any),242 value: value.toBigInt(),243 };244 }245 }246 throw new Error('no transfer event');247}248249interface Nft {250 type: 'NFT';251}252253interface Fungible {254 type: 'Fungible';255 decimalPoints: number;256}257258interface ReFungible {259 type: 'ReFungible';260}261262type CollectionMode = Nft | Fungible | ReFungible;263264export type CreateCollectionParams = {265 mode: CollectionMode,266 name: string,267 description: string,268 tokenPrefix: string,269 schemaVersion: string,270};271272const defaultCreateCollectionParams: CreateCollectionParams = {273 description: 'description',274 mode: {type: 'NFT'},275 name: 'name',276 tokenPrefix: 'prefix',277 schemaVersion: 'ImageURL',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};282283 let collectionId = 0;284 await usingApi(async (api) => {285 286 const collectionCountBefore = await getCreatedCollectionCount(api);287288 289 const alicePrivateKey = privateKey('//Alice');290291 let modeprm = {};292 if (mode.type === 'NFT') {293 modeprm = {nft: null};294 } else if (mode.type === 'Fungible') {295 modeprm = {fungible: mode.decimalPoints};296 } else if (mode.type === 'ReFungible') {297 modeprm = {refungible: null};298 }299300 const tx = api.tx.unique.createCollectionEx({301 name: strToUTF16(name),302 description: strToUTF16(description),303 tokenPrefix: strToUTF16(tokenPrefix),304 mode: modeprm as any,305 schemaVersion: schemaVersion,306 });307 const events = await submitTransactionAsync(alicePrivateKey, tx);308 const result = getCreateCollectionResult(events);309310 311 const collectionCountAfter = await getCreatedCollectionCount(api);312313 314 const collection = await queryCollectionExpectSuccess(api, result.collectionId);315316 317 318 expect(result.success).to.be.true;319 expect(result.collectionId).to.be.equal(collectionCountAfter);320 321 expect(collection).to.be.not.null;322 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');323 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));324 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);325 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);326 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);327328 collectionId = result.collectionId;329 });330331 return collectionId;332}333334export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {335 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};336337 let modeprm = {};338 if (mode.type === 'NFT') {339 modeprm = {nft: null};340 } else if (mode.type === 'Fungible') {341 modeprm = {fungible: mode.decimalPoints};342 } else if (mode.type === 'ReFungible') {343 modeprm = {refungible: null};344 }345346 await usingApi(async (api) => {347 348 const collectionCountBefore = await getCreatedCollectionCount(api);349350 351 const alicePrivateKey = privateKey('//Alice');352 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});353 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;354355 356 const collectionCountAfter = await getCreatedCollectionCount(api);357358 359 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');360 });361}362363export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {364 let bal = 0n;365 let unused;366 do {367 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;368 const keyring = new Keyring({type: 'sr25519'});369 unused = keyring.addFromUri(`//${randomSeed}`);370 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();371 } while (bal !== 0n);372 return unused;373}374375export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {376 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();377}378379export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {380 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));381}382383export async function findNotExistingCollection(api: ApiPromise): Promise<number> {384 const totalNumber = await getCreatedCollectionCount(api);385 const newCollection: number = totalNumber + 1;386 return newCollection;387}388389function getDestroyResult(events: EventRecord[]): boolean {390 let success = false;391 events.forEach(({event: {method}}) => {392 if (method == 'ExtrinsicSuccess') {393 success = true;394 }395 });396 return success;397}398399export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {400 await usingApi(async (api) => {401 402 const alicePrivateKey = privateKey(senderSeed);403 const tx = api.tx.unique.destroyCollection(collectionId);404 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;405 });406}407408export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {409 await usingApi(async (api) => {410 411 const alicePrivateKey = privateKey(senderSeed);412 const tx = api.tx.unique.destroyCollection(collectionId);413 const events = await submitTransactionAsync(alicePrivateKey, tx);414 const result = getDestroyResult(events);415 expect(result).to.be.true;416417 418 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;419 });420}421422export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {423 await usingApi(async (api) => {424 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);425 const events = await submitTransactionAsync(sender, tx);426 const result = getGenericResult(events);427428 expect(result.success).to.be.true;429 });430}431432export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {433 await usingApi(async (api) => {434 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);435 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;436 const result = getGenericResult(events);437438 expect(result.success).to.be.false;439 });440}441442export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {443 await usingApi(async (api) => {444445 446 const senderPrivateKey = privateKey(sender);447 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);448 const events = await submitTransactionAsync(senderPrivateKey, tx);449 const result = getGenericResult(events);450451 452 const collection = await queryCollectionExpectSuccess(api, collectionId);453454 455 expect(result.success).to.be.true;456 expect(collection.sponsorship.toJSON()).to.deep.equal({457 unconfirmed: sponsor,458 });459 });460}461462export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {463 await usingApi(async (api) => {464465 466 const alicePrivateKey = privateKey(sender);467 const tx = api.tx.unique.removeCollectionSponsor(collectionId);468 const events = await submitTransactionAsync(alicePrivateKey, tx);469 const result = getGenericResult(events);470471 472 const collection = await queryCollectionExpectSuccess(api, collectionId);473474 475 expect(result.success).to.be.true;476 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});477 });478}479480export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {481 await usingApi(async (api) => {482483 484 const alicePrivateKey = privateKey(senderSeed);485 const tx = api.tx.unique.removeCollectionSponsor(collectionId);486 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;487 });488}489490export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {491 await usingApi(async (api) => {492493 494 const alicePrivateKey = privateKey(senderSeed);495 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);496 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;497 });498}499500export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {501 await usingApi(async (api) => {502503 504 const sender = privateKey(senderSeed);505 const tx = api.tx.unique.confirmSponsorship(collectionId);506 const events = await submitTransactionAsync(sender, tx);507 const result = getGenericResult(events);508509 510 const collection = await queryCollectionExpectSuccess(api, collectionId);511512 513 expect(result.success).to.be.true;514 expect(collection.sponsorship.toJSON()).to.be.deep.equal({515 confirmed: sender.address,516 });517 });518}519520521export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {522 await usingApi(async (api) => {523524 525 const sender = privateKey(senderSeed);526 const tx = api.tx.unique.confirmSponsorship(collectionId);527 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;528 });529}530531export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {532533 await usingApi(async (api) => {534 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);535 const events = await submitTransactionAsync(sender, tx);536 const result = getGenericResult(events);537538 expect(result.success).to.be.true;539 });540}541542export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {543544 await usingApi(async (api) => {545 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);546 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;547 const result = getGenericResult(events);548549 expect(result.success).to.be.false;550 });551}552553export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {554 await usingApi(async (api) => {555 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {564 await usingApi(async (api) => {565 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);566 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567 const result = getGenericResult(events);568569 expect(result.success).to.be.false;570 });571}572573export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {574575 await usingApi(async (api) => {576577 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);578 const events = await submitTransactionAsync(sender, tx);579 const result = getGenericResult(events);580581 expect(result.success).to.be.true;582 });583}584585export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {586587 await usingApi(async (api) => {588589 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);590 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;591 const result = getGenericResult(events);592593 expect(result.success).to.be.false;594 });595}596597export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {598 await usingApi(async (api) => {599 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);600 const events = await submitTransactionAsync(sender, tx);601 const result = getGenericResult(events);602603 expect(result.success).to.be.true;604 });605}606607export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {608 await usingApi(async (api) => {609 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);610 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;611 const result = getGenericResult(events);612613 expect(result.success).to.be.false;614 });615}616617export async function getNextSponsored(618 api: ApiPromise,619 collectionId: number,620 account: string | CrossAccountId,621 tokenId: number,622): Promise<number> {623 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));624}625626export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {627 await usingApi(async (api) => {628 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);629 const events = await submitTransactionAsync(sender, tx);630 const result = getGenericResult(events);631632 expect(result.success).to.be.true;633 });634}635636export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {637 let allowlisted = false;638 await usingApi(async (api) => {639 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;640 });641 return allowlisted;642}643644export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {645 await usingApi(async (api) => {646 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());647 const events = await submitTransactionAsync(sender, tx);648 const result = getGenericResult(events);649650 expect(result.success).to.be.true;651 });652}653654export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {655 await usingApi(async (api) => {656 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());657 const events = await submitTransactionAsync(sender, tx);658 const result = getGenericResult(events);659660 expect(result.success).to.be.true;661 });662}663664export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {665 await usingApi(async (api) => {666 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());667 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668 const result = getGenericResult(events);669670 expect(result.success).to.be.false;671 });672}673674export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {675 await usingApi(async (api) => {676 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));677 const events = await submitTransactionAsync(sender, tx);678 const result = getGenericResult(events);679680 expect(result.success).to.be.true;681 });682}683684export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {685 await usingApi(async (api) => {686 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));687 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;688 });689}690691export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {692 await usingApi(async (api) => {693 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));694 const events = await submitTransactionAsync(sender, tx);695 const result = getGenericResult(events);696697 expect(result.success).to.be.true;698 });699}700701export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {702 await usingApi(async (api) => {703 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));704 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;705 });706}707708export interface CreateFungibleData {709 readonly Value: bigint;710}711712export interface CreateReFungibleData { }713export interface CreateNftData { }714715export type CreateItemData = {716 NFT: CreateNftData;717} | {718 Fungible: CreateFungibleData;719} | {720 ReFungible: CreateReFungibleData;721};722723export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {724 await usingApi(async (api) => {725 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);726 727 expect(balanceBefore >= BigInt(value)).to.be.true;728729 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);730 const events = await submitTransactionAsync(sender, tx);731 const result = getGenericResult(events);732 expect(result.success).to.be.true;733734 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);735 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);736 });737}738739export async function740approveExpectSuccess(741 collectionId: number,742 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,743) {744 await usingApi(async (api: ApiPromise) => {745 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);746 const events = await submitTransactionAsync(owner, approveUniqueTx);747 const result = getGenericResult(events);748 expect(result.success).to.be.true;749750 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));751 });752}753754export async function adminApproveFromExpectSuccess(755 collectionId: number,756 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,757) {758 await usingApi(async (api: ApiPromise) => {759 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);760 const events = await submitTransactionAsync(admin, approveUniqueTx);761 const result = getGenericResult(events);762 expect(result.success).to.be.true;763764 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));765 });766}767768export async function769transferFromExpectSuccess(770 collectionId: number,771 tokenId: number,772 accountApproved: IKeyringPair,773 accountFrom: IKeyringPair | CrossAccountId,774 accountTo: IKeyringPair | CrossAccountId,775 value: number | bigint = 1,776 type = 'NFT',777) {778 await usingApi(async (api: ApiPromise) => {779 const from = normalizeAccountId(accountFrom);780 const to = normalizeAccountId(accountTo);781 let balanceBefore = 0n;782 if (type === 'Fungible') {783 balanceBefore = await getBalance(api, collectionId, to, tokenId);784 }785 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);786 const events = await submitTransactionAsync(accountApproved, transferFromTx);787 const result = getCreateItemResult(events);788 789 expect(result.success).to.be.true;790 if (type === 'NFT') {791 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);792 }793 if (type === 'Fungible') {794 const balanceAfter = await getBalance(api, collectionId, to, tokenId);795 if (JSON.stringify(to) !== JSON.stringify(from)) {796 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));797 } else {798 expect(balanceAfter).to.be.equal(balanceBefore);799 }800 }801 if (type === 'ReFungible') {802 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));803 }804 });805}806807export async function808transferFromExpectFail(809 collectionId: number,810 tokenId: number,811 accountApproved: IKeyringPair,812 accountFrom: IKeyringPair,813 accountTo: IKeyringPair,814 value: number | bigint = 1,815) {816 await usingApi(async (api: ApiPromise) => {817 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);818 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;819 const result = getCreateCollectionResult(events);820 821 expect(result.success).to.be.false;822 });823}824825826async function getBlockNumber(api: ApiPromise): Promise<number> {827 return new Promise<number>(async (resolve) => {828 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {829 unsubscribe();830 resolve(head.number.toNumber());831 });832 });833}834835export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {836 await usingApi(async (api) => {837 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));838 const events = await submitTransactionAsync(sender, changeAdminTx);839 const result = getCreateCollectionResult(events);840 expect(result.success).to.be.true;841 });842}843844export async function845getFreeBalance(account: IKeyringPair): Promise<bigint> {846 let balance = 0n;847 await usingApi(async (api) => {848 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());849 });850851 return balance;852}853854export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {855 const tx = api.tx.balances.transfer(target, amount);856 const events = await submitTransactionAsync(source, tx);857 const result = getGenericResult(events);858 expect(result.success).to.be.true;859}860861export async function862scheduleTransferExpectSuccess(863 collectionId: number,864 tokenId: number,865 sender: IKeyringPair,866 recipient: IKeyringPair,867 value: number | bigint = 1,868 blockSchedule: number,869) {870 await usingApi(async (api: ApiPromise) => {871 const blockNumber: number | undefined = await getBlockNumber(api);872 const expectedBlockNumber = blockNumber + blockSchedule;873874 expect(blockNumber).to.be.greaterThan(0);875 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);876 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);877878 await submitTransactionAsync(sender, scheduleTx);879880 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();881882 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));883884 885 await waitNewBlocks(blockSchedule + 1);886887 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();888889 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));890 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);891 });892}893894895export async function896transferExpectSuccess(897 collectionId: number,898 tokenId: number,899 sender: IKeyringPair,900 recipient: IKeyringPair | CrossAccountId,901 value: number | bigint = 1,902 type = 'NFT',903) {904 await usingApi(async (api: ApiPromise) => {905 const from = normalizeAccountId(sender);906 const to = normalizeAccountId(recipient);907908 let balanceBefore = 0n;909 if (type === 'Fungible') {910 balanceBefore = await getBalance(api, collectionId, to, tokenId);911 }912 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);913 const events = await executeTransaction(api, sender, transferTx);914915 const result = getTransferResult(api, events);916 expect(result.collectionId).to.be.equal(collectionId);917 expect(result.itemId).to.be.equal(tokenId);918 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));919 expect(result.recipient).to.be.deep.equal(to);920 expect(result.value).to.be.equal(BigInt(value));921922 if (type === 'NFT') {923 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);924 }925 if (type === 'Fungible') {926 const balanceAfter = await getBalance(api, collectionId, to, tokenId);927 if (JSON.stringify(to) !== JSON.stringify(from)) {928 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));929 } else {930 expect(balanceAfter).to.be.equal(balanceBefore);931 }932 }933 if (type === 'ReFungible') {934 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;935 }936 });937}938939export async function940transferExpectFailure(941 collectionId: number,942 tokenId: number,943 sender: IKeyringPair,944 recipient: IKeyringPair | CrossAccountId,945 value: number | bigint = 1,946) {947 await usingApi(async (api: ApiPromise) => {948 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);949 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;950 const result = getGenericResult(events);951 952 953 954 expect(result.success).to.be.false;955 956 });957}958959export async function960approveExpectFail(961 collectionId: number,962 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,963) {964 await usingApi(async (api: ApiPromise) => {965 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);966 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;967 const result = getCreateCollectionResult(events);968 969 expect(result.success).to.be.false;970 });971}972973export async function getBalance(974 api: ApiPromise,975 collectionId: number,976 owner: string | CrossAccountId,977 token: number,978): Promise<bigint> {979 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();980}981export async function getTokenOwner(982 api: ApiPromise,983 collectionId: number,984 token: number,985): Promise<CrossAccountId> {986 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;987 if (owner == null) throw new Error('owner == null');988 return normalizeAccountId(owner);989}990export async function getTopmostTokenOwner(991 api: ApiPromise,992 collectionId: number,993 token: number,994): Promise<CrossAccountId> {995 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;996 if (owner == null) throw new Error('owner == null');997 return normalizeAccountId(owner);998}999export async function isTokenExists(1000 api: ApiPromise,1001 collectionId: number,1002 token: number,1003): Promise<boolean> {1004 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1005}1006export async function getLastTokenId(1007 api: ApiPromise,1008 collectionId: number,1009): Promise<number> {1010 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1011}1012export async function getAdminList(1013 api: ApiPromise,1014 collectionId: number,1015): Promise<string[]> {1016 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1017}1018export async function getVariableMetadata(1019 api: ApiPromise,1020 collectionId: number,1021 tokenId: number,1022): Promise<number[]> {1023 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1024}1025export async function getConstMetadata(1026 api: ApiPromise,1027 collectionId: number,1028 tokenId: number,1029): Promise<number[]> {1030 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1031}10321033export async function createFungibleItemExpectSuccess(1034 sender: IKeyringPair,1035 collectionId: number,1036 data: CreateFungibleData,1037 owner: CrossAccountId | string = sender.address,1038) {1039 return await usingApi(async (api) => {1040 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10411042 const events = await submitTransactionAsync(sender, tx);1043 const result = getCreateItemResult(events);10441045 expect(result.success).to.be.true;1046 return result.itemId;1047 });1048}10491050export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1051 let newItemId = 0;1052 await usingApi(async (api) => {1053 const to = normalizeAccountId(owner);1054 const itemCountBefore = await getLastTokenId(api, collectionId);1055 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10561057 let tx;1058 if (createMode === 'Fungible') {1059 const createData = {fungible: {value: 10}};1060 tx = api.tx.unique.createItem(collectionId, to, createData as any);1061 } else if (createMode === 'ReFungible') {1062 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1063 tx = api.tx.unique.createItem(collectionId, to, createData as any);1064 } else {1065 const createData = {nft: {const_data: [], variable_data: []}};1066 tx = api.tx.unique.createItem(collectionId, to, createData as any);1067 }10681069 const events = await submitTransactionAsync(sender, tx);1070 const result = getCreateItemResult(events);10711072 const itemCountAfter = await getLastTokenId(api, collectionId);1073 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10741075 1076 1077 expect(result.success).to.be.true;1078 if (createMode === 'Fungible') {1079 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1080 } else {1081 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1082 }1083 expect(collectionId).to.be.equal(result.collectionId);1084 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1085 expect(to).to.be.deep.equal(result.recipient);1086 newItemId = result.itemId;1087 });1088 return newItemId;1089}10901091export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1092 await usingApi(async (api) => {1093 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10941095 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1096 const result = getCreateItemResult(events);10971098 expect(result.success).to.be.false;1099 });1100}11011102export async function setPublicAccessModeExpectSuccess(1103 sender: IKeyringPair, collectionId: number,1104 accessMode: 'Normal' | 'AllowList',1105) {1106 await usingApi(async (api) => {11071108 1109 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1110 const events = await submitTransactionAsync(sender, tx);1111 const result = getGenericResult(events);11121113 1114 const collection = await queryCollectionExpectSuccess(api, collectionId);11151116 1117 1118 expect(result.success).to.be.true;1119 expect(collection.access.toHuman()).to.be.equal(accessMode);1120 });1121}11221123export async function setPublicAccessModeExpectFail(1124 sender: IKeyringPair, collectionId: number,1125 accessMode: 'Normal' | 'AllowList',1126) {1127 await usingApi(async (api) => {11281129 1130 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1131 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1132 const result = getGenericResult(events);11331134 1135 1136 expect(result.success).to.be.false;1137 });1138}11391140export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1141 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1142}11431144export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1145 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1146}11471148export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1149 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1150}11511152export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1153 await usingApi(async (api) => {11541155 1156 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1157 const events = await submitTransactionAsync(sender, tx);1158 const result = getGenericResult(events);1159 expect(result.success).to.be.true;11601161 1162 const collection = await queryCollectionExpectSuccess(api, collectionId);11631164 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1165 });1166}11671168export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1169 await setMintPermissionExpectSuccess(sender, collectionId, true);1170}11711172export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1173 await usingApi(async (api) => {1174 1175 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1176 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1177 const result = getCreateCollectionResult(events);1178 1179 expect(result.success).to.be.false;1180 });1181}11821183export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1184 await usingApi(async (api) => {1185 1186 const tx = api.tx.unique.setChainLimits(limits);1187 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1188 const result = getCreateCollectionResult(events);1189 1190 expect(result.success).to.be.false;1191 });1192}11931194export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1195 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1196}11971198export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1199 await usingApi(async (api) => {1200 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12011202 1203 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1204 const events = await submitTransactionAsync(sender, tx);1205 const result = getGenericResult(events);1206 expect(result.success).to.be.true;12071208 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1209 });1210}12111212export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1213 await usingApi(async (api) => {12141215 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12161217 1218 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1219 const events = await submitTransactionAsync(sender, tx);1220 const result = getGenericResult(events);1221 expect(result.success).to.be.true;12221223 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1224 });1225}12261227export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1228 await usingApi(async (api) => {12291230 1231 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1232 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1233 const result = getGenericResult(events);12341235 1236 1237 expect(result.success).to.be.false;1238 });1239}12401241export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1242 await usingApi(async (api) => {1243 1244 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1245 const events = await submitTransactionAsync(sender, tx);1246 const result = getGenericResult(events);12471248 1249 1250 expect(result.success).to.be.true;1251 });1252}12531254export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1255 await usingApi(async (api) => {1256 1257 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1258 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1259 const result = getGenericResult(events);12601261 1262 1263 expect(result.success).to.be.false;1264 });1265}12661267export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1268 : Promise<UpDataStructsRpcCollection | null> => {1269 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1270};12711272export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1273 1274 return (await api.rpc.unique.collectionStats()).created.toNumber();1275};12761277export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1278 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1279}12801281export async function waitNewBlocks(blocksCount = 1): Promise<void> {1282 await usingApi(async (api) => {1283 const promise = new Promise<void>(async (resolve) => {1284 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1285 if (blocksCount > 0) {1286 blocksCount--;1287 } else {1288 unsubscribe();1289 resolve();1290 }1291 });1292 });1293 return promise;1294 });1295}