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};40export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {41 if (typeof input === 'string') {42 if (input.length === 48 || input.length === 47) {43 return {Substrate: input};44 } else if (input.length === 42 && input.startsWith('0x')) {45 return {Ethereum: input.toLowerCase()};46 } else if (input.length === 40 && !input.startsWith('0x')) {47 return {Ethereum: '0x' + input.toLowerCase()};48 } else {49 throw new Error(`Unknown address format: "${input}"`);50 }51 }52 if ('address' in input) {53 return {Substrate: input.address};54 }55 if ('Ethereum' in input) {56 return {57 Ethereum: input.Ethereum.toLowerCase(),58 };59 } else if ('ethereum' in input) {60 return {61 Ethereum: (input as any).ethereum.toLowerCase(),62 };63 } else if ('Substrate' in input) {64 return input;65 } else if ('substrate' in input) {66 return {67 Substrate: (input as any).substrate,68 };69 }7071 72 return {Substrate: input.toString()};73}74export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {75 input = normalizeAccountId(input);76 if ('Substrate' in input) {77 return input.Substrate;78 } else {79 return evmToAddress(input.Ethereum);80 }81}8283export const U128_MAX = (1n << 128n) - 1n;8485const MICROUNIQUE = 1_000_000_000_000n;86const MILLIUNIQUE = 1_000n * MICROUNIQUE;87const CENTIUNIQUE = 10n * MILLIUNIQUE;88export const UNIQUE = 100n * CENTIUNIQUE;8990type GenericResult = {91 success: boolean,92};9394interface CreateCollectionResult {95 success: boolean;96 collectionId: number;97}9899interface CreateItemResult {100 success: boolean;101 collectionId: number;102 itemId: number;103 recipient?: CrossAccountId;104}105106interface TransferResult {107 success: boolean;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 getGenericResult(events: EventRecord[]): GenericResult {171 const result: GenericResult = {172 success: false,173 };174 events.forEach(({event: {method}}) => {175 176 if (method === 'ExtrinsicSuccess') {177 result.success = true;178 }179 });180 return result;181}182183184185export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {186 let success = false;187 let collectionId = 0;188 events.forEach(({event: {data, method, section}}) => {189 190 if (method == 'ExtrinsicSuccess') {191 success = true;192 } else if ((section == 'common') && (method == 'CollectionCreated')) {193 collectionId = parseInt(data[0].toString(), 10);194 }195 });196 const result: CreateCollectionResult = {197 success,198 collectionId,199 };200 return result;201}202203export function getCreateItemResult(events: EventRecord[]): CreateItemResult {204 let success = false;205 let collectionId = 0;206 let itemId = 0;207 let recipient;208 events.forEach(({event: {data, method, section}}) => {209 210 if (method == 'ExtrinsicSuccess') {211 success = true;212 } else if ((section == 'common') && (method == 'ItemCreated')) {213 collectionId = parseInt(data[0].toString(), 10);214 itemId = parseInt(data[1].toString(), 10);215 recipient = normalizeAccountId(data[2].toJSON() as any);216 }217 });218 const result: CreateItemResult = {219 success,220 collectionId,221 itemId,222 recipient,223 };224 return result;225}226227export function getTransferResult(events: EventRecord[]): TransferResult {228 const result: TransferResult = {229 success: false,230 collectionId: 0,231 itemId: 0,232 value: 0n,233 };234235 events.forEach(({event: {data, method, section}}) => {236 if (method === 'ExtrinsicSuccess') {237 result.success = true;238 } else if (section === 'common' && method === 'Transfer') {239 result.collectionId = +data[0].toString();240 result.itemId = +data[1].toString();241 result.sender = normalizeAccountId(data[2].toJSON() as any);242 result.recipient = normalizeAccountId(data[3].toJSON() as any);243 result.value = BigInt(data[4].toString());244 }245 });246247 return result;248}249250interface Nft {251 type: 'NFT';252}253254interface Fungible {255 type: 'Fungible';256 decimalPoints: number;257}258259interface ReFungible {260 type: 'ReFungible';261}262263type CollectionMode = Nft | Fungible | ReFungible;264265export type CreateCollectionParams = {266 mode: CollectionMode,267 name: string,268 description: string,269 tokenPrefix: string,270};271272const defaultCreateCollectionParams: CreateCollectionParams = {273 description: 'description',274 mode: {type: 'NFT'},275 name: 'name',276 tokenPrefix: 'prefix',277};278279export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {280 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};281282 let collectionId = 0;283 await usingApi(async (api) => {284 285 const collectionCountBefore = await getCreatedCollectionCount(api);286287 288 const alicePrivateKey = privateKey('//Alice');289290 let modeprm = {};291 if (mode.type === 'NFT') {292 modeprm = {nft: null};293 } else if (mode.type === 'Fungible') {294 modeprm = {fungible: mode.decimalPoints};295 } else if (mode.type === 'ReFungible') {296 modeprm = {refungible: null};297 }298299 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});300 const events = await submitTransactionAsync(alicePrivateKey, tx);301 const result = getCreateCollectionResult(events);302303 304 const collectionCountAfter = await getCreatedCollectionCount(api);305306 307 const collection = await queryCollectionExpectSuccess(api, result.collectionId);308309 310 311 expect(result.success).to.be.true;312 expect(result.collectionId).to.be.equal(collectionCountAfter);313 314 expect(collection).to.be.not.null;315 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');316 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));317 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);318 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);319 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);320321 collectionId = result.collectionId;322 });323324 return collectionId;325}326327export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {328 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};329330 let modeprm = {};331 if (mode.type === 'NFT') {332 modeprm = {nft: null};333 } else if (mode.type === 'Fungible') {334 modeprm = {fungible: mode.decimalPoints};335 } else if (mode.type === 'ReFungible') {336 modeprm = {refungible: null};337 }338339 await usingApi(async (api) => {340 341 const collectionCountBefore = await getCreatedCollectionCount(api);342343 344 const alicePrivateKey = privateKey('//Alice');345 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});346 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;347 const result = getCreateCollectionResult(events);348349 350 const collectionCountAfter = await getCreatedCollectionCount(api);351352 353 354 expect(result.success).to.be.false;355 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');356 });357}358359export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {360 let bal = 0n;361 let unused;362 do {363 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;364 const keyring = new Keyring({type: 'sr25519'});365 unused = keyring.addFromUri(`//${randomSeed}`);366 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();367 } while (bal !== 0n);368 return unused;369}370371export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {372 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();373}374375export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {376 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));377}378379export async function findNotExistingCollection(api: ApiPromise): Promise<number> {380 const totalNumber = await getCreatedCollectionCount(api);381 const newCollection: number = totalNumber + 1;382 return newCollection;383}384385function getDestroyResult(events: EventRecord[]): boolean {386 let success = false;387 events.forEach(({event: {method}}) => {388 if (method == 'ExtrinsicSuccess') {389 success = true;390 }391 });392 return success;393}394395export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {396 await usingApi(async (api) => {397 398 const alicePrivateKey = privateKey(senderSeed);399 const tx = api.tx.unique.destroyCollection(collectionId);400 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;401 });402}403404export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {405 await usingApi(async (api) => {406 407 const alicePrivateKey = privateKey(senderSeed);408 const tx = api.tx.unique.destroyCollection(collectionId);409 const events = await submitTransactionAsync(alicePrivateKey, tx);410 const result = getDestroyResult(events);411 expect(result).to.be.true;412413 414 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;415 });416}417418export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {419 await usingApi(async (api) => {420 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);421 const events = await submitTransactionAsync(sender, tx);422 const result = getGenericResult(events);423424 expect(result.success).to.be.true;425 });426}427428export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {429 await usingApi(async (api) => {430 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);431 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;432 const result = getGenericResult(events);433434 expect(result.success).to.be.false;435 });436}437438export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {439 await usingApi(async (api) => {440441 442 const senderPrivateKey = privateKey(sender);443 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);444 const events = await submitTransactionAsync(senderPrivateKey, tx);445 const result = getGenericResult(events);446447 448 const collection = await queryCollectionExpectSuccess(api, collectionId);449450 451 expect(result.success).to.be.true;452 expect(collection.sponsorship.toJSON()).to.deep.equal({453 unconfirmed: sponsor,454 });455 });456}457458export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {459 await usingApi(async (api) => {460461 462 const alicePrivateKey = privateKey(sender);463 const tx = api.tx.unique.removeCollectionSponsor(collectionId);464 const events = await submitTransactionAsync(alicePrivateKey, tx);465 const result = getGenericResult(events);466467 468 const collection = await queryCollectionExpectSuccess(api, collectionId);469470 471 expect(result.success).to.be.true;472 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});473 });474}475476export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {477 await usingApi(async (api) => {478479 480 const alicePrivateKey = privateKey(senderSeed);481 const tx = api.tx.unique.removeCollectionSponsor(collectionId);482 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;483 });484}485486export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {487 await usingApi(async (api) => {488489 490 const alicePrivateKey = privateKey(senderSeed);491 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);492 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;493 });494}495496export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {497 await usingApi(async (api) => {498499 500 const sender = privateKey(senderSeed);501 const tx = api.tx.unique.confirmSponsorship(collectionId);502 const events = await submitTransactionAsync(sender, tx);503 const result = getGenericResult(events);504505 506 const collection = await queryCollectionExpectSuccess(api, collectionId);507508 509 expect(result.success).to.be.true;510 expect(collection.sponsorship.toJSON()).to.be.deep.equal({511 confirmed: sender.address,512 });513 });514}515516517export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {518 await usingApi(async (api) => {519520 521 const sender = privateKey(senderSeed);522 const tx = api.tx.unique.confirmSponsorship(collectionId);523 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;524 });525}526527export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {528529 await usingApi(async (api) => {530 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);531 const events = await submitTransactionAsync(sender, tx);532 const result = getGenericResult(events);533534 expect(result.success).to.be.true;535 });536}537538export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {539540 await usingApi(async (api) => {541 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);542 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;543 const result = getGenericResult(events);544545 expect(result.success).to.be.false;546 });547}548549export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {550 await usingApi(async (api) => {551 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);552 const events = await submitTransactionAsync(sender, tx);553 const result = getGenericResult(events);554555 expect(result.success).to.be.true;556 });557}558559export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {560 await usingApi(async (api) => {561 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);562 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;563 const result = getGenericResult(events);564565 expect(result.success).to.be.false;566 });567}568569export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {570571 await usingApi(async (api) => {572573 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);574 const events = await submitTransactionAsync(sender, tx);575 const result = getGenericResult(events);576577 expect(result.success).to.be.true;578 });579}580581export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {582583 await usingApi(async (api) => {584585 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);586 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587 const result = getGenericResult(events);588589 expect(result.success).to.be.false;590 });591}592593export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {594 await usingApi(async (api) => {595 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);596 const events = await submitTransactionAsync(sender, tx);597 const result = getGenericResult(events);598599 expect(result.success).to.be.true;600 });601}602603export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {604 await usingApi(async (api) => {605 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);606 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;607 const result = getGenericResult(events);608609 expect(result.success).to.be.false;610 });611}612613export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {614 await usingApi(async (api) => {615 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);616 const events = await submitTransactionAsync(sender, tx);617 const result = getGenericResult(events);618619 expect(result.success).to.be.true;620 });621}622623export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {624 let allowlisted = false;625 await usingApi(async (api) => {626 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;627 });628 return allowlisted;629}630631export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {632 await usingApi(async (api) => {633 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());634 const events = await submitTransactionAsync(sender, tx);635 const result = getGenericResult(events);636637 expect(result.success).to.be.true;638 });639}640641export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {642 await usingApi(async (api) => {643 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());644 const events = await submitTransactionAsync(sender, tx);645 const result = getGenericResult(events);646647 expect(result.success).to.be.true;648 });649}650651export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {652 await usingApi(async (api) => {653 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());654 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;655 const result = getGenericResult(events);656657 expect(result.success).to.be.false;658 });659}660661export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {662 await usingApi(async (api) => {663 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));664 const events = await submitTransactionAsync(sender, tx);665 const result = getGenericResult(events);666667 expect(result.success).to.be.true;668 });669}670671export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {672 await usingApi(async (api) => {673 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));674 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;675 });676}677678export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {679 await usingApi(async (api) => {680 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686}687688export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));691 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 });693}694695export interface CreateFungibleData {696 readonly Value: bigint;697}698699export interface CreateReFungibleData { }700export interface CreateNftData { }701702export type CreateItemData = {703 NFT: CreateNftData;704} | {705 Fungible: CreateFungibleData;706} | {707 ReFungible: CreateReFungibleData;708};709710export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {711 await usingApi(async (api) => {712 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);713 714 expect(balanceBefore >= BigInt(value)).to.be.true;715716 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);717 const events = await submitTransactionAsync(sender, tx);718 const result = getGenericResult(events);719 expect(result.success).to.be.true;720721 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);722 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);723 });724}725726export async function727approveExpectSuccess(728 collectionId: number,729 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,730) {731 await usingApi(async (api: ApiPromise) => {732 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);733 const events = await submitTransactionAsync(owner, approveUniqueTx);734 const result = getGenericResult(events);735 expect(result.success).to.be.true;736737 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));738 });739}740741export async function adminApproveFromExpectSuccess(742 collectionId: number,743 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,744) {745 await usingApi(async (api: ApiPromise) => {746 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);747 const events = await submitTransactionAsync(admin, approveUniqueTx);748 const result = getGenericResult(events);749 expect(result.success).to.be.true;750751 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));752 });753}754755export async function756transferFromExpectSuccess(757 collectionId: number,758 tokenId: number,759 accountApproved: IKeyringPair,760 accountFrom: IKeyringPair | CrossAccountId,761 accountTo: IKeyringPair | CrossAccountId,762 value: number | bigint = 1,763 type = 'NFT',764) {765 await usingApi(async (api: ApiPromise) => {766 const to = normalizeAccountId(accountTo);767 let balanceBefore = 0n;768 if (type === 'Fungible') {769 balanceBefore = await getBalance(api, collectionId, to, tokenId);770 }771 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);772 const events = await submitTransactionAsync(accountApproved, transferFromTx);773 const result = getCreateItemResult(events);774 775 expect(result.success).to.be.true;776 if (type === 'NFT') {777 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);778 }779 if (type === 'Fungible') {780 const balanceAfter = await getBalance(api, collectionId, to, tokenId);781 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));782 }783 if (type === 'ReFungible') {784 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));785 }786 });787}788789export async function790transferFromExpectFail(791 collectionId: number,792 tokenId: number,793 accountApproved: IKeyringPair,794 accountFrom: IKeyringPair,795 accountTo: IKeyringPair,796 value: number | bigint = 1,797) {798 await usingApi(async (api: ApiPromise) => {799 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);800 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;801 const result = getCreateCollectionResult(events);802 803 expect(result.success).to.be.false;804 });805}806807808async function getBlockNumber(api: ApiPromise): Promise<number> {809 return new Promise<number>(async (resolve) => {810 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {811 unsubscribe();812 resolve(head.number.toNumber());813 });814 });815}816817export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {818 await usingApi(async (api) => {819 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));820 const events = await submitTransactionAsync(sender, changeAdminTx);821 const result = getCreateCollectionResult(events);822 expect(result.success).to.be.true;823 });824}825826export async function827getFreeBalance(account: IKeyringPair): Promise<bigint> {828 let balance = 0n;829 await usingApi(async (api) => {830 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());831 });832833 return balance;834}835836export async function837scheduleTransferExpectSuccess(838 collectionId: number,839 tokenId: number,840 sender: IKeyringPair,841 recipient: IKeyringPair,842 value: number | bigint = 1,843 blockSchedule: number,844) {845 await usingApi(async (api: ApiPromise) => {846 const blockNumber: number | undefined = await getBlockNumber(api);847 const expectedBlockNumber = blockNumber + blockSchedule;848849 expect(blockNumber).to.be.greaterThan(0);850 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);851 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);852853 await submitTransactionAsync(sender, scheduleTx);854855 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();856857 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));858859 860 await waitNewBlocks(blockSchedule + 1);861862 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();863864 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));865 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);866 });867}868869870export async function871transferExpectSuccess(872 collectionId: number,873 tokenId: number,874 sender: IKeyringPair,875 recipient: IKeyringPair | CrossAccountId,876 value: number | bigint = 1,877 type = 'NFT',878) {879 await usingApi(async (api: ApiPromise) => {880 const to = normalizeAccountId(recipient);881882 let balanceBefore = 0n;883 if (type === 'Fungible') {884 balanceBefore = await getBalance(api, collectionId, to, tokenId);885 }886 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);887 const events = await submitTransactionAsync(sender, transferTx);888 const result = getTransferResult(events);889 890 expect(result.success).to.be.true;891 expect(result.collectionId).to.be.equal(collectionId);892 expect(result.itemId).to.be.equal(tokenId);893 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));894 expect(result.recipient).to.be.deep.equal(to);895 expect(result.value).to.be.equal(BigInt(value));896 if (type === 'NFT') {897 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);898 }899 if (type === 'Fungible') {900 const balanceAfter = await getBalance(api, collectionId, to, tokenId);901 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));902 }903 if (type === 'ReFungible') {904 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;905 }906 });907}908909export async function910transferExpectFailure(911 collectionId: number,912 tokenId: number,913 sender: IKeyringPair,914 recipient: IKeyringPair,915 value: number | bigint = 1,916) {917 await usingApi(async (api: ApiPromise) => {918 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);919 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;920 const result = getGenericResult(events);921 922 923 924 expect(result.success).to.be.false;925 926 });927}928929export async function930approveExpectFail(931 collectionId: number,932 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,933) {934 await usingApi(async (api: ApiPromise) => {935 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);936 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;937 const result = getCreateCollectionResult(events);938 939 expect(result.success).to.be.false;940 });941}942943export async function getBalance(944 api: ApiPromise,945 collectionId: number,946 owner: string | CrossAccountId,947 token: number,948): Promise<bigint> {949 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();950}951export async function getTokenOwner(952 api: ApiPromise,953 collectionId: number,954 token: number,955): Promise<CrossAccountId> {956 return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);957}958export async function isTokenExists(959 api: ApiPromise,960 collectionId: number,961 token: number,962): Promise<boolean> {963 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();964}965export async function getLastTokenId(966 api: ApiPromise,967 collectionId: number,968): Promise<number> {969 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();970}971export async function getAdminList(972 api: ApiPromise,973 collectionId: number,974): Promise<string[]> {975 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;976}977export async function getVariableMetadata(978 api: ApiPromise,979 collectionId: number,980 tokenId: number,981): Promise<number[]> {982 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];983}984export async function getConstMetadata(985 api: ApiPromise,986 collectionId: number,987 tokenId: number,988): Promise<number[]> {989 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];990}991992export async function createFungibleItemExpectSuccess(993 sender: IKeyringPair,994 collectionId: number,995 data: CreateFungibleData,996 owner: CrossAccountId | string = sender.address,997) {998 return await usingApi(async (api) => {999 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10001001 const events = await submitTransactionAsync(sender, tx);1002 const result = getCreateItemResult(events);10031004 expect(result.success).to.be.true;1005 return result.itemId;1006 });1007}10081009export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1010 let newItemId = 0;1011 await usingApi(async (api) => {1012 const to = normalizeAccountId(owner);1013 const itemCountBefore = await getLastTokenId(api, collectionId);1014 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10151016 let tx;1017 if (createMode === 'Fungible') {1018 const createData = {fungible: {value: 10}};1019 tx = api.tx.unique.createItem(collectionId, to, createData as any);1020 } else if (createMode === 'ReFungible') {1021 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1022 tx = api.tx.unique.createItem(collectionId, to, createData as any);1023 } else {1024 const createData = {nft: {const_data: [], variable_data: []}};1025 tx = api.tx.unique.createItem(collectionId, to, createData as any);1026 }10271028 const events = await submitTransactionAsync(sender, tx);1029 const result = getCreateItemResult(events);10301031 const itemCountAfter = await getLastTokenId(api, collectionId);1032 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10331034 1035 1036 expect(result.success).to.be.true;1037 if (createMode === 'Fungible') {1038 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1039 } else {1040 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1041 }1042 expect(collectionId).to.be.equal(result.collectionId);1043 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1044 expect(to).to.be.deep.equal(result.recipient);1045 newItemId = result.itemId;1046 });1047 return newItemId;1048}10491050export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1051 await usingApi(async (api) => {1052 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10531054 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1055 const result = getCreateItemResult(events);10561057 expect(result.success).to.be.false;1058 });1059}10601061export async function setPublicAccessModeExpectSuccess(1062 sender: IKeyringPair, collectionId: number,1063 accessMode: 'Normal' | 'AllowList',1064) {1065 await usingApi(async (api) => {10661067 1068 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1069 const events = await submitTransactionAsync(sender, tx);1070 const result = getGenericResult(events);10711072 1073 const collection = await queryCollectionExpectSuccess(api, collectionId);10741075 1076 1077 expect(result.success).to.be.true;1078 expect(collection.access.toHuman()).to.be.equal(accessMode);1079 });1080}10811082export async function setPublicAccessModeExpectFail(1083 sender: IKeyringPair, collectionId: number,1084 accessMode: 'Normal' | 'AllowList',1085) {1086 await usingApi(async (api) => {10871088 1089 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1090 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1091 const result = getGenericResult(events);10921093 1094 1095 expect(result.success).to.be.false;1096 });1097}10981099export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1100 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1101}11021103export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1104 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1105}11061107export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1108 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1109}11101111export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1112 await usingApi(async (api) => {11131114 1115 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1116 const events = await submitTransactionAsync(sender, tx);1117 const result = getGenericResult(events);1118 expect(result.success).to.be.true;11191120 1121 const collection = await queryCollectionExpectSuccess(api, collectionId);11221123 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1124 });1125}11261127export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1128 await setMintPermissionExpectSuccess(sender, collectionId, true);1129}11301131export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1132 await usingApi(async (api) => {1133 1134 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1135 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1136 const result = getCreateCollectionResult(events);1137 1138 expect(result.success).to.be.false;1139 });1140}11411142export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1143 await usingApi(async (api) => {1144 1145 const tx = api.tx.unique.setChainLimits(limits);1146 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1147 const result = getCreateCollectionResult(events);1148 1149 expect(result.success).to.be.false;1150 });1151}11521153export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1154 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1155}11561157export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1158 await usingApi(async (api) => {1159 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11601161 1162 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1163 const events = await submitTransactionAsync(sender, tx);1164 const result = getGenericResult(events);1165 expect(result.success).to.be.true;11661167 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1168 });1169}11701171export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1172 await usingApi(async (api) => {11731174 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11751176 1177 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1178 const events = await submitTransactionAsync(sender, tx);1179 const result = getGenericResult(events);1180 expect(result.success).to.be.true;11811182 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1183 });1184}11851186export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1187 await usingApi(async (api) => {11881189 1190 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1191 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1192 const result = getGenericResult(events);11931194 1195 1196 expect(result.success).to.be.false;1197 });1198}11991200export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1201 await usingApi(async (api) => {1202 1203 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1204 const events = await submitTransactionAsync(sender, tx);1205 const result = getGenericResult(events);12061207 1208 1209 expect(result.success).to.be.true;1210 });1211}12121213export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1214 await usingApi(async (api) => {1215 1216 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1217 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1218 const result = getGenericResult(events);12191220 1221 1222 expect(result.success).to.be.false;1223 });1224}12251226export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1227 : Promise<UpDataStructsCollection | null> => {1228 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1229};12301231export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1232 1233 return (await api.rpc.unique.collectionStats()).created.toNumber();1234};12351236export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1237 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1238}12391240export async function waitNewBlocks(blocksCount = 1): Promise<void> {1241 await usingApi(async (api) => {1242 const promise = new Promise<void>(async (resolve) => {1243 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1244 if (blocksCount > 0) {1245 blocksCount--;1246 } else {1247 unsubscribe();1248 resolve();1249 }1250 });1251 });1252 return promise;1253 });1254}