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 shemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275 description: 'description',276 mode: {type: 'NFT'},277 name: 'name',278 tokenPrefix: 'prefix',279 shemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283 const {name, description, mode, tokenPrefix, shemaVersion} = {...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: shemaVersion,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 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356 const result = getCreateCollectionResult(events);357358 359 const collectionCountAfter = await getCreatedCollectionCount(api);360361 362 363 expect(result.success).to.be.false;364 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');365 });366}367368export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {369 let bal = 0n;370 let unused;371 do {372 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;373 const keyring = new Keyring({type: 'sr25519'});374 unused = keyring.addFromUri(`//${randomSeed}`);375 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();376 } while (bal !== 0n);377 return unused;378}379380export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {381 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();382}383384export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {385 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));386}387388export async function findNotExistingCollection(api: ApiPromise): Promise<number> {389 const totalNumber = await getCreatedCollectionCount(api);390 const newCollection: number = totalNumber + 1;391 return newCollection;392}393394function getDestroyResult(events: EventRecord[]): boolean {395 let success = false;396 events.forEach(({event: {method}}) => {397 if (method == 'ExtrinsicSuccess') {398 success = true;399 }400 });401 return success;402}403404export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {405 await usingApi(async (api) => {406 407 const alicePrivateKey = privateKey(senderSeed);408 const tx = api.tx.unique.destroyCollection(collectionId);409 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410 });411}412413export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {414 await usingApi(async (api) => {415 416 const alicePrivateKey = privateKey(senderSeed);417 const tx = api.tx.unique.destroyCollection(collectionId);418 const events = await submitTransactionAsync(alicePrivateKey, tx);419 const result = getDestroyResult(events);420 expect(result).to.be.true;421422 423 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;424 });425}426427export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {428 await usingApi(async (api) => {429 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);430 const events = await submitTransactionAsync(sender, tx);431 const result = getGenericResult(events);432433 expect(result.success).to.be.true;434 });435}436437export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {438 await usingApi(async (api) => {439 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);440 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;441 const result = getGenericResult(events);442443 expect(result.success).to.be.false;444 });445}446447export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {448 await usingApi(async (api) => {449450 451 const senderPrivateKey = privateKey(sender);452 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);453 const events = await submitTransactionAsync(senderPrivateKey, tx);454 const result = getGenericResult(events);455456 457 const collection = await queryCollectionExpectSuccess(api, collectionId);458459 460 expect(result.success).to.be.true;461 expect(collection.sponsorship.toJSON()).to.deep.equal({462 unconfirmed: sponsor,463 });464 });465}466467export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {468 await usingApi(async (api) => {469470 471 const alicePrivateKey = privateKey(sender);472 const tx = api.tx.unique.removeCollectionSponsor(collectionId);473 const events = await submitTransactionAsync(alicePrivateKey, tx);474 const result = getGenericResult(events);475476 477 const collection = await queryCollectionExpectSuccess(api, collectionId);478479 480 expect(result.success).to.be.true;481 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});482 });483}484485export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {486 await usingApi(async (api) => {487488 489 const alicePrivateKey = privateKey(senderSeed);490 const tx = api.tx.unique.removeCollectionSponsor(collectionId);491 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;492 });493}494495export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {496 await usingApi(async (api) => {497498 499 const alicePrivateKey = privateKey(senderSeed);500 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);501 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;502 });503}504505export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {506 await usingApi(async (api) => {507508 509 const sender = privateKey(senderSeed);510 const tx = api.tx.unique.confirmSponsorship(collectionId);511 const events = await submitTransactionAsync(sender, tx);512 const result = getGenericResult(events);513514 515 const collection = await queryCollectionExpectSuccess(api, collectionId);516517 518 expect(result.success).to.be.true;519 expect(collection.sponsorship.toJSON()).to.be.deep.equal({520 confirmed: sender.address,521 });522 });523}524525526export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {527 await usingApi(async (api) => {528529 530 const sender = privateKey(senderSeed);531 const tx = api.tx.unique.confirmSponsorship(collectionId);532 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;533 });534}535536export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {537538 await usingApi(async (api) => {539 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);540 const events = await submitTransactionAsync(sender, tx);541 const result = getGenericResult(events);542543 expect(result.success).to.be.true;544 });545}546547export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {548549 await usingApi(async (api) => {550 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);551 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;552 const result = getGenericResult(events);553554 expect(result.success).to.be.false;555 });556}557558export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {559 await usingApi(async (api) => {560 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {569 await usingApi(async (api) => {570 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);571 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;572 const result = getGenericResult(events);573574 expect(result.success).to.be.false;575 });576}577578export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {579580 await usingApi(async (api) => {581582 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);583 const events = await submitTransactionAsync(sender, tx);584 const result = getGenericResult(events);585586 expect(result.success).to.be.true;587 });588}589590export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {591592 await usingApi(async (api) => {593594 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;596 const result = getGenericResult(events);597598 expect(result.success).to.be.false;599 });600}601602export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {603 await usingApi(async (api) => {604 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);605 const events = await submitTransactionAsync(sender, tx);606 const result = getGenericResult(events);607608 expect(result.success).to.be.true;609 });610}611612export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {613 await usingApi(async (api) => {614 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);615 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;616 const result = getGenericResult(events);617618 expect(result.success).to.be.false;619 });620}621622export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {623 await usingApi(async (api) => {624 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);625 const events = await submitTransactionAsync(sender, tx);626 const result = getGenericResult(events);627628 expect(result.success).to.be.true;629 });630}631632export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {633 let allowlisted = false;634 await usingApi(async (api) => {635 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;636 });637 return allowlisted;638}639640export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {641 await usingApi(async (api) => {642 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());643 const events = await submitTransactionAsync(sender, tx);644 const result = getGenericResult(events);645646 expect(result.success).to.be.true;647 });648}649650export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {651 await usingApi(async (api) => {652 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());653 const events = await submitTransactionAsync(sender, tx);654 const result = getGenericResult(events);655656 expect(result.success).to.be.true;657 });658}659660export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {661 await usingApi(async (api) => {662 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());663 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;664 const result = getGenericResult(events);665666 expect(result.success).to.be.false;667 });668}669670export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {671 await usingApi(async (api) => {672 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));673 const events = await submitTransactionAsync(sender, tx);674 const result = getGenericResult(events);675676 expect(result.success).to.be.true;677 });678}679680export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));683 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;684 });685}686687export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {688 await usingApi(async (api) => {689 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));690 const events = await submitTransactionAsync(sender, tx);691 const result = getGenericResult(events);692693 expect(result.success).to.be.true;694 });695}696697export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {698 await usingApi(async (api) => {699 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));700 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;701 });702}703704export interface CreateFungibleData {705 readonly Value: bigint;706}707708export interface CreateReFungibleData { }709export interface CreateNftData { }710711export type CreateItemData = {712 NFT: CreateNftData;713} | {714 Fungible: CreateFungibleData;715} | {716 ReFungible: CreateReFungibleData;717};718719export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {720 await usingApi(async (api) => {721 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);722 723 expect(balanceBefore >= BigInt(value)).to.be.true;724725 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);726 const events = await submitTransactionAsync(sender, tx);727 const result = getGenericResult(events);728 expect(result.success).to.be.true;729730 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);731 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);732 });733}734735export async function736approveExpectSuccess(737 collectionId: number,738 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,739) {740 await usingApi(async (api: ApiPromise) => {741 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);742 const events = await submitTransactionAsync(owner, approveUniqueTx);743 const result = getGenericResult(events);744 expect(result.success).to.be.true;745746 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));747 });748}749750export async function adminApproveFromExpectSuccess(751 collectionId: number,752 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,753) {754 await usingApi(async (api: ApiPromise) => {755 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);756 const events = await submitTransactionAsync(admin, approveUniqueTx);757 const result = getGenericResult(events);758 expect(result.success).to.be.true;759760 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));761 });762}763764export async function765transferFromExpectSuccess(766 collectionId: number,767 tokenId: number,768 accountApproved: IKeyringPair,769 accountFrom: IKeyringPair | CrossAccountId,770 accountTo: IKeyringPair | CrossAccountId,771 value: number | bigint = 1,772 type = 'NFT',773) {774 await usingApi(async (api: ApiPromise) => {775 const from = normalizeAccountId(accountFrom);776 const to = normalizeAccountId(accountTo);777 let balanceBefore = 0n;778 if (type === 'Fungible') {779 balanceBefore = await getBalance(api, collectionId, to, tokenId);780 }781 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);782 const events = await submitTransactionAsync(accountApproved, transferFromTx);783 const result = getCreateItemResult(events);784 785 expect(result.success).to.be.true;786 if (type === 'NFT') {787 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);788 }789 if (type === 'Fungible') {790 const balanceAfter = await getBalance(api, collectionId, to, tokenId);791 if (JSON.stringify(to) !== JSON.stringify(from)) {792 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));793 } else {794 expect(balanceAfter).to.be.equal(balanceBefore);795 }796 }797 if (type === 'ReFungible') {798 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));799 }800 });801}802803export async function804transferFromExpectFail(805 collectionId: number,806 tokenId: number,807 accountApproved: IKeyringPair,808 accountFrom: IKeyringPair,809 accountTo: IKeyringPair,810 value: number | bigint = 1,811) {812 await usingApi(async (api: ApiPromise) => {813 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);814 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;815 const result = getCreateCollectionResult(events);816 817 expect(result.success).to.be.false;818 });819}820821822async function getBlockNumber(api: ApiPromise): Promise<number> {823 return new Promise<number>(async (resolve) => {824 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {825 unsubscribe();826 resolve(head.number.toNumber());827 });828 });829}830831export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {832 await usingApi(async (api) => {833 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));834 const events = await submitTransactionAsync(sender, changeAdminTx);835 const result = getCreateCollectionResult(events);836 expect(result.success).to.be.true;837 });838}839840export async function841getFreeBalance(account: IKeyringPair): Promise<bigint> {842 let balance = 0n;843 await usingApi(async (api) => {844 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());845 });846847 return balance;848}849850export async function851scheduleTransferExpectSuccess(852 collectionId: number,853 tokenId: number,854 sender: IKeyringPair,855 recipient: IKeyringPair,856 value: number | bigint = 1,857 blockSchedule: number,858) {859 await usingApi(async (api: ApiPromise) => {860 const blockNumber: number | undefined = await getBlockNumber(api);861 const expectedBlockNumber = blockNumber + blockSchedule;862863 expect(blockNumber).to.be.greaterThan(0);864 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);865 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);866867 await submitTransactionAsync(sender, scheduleTx);868869 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();870871 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));872873 874 await waitNewBlocks(blockSchedule + 1);875876 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();877878 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));879 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);880 });881}882883884export async function885transferExpectSuccess(886 collectionId: number,887 tokenId: number,888 sender: IKeyringPair,889 recipient: IKeyringPair | CrossAccountId,890 value: number | bigint = 1,891 type = 'NFT',892) {893 await usingApi(async (api: ApiPromise) => {894 const from = normalizeAccountId(sender);895 const to = normalizeAccountId(recipient);896897 let balanceBefore = 0n;898 if (type === 'Fungible') {899 balanceBefore = await getBalance(api, collectionId, to, tokenId);900 }901 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);902 const events = await submitTransactionAsync(sender, transferTx);903 const result = getTransferResult(events);904 905 expect(result.success).to.be.true;906 expect(result.collectionId).to.be.equal(collectionId);907 expect(result.itemId).to.be.equal(tokenId);908 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));909 expect(result.recipient).to.be.deep.equal(to);910 expect(result.value).to.be.equal(BigInt(value));911 if (type === 'NFT') {912 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);913 }914 if (type === 'Fungible') {915 const balanceAfter = await getBalance(api, collectionId, to, tokenId);916 if (JSON.stringify(to) !== JSON.stringify(from)) {917 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));918 } else {919 expect(balanceAfter).to.be.equal(balanceBefore);920 }921 }922 if (type === 'ReFungible') {923 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;924 }925 });926}927928export async function929transferExpectFailure(930 collectionId: number,931 tokenId: number,932 sender: IKeyringPair,933 recipient: IKeyringPair,934 value: number | bigint = 1,935) {936 await usingApi(async (api: ApiPromise) => {937 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);938 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;939 const result = getGenericResult(events);940 941 942 943 expect(result.success).to.be.false;944 945 });946}947948export async function949approveExpectFail(950 collectionId: number,951 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,952) {953 await usingApi(async (api: ApiPromise) => {954 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);955 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;956 const result = getCreateCollectionResult(events);957 958 expect(result.success).to.be.false;959 });960}961962export async function getBalance(963 api: ApiPromise,964 collectionId: number,965 owner: string | CrossAccountId,966 token: number,967): Promise<bigint> {968 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();969}970export async function getTokenOwner(971 api: ApiPromise,972 collectionId: number,973 token: number,974): Promise<CrossAccountId> {975 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);976}977export async function isTokenExists(978 api: ApiPromise,979 collectionId: number,980 token: number,981): Promise<boolean> {982 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();983}984export async function getLastTokenId(985 api: ApiPromise,986 collectionId: number,987): Promise<number> {988 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();989}990export async function getAdminList(991 api: ApiPromise,992 collectionId: number,993): Promise<string[]> {994 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;995}996export async function getVariableMetadata(997 api: ApiPromise,998 collectionId: number,999 tokenId: number,1000): Promise<number[]> {1001 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1002}1003export async function getConstMetadata(1004 api: ApiPromise,1005 collectionId: number,1006 tokenId: number,1007): Promise<number[]> {1008 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1009}10101011export async function createFungibleItemExpectSuccess(1012 sender: IKeyringPair,1013 collectionId: number,1014 data: CreateFungibleData,1015 owner: CrossAccountId | string = sender.address,1016) {1017 return await usingApi(async (api) => {1018 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10191020 const events = await submitTransactionAsync(sender, tx);1021 const result = getCreateItemResult(events);10221023 expect(result.success).to.be.true;1024 return result.itemId;1025 });1026}10271028export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1029 let newItemId = 0;1030 await usingApi(async (api) => {1031 const to = normalizeAccountId(owner);1032 const itemCountBefore = await getLastTokenId(api, collectionId);1033 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10341035 let tx;1036 if (createMode === 'Fungible') {1037 const createData = {fungible: {value: 10}};1038 tx = api.tx.unique.createItem(collectionId, to, createData as any);1039 } else if (createMode === 'ReFungible') {1040 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1041 tx = api.tx.unique.createItem(collectionId, to, createData as any);1042 } else {1043 const createData = {nft: {const_data: [], variable_data: []}};1044 tx = api.tx.unique.createItem(collectionId, to, createData as any);1045 }10461047 const events = await submitTransactionAsync(sender, tx);1048 const result = getCreateItemResult(events);10491050 const itemCountAfter = await getLastTokenId(api, collectionId);1051 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10521053 1054 1055 expect(result.success).to.be.true;1056 if (createMode === 'Fungible') {1057 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1058 } else {1059 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1060 }1061 expect(collectionId).to.be.equal(result.collectionId);1062 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1063 expect(to).to.be.deep.equal(result.recipient);1064 newItemId = result.itemId;1065 });1066 return newItemId;1067}10681069export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1070 await usingApi(async (api) => {1071 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10721073 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1074 const result = getCreateItemResult(events);10751076 expect(result.success).to.be.false;1077 });1078}10791080export async function setPublicAccessModeExpectSuccess(1081 sender: IKeyringPair, collectionId: number,1082 accessMode: 'Normal' | 'AllowList',1083) {1084 await usingApi(async (api) => {10851086 1087 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1088 const events = await submitTransactionAsync(sender, tx);1089 const result = getGenericResult(events);10901091 1092 const collection = await queryCollectionExpectSuccess(api, collectionId);10931094 1095 1096 expect(result.success).to.be.true;1097 expect(collection.access.toHuman()).to.be.equal(accessMode);1098 });1099}11001101export async function setPublicAccessModeExpectFail(1102 sender: IKeyringPair, collectionId: number,1103 accessMode: 'Normal' | 'AllowList',1104) {1105 await usingApi(async (api) => {11061107 1108 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1109 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1110 const result = getGenericResult(events);11111112 1113 1114 expect(result.success).to.be.false;1115 });1116}11171118export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1119 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1120}11211122export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1123 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1124}11251126export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1127 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1128}11291130export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1131 await usingApi(async (api) => {11321133 1134 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1135 const events = await submitTransactionAsync(sender, tx);1136 const result = getGenericResult(events);1137 expect(result.success).to.be.true;11381139 1140 const collection = await queryCollectionExpectSuccess(api, collectionId);11411142 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1143 });1144}11451146export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1147 await setMintPermissionExpectSuccess(sender, collectionId, true);1148}11491150export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1151 await usingApi(async (api) => {1152 1153 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1154 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1155 const result = getCreateCollectionResult(events);1156 1157 expect(result.success).to.be.false;1158 });1159}11601161export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1162 await usingApi(async (api) => {1163 1164 const tx = api.tx.unique.setChainLimits(limits);1165 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1166 const result = getCreateCollectionResult(events);1167 1168 expect(result.success).to.be.false;1169 });1170}11711172export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1173 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1174}11751176export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1177 await usingApi(async (api) => {1178 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11791180 1181 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1182 const events = await submitTransactionAsync(sender, tx);1183 const result = getGenericResult(events);1184 expect(result.success).to.be.true;11851186 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1187 });1188}11891190export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1191 await usingApi(async (api) => {11921193 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11941195 1196 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1197 const events = await submitTransactionAsync(sender, tx);1198 const result = getGenericResult(events);1199 expect(result.success).to.be.true;12001201 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1202 });1203}12041205export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1206 await usingApi(async (api) => {12071208 1209 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1210 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1211 const result = getGenericResult(events);12121213 1214 1215 expect(result.success).to.be.false;1216 });1217}12181219export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1220 await usingApi(async (api) => {1221 1222 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1223 const events = await submitTransactionAsync(sender, tx);1224 const result = getGenericResult(events);12251226 1227 1228 expect(result.success).to.be.true;1229 });1230}12311232export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1233 await usingApi(async (api) => {1234 1235 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1236 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1237 const result = getGenericResult(events);12381239 1240 1241 expect(result.success).to.be.false;1242 });1243}12441245export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1246 : Promise<UpDataStructsCollection | null> => {1247 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1248};12491250export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1251 1252 return (await api.rpc.unique.collectionStats()).created.toNumber();1253};12541255export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1256 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1257}12581259export async function waitNewBlocks(blocksCount = 1): Promise<void> {1260 await usingApi(async (api) => {1261 const promise = new Promise<void>(async (resolve) => {1262 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1263 if (blocksCount > 0) {1264 blocksCount--;1265 } else {1266 unsubscribe();1267 resolve();1268 }1269 });1270 });1271 return promise;1272 });1273}