1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 collectionId: number;109 itemId: number;110 sender?: CrossAccountId;111 recipient?: CrossAccountId;112 value: bigint;113}114115interface IReFungibleOwner {116 fraction: BN;117 owner: number[];118}119120interface IGetMessage {121 checkMsgUnqMethod: string;122 checkMsgTrsMethod: string;123 checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127 value: number;128}129130export interface IChainLimits {131 collectionNumbersLimit: number;132 accountTokenOwnershipLimit: number;133 collectionsAdminsLimit: number;134 customDataLimit: number;135 nftSponsorTransferTimeout: number;136 fungibleSponsorTransferTimeout: number;137 refungibleSponsorTransferTimeout: number;138 offchainSchemaLimit: number;139 constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143 owner: IReFungibleOwner[];144 constData: number[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175 const result: GenericResult = {176 success: false,177 };178 events.forEach(({event: {method}}) => {179 180 if (method === 'ExtrinsicSuccess') {181 result.success = true;182 }183 });184 return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190 let success = false;191 let collectionId = 0;192 events.forEach(({event: {data, method, section}}) => {193 194 if (method == 'ExtrinsicSuccess') {195 success = true;196 } else if ((section == 'common') && (method == 'CollectionCreated')) {197 collectionId = parseInt(data[0].toString(), 10);198 }199 });200 const result: CreateCollectionResult = {201 success,202 collectionId,203 };204 return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208 let success = false;209 let collectionId = 0;210 let itemId = 0;211 let recipient;212213 const results : CreateItemResult[] = [];214215 events.forEach(({event: {data, method, section}}) => {216 217 if (method == 'ExtrinsicSuccess') {218 success = true;219 } else if ((section == 'common') && (method == 'ItemCreated')) {220 collectionId = parseInt(data[0].toString(), 10);221 itemId = parseInt(data[1].toString(), 10);222 recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 }233 });234235 return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239 let success = false;240 let collectionId = 0;241 let itemId = 0;242 let recipient;243 events.forEach(({event: {data, method, section}}) => {244 245 if (method == 'ExtrinsicSuccess') {246 success = true;247 } else if ((section == 'common') && (method == 'ItemCreated')) {248 collectionId = parseInt(data[0].toString(), 10);249 itemId = parseInt(data[1].toString(), 10);250 recipient = normalizeAccountId(data[2].toJSON() as any);251 }252 });253 const result: CreateItemResult = {254 success,255 collectionId,256 itemId,257 recipient,258 };259 return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263 for (const {event} of events) {264 if (api.events.common.Transfer.is(event)) {265 const [collection, token, sender, recipient, value] = event.data;266 return {267 collectionId: collection.toNumber(),268 itemId: token.toNumber(),269 sender: normalizeAccountId(sender.toJSON() as any),270 recipient: normalizeAccountId(recipient.toJSON() as any),271 value: value.toBigInt(),272 };273 }274 }275 throw new Error('no transfer event');276}277278interface Nft {279 type: 'NFT';280}281282interface Fungible {283 type: 'Fungible';284 decimalPoints: number;285}286287interface ReFungible {288 type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294 key: any,295 value: any,296};297298type PropertyPermission = {299 key: any,300 mutable: boolean;301 collectionAdmin: boolean;302 tokenOwner: boolean;303}304305export type CreateCollectionParams = {306 mode: CollectionMode,307 name: string,308 description: string,309 tokenPrefix: string,310 schemaVersion: string,311 properties?: Array<Property>,312 propPerm?: Array<PropertyPermission>313};314315const defaultCreateCollectionParams: CreateCollectionParams = {316 description: 'description',317 mode: {type: 'NFT'},318 name: 'name',319 tokenPrefix: 'prefix',320 schemaVersion: 'ImageURL',321};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};325326 let collectionId = 0;327 await usingApi(async (api) => {328 329 const collectionCountBefore = await getCreatedCollectionCount(api);330331 332 const alicePrivateKey = privateKey('//Alice');333334 let modeprm = {};335 if (mode.type === 'NFT') {336 modeprm = {nft: null};337 } else if (mode.type === 'Fungible') {338 modeprm = {fungible: mode.decimalPoints};339 } else if (mode.type === 'ReFungible') {340 modeprm = {refungible: null};341 }342343 const tx = api.tx.unique.createCollectionEx({344 name: strToUTF16(name),345 description: strToUTF16(description),346 tokenPrefix: strToUTF16(tokenPrefix),347 mode: modeprm as any,348 schemaVersion: schemaVersion,349 });350 const events = await submitTransactionAsync(alicePrivateKey, tx);351 const result = getCreateCollectionResult(events);352353 354 const collectionCountAfter = await getCreatedCollectionCount(api);355356 357 const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359 360 361 expect(result.success).to.be.true;362 expect(result.collectionId).to.be.equal(collectionCountAfter);363 364 expect(collection).to.be.not.null;365 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371 collectionId = result.collectionId;372 });373374 return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380 let collectionId = 0;381 await usingApi(async (api) => {382 383 const collectionCountBefore = await getCreatedCollectionCount(api);384385 386 const alicePrivateKey = privateKey('//Alice');387388 let modeprm = {};389 if (mode.type === 'NFT') {390 modeprm = {nft: null};391 } else if (mode.type === 'Fungible') {392 modeprm = {fungible: mode.decimalPoints};393 } else if (mode.type === 'ReFungible') {394 modeprm = {refungible: null};395 }396397 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});398 const events = await submitTransactionAsync(alicePrivateKey, tx);399 const result = getCreateCollectionResult(events);400401 402 const collectionCountAfter = await getCreatedCollectionCount(api);403404 405 const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407 408 409 expect(result.success).to.be.true;410 expect(result.collectionId).to.be.equal(collectionCountAfter);411 412 expect(collection).to.be.not.null;413 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420 collectionId = result.collectionId;421 });422423 return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429 await usingApi(async (api) => {430 431 const collectionCountBefore = await getCreatedCollectionCount(api);432433 434 const alicePrivateKey = privateKey('//Alice');435436 let modeprm = {};437 if (mode.type === 'NFT') {438 modeprm = {nft: null};439 } else if (mode.type === 'Fungible') {440 modeprm = {fungible: mode.decimalPoints};441 } else if (mode.type === 'ReFungible') {442 modeprm = {refungible: null};443 }444445 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});446 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449 450 const collectionCountAfter = await getCreatedCollectionCount(api);451452 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453 });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459 let modeprm = {};460 if (mode.type === 'NFT') {461 modeprm = {nft: null};462 } else if (mode.type === 'Fungible') {463 modeprm = {fungible: mode.decimalPoints};464 } else if (mode.type === 'ReFungible') {465 modeprm = {refungible: null};466 }467468 await usingApi(async (api) => {469 470 const collectionCountBefore = await getCreatedCollectionCount(api);471472 473 const alicePrivateKey = privateKey('//Alice');474 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477 478 const collectionCountAfter = await getCreatedCollectionCount(api);479480 481 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482 });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486 let bal = 0n;487 let unused;488 do {489 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490 const keyring = new Keyring({type: 'sr25519'});491 unused = keyring.addFromUri(`//${randomSeed}`);492 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493 } while (bal !== 0n);494 return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506 const totalNumber = await getCreatedCollectionCount(api);507 const newCollection: number = totalNumber + 1;508 return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512 let success = false;513 events.forEach(({event: {method}}) => {514 if (method == 'ExtrinsicSuccess') {515 success = true;516 }517 });518 return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522 await usingApi(async (api) => {523 524 const alicePrivateKey = privateKey(senderSeed);525 const tx = api.tx.unique.destroyCollection(collectionId);526 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527 });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531 await usingApi(async (api) => {532 533 const alicePrivateKey = privateKey(senderSeed);534 const tx = api.tx.unique.destroyCollection(collectionId);535 const events = await submitTransactionAsync(alicePrivateKey, tx);536 const result = getDestroyResult(events);537 expect(result).to.be.true;538539 540 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541 });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545 await usingApi(async (api) => {546 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547 const events = await submitTransactionAsync(sender, tx);548 const result = getGenericResult(events);549550 expect(result.success).to.be.true;551 });552}553554export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {555 await usingApi(async (api) => {556 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);557 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;558 const result = getGenericResult(events);559560 expect(result.success).to.be.false;561 });562}563564export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {565 await usingApi(async (api) => {566567 568 const senderPrivateKey = privateKey(sender);569 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);570 const events = await submitTransactionAsync(senderPrivateKey, tx);571 const result = getGenericResult(events);572573 574 const collection = await queryCollectionExpectSuccess(api, collectionId);575576 577 expect(result.success).to.be.true;578 expect(collection.sponsorship.toJSON()).to.deep.equal({579 unconfirmed: sponsor,580 });581 });582}583584export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {585 await usingApi(async (api) => {586587 588 const alicePrivateKey = privateKey(sender);589 const tx = api.tx.unique.removeCollectionSponsor(collectionId);590 const events = await submitTransactionAsync(alicePrivateKey, tx);591 const result = getGenericResult(events);592593 594 const collection = await queryCollectionExpectSuccess(api, collectionId);595596 597 expect(result.success).to.be.true;598 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});599 });600}601602export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {603 await usingApi(async (api) => {604605 606 const alicePrivateKey = privateKey(senderSeed);607 const tx = api.tx.unique.removeCollectionSponsor(collectionId);608 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;609 });610}611612export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {613 await usingApi(async (api) => {614615 616 const alicePrivateKey = privateKey(senderSeed);617 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);618 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619 });620}621622export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {623 await usingApi(async (api) => {624625 626 const sender = privateKey(senderSeed);627 const tx = api.tx.unique.confirmSponsorship(collectionId);628 const events = await submitTransactionAsync(sender, tx);629 const result = getGenericResult(events);630631 632 const collection = await queryCollectionExpectSuccess(api, collectionId);633634 635 expect(result.success).to.be.true;636 expect(collection.sponsorship.toJSON()).to.be.deep.equal({637 confirmed: sender.address,638 });639 });640}641642643export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {644 await usingApi(async (api) => {645646 647 const sender = privateKey(senderSeed);648 const tx = api.tx.unique.confirmSponsorship(collectionId);649 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;650 });651}652653export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {654655 await usingApi(async (api) => {656 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);657 const events = await submitTransactionAsync(sender, tx);658 const result = getGenericResult(events);659660 expect(result.success).to.be.true;661 });662}663664export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {665666 await usingApi(async (api) => {667 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);668 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;669 const result = getGenericResult(events);670671 expect(result.success).to.be.false;672 });673}674675export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {676 await usingApi(async (api) => {677 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);678 const events = await submitTransactionAsync(sender, tx);679 const result = getGenericResult(events);680681 expect(result.success).to.be.true;682 });683}684685export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {686 await usingApi(async (api) => {687 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);688 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;689 const result = getGenericResult(events);690691 expect(result.success).to.be.false;692 });693}694695export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {696697 await usingApi(async (api) => {698699 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);700 const events = await submitTransactionAsync(sender, tx);701 const result = getGenericResult(events);702703 expect(result.success).to.be.true;704 });705}706707export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {708709 await usingApi(async (api) => {710711 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);712 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;713 const result = getGenericResult(events);714715 expect(result.success).to.be.false;716 });717}718719export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {720 await usingApi(async (api) => {721 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);722 const events = await submitTransactionAsync(sender, tx);723 const result = getGenericResult(events);724725 expect(result.success).to.be.true;726 });727}728729export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {730 await usingApi(async (api) => {731 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);732 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;733 const result = getGenericResult(events);734735 expect(result.success).to.be.false;736 });737}738739export async function getNextSponsored(740 api: ApiPromise,741 collectionId: number,742 account: string | CrossAccountId,743 tokenId: number,744): Promise<number> {745 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));746}747748export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {749 await usingApi(async (api) => {750 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);751 const events = await submitTransactionAsync(sender, tx);752 const result = getGenericResult(events);753754 expect(result.success).to.be.true;755 });756}757758export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {759 let allowlisted = false;760 await usingApi(async (api) => {761 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;762 });763 return allowlisted;764}765766export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {767 await usingApi(async (api) => {768 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());769 const events = await submitTransactionAsync(sender, tx);770 const result = getGenericResult(events);771772 expect(result.success).to.be.true;773 });774}775776export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {777 await usingApi(async (api) => {778 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());779 const events = await submitTransactionAsync(sender, tx);780 const result = getGenericResult(events);781782 expect(result.success).to.be.true;783 });784}785786export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {787 await usingApi(async (api) => {788 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());789 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790 const result = getGenericResult(events);791792 expect(result.success).to.be.false;793 });794}795796export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {797 await usingApi(async (api) => {798 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));799 const events = await submitTransactionAsync(sender, tx);800 const result = getGenericResult(events);801802 expect(result.success).to.be.true;803 });804}805806export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {807 await usingApi(async (api) => {808 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));809 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;810 });811}812813export interface CreateFungibleData {814 readonly Value: bigint;815}816817export interface CreateReFungibleData { }818export interface CreateNftData { }819820export type CreateItemData = {821 NFT: CreateNftData;822} | {823 Fungible: CreateFungibleData;824} | {825 ReFungible: CreateReFungibleData;826};827828export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {829 await usingApi(async (api) => {830 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);831 832 expect(balanceBefore >= BigInt(value)).to.be.true;833834 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);835 const events = await submitTransactionAsync(sender, tx);836 const result = getGenericResult(events);837 expect(result.success).to.be.true;838839 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);840 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);841 });842}843844export async function845approveExpectSuccess(846 collectionId: number,847 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,848) {849 await usingApi(async (api: ApiPromise) => {850 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);851 const events = await submitTransactionAsync(owner, approveUniqueTx);852 const result = getGenericResult(events);853 expect(result.success).to.be.true;854855 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));856 });857}858859export async function adminApproveFromExpectSuccess(860 collectionId: number,861 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,862) {863 await usingApi(async (api: ApiPromise) => {864 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);865 const events = await submitTransactionAsync(admin, approveUniqueTx);866 const result = getGenericResult(events);867 expect(result.success).to.be.true;868869 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));870 });871}872873export async function874transferFromExpectSuccess(875 collectionId: number,876 tokenId: number,877 accountApproved: IKeyringPair,878 accountFrom: IKeyringPair | CrossAccountId,879 accountTo: IKeyringPair | CrossAccountId,880 value: number | bigint = 1,881 type = 'NFT',882) {883 await usingApi(async (api: ApiPromise) => {884 const from = normalizeAccountId(accountFrom);885 const to = normalizeAccountId(accountTo);886 let balanceBefore = 0n;887 if (type === 'Fungible' || type === 'ReFungible') {888 balanceBefore = await getBalance(api, collectionId, to, tokenId);889 }890 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);891 const events = await submitTransactionAsync(accountApproved, transferFromTx);892 const result = getCreateItemResult(events);893 894 expect(result.success).to.be.true;895 if (type === 'NFT') {896 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);897 }898 if (type === 'Fungible') {899 const balanceAfter = await getBalance(api, collectionId, to, tokenId);900 if (JSON.stringify(to) !== JSON.stringify(from)) {901 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));902 } else {903 expect(balanceAfter).to.be.equal(balanceBefore);904 }905 }906 if (type === 'ReFungible') {907 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));908 }909 });910}911912export async function913transferFromExpectFail(914 collectionId: number,915 tokenId: number,916 accountApproved: IKeyringPair,917 accountFrom: IKeyringPair,918 accountTo: IKeyringPair,919 value: number | bigint = 1,920) {921 await usingApi(async (api: ApiPromise) => {922 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);923 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;924 const result = getCreateCollectionResult(events);925 926 expect(result.success).to.be.false;927 });928}929930931async function getBlockNumber(api: ApiPromise): Promise<number> {932 return new Promise<number>(async (resolve) => {933 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {934 unsubscribe();935 resolve(head.number.toNumber());936 });937 });938}939940export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {941 await usingApi(async (api) => {942 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));943 const events = await submitTransactionAsync(sender, changeAdminTx);944 const result = getCreateCollectionResult(events);945 expect(result.success).to.be.true;946 });947}948949export async function950getFreeBalance(account: IKeyringPair): Promise<bigint> {951 let balance = 0n;952 await usingApi(async (api) => {953 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());954 });955956 return balance;957}958959export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {960 const tx = api.tx.balances.transfer(target, amount);961 const events = await submitTransactionAsync(source, tx);962 const result = getGenericResult(events);963 expect(result.success).to.be.true;964}965966export async function967scheduleTransferExpectSuccess(968 collectionId: number,969 tokenId: number,970 sender: IKeyringPair,971 recipient: IKeyringPair,972 value: number | bigint = 1,973 blockSchedule: number,974) {975 await usingApi(async (api: ApiPromise) => {976 const blockNumber: number | undefined = await getBlockNumber(api);977 const expectedBlockNumber = blockNumber + blockSchedule;978979 expect(blockNumber).to.be.greaterThan(0);980 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);981 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);982983 await submitTransactionAsync(sender, scheduleTx);984985 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();986987 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));988989 990 await waitNewBlocks(blockSchedule + 1);991992 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();993994 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));995 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);996 });997}9989991000export async function1001transferExpectSuccess(1002 collectionId: number,1003 tokenId: number,1004 sender: IKeyringPair,1005 recipient: IKeyringPair | CrossAccountId,1006 value: number | bigint = 1,1007 type = 'NFT',1008) {1009 await usingApi(async (api: ApiPromise) => {1010 const from = normalizeAccountId(sender);1011 const to = normalizeAccountId(recipient);10121013 let balanceBefore = 0n;1014 if (type === 'Fungible') {1015 balanceBefore = await getBalance(api, collectionId, to, tokenId);1016 }1017 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1018 const events = await executeTransaction(api, sender, transferTx);10191020 const result = getTransferResult(api, events);1021 expect(result.collectionId).to.be.equal(collectionId);1022 expect(result.itemId).to.be.equal(tokenId);1023 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1024 expect(result.recipient).to.be.deep.equal(to);1025 expect(result.value).to.be.equal(BigInt(value));10261027 if (type === 'NFT') {1028 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1029 }1030 if (type === 'Fungible') {1031 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1032 if (JSON.stringify(to) !== JSON.stringify(from)) {1033 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1034 } else {1035 expect(balanceAfter).to.be.equal(balanceBefore);1036 }1037 }1038 if (type === 'ReFungible') {1039 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1040 }1041 });1042}10431044export async function1045transferExpectFailure(1046 collectionId: number,1047 tokenId: number,1048 sender: IKeyringPair,1049 recipient: IKeyringPair | CrossAccountId,1050 value: number | bigint = 1,1051) {1052 await usingApi(async (api: ApiPromise) => {1053 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1054 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1055 const result = getGenericResult(events);1056 1057 1058 1059 expect(result.success).to.be.false;1060 1061 });1062}10631064export async function1065approveExpectFail(1066 collectionId: number,1067 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1068) {1069 await usingApi(async (api: ApiPromise) => {1070 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1071 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1072 const result = getCreateCollectionResult(events);1073 1074 expect(result.success).to.be.false;1075 });1076}10771078export async function getBalance(1079 api: ApiPromise,1080 collectionId: number,1081 owner: string | CrossAccountId,1082 token: number,1083): Promise<bigint> {1084 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1085}1086export async function getTokenOwner(1087 api: ApiPromise,1088 collectionId: number,1089 token: number,1090): Promise<CrossAccountId> {1091 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1092 if (owner == null) throw new Error('owner == null');1093 return normalizeAccountId(owner);1094}1095export async function getTopmostTokenOwner(1096 api: ApiPromise,1097 collectionId: number,1098 token: number,1099): Promise<CrossAccountId> {1100 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1101 if (owner == null) throw new Error('owner == null');1102 return normalizeAccountId(owner);1103}1104export async function isTokenExists(1105 api: ApiPromise,1106 collectionId: number,1107 token: number,1108): Promise<boolean> {1109 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1110}1111export async function getLastTokenId(1112 api: ApiPromise,1113 collectionId: number,1114): Promise<number> {1115 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1116}1117export async function getAdminList(1118 api: ApiPromise,1119 collectionId: number,1120): Promise<string[]> {1121 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1122}1123export async function getConstMetadata(1124 api: ApiPromise,1125 collectionId: number,1126 tokenId: number,1127): Promise<number[]> {1128 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1129}11301131export async function createFungibleItemExpectSuccess(1132 sender: IKeyringPair,1133 collectionId: number,1134 data: CreateFungibleData,1135 owner: CrossAccountId | string = sender.address,1136) {1137 return await usingApi(async (api) => {1138 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11391140 const events = await submitTransactionAsync(sender, tx);1141 const result = getCreateItemResult(events);11421143 expect(result.success).to.be.true;1144 return result.itemId;1145 });1146}11471148export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1149 let newItemId = 0;1150 await usingApi(async (api) => {1151 const to = normalizeAccountId(owner);1152 const itemCountBefore = await getLastTokenId(api, collectionId);1153 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11541155 let tx;1156 if (createMode === 'Fungible') {1157 const createData = {fungible: {value: 10}};1158 tx = api.tx.unique.createItem(collectionId, to, createData as any);1159 } else if (createMode === 'ReFungible') {1160 const createData = {refungible: {const_data: [], pieces: 100}};1161 tx = api.tx.unique.createItem(collectionId, to, createData as any);1162 } else {1163 const createData = {nft: {const_data: []}};1164 tx = api.tx.unique.createItem(collectionId, to, createData as any);1165 }11661167 const events = await submitTransactionAsync(sender, tx);1168 const result = getCreateItemResult(events);11691170 const itemCountAfter = await getLastTokenId(api, collectionId);1171 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11721173 1174 1175 expect(result.success).to.be.true;1176 if (createMode === 'Fungible') {1177 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1178 } else {1179 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1180 }1181 expect(collectionId).to.be.equal(result.collectionId);1182 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1183 expect(to).to.be.deep.equal(result.recipient);1184 newItemId = result.itemId;1185 });1186 return newItemId;1187}11881189export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1190 await usingApi(async (api) => {1191 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11921193 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1194 const result = getCreateItemResult(events);11951196 expect(result.success).to.be.false;1197 });1198}11991200export async function setPublicAccessModeExpectSuccess(1201 sender: IKeyringPair, collectionId: number,1202 accessMode: 'Normal' | 'AllowList',1203) {1204 await usingApi(async (api) => {12051206 1207 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1208 const events = await submitTransactionAsync(sender, tx);1209 const result = getGenericResult(events);12101211 1212 const collection = await queryCollectionExpectSuccess(api, collectionId);12131214 1215 1216 expect(result.success).to.be.true;1217 expect(collection.access.toHuman()).to.be.equal(accessMode);1218 });1219}12201221export async function setPublicAccessModeExpectFail(1222 sender: IKeyringPair, collectionId: number,1223 accessMode: 'Normal' | 'AllowList',1224) {1225 await usingApi(async (api) => {12261227 1228 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1229 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1230 const result = getGenericResult(events);12311232 1233 1234 expect(result.success).to.be.false;1235 });1236}12371238export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1239 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1240}12411242export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1243 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1244}12451246export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1247 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1248}12491250export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1251 await usingApi(async (api) => {12521253 1254 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1255 const events = await submitTransactionAsync(sender, tx);1256 const result = getGenericResult(events);1257 expect(result.success).to.be.true;12581259 1260 const collection = await queryCollectionExpectSuccess(api, collectionId);12611262 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1263 });1264}12651266export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1267 await setMintPermissionExpectSuccess(sender, collectionId, true);1268}12691270export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1271 await usingApi(async (api) => {1272 1273 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1274 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1275 const result = getCreateCollectionResult(events);1276 1277 expect(result.success).to.be.false;1278 });1279}12801281export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1282 await usingApi(async (api) => {1283 1284 const tx = api.tx.unique.setChainLimits(limits);1285 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1286 const result = getCreateCollectionResult(events);1287 1288 expect(result.success).to.be.false;1289 });1290}12911292export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1293 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1294}12951296export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1297 await usingApi(async (api) => {1298 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12991300 1301 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1302 const events = await submitTransactionAsync(sender, tx);1303 const result = getGenericResult(events);1304 expect(result.success).to.be.true;13051306 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1307 });1308}13091310export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1311 await usingApi(async (api) => {13121313 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13141315 1316 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1317 const events = await submitTransactionAsync(sender, tx);1318 const result = getGenericResult(events);1319 expect(result.success).to.be.true;13201321 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1322 });1323}13241325export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1326 await usingApi(async (api) => {13271328 1329 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1330 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1331 const result = getGenericResult(events);13321333 1334 1335 expect(result.success).to.be.false;1336 });1337}13381339export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1340 await usingApi(async (api) => {1341 1342 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1343 const events = await submitTransactionAsync(sender, tx);1344 const result = getGenericResult(events);13451346 1347 1348 expect(result.success).to.be.true;1349 });1350}13511352export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1353 await usingApi(async (api) => {1354 1355 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1356 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357 const result = getGenericResult(events);13581359 1360 1361 expect(result.success).to.be.false;1362 });1363}13641365export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1366 : Promise<UpDataStructsRpcCollection | null> => {1367 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1368};13691370export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1371 1372 return (await api.rpc.unique.collectionStats()).created.toNumber();1373};13741375export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1376 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1377}13781379export async function waitNewBlocks(blocksCount = 1): Promise<void> {1380 await usingApi(async (api) => {1381 const promise = new Promise<void>(async (resolve) => {1382 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1383 if (blocksCount > 0) {1384 blocksCount--;1385 } else {1386 unsubscribe();1387 resolve();1388 }1389 });1390 });1391 return promise;1392 });1393}