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 enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {654 await usingApi(async (api) => {655 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);656 const events = await submitTransactionAsync(sender, tx);657 const result = getGenericResult(events);658659 expect(result.success).to.be.true;660 });661}662663export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {664 await usingApi(async (api) => {665 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);666 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;667 const result = getGenericResult(events);668669 expect(result.success).to.be.false;670 });671}672673export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {674675 await usingApi(async (api) => {676677 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);678 const events = await submitTransactionAsync(sender, tx);679 const result = getGenericResult(events);680681 expect(result.success).to.be.true;682 });683}684685export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {686687 await usingApi(async (api) => {688689 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);690 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;691 const result = getGenericResult(events);692693 expect(result.success).to.be.false;694 });695}696697export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {698 await usingApi(async (api) => {699 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);700 const events = await submitTransactionAsync(sender, tx);701 const result = getGenericResult(events);702703 expect(result.success).to.be.true;704 });705}706707export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {708 await usingApi(async (api) => {709 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);710 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;711 const result = getGenericResult(events);712713 expect(result.success).to.be.false;714 });715}716717export async function getNextSponsored(718 api: ApiPromise,719 collectionId: number,720 account: string | CrossAccountId,721 tokenId: number,722): Promise<number> {723 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));724}725726export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {727 await usingApi(async (api) => {728 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);729 const events = await submitTransactionAsync(sender, tx);730 const result = getGenericResult(events);731732 expect(result.success).to.be.true;733 });734}735736export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {737 let allowlisted = false;738 await usingApi(async (api) => {739 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;740 });741 return allowlisted;742}743744export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {745 await usingApi(async (api) => {746 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());747 const events = await submitTransactionAsync(sender, tx);748 const result = getGenericResult(events);749750 expect(result.success).to.be.true;751 });752}753754export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {755 await usingApi(async (api) => {756 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());757 const events = await submitTransactionAsync(sender, tx);758 const result = getGenericResult(events);759760 expect(result.success).to.be.true;761 });762}763764export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {765 await usingApi(async (api) => {766 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());767 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;768 const result = getGenericResult(events);769770 expect(result.success).to.be.false;771 });772}773774export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {775 await usingApi(async (api) => {776 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));777 const events = await submitTransactionAsync(sender, tx);778 const result = getGenericResult(events);779780 expect(result.success).to.be.true;781 });782}783784export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {785 await usingApi(async (api) => {786 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));787 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;788 });789}790791export interface CreateFungibleData {792 readonly Value: bigint;793}794795export interface CreateReFungibleData { }796export interface CreateNftData { }797798export type CreateItemData = {799 NFT: CreateNftData;800} | {801 Fungible: CreateFungibleData;802} | {803 ReFungible: CreateReFungibleData;804};805806export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {807 await usingApi(async (api) => {808 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);809 810 expect(balanceBefore >= BigInt(value)).to.be.true;811812 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);813 const events = await submitTransactionAsync(sender, tx);814 const result = getGenericResult(events);815 expect(result.success).to.be.true;816817 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);818 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);819 });820}821822export async function823approveExpectSuccess(824 collectionId: number,825 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,826) {827 await usingApi(async (api: ApiPromise) => {828 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);829 const events = await submitTransactionAsync(owner, approveUniqueTx);830 const result = getGenericResult(events);831 expect(result.success).to.be.true;832833 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));834 });835}836837export async function adminApproveFromExpectSuccess(838 collectionId: number,839 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,840) {841 await usingApi(async (api: ApiPromise) => {842 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);843 const events = await submitTransactionAsync(admin, approveUniqueTx);844 const result = getGenericResult(events);845 expect(result.success).to.be.true;846847 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));848 });849}850851export async function852transferFromExpectSuccess(853 collectionId: number,854 tokenId: number,855 accountApproved: IKeyringPair,856 accountFrom: IKeyringPair | CrossAccountId,857 accountTo: IKeyringPair | CrossAccountId,858 value: number | bigint = 1,859 type = 'NFT',860) {861 await usingApi(async (api: ApiPromise) => {862 const from = normalizeAccountId(accountFrom);863 const to = normalizeAccountId(accountTo);864 let balanceBefore = 0n;865 if (type === 'Fungible' || type === 'ReFungible') {866 balanceBefore = await getBalance(api, collectionId, to, tokenId);867 }868 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);869 const events = await submitTransactionAsync(accountApproved, transferFromTx);870 const result = getCreateItemResult(events);871 872 expect(result.success).to.be.true;873 if (type === 'NFT') {874 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);875 }876 if (type === 'Fungible') {877 const balanceAfter = await getBalance(api, collectionId, to, tokenId);878 if (JSON.stringify(to) !== JSON.stringify(from)) {879 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));880 } else {881 expect(balanceAfter).to.be.equal(balanceBefore);882 }883 }884 if (type === 'ReFungible') {885 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));886 }887 });888}889890export async function891transferFromExpectFail(892 collectionId: number,893 tokenId: number,894 accountApproved: IKeyringPair,895 accountFrom: IKeyringPair,896 accountTo: IKeyringPair,897 value: number | bigint = 1,898) {899 await usingApi(async (api: ApiPromise) => {900 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);901 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;902 const result = getCreateCollectionResult(events);903 904 expect(result.success).to.be.false;905 });906}907908909async function getBlockNumber(api: ApiPromise): Promise<number> {910 return new Promise<number>(async (resolve) => {911 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {912 unsubscribe();913 resolve(head.number.toNumber());914 });915 });916}917918export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {919 await usingApi(async (api) => {920 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));921 const events = await submitTransactionAsync(sender, changeAdminTx);922 const result = getCreateCollectionResult(events);923 expect(result.success).to.be.true;924 });925}926927export async function928getFreeBalance(account: IKeyringPair): Promise<bigint> {929 let balance = 0n;930 await usingApi(async (api) => {931 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());932 });933934 return balance;935}936937export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {938 const tx = api.tx.balances.transfer(target, amount);939 const events = await submitTransactionAsync(source, tx);940 const result = getGenericResult(events);941 expect(result.success).to.be.true;942}943944export async function945scheduleTransferExpectSuccess(946 collectionId: number,947 tokenId: number,948 sender: IKeyringPair,949 recipient: IKeyringPair,950 value: number | bigint = 1,951 blockSchedule: number,952) {953 await usingApi(async (api: ApiPromise) => {954 const blockNumber: number | undefined = await getBlockNumber(api);955 const expectedBlockNumber = blockNumber + blockSchedule;956957 expect(blockNumber).to.be.greaterThan(0);958 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);959 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);960961 await submitTransactionAsync(sender, scheduleTx);962963 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();964965 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));966967 968 await waitNewBlocks(blockSchedule + 1);969970 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();971972 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));973 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);974 });975}976977978export async function979transferExpectSuccess(980 collectionId: number,981 tokenId: number,982 sender: IKeyringPair,983 recipient: IKeyringPair | CrossAccountId,984 value: number | bigint = 1,985 type = 'NFT',986) {987 await usingApi(async (api: ApiPromise) => {988 const from = normalizeAccountId(sender);989 const to = normalizeAccountId(recipient);990991 let balanceBefore = 0n;992 if (type === 'Fungible') {993 balanceBefore = await getBalance(api, collectionId, to, tokenId);994 }995 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);996 const events = await executeTransaction(api, sender, transferTx);997998 const result = getTransferResult(api, events);999 expect(result.collectionId).to.be.equal(collectionId);1000 expect(result.itemId).to.be.equal(tokenId);1001 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1002 expect(result.recipient).to.be.deep.equal(to);1003 expect(result.value).to.be.equal(BigInt(value));10041005 if (type === 'NFT') {1006 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1007 }1008 if (type === 'Fungible') {1009 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1010 if (JSON.stringify(to) !== JSON.stringify(from)) {1011 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1012 } else {1013 expect(balanceAfter).to.be.equal(balanceBefore);1014 }1015 }1016 if (type === 'ReFungible') {1017 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1018 }1019 });1020}10211022export async function1023transferExpectFailure(1024 collectionId: number,1025 tokenId: number,1026 sender: IKeyringPair,1027 recipient: IKeyringPair | CrossAccountId,1028 value: number | bigint = 1,1029) {1030 await usingApi(async (api: ApiPromise) => {1031 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1032 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1033 const result = getGenericResult(events);1034 1035 1036 1037 expect(result.success).to.be.false;1038 1039 });1040}10411042export async function1043approveExpectFail(1044 collectionId: number,1045 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1046) {1047 await usingApi(async (api: ApiPromise) => {1048 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1049 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1050 const result = getCreateCollectionResult(events);1051 1052 expect(result.success).to.be.false;1053 });1054}10551056export async function getBalance(1057 api: ApiPromise,1058 collectionId: number,1059 owner: string | CrossAccountId,1060 token: number,1061): Promise<bigint> {1062 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1063}1064export async function getTokenOwner(1065 api: ApiPromise,1066 collectionId: number,1067 token: number,1068): Promise<CrossAccountId> {1069 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1070 if (owner == null) throw new Error('owner == null');1071 return normalizeAccountId(owner);1072}1073export async function getTopmostTokenOwner(1074 api: ApiPromise,1075 collectionId: number,1076 token: number,1077): Promise<CrossAccountId> {1078 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1079 if (owner == null) throw new Error('owner == null');1080 return normalizeAccountId(owner);1081}1082export async function isTokenExists(1083 api: ApiPromise,1084 collectionId: number,1085 token: number,1086): Promise<boolean> {1087 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1088}1089export async function getLastTokenId(1090 api: ApiPromise,1091 collectionId: number,1092): Promise<number> {1093 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1094}1095export async function getAdminList(1096 api: ApiPromise,1097 collectionId: number,1098): Promise<string[]> {1099 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1100}1101export async function getConstMetadata(1102 api: ApiPromise,1103 collectionId: number,1104 tokenId: number,1105): Promise<number[]> {1106 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1107}11081109export async function createFungibleItemExpectSuccess(1110 sender: IKeyringPair,1111 collectionId: number,1112 data: CreateFungibleData,1113 owner: CrossAccountId | string = sender.address,1114) {1115 return await usingApi(async (api) => {1116 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11171118 const events = await submitTransactionAsync(sender, tx);1119 const result = getCreateItemResult(events);11201121 expect(result.success).to.be.true;1122 return result.itemId;1123 });1124}11251126export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1127 let newItemId = 0;1128 await usingApi(async (api) => {1129 const to = normalizeAccountId(owner);1130 const itemCountBefore = await getLastTokenId(api, collectionId);1131 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11321133 let tx;1134 if (createMode === 'Fungible') {1135 const createData = {fungible: {value: 10}};1136 tx = api.tx.unique.createItem(collectionId, to, createData as any);1137 } else if (createMode === 'ReFungible') {1138 const createData = {refungible: {const_data: [], pieces: 100}};1139 tx = api.tx.unique.createItem(collectionId, to, createData as any);1140 } else {1141 const createData = {nft: {const_data: []}};1142 tx = api.tx.unique.createItem(collectionId, to, createData as any);1143 }11441145 const events = await submitTransactionAsync(sender, tx);1146 const result = getCreateItemResult(events);11471148 const itemCountAfter = await getLastTokenId(api, collectionId);1149 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11501151 1152 1153 expect(result.success).to.be.true;1154 if (createMode === 'Fungible') {1155 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1156 } else {1157 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1158 }1159 expect(collectionId).to.be.equal(result.collectionId);1160 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1161 expect(to).to.be.deep.equal(result.recipient);1162 newItemId = result.itemId;1163 });1164 return newItemId;1165}11661167export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1168 await usingApi(async (api) => {1169 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11701171 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1172 const result = getCreateItemResult(events);11731174 expect(result.success).to.be.false;1175 });1176}11771178export async function setPublicAccessModeExpectSuccess(1179 sender: IKeyringPair, collectionId: number,1180 accessMode: 'Normal' | 'AllowList',1181) {1182 await usingApi(async (api) => {11831184 1185 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1186 const events = await submitTransactionAsync(sender, tx);1187 const result = getGenericResult(events);11881189 1190 const collection = await queryCollectionExpectSuccess(api, collectionId);11911192 1193 1194 expect(result.success).to.be.true;1195 expect(collection.access.toHuman()).to.be.equal(accessMode);1196 });1197}11981199export async function setPublicAccessModeExpectFail(1200 sender: IKeyringPair, collectionId: number,1201 accessMode: 'Normal' | 'AllowList',1202) {1203 await usingApi(async (api) => {12041205 1206 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1207 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1208 const result = getGenericResult(events);12091210 1211 1212 expect(result.success).to.be.false;1213 });1214}12151216export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1217 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1218}12191220export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1221 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1222}12231224export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1225 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1226}12271228export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1229 await usingApi(async (api) => {12301231 1232 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1233 const events = await submitTransactionAsync(sender, tx);1234 const result = getGenericResult(events);1235 expect(result.success).to.be.true;12361237 1238 const collection = await queryCollectionExpectSuccess(api, collectionId);12391240 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1241 });1242}12431244export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1245 await setMintPermissionExpectSuccess(sender, collectionId, true);1246}12471248export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1249 await usingApi(async (api) => {1250 1251 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1252 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1253 const result = getCreateCollectionResult(events);1254 1255 expect(result.success).to.be.false;1256 });1257}12581259export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1260 await usingApi(async (api) => {1261 1262 const tx = api.tx.unique.setChainLimits(limits);1263 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1264 const result = getCreateCollectionResult(events);1265 1266 expect(result.success).to.be.false;1267 });1268}12691270export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1271 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1272}12731274export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1275 await usingApi(async (api) => {1276 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12771278 1279 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1280 const events = await submitTransactionAsync(sender, tx);1281 const result = getGenericResult(events);1282 expect(result.success).to.be.true;12831284 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1285 });1286}12871288export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1289 await usingApi(async (api) => {12901291 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12921293 1294 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1295 const events = await submitTransactionAsync(sender, tx);1296 const result = getGenericResult(events);1297 expect(result.success).to.be.true;12981299 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1300 });1301}13021303export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1304 await usingApi(async (api) => {13051306 1307 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1308 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1309 const result = getGenericResult(events);13101311 1312 1313 expect(result.success).to.be.false;1314 });1315}13161317export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1318 await usingApi(async (api) => {1319 1320 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1321 const events = await submitTransactionAsync(sender, tx);1322 const result = getGenericResult(events);13231324 1325 1326 expect(result.success).to.be.true;1327 });1328}13291330export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1331 await usingApi(async (api) => {1332 1333 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1334 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1335 const result = getGenericResult(events);13361337 1338 1339 expect(result.success).to.be.false;1340 });1341}13421343export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1344 : Promise<UpDataStructsRpcCollection | null> => {1345 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1346};13471348export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1349 1350 return (await api.rpc.unique.collectionStats()).created.toNumber();1351};13521353export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1354 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1355}13561357export async function waitNewBlocks(blocksCount = 1): Promise<void> {1358 await usingApi(async (api) => {1359 const promise = new Promise<void>(async (resolve) => {1360 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1361 if (blocksCount > 0) {1362 blocksCount--;1363 } else {1364 unsubscribe();1365 resolve();1366 }1367 });1368 });1369 return promise;1370 });1371}