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};272273const defaultCreateCollectionParams: CreateCollectionParams = {274 description: 'description',275 mode: {type: 'NFT'},276 name: 'name',277 tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281 const {name, description, mode, tokenPrefix} = {...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({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301 const events = await submitTransactionAsync(alicePrivateKey, tx);302 const result = getCreateCollectionResult(events);303304 305 const collectionCountAfter = await getCreatedCollectionCount(api);306307 308 const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310 311 312 expect(result.success).to.be.true;313 expect(result.collectionId).to.be.equal(collectionCountAfter);314 315 expect(collection).to.be.not.null;316 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322 collectionId = result.collectionId;323 });324325 return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331 let modeprm = {};332 if (mode.type === 'NFT') {333 modeprm = {nft: null};334 } else if (mode.type === 'Fungible') {335 modeprm = {fungible: mode.decimalPoints};336 } else if (mode.type === 'ReFungible') {337 modeprm = {refungible: null};338 }339340 await usingApi(async (api) => {341 342 const collectionCountBefore = await getCreatedCollectionCount(api);343344 345 const alicePrivateKey = privateKey('//Alice');346 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348349 350 const collectionCountAfter = await getCreatedCollectionCount(api);351352 353 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');354 });355}356357export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {358 let bal = 0n;359 let unused;360 do {361 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;362 const keyring = new Keyring({type: 'sr25519'});363 unused = keyring.addFromUri(`//${randomSeed}`);364 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();365 } while (bal !== 0n);366 return unused;367}368369export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {370 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();371}372373export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {374 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));375}376377export async function findNotExistingCollection(api: ApiPromise): Promise<number> {378 const totalNumber = await getCreatedCollectionCount(api);379 const newCollection: number = totalNumber + 1;380 return newCollection;381}382383function getDestroyResult(events: EventRecord[]): boolean {384 let success = false;385 events.forEach(({event: {method}}) => {386 if (method == 'ExtrinsicSuccess') {387 success = true;388 }389 });390 return success;391}392393export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {394 await usingApi(async (api) => {395 396 const alicePrivateKey = privateKey(senderSeed);397 const tx = api.tx.unique.destroyCollection(collectionId);398 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;399 });400}401402export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {403 await usingApi(async (api) => {404 405 const alicePrivateKey = privateKey(senderSeed);406 const tx = api.tx.unique.destroyCollection(collectionId);407 const events = await submitTransactionAsync(alicePrivateKey, tx);408 const result = getDestroyResult(events);409 expect(result).to.be.true;410411 412 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;413 });414}415416export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {417 await usingApi(async (api) => {418 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);419 const events = await submitTransactionAsync(sender, tx);420 const result = getGenericResult(events);421422 expect(result.success).to.be.true;423 });424}425426export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {427 await usingApi(async (api) => {428 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);429 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;430 const result = getGenericResult(events);431432 expect(result.success).to.be.false;433 });434}435436export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {437 await usingApi(async (api) => {438439 440 const senderPrivateKey = privateKey(sender);441 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);442 const events = await submitTransactionAsync(senderPrivateKey, tx);443 const result = getGenericResult(events);444445 446 const collection = await queryCollectionExpectSuccess(api, collectionId);447448 449 expect(result.success).to.be.true;450 expect(collection.sponsorship.toJSON()).to.deep.equal({451 unconfirmed: sponsor,452 });453 });454}455456export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {457 await usingApi(async (api) => {458459 460 const alicePrivateKey = privateKey(sender);461 const tx = api.tx.unique.removeCollectionSponsor(collectionId);462 const events = await submitTransactionAsync(alicePrivateKey, tx);463 const result = getGenericResult(events);464465 466 const collection = await queryCollectionExpectSuccess(api, collectionId);467468 469 expect(result.success).to.be.true;470 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});471 });472}473474export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {475 await usingApi(async (api) => {476477 478 const alicePrivateKey = privateKey(senderSeed);479 const tx = api.tx.unique.removeCollectionSponsor(collectionId);480 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;481 });482}483484export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {485 await usingApi(async (api) => {486487 488 const alicePrivateKey = privateKey(senderSeed);489 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);490 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;491 });492}493494export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {495 await usingApi(async (api) => {496497 498 const sender = privateKey(senderSeed);499 const tx = api.tx.unique.confirmSponsorship(collectionId);500 const events = await submitTransactionAsync(sender, tx);501 const result = getGenericResult(events);502503 504 const collection = await queryCollectionExpectSuccess(api, collectionId);505506 507 expect(result.success).to.be.true;508 expect(collection.sponsorship.toJSON()).to.be.deep.equal({509 confirmed: sender.address,510 });511 });512}513514515export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {516 await usingApi(async (api) => {517518 519 const sender = privateKey(senderSeed);520 const tx = api.tx.unique.confirmSponsorship(collectionId);521 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;522 });523}524525export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {526527 await usingApi(async (api) => {528 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);529 const events = await submitTransactionAsync(sender, tx);530 const result = getGenericResult(events);531532 expect(result.success).to.be.true;533 });534}535536export async function setMetadataUpdatePermissionFlagExpectFailure(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 expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;541 const result = getGenericResult(events);542543 expect(result.success).to.be.false;544 });545}546547export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {548 await usingApi(async (api) => {549 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);550 const events = await submitTransactionAsync(sender, tx);551 const result = getGenericResult(events);552553 expect(result.success).to.be.true;554 });555}556557export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {558 await usingApi(async (api) => {559 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);560 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561 const result = getGenericResult(events);562563 expect(result.success).to.be.false;564 });565}566567export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {568569 await usingApi(async (api) => {570571 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);572 const events = await submitTransactionAsync(sender, tx);573 const result = getGenericResult(events);574575 expect(result.success).to.be.true;576 });577}578579export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {580581 await usingApi(async (api) => {582583 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);584 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;585 const result = getGenericResult(events);586587 expect(result.success).to.be.false;588 });589}590591export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {592 await usingApi(async (api) => {593 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);594 const events = await submitTransactionAsync(sender, tx);595 const result = getGenericResult(events);596597 expect(result.success).to.be.true;598 });599}600601export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {602 await usingApi(async (api) => {603 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);604 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;605 const result = getGenericResult(events);606607 expect(result.success).to.be.false;608 });609}610611export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {612 await usingApi(async (api) => {613 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);614 const events = await submitTransactionAsync(sender, tx);615 const result = getGenericResult(events);616617 expect(result.success).to.be.true;618 });619}620621export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {622 let allowlisted = false;623 await usingApi(async (api) => {624 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;625 });626 return allowlisted;627}628629export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {630 await usingApi(async (api) => {631 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());632 const events = await submitTransactionAsync(sender, tx);633 const result = getGenericResult(events);634635 expect(result.success).to.be.true;636 });637}638639export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {640 await usingApi(async (api) => {641 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());642 const events = await submitTransactionAsync(sender, tx);643 const result = getGenericResult(events);644645 expect(result.success).to.be.true;646 });647}648649export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {650 await usingApi(async (api) => {651 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());652 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;653 const result = getGenericResult(events);654655 expect(result.success).to.be.false;656 });657}658659export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {660 await usingApi(async (api) => {661 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));662 const events = await submitTransactionAsync(sender, tx);663 const result = getGenericResult(events);664665 expect(result.success).to.be.true;666 });667}668669export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {670 await usingApi(async (api) => {671 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));672 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;673 });674}675676export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {677 await usingApi(async (api) => {678 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));679 const events = await submitTransactionAsync(sender, tx);680 const result = getGenericResult(events);681682 expect(result.success).to.be.true;683 });684}685686export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {687 await usingApi(async (api) => {688 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));689 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690 });691}692693export interface CreateFungibleData {694 readonly Value: bigint;695}696697export interface CreateReFungibleData { }698export interface CreateNftData { }699700export type CreateItemData = {701 NFT: CreateNftData;702} | {703 Fungible: CreateFungibleData;704} | {705 ReFungible: CreateReFungibleData;706};707708export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {709 await usingApi(async (api) => {710 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);711 712 expect(balanceBefore >= BigInt(value)).to.be.true;713714 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);715 const events = await submitTransactionAsync(sender, tx);716 const result = getGenericResult(events);717 expect(result.success).to.be.true;718719 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);720 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);721 });722}723724export async function725approveExpectSuccess(726 collectionId: number,727 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,728) {729 await usingApi(async (api: ApiPromise) => {730 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);731 const events = await submitTransactionAsync(owner, approveUniqueTx);732 const result = getGenericResult(events);733 expect(result.success).to.be.true;734735 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));736 });737}738739export async function adminApproveFromExpectSuccess(740 collectionId: number,741 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,742) {743 await usingApi(async (api: ApiPromise) => {744 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);745 const events = await submitTransactionAsync(admin, approveUniqueTx);746 const result = getGenericResult(events);747 expect(result.success).to.be.true;748749 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));750 });751}752753export async function754transferFromExpectSuccess(755 collectionId: number,756 tokenId: number,757 accountApproved: IKeyringPair,758 accountFrom: IKeyringPair | CrossAccountId,759 accountTo: IKeyringPair | CrossAccountId,760 value: number | bigint = 1,761 type = 'NFT',762) {763 await usingApi(async (api: ApiPromise) => {764 const from = normalizeAccountId(accountFrom);765 const to = normalizeAccountId(accountTo);766 let balanceBefore = 0n;767 if (type === 'Fungible') {768 balanceBefore = await getBalance(api, collectionId, to, tokenId);769 }770 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);771 const events = await submitTransactionAsync(accountApproved, transferFromTx);772 const result = getCreateItemResult(events);773 774 expect(result.success).to.be.true;775 if (type === 'NFT') {776 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);777 }778 if (type === 'Fungible') {779 const balanceAfter = await getBalance(api, collectionId, to, tokenId);780 if (JSON.stringify(to) !== JSON.stringify(from)) {781 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));782 } else {783 expect(balanceAfter).to.be.equal(balanceBefore);784 }785 }786 if (type === 'ReFungible') {787 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));788 }789 });790}791792export async function793transferFromExpectFail(794 collectionId: number,795 tokenId: number,796 accountApproved: IKeyringPair,797 accountFrom: IKeyringPair,798 accountTo: IKeyringPair,799 value: number | bigint = 1,800) {801 await usingApi(async (api: ApiPromise) => {802 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);803 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;804 const result = getCreateCollectionResult(events);805 806 expect(result.success).to.be.false;807 });808}809810811async function getBlockNumber(api: ApiPromise): Promise<number> {812 return new Promise<number>(async (resolve) => {813 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {814 unsubscribe();815 resolve(head.number.toNumber());816 });817 });818}819820export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {821 await usingApi(async (api) => {822 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));823 const events = await submitTransactionAsync(sender, changeAdminTx);824 const result = getCreateCollectionResult(events);825 expect(result.success).to.be.true;826 });827}828829export async function830getFreeBalance(account: IKeyringPair): Promise<bigint> {831 let balance = 0n;832 await usingApi(async (api) => {833 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());834 });835836 return balance;837}838839export async function840scheduleTransferExpectSuccess(841 collectionId: number,842 tokenId: number,843 sender: IKeyringPair,844 recipient: IKeyringPair,845 value: number | bigint = 1,846 blockSchedule: number,847) {848 await usingApi(async (api: ApiPromise) => {849 const blockNumber: number | undefined = await getBlockNumber(api);850 const expectedBlockNumber = blockNumber + blockSchedule;851852 expect(blockNumber).to.be.greaterThan(0);853 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);854 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);855856 await submitTransactionAsync(sender, scheduleTx);857858 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();859860 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));861862 863 await waitNewBlocks(blockSchedule + 1);864865 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();866867 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));868 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);869 });870}871872873export async function874transferExpectSuccess(875 collectionId: number,876 tokenId: number,877 sender: IKeyringPair,878 recipient: IKeyringPair | CrossAccountId,879 value: number | bigint = 1,880 type = 'NFT',881) {882 await usingApi(async (api: ApiPromise) => {883 const from = normalizeAccountId(sender);884 const to = normalizeAccountId(recipient);885886 let balanceBefore = 0n;887 if (type === 'Fungible') {888 balanceBefore = await getBalance(api, collectionId, to, tokenId);889 }890 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);891 const events = await submitTransactionAsync(sender, transferTx);892 const result = getTransferResult(events);893 894 expect(result.success).to.be.true;895 expect(result.collectionId).to.be.equal(collectionId);896 expect(result.itemId).to.be.equal(tokenId);897 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));898 expect(result.recipient).to.be.deep.equal(to);899 expect(result.value).to.be.equal(BigInt(value));900 if (type === 'NFT') {901 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);902 }903 if (type === 'Fungible') {904 const balanceAfter = await getBalance(api, collectionId, to, tokenId);905 if (JSON.stringify(to) !== JSON.stringify(from)) {906 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));907 } else {908 expect(balanceAfter).to.be.equal(balanceBefore);909 }910 }911 if (type === 'ReFungible') {912 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;913 }914 });915}916917export async function918transferExpectFailure(919 collectionId: number,920 tokenId: number,921 sender: IKeyringPair,922 recipient: IKeyringPair,923 value: number | bigint = 1,924) {925 await usingApi(async (api: ApiPromise) => {926 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);927 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;928 const result = getGenericResult(events);929 930 931 932 expect(result.success).to.be.false;933 934 });935}936937export async function938approveExpectFail(939 collectionId: number,940 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,941) {942 await usingApi(async (api: ApiPromise) => {943 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);944 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;945 const result = getCreateCollectionResult(events);946 947 expect(result.success).to.be.false;948 });949}950951export async function getBalance(952 api: ApiPromise,953 collectionId: number,954 owner: string | CrossAccountId,955 token: number,956): Promise<bigint> {957 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();958}959export async function getTokenOwner(960 api: ApiPromise,961 collectionId: number,962 token: number,963): Promise<CrossAccountId> {964 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);965}966export async function isTokenExists(967 api: ApiPromise,968 collectionId: number,969 token: number,970): Promise<boolean> {971 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();972}973export async function getLastTokenId(974 api: ApiPromise,975 collectionId: number,976): Promise<number> {977 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();978}979export async function getAdminList(980 api: ApiPromise,981 collectionId: number,982): Promise<string[]> {983 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;984}985export async function getVariableMetadata(986 api: ApiPromise,987 collectionId: number,988 tokenId: number,989): Promise<number[]> {990 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];991}992export async function getConstMetadata(993 api: ApiPromise,994 collectionId: number,995 tokenId: number,996): Promise<number[]> {997 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];998}9991000export async function createFungibleItemExpectSuccess(1001 sender: IKeyringPair,1002 collectionId: number,1003 data: CreateFungibleData,1004 owner: CrossAccountId | string = sender.address,1005) {1006 return await usingApi(async (api) => {1007 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10081009 const events = await submitTransactionAsync(sender, tx);1010 const result = getCreateItemResult(events);10111012 expect(result.success).to.be.true;1013 return result.itemId;1014 });1015}10161017export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1018 let newItemId = 0;1019 await usingApi(async (api) => {1020 const to = normalizeAccountId(owner);1021 const itemCountBefore = await getLastTokenId(api, collectionId);1022 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10231024 let tx;1025 if (createMode === 'Fungible') {1026 const createData = {fungible: {value: 10}};1027 tx = api.tx.unique.createItem(collectionId, to, createData as any);1028 } else if (createMode === 'ReFungible') {1029 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1030 tx = api.tx.unique.createItem(collectionId, to, createData as any);1031 } else {1032 const createData = {nft: {const_data: [], variable_data: []}};1033 tx = api.tx.unique.createItem(collectionId, to, createData as any);1034 }10351036 const events = await submitTransactionAsync(sender, tx);1037 const result = getCreateItemResult(events);10381039 const itemCountAfter = await getLastTokenId(api, collectionId);1040 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10411042 1043 1044 expect(result.success).to.be.true;1045 if (createMode === 'Fungible') {1046 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1047 } else {1048 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1049 }1050 expect(collectionId).to.be.equal(result.collectionId);1051 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1052 expect(to).to.be.deep.equal(result.recipient);1053 newItemId = result.itemId;1054 });1055 return newItemId;1056}10571058export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1059 await usingApi(async (api) => {1060 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10611062 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1063 const result = getCreateItemResult(events);10641065 expect(result.success).to.be.false;1066 });1067}10681069export async function setPublicAccessModeExpectSuccess(1070 sender: IKeyringPair, collectionId: number,1071 accessMode: 'Normal' | 'AllowList',1072) {1073 await usingApi(async (api) => {10741075 1076 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1077 const events = await submitTransactionAsync(sender, tx);1078 const result = getGenericResult(events);10791080 1081 const collection = await queryCollectionExpectSuccess(api, collectionId);10821083 1084 1085 expect(result.success).to.be.true;1086 expect(collection.access.toHuman()).to.be.equal(accessMode);1087 });1088}10891090export async function setPublicAccessModeExpectFail(1091 sender: IKeyringPair, collectionId: number,1092 accessMode: 'Normal' | 'AllowList',1093) {1094 await usingApi(async (api) => {10951096 1097 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1098 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1099 const result = getGenericResult(events);11001101 1102 1103 expect(result.success).to.be.false;1104 });1105}11061107export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1108 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1109}11101111export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1112 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1113}11141115export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1116 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1117}11181119export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1120 await usingApi(async (api) => {11211122 1123 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1124 const events = await submitTransactionAsync(sender, tx);1125 const result = getGenericResult(events);1126 expect(result.success).to.be.true;11271128 1129 const collection = await queryCollectionExpectSuccess(api, collectionId);11301131 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1132 });1133}11341135export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1136 await setMintPermissionExpectSuccess(sender, collectionId, true);1137}11381139export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1140 await usingApi(async (api) => {1141 1142 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1143 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1144 const result = getCreateCollectionResult(events);1145 1146 expect(result.success).to.be.false;1147 });1148}11491150export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1151 await usingApi(async (api) => {1152 1153 const tx = api.tx.unique.setChainLimits(limits);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 isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1162 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1163}11641165export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1166 await usingApi(async (api) => {1167 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11681169 1170 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1171 const events = await submitTransactionAsync(sender, tx);1172 const result = getGenericResult(events);1173 expect(result.success).to.be.true;11741175 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1176 });1177}11781179export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1180 await usingApi(async (api) => {11811182 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11831184 1185 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1186 const events = await submitTransactionAsync(sender, tx);1187 const result = getGenericResult(events);1188 expect(result.success).to.be.true;11891190 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1191 });1192}11931194export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1195 await usingApi(async (api) => {11961197 1198 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1199 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1200 const result = getGenericResult(events);12011202 1203 1204 expect(result.success).to.be.false;1205 });1206}12071208export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1209 await usingApi(async (api) => {1210 1211 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1212 const events = await submitTransactionAsync(sender, tx);1213 const result = getGenericResult(events);12141215 1216 1217 expect(result.success).to.be.true;1218 });1219}12201221export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1222 await usingApi(async (api) => {1223 1224 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1225 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1226 const result = getGenericResult(events);12271228 1229 1230 expect(result.success).to.be.false;1231 });1232}12331234export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1235 : Promise<UpDataStructsCollection | null> => {1236 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1237};12381239export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1240 1241 return (await api.rpc.unique.collectionStats()).created.toNumber();1242};12431244export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1245 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1246}12471248export async function waitNewBlocks(blocksCount = 1): Promise<void> {1249 await usingApi(async (api) => {1250 const promise = new Promise<void>(async (resolve) => {1251 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1252 if (blocksCount > 0) {1253 blocksCount--;1254 } else {1255 unsubscribe();1256 resolve();1257 }1258 });1259 });1260 return promise;1261 });1262}