1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length === 48 || input.length === 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 collectionId: number;109 itemId: number;110 sender?: CrossAccountId;111 recipient?: CrossAccountId;112 value: bigint;113}114115interface IReFungibleOwner {116 fraction: BN;117 owner: number[];118}119120interface IGetMessage {121 checkMsgUnqMethod: string;122 checkMsgTrsMethod: string;123 checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127 value: number;128}129130export interface IChainLimits {131 collectionNumbersLimit: number;132 accountTokenOwnershipLimit: number;133 collectionsAdminsLimit: number;134 customDataLimit: number;135 nftSponsorTransferTimeout: number;136 fungibleSponsorTransferTimeout: number;137 refungibleSponsorTransferTimeout: number;138 offchainSchemaLimit: number;139 variableOnChainSchemaLimit: number;140 constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144 owner: IReFungibleOwner[];145 constData: number[];146 variableData: number[];147}148149export function uniqueEventMessage(events: EventRecord[]): IGetMessage {150 let checkMsgUnqMethod = '';151 let checkMsgTrsMethod = '';152 let checkMsgSysMethod = '';153 events.forEach(({event: {method, section}}) => {154 if (section === 'common') {155 checkMsgUnqMethod = method;156 } else if (section === 'treasury') {157 checkMsgTrsMethod = method;158 } else if (section === 'system') {159 checkMsgSysMethod = method;160 } else { return null; }161 });162 const result: IGetMessage = {163 checkMsgUnqMethod,164 checkMsgTrsMethod,165 checkMsgSysMethod,166 };167 return result;168}169170export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {171 const event = events.find(r => check(r.event));172 if (!event) return;173 return event.event as T;174}175176export function getGenericResult(events: EventRecord[]): GenericResult {177 const result: GenericResult = {178 success: false,179 };180 events.forEach(({event: {method}}) => {181 182 if (method === 'ExtrinsicSuccess') {183 result.success = true;184 }185 });186 return result;187}188189190191export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {192 let success = false;193 let collectionId = 0;194 events.forEach(({event: {data, method, section}}) => {195 196 if (method == 'ExtrinsicSuccess') {197 success = true;198 } else if ((section == 'common') && (method == 'CollectionCreated')) {199 collectionId = parseInt(data[0].toString(), 10);200 }201 });202 const result: CreateCollectionResult = {203 success,204 collectionId,205 };206 return result;207}208209export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {210 let success = false;211 let collectionId = 0;212 let itemId = 0;213 let recipient;214215 const results : CreateItemResult[] = [];216217 events.forEach(({event: {data, method, section}}) => {218 219 if (method == 'ExtrinsicSuccess') {220 success = true;221 } else if ((section == 'common') && (method == 'ItemCreated')) {222 collectionId = parseInt(data[0].toString(), 10);223 itemId = parseInt(data[1].toString(), 10);224 recipient = normalizeAccountId(data[2].toJSON() as any);225226 const itemRes: CreateItemResult = {227 success,228 collectionId,229 itemId,230 recipient,231 };232233 results.push(itemRes);234 }235 });236237 return results;238}239240export function getCreateItemResult(events: EventRecord[]): CreateItemResult {241 let success = false;242 let collectionId = 0;243 let itemId = 0;244 let recipient;245 events.forEach(({event: {data, method, section}}) => {246 247 if (method == 'ExtrinsicSuccess') {248 success = true;249 } else if ((section == 'common') && (method == 'ItemCreated')) {250 collectionId = parseInt(data[0].toString(), 10);251 itemId = parseInt(data[1].toString(), 10);252 recipient = normalizeAccountId(data[2].toJSON() as any);253 }254 });255 const result: CreateItemResult = {256 success,257 collectionId,258 itemId,259 recipient,260 };261 return result;262}263264export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {265 for (const {event} of events) {266 if (api.events.common.Transfer.is(event)) {267 const [collection, token, sender, recipient, value] = event.data;268 return {269 collectionId: collection.toNumber(),270 itemId: token.toNumber(),271 sender: normalizeAccountId(sender.toJSON() as any),272 recipient: normalizeAccountId(recipient.toJSON() as any),273 value: value.toBigInt(),274 };275 }276 }277 throw new Error('no transfer event');278}279280interface Nft {281 type: 'NFT';282}283284interface Fungible {285 type: 'Fungible';286 decimalPoints: number;287}288289interface ReFungible {290 type: 'ReFungible';291}292293type CollectionMode = Nft | Fungible | ReFungible;294295export type Property = {296 key: any,297 value: any,298};299300type PropertyPermission = {301 key: any,302 mutable: boolean;303 collectionAdmin: boolean;304 tokenOwner: boolean;305}306307export type CreateCollectionParams = {308 mode: CollectionMode,309 name: string,310 description: string,311 tokenPrefix: string,312 schemaVersion: string,313 properties?: Array<Property>,314 propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318 description: 'description',319 mode: {type: 'NFT'},320 name: 'name',321 tokenPrefix: 'prefix',322 schemaVersion: 'ImageURL',323};324325export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {326 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};327328 let collectionId = 0;329 await usingApi(async (api) => {330 331 const collectionCountBefore = await getCreatedCollectionCount(api);332333 334 const alicePrivateKey = privateKey('//Alice');335336 let modeprm = {};337 if (mode.type === 'NFT') {338 modeprm = {nft: null};339 } else if (mode.type === 'Fungible') {340 modeprm = {fungible: mode.decimalPoints};341 } else if (mode.type === 'ReFungible') {342 modeprm = {refungible: null};343 }344345 const tx = api.tx.unique.createCollectionEx({346 name: strToUTF16(name),347 description: strToUTF16(description),348 tokenPrefix: strToUTF16(tokenPrefix),349 mode: modeprm as any,350 schemaVersion: schemaVersion,351 });352 const events = await submitTransactionAsync(alicePrivateKey, tx);353 const result = getCreateCollectionResult(events);354355 356 const collectionCountAfter = await getCreatedCollectionCount(api);357358 359 const collection = await queryCollectionExpectSuccess(api, result.collectionId);360361 362 363 expect(result.success).to.be.true;364 expect(result.collectionId).to.be.equal(collectionCountAfter);365 366 expect(collection).to.be.not.null;367 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');368 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));369 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);370 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);371 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);372373 collectionId = result.collectionId;374 });375376 return collectionId;377}378379export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {380 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};381382 let collectionId = 0;383 await usingApi(async (api) => {384 385 const collectionCountBefore = await getCreatedCollectionCount(api);386387 388 const alicePrivateKey = privateKey('//Alice');389390 let modeprm = {};391 if (mode.type === 'NFT') {392 modeprm = {nft: null};393 } else if (mode.type === 'Fungible') {394 modeprm = {fungible: mode.decimalPoints};395 } else if (mode.type === 'ReFungible') {396 modeprm = {refungible: null};397 }398399 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});400 const events = await submitTransactionAsync(alicePrivateKey, tx);401 const result = getCreateCollectionResult(events);402403 404 const collectionCountAfter = await getCreatedCollectionCount(api);405406 407 const collection = await queryCollectionExpectSuccess(api, result.collectionId);408409 410 411 expect(result.success).to.be.true;412 expect(result.collectionId).to.be.equal(collectionCountAfter);413 414 expect(collection).to.be.not.null;415 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');416 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));417 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);418 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);419 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);420421422 collectionId = result.collectionId;423 });424425 return collectionId;426}427428export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {429 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431 const collectionId = 0;432 await usingApi(async (api) => {433 434 const collectionCountBefore = await getCreatedCollectionCount(api);435436 437 const alicePrivateKey = privateKey('//Alice');438439 let modeprm = {};440 if (mode.type === 'NFT') {441 modeprm = {nft: null};442 } else if (mode.type === 'Fungible') {443 modeprm = {fungible: mode.decimalPoints};444 } else if (mode.type === 'ReFungible') {445 modeprm = {refungible: null};446 }447448 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});449 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;450451452 453 const collectionCountAfter = await getCreatedCollectionCount(api);454455 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');456 });457}458459export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {460 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};461462 let modeprm = {};463 if (mode.type === 'NFT') {464 modeprm = {nft: null};465 } else if (mode.type === 'Fungible') {466 modeprm = {fungible: mode.decimalPoints};467 } else if (mode.type === 'ReFungible') {468 modeprm = {refungible: null};469 }470471 await usingApi(async (api) => {472 473 const collectionCountBefore = await getCreatedCollectionCount(api);474475 476 const alicePrivateKey = privateKey('//Alice');477 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});478 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479480 481 const collectionCountAfter = await getCreatedCollectionCount(api);482483 484 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');485 });486}487488export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {489 let bal = 0n;490 let unused;491 do {492 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;493 const keyring = new Keyring({type: 'sr25519'});494 unused = keyring.addFromUri(`//${randomSeed}`);495 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();496 } while (bal !== 0n);497 return unused;498}499500export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {501 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();502}503504export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {505 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));506}507508export async function findNotExistingCollection(api: ApiPromise): Promise<number> {509 const totalNumber = await getCreatedCollectionCount(api);510 const newCollection: number = totalNumber + 1;511 return newCollection;512}513514function getDestroyResult(events: EventRecord[]): boolean {515 let success = false;516 events.forEach(({event: {method}}) => {517 if (method == 'ExtrinsicSuccess') {518 success = true;519 }520 });521 return success;522}523524export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {525 await usingApi(async (api) => {526 527 const alicePrivateKey = privateKey(senderSeed);528 const tx = api.tx.unique.destroyCollection(collectionId);529 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;530 });531}532533export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {534 await usingApi(async (api) => {535 536 const alicePrivateKey = privateKey(senderSeed);537 const tx = api.tx.unique.destroyCollection(collectionId);538 const events = await submitTransactionAsync(alicePrivateKey, tx);539 const result = getDestroyResult(events);540 expect(result).to.be.true;541542 543 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;544 });545}546547export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {548 await usingApi(async (api) => {549 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);550 const events = await submitTransactionAsync(sender, tx);551 const result = getGenericResult(events);552553 expect(result.success).to.be.true;554 });555}556557export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {558 await usingApi(async (api) => {559 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);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 setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {568 await usingApi(async (api) => {569570 571 const senderPrivateKey = privateKey(sender);572 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);573 const events = await submitTransactionAsync(senderPrivateKey, tx);574 const result = getGenericResult(events);575576 577 const collection = await queryCollectionExpectSuccess(api, collectionId);578579 580 expect(result.success).to.be.true;581 expect(collection.sponsorship.toJSON()).to.deep.equal({582 unconfirmed: sponsor,583 });584 });585}586587export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {588 await usingApi(async (api) => {589590 591 const alicePrivateKey = privateKey(sender);592 const tx = api.tx.unique.removeCollectionSponsor(collectionId);593 const events = await submitTransactionAsync(alicePrivateKey, tx);594 const result = getGenericResult(events);595596 597 const collection = await queryCollectionExpectSuccess(api, collectionId);598599 600 expect(result.success).to.be.true;601 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});602 });603}604605export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {606 await usingApi(async (api) => {607608 609 const alicePrivateKey = privateKey(senderSeed);610 const tx = api.tx.unique.removeCollectionSponsor(collectionId);611 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;612 });613}614615export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {616 await usingApi(async (api) => {617618 619 const alicePrivateKey = privateKey(senderSeed);620 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);621 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;622 });623}624625export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {626 await usingApi(async (api) => {627628 629 const sender = privateKey(senderSeed);630 const tx = api.tx.unique.confirmSponsorship(collectionId);631 const events = await submitTransactionAsync(sender, tx);632 const result = getGenericResult(events);633634 635 const collection = await queryCollectionExpectSuccess(api, collectionId);636637 638 expect(result.success).to.be.true;639 expect(collection.sponsorship.toJSON()).to.be.deep.equal({640 confirmed: sender.address,641 });642 });643}644645646export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {647 await usingApi(async (api) => {648649 650 const sender = privateKey(senderSeed);651 const tx = api.tx.unique.confirmSponsorship(collectionId);652 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;653 });654}655656export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {657658 await usingApi(async (api) => {659 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);660 const events = await submitTransactionAsync(sender, tx);661 const result = getGenericResult(events);662663 expect(result.success).to.be.true;664 });665}666667export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {668669 await usingApi(async (api) => {670 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);671 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;672 const result = getGenericResult(events);673674 expect(result.success).to.be.false;675 });676}677678export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {679 await usingApi(async (api) => {680 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686}687688export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);691 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 const result = getGenericResult(events);693694 expect(result.success).to.be.false;695 });696}697698export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700 await usingApi(async (api) => {701702 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703 const events = await submitTransactionAsync(sender, tx);704 const result = getGenericResult(events);705706 expect(result.success).to.be.true;707 });708}709710export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {711712 await usingApi(async (api) => {713714 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);715 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;716 const result = getGenericResult(events);717718 expect(result.success).to.be.false;719 });720}721722export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {723 await usingApi(async (api) => {724 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);725 const events = await submitTransactionAsync(sender, tx);726 const result = getGenericResult(events);727728 expect(result.success).to.be.true;729 });730}731732export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {733 await usingApi(async (api) => {734 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);735 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;736 const result = getGenericResult(events);737738 expect(result.success).to.be.false;739 });740}741742export async function getNextSponsored(743 api: ApiPromise,744 collectionId: number,745 account: string | CrossAccountId,746 tokenId: number,747): Promise<number> {748 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));749}750751export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {752 await usingApi(async (api) => {753 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);754 const events = await submitTransactionAsync(sender, tx);755 const result = getGenericResult(events);756757 expect(result.success).to.be.true;758 });759}760761export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {762 let allowlisted = false;763 await usingApi(async (api) => {764 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;765 });766 return allowlisted;767}768769export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {770 await usingApi(async (api) => {771 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 expect(result.success).to.be.true;776 });777}778779export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {780 await usingApi(async (api) => {781 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());782 const events = await submitTransactionAsync(sender, tx);783 const result = getGenericResult(events);784785 expect(result.success).to.be.true;786 });787}788789export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {790 await usingApi(async (api) => {791 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());792 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793 const result = getGenericResult(events);794795 expect(result.success).to.be.false;796 });797}798799export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {800 await usingApi(async (api) => {801 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));802 const events = await submitTransactionAsync(sender, tx);803 const result = getGenericResult(events);804805 expect(result.success).to.be.true;806 });807}808809export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {810 await usingApi(async (api) => {811 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));812 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;813 });814}815816export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {817 await usingApi(async (api) => {818 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));819 const events = await submitTransactionAsync(sender, tx);820 const result = getGenericResult(events);821822 expect(result.success).to.be.true;823 });824}825826export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {827 await usingApi(async (api) => {828 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));829 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;830 });831}832833export interface CreateFungibleData {834 readonly Value: bigint;835}836837export interface CreateReFungibleData { }838export interface CreateNftData { }839840export type CreateItemData = {841 NFT: CreateNftData;842} | {843 Fungible: CreateFungibleData;844} | {845 ReFungible: CreateReFungibleData;846};847848export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {849 await usingApi(async (api) => {850 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);851 852 expect(balanceBefore >= BigInt(value)).to.be.true;853854 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);855 const events = await submitTransactionAsync(sender, tx);856 const result = getGenericResult(events);857 expect(result.success).to.be.true;858859 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);860 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);861 });862}863864export async function865approveExpectSuccess(866 collectionId: number,867 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,868) {869 await usingApi(async (api: ApiPromise) => {870 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);871 const events = await submitTransactionAsync(owner, approveUniqueTx);872 const result = getGenericResult(events);873 expect(result.success).to.be.true;874875 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));876 });877}878879export async function adminApproveFromExpectSuccess(880 collectionId: number,881 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,882) {883 await usingApi(async (api: ApiPromise) => {884 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);885 const events = await submitTransactionAsync(admin, approveUniqueTx);886 const result = getGenericResult(events);887 expect(result.success).to.be.true;888889 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));890 });891}892893export async function894transferFromExpectSuccess(895 collectionId: number,896 tokenId: number,897 accountApproved: IKeyringPair,898 accountFrom: IKeyringPair | CrossAccountId,899 accountTo: IKeyringPair | CrossAccountId,900 value: number | bigint = 1,901 type = 'NFT',902) {903 await usingApi(async (api: ApiPromise) => {904 const from = normalizeAccountId(accountFrom);905 const to = normalizeAccountId(accountTo);906 let balanceBefore = 0n;907 if (type === 'Fungible') {908 balanceBefore = await getBalance(api, collectionId, to, tokenId);909 }910 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);911 const events = await submitTransactionAsync(accountApproved, transferFromTx);912 const result = getCreateItemResult(events);913 914 expect(result.success).to.be.true;915 if (type === 'NFT') {916 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);917 }918 if (type === 'Fungible') {919 const balanceAfter = await getBalance(api, collectionId, to, tokenId);920 if (JSON.stringify(to) !== JSON.stringify(from)) {921 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));922 } else {923 expect(balanceAfter).to.be.equal(balanceBefore);924 }925 }926 if (type === 'ReFungible') {927 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));928 }929 });930}931932export async function933transferFromExpectFail(934 collectionId: number,935 tokenId: number,936 accountApproved: IKeyringPair,937 accountFrom: IKeyringPair,938 accountTo: IKeyringPair,939 value: number | bigint = 1,940) {941 await usingApi(async (api: ApiPromise) => {942 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);943 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;944 const result = getCreateCollectionResult(events);945 946 expect(result.success).to.be.false;947 });948}949950951async function getBlockNumber(api: ApiPromise): Promise<number> {952 return new Promise<number>(async (resolve) => {953 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {954 unsubscribe();955 resolve(head.number.toNumber());956 });957 });958}959960export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {961 await usingApi(async (api) => {962 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));963 const events = await submitTransactionAsync(sender, changeAdminTx);964 const result = getCreateCollectionResult(events);965 expect(result.success).to.be.true;966 });967}968969export async function970getFreeBalance(account: IKeyringPair): Promise<bigint> {971 let balance = 0n;972 await usingApi(async (api) => {973 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());974 });975976 return balance;977}978979export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {980 const tx = api.tx.balances.transfer(target, amount);981 const events = await submitTransactionAsync(source, tx);982 const result = getGenericResult(events);983 expect(result.success).to.be.true;984}985986export async function987scheduleTransferExpectSuccess(988 collectionId: number,989 tokenId: number,990 sender: IKeyringPair,991 recipient: IKeyringPair,992 value: number | bigint = 1,993 blockSchedule: number,994) {995 await usingApi(async (api: ApiPromise) => {996 const blockNumber: number | undefined = await getBlockNumber(api);997 const expectedBlockNumber = blockNumber + blockSchedule;998999 expect(blockNumber).to.be.greaterThan(0);1000 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1001 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10021003 await submitTransactionAsync(sender, scheduleTx);10041005 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10061007 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10081009 1010 await waitNewBlocks(blockSchedule + 1);10111012 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10131014 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1015 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1016 });1017}101810191020export async function1021transferExpectSuccess(1022 collectionId: number,1023 tokenId: number,1024 sender: IKeyringPair,1025 recipient: IKeyringPair | CrossAccountId,1026 value: number | bigint = 1,1027 type = 'NFT',1028) {1029 await usingApi(async (api: ApiPromise) => {1030 const from = normalizeAccountId(sender);1031 const to = normalizeAccountId(recipient);10321033 let balanceBefore = 0n;1034 if (type === 'Fungible') {1035 balanceBefore = await getBalance(api, collectionId, to, tokenId);1036 }1037 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1038 const events = await executeTransaction(api, sender, transferTx);10391040 const result = getTransferResult(api, events);1041 expect(result.collectionId).to.be.equal(collectionId);1042 expect(result.itemId).to.be.equal(tokenId);1043 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1044 expect(result.recipient).to.be.deep.equal(to);1045 expect(result.value).to.be.equal(BigInt(value));10461047 if (type === 'NFT') {1048 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1049 }1050 if (type === 'Fungible') {1051 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1052 if (JSON.stringify(to) !== JSON.stringify(from)) {1053 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1054 } else {1055 expect(balanceAfter).to.be.equal(balanceBefore);1056 }1057 }1058 if (type === 'ReFungible') {1059 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1060 }1061 });1062}10631064export async function1065transferExpectFailure(1066 collectionId: number,1067 tokenId: number,1068 sender: IKeyringPair,1069 recipient: IKeyringPair | CrossAccountId,1070 value: number | bigint = 1,1071) {1072 await usingApi(async (api: ApiPromise) => {1073 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1074 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1075 const result = getGenericResult(events);1076 1077 1078 1079 expect(result.success).to.be.false;1080 1081 });1082}10831084export async function1085approveExpectFail(1086 collectionId: number,1087 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1088) {1089 await usingApi(async (api: ApiPromise) => {1090 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1091 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1092 const result = getCreateCollectionResult(events);1093 1094 expect(result.success).to.be.false;1095 });1096}10971098export async function getBalance(1099 api: ApiPromise,1100 collectionId: number,1101 owner: string | CrossAccountId,1102 token: number,1103): Promise<bigint> {1104 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1105}1106export async function getTokenOwner(1107 api: ApiPromise,1108 collectionId: number,1109 token: number,1110): Promise<CrossAccountId> {1111 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1112 if (owner == null) throw new Error('owner == null');1113 return normalizeAccountId(owner);1114}1115export async function getTopmostTokenOwner(1116 api: ApiPromise,1117 collectionId: number,1118 token: number,1119): Promise<CrossAccountId> {1120 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1121 if (owner == null) throw new Error('owner == null');1122 return normalizeAccountId(owner);1123}1124export async function isTokenExists(1125 api: ApiPromise,1126 collectionId: number,1127 token: number,1128): Promise<boolean> {1129 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1130}1131export async function getLastTokenId(1132 api: ApiPromise,1133 collectionId: number,1134): Promise<number> {1135 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1136}1137export async function getAdminList(1138 api: ApiPromise,1139 collectionId: number,1140): Promise<string[]> {1141 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1142}1143export async function getVariableMetadata(1144 api: ApiPromise,1145 collectionId: number,1146 tokenId: number,1147): Promise<number[]> {1148 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1149}1150export async function getConstMetadata(1151 api: ApiPromise,1152 collectionId: number,1153 tokenId: number,1154): Promise<number[]> {1155 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1156}11571158export async function createFungibleItemExpectSuccess(1159 sender: IKeyringPair,1160 collectionId: number,1161 data: CreateFungibleData,1162 owner: CrossAccountId | string = sender.address,1163) {1164 return await usingApi(async (api) => {1165 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11661167 const events = await submitTransactionAsync(sender, tx);1168 const result = getCreateItemResult(events);11691170 expect(result.success).to.be.true;1171 return result.itemId;1172 });1173}11741175export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1176 let newItemId = 0;1177 await usingApi(async (api) => {1178 const to = normalizeAccountId(owner);1179 const itemCountBefore = await getLastTokenId(api, collectionId);1180 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11811182 let tx;1183 if (createMode === 'Fungible') {1184 const createData = {fungible: {value: 10}};1185 tx = api.tx.unique.createItem(collectionId, to, createData as any);1186 } else if (createMode === 'ReFungible') {1187 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1188 tx = api.tx.unique.createItem(collectionId, to, createData as any);1189 } else {1190 const createData = {nft: {const_data: [], variable_data: []}};1191 tx = api.tx.unique.createItem(collectionId, to, createData as any);1192 }11931194 const events = await submitTransactionAsync(sender, tx);1195 const result = getCreateItemResult(events);11961197 const itemCountAfter = await getLastTokenId(api, collectionId);1198 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11991200 1201 1202 expect(result.success).to.be.true;1203 if (createMode === 'Fungible') {1204 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1205 } else {1206 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1207 }1208 expect(collectionId).to.be.equal(result.collectionId);1209 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1210 expect(to).to.be.deep.equal(result.recipient);1211 newItemId = result.itemId;1212 });1213 return newItemId;1214}12151216export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1217 await usingApi(async (api) => {1218 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12191220 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1221 const result = getCreateItemResult(events);12221223 expect(result.success).to.be.false;1224 });1225}12261227export async function setPublicAccessModeExpectSuccess(1228 sender: IKeyringPair, collectionId: number,1229 accessMode: 'Normal' | 'AllowList',1230) {1231 await usingApi(async (api) => {12321233 1234 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1235 const events = await submitTransactionAsync(sender, tx);1236 const result = getGenericResult(events);12371238 1239 const collection = await queryCollectionExpectSuccess(api, collectionId);12401241 1242 1243 expect(result.success).to.be.true;1244 expect(collection.access.toHuman()).to.be.equal(accessMode);1245 });1246}12471248export async function setPublicAccessModeExpectFail(1249 sender: IKeyringPair, collectionId: number,1250 accessMode: 'Normal' | 'AllowList',1251) {1252 await usingApi(async (api) => {12531254 1255 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1256 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1257 const result = getGenericResult(events);12581259 1260 1261 expect(result.success).to.be.false;1262 });1263}12641265export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1266 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1267}12681269export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1270 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1271}12721273export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1274 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1275}12761277export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1278 await usingApi(async (api) => {12791280 1281 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1282 const events = await submitTransactionAsync(sender, tx);1283 const result = getGenericResult(events);1284 expect(result.success).to.be.true;12851286 1287 const collection = await queryCollectionExpectSuccess(api, collectionId);12881289 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1290 });1291}12921293export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1294 await setMintPermissionExpectSuccess(sender, collectionId, true);1295}12961297export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1298 await usingApi(async (api) => {1299 1300 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1301 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1302 const result = getCreateCollectionResult(events);1303 1304 expect(result.success).to.be.false;1305 });1306}13071308export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1309 await usingApi(async (api) => {1310 1311 const tx = api.tx.unique.setChainLimits(limits);1312 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1313 const result = getCreateCollectionResult(events);1314 1315 expect(result.success).to.be.false;1316 });1317}13181319export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1320 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1321}13221323export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1324 await usingApi(async (api) => {1325 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13261327 1328 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1329 const events = await submitTransactionAsync(sender, tx);1330 const result = getGenericResult(events);1331 expect(result.success).to.be.true;13321333 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1334 });1335}13361337export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1338 await usingApi(async (api) => {13391340 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13411342 1343 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1344 const events = await submitTransactionAsync(sender, tx);1345 const result = getGenericResult(events);1346 expect(result.success).to.be.true;13471348 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1349 });1350}13511352export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1353 await usingApi(async (api) => {13541355 1356 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1357 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1358 const result = getGenericResult(events);13591360 1361 1362 expect(result.success).to.be.false;1363 });1364}13651366export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1367 await usingApi(async (api) => {1368 1369 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1370 const events = await submitTransactionAsync(sender, tx);1371 const result = getGenericResult(events);13721373 1374 1375 expect(result.success).to.be.true;1376 });1377}13781379export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1380 await usingApi(async (api) => {1381 1382 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1383 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1384 const result = getGenericResult(events);13851386 1387 1388 expect(result.success).to.be.false;1389 });1390}13911392export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1393 : Promise<UpDataStructsRpcCollection | null> => {1394 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1395};13961397export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1398 1399 return (await api.rpc.unique.collectionStats()).created.toNumber();1400};14011402export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1403 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1404}14051406export async function waitNewBlocks(blocksCount = 1): Promise<void> {1407 await usingApi(async (api) => {1408 const promise = new Promise<void>(async (resolve) => {1409 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1410 if (blocksCount > 0) {1411 blocksCount--;1412 } else {1413 unsubscribe();1414 resolve();1415 }1416 });1417 });1418 return promise;1419 });1420}