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 variableData: number[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult(events: EventRecord[]): GenericResult {176 const result: GenericResult = {177 success: false,178 };179 events.forEach(({event: {method}}) => {180 181 if (method === 'ExtrinsicSuccess') {182 result.success = true;183 }184 });185 return result;186}187188189190export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {191 let success = false;192 let collectionId = 0;193 events.forEach(({event: {data, method, section}}) => {194 195 if (method == 'ExtrinsicSuccess') {196 success = true;197 } else if ((section == 'common') && (method == 'CollectionCreated')) {198 collectionId = parseInt(data[0].toString(), 10);199 }200 });201 const result: CreateCollectionResult = {202 success,203 collectionId,204 };205 return result;206}207208export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {209 let success = false;210 let collectionId = 0;211 let itemId = 0;212 let recipient;213214 const results : CreateItemResult[] = [];215216 events.forEach(({event: {data, method, section}}) => {217 218 if (method == 'ExtrinsicSuccess') {219 success = true;220 } else if ((section == 'common') && (method == 'ItemCreated')) {221 collectionId = parseInt(data[0].toString(), 10);222 itemId = parseInt(data[1].toString(), 10);223 recipient = normalizeAccountId(data[2].toJSON() as any);224225 const itemRes: CreateItemResult = {226 success,227 collectionId,228 itemId,229 recipient,230 };231232 results.push(itemRes);233 }234 });235236 return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240 let success = false;241 let collectionId = 0;242 let itemId = 0;243 let recipient;244 events.forEach(({event: {data, method, section}}) => {245 246 if (method == 'ExtrinsicSuccess') {247 success = true;248 } else if ((section == 'common') && (method == 'ItemCreated')) {249 collectionId = parseInt(data[0].toString(), 10);250 itemId = parseInt(data[1].toString(), 10);251 recipient = normalizeAccountId(data[2].toJSON() as any);252 }253 });254 const result: CreateItemResult = {255 success,256 collectionId,257 itemId,258 recipient,259 };260 return result;261}262263export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {264 for (const {event} of events) {265 if (api.events.common.Transfer.is(event)) {266 const [collection, token, sender, recipient, value] = event.data;267 return {268 collectionId: collection.toNumber(),269 itemId: token.toNumber(),270 sender: normalizeAccountId(sender.toJSON() as any),271 recipient: normalizeAccountId(recipient.toJSON() as any),272 value: value.toBigInt(),273 };274 }275 }276 throw new Error('no transfer event');277}278279interface Nft {280 type: 'NFT';281}282283interface Fungible {284 type: 'Fungible';285 decimalPoints: number;286}287288interface ReFungible {289 type: 'ReFungible';290}291292type CollectionMode = Nft | Fungible | ReFungible;293294export type Property = {295 key: any,296 value: any,297};298299type PropertyPermission = {300 key: any,301 mutable: boolean;302 collectionAdmin: boolean;303 tokenOwner: boolean;304}305306export type CreateCollectionParams = {307 mode: CollectionMode,308 name: string,309 description: string,310 tokenPrefix: string,311 schemaVersion: string,312 properties?: Array<Property>,313 propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317 description: 'description',318 mode: {type: 'NFT'},319 name: 'name',320 tokenPrefix: 'prefix',321 schemaVersion: 'ImageURL',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api) => {329 330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 333 const alicePrivateKey = privateKey('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 schemaVersion: schemaVersion,350 });351 const events = await submitTransactionAsync(alicePrivateKey, tx);352 const result = getCreateCollectionResult(events);353354 355 const collectionCountAfter = await getCreatedCollectionCount(api);356357 358 const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360 361 362 expect(result.success).to.be.true;363 expect(result.collectionId).to.be.equal(collectionCountAfter);364 365 expect(collection).to.be.not.null;366 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372 collectionId = result.collectionId;373 });374375 return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381 let collectionId = 0;382 await usingApi(async (api) => {383 384 const collectionCountBefore = await getCreatedCollectionCount(api);385386 387 const alicePrivateKey = privateKey('//Alice');388389 let modeprm = {};390 if (mode.type === 'NFT') {391 modeprm = {nft: null};392 } else if (mode.type === 'Fungible') {393 modeprm = {fungible: mode.decimalPoints};394 } else if (mode.type === 'ReFungible') {395 modeprm = {refungible: null};396 }397398 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});399 const events = await submitTransactionAsync(alicePrivateKey, tx);400 const result = getCreateCollectionResult(events);401402 403 const collectionCountAfter = await getCreatedCollectionCount(api);404405 406 const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408 409 410 expect(result.success).to.be.true;411 expect(result.collectionId).to.be.equal(collectionCountAfter);412 413 expect(collection).to.be.not.null;414 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421 collectionId = result.collectionId;422 });423424 return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430 await usingApi(async (api) => {431 432 const collectionCountBefore = await getCreatedCollectionCount(api);433434 435 const alicePrivateKey = privateKey('//Alice');436437 let modeprm = {};438 if (mode.type === 'NFT') {439 modeprm = {nft: null};440 } else if (mode.type === 'Fungible') {441 modeprm = {fungible: mode.decimalPoints};442 } else if (mode.type === 'ReFungible') {443 modeprm = {refungible: null};444 }445446 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});447 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;448449450 451 const collectionCountAfter = await getCreatedCollectionCount(api);452453 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');454 });455}456457export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {458 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};459460 let modeprm = {};461 if (mode.type === 'NFT') {462 modeprm = {nft: null};463 } else if (mode.type === 'Fungible') {464 modeprm = {fungible: mode.decimalPoints};465 } else if (mode.type === 'ReFungible') {466 modeprm = {refungible: null};467 }468469 await usingApi(async (api) => {470 471 const collectionCountBefore = await getCreatedCollectionCount(api);472473 474 const alicePrivateKey = privateKey('//Alice');475 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});476 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;477478 479 const collectionCountAfter = await getCreatedCollectionCount(api);480481 482 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');483 });484}485486export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {487 let bal = 0n;488 let unused;489 do {490 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;491 const keyring = new Keyring({type: 'sr25519'});492 unused = keyring.addFromUri(`//${randomSeed}`);493 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();494 } while (bal !== 0n);495 return unused;496}497498export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {499 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();500}501502export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {503 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));504}505506export async function findNotExistingCollection(api: ApiPromise): Promise<number> {507 const totalNumber = await getCreatedCollectionCount(api);508 const newCollection: number = totalNumber + 1;509 return newCollection;510}511512function getDestroyResult(events: EventRecord[]): boolean {513 let success = false;514 events.forEach(({event: {method}}) => {515 if (method == 'ExtrinsicSuccess') {516 success = true;517 }518 });519 return success;520}521522export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {523 await usingApi(async (api) => {524 525 const alicePrivateKey = privateKey(senderSeed);526 const tx = api.tx.unique.destroyCollection(collectionId);527 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;528 });529}530531export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {532 await usingApi(async (api) => {533 534 const alicePrivateKey = privateKey(senderSeed);535 const tx = api.tx.unique.destroyCollection(collectionId);536 const events = await submitTransactionAsync(alicePrivateKey, tx);537 const result = getDestroyResult(events);538 expect(result).to.be.true;539540 541 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;542 });543}544545export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {546 await usingApi(async (api) => {547 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);548 const events = await submitTransactionAsync(sender, tx);549 const result = getGenericResult(events);550551 expect(result.success).to.be.true;552 });553}554555export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {556 await usingApi(async (api) => {557 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);558 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;559 const result = getGenericResult(events);560561 expect(result.success).to.be.false;562 });563}564565export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {566 await usingApi(async (api) => {567568 569 const senderPrivateKey = privateKey(sender);570 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);571 const events = await submitTransactionAsync(senderPrivateKey, tx);572 const result = getGenericResult(events);573574 575 const collection = await queryCollectionExpectSuccess(api, collectionId);576577 578 expect(result.success).to.be.true;579 expect(collection.sponsorship.toJSON()).to.deep.equal({580 unconfirmed: sponsor,581 });582 });583}584585export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {586 await usingApi(async (api) => {587588 589 const alicePrivateKey = privateKey(sender);590 const tx = api.tx.unique.removeCollectionSponsor(collectionId);591 const events = await submitTransactionAsync(alicePrivateKey, tx);592 const result = getGenericResult(events);593594 595 const collection = await queryCollectionExpectSuccess(api, collectionId);596597 598 expect(result.success).to.be.true;599 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});600 });601}602603export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {604 await usingApi(async (api) => {605606 607 const alicePrivateKey = privateKey(senderSeed);608 const tx = api.tx.unique.removeCollectionSponsor(collectionId);609 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;610 });611}612613export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {614 await usingApi(async (api) => {615616 617 const alicePrivateKey = privateKey(senderSeed);618 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);619 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;620 });621}622623export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {624 await usingApi(async (api) => {625626 627 const sender = privateKey(senderSeed);628 const tx = api.tx.unique.confirmSponsorship(collectionId);629 const events = await submitTransactionAsync(sender, tx);630 const result = getGenericResult(events);631632 633 const collection = await queryCollectionExpectSuccess(api, collectionId);634635 636 expect(result.success).to.be.true;637 expect(collection.sponsorship.toJSON()).to.be.deep.equal({638 confirmed: sender.address,639 });640 });641}642643644export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {645 await usingApi(async (api) => {646647 648 const sender = privateKey(senderSeed);649 const tx = api.tx.unique.confirmSponsorship(collectionId);650 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;651 });652}653654export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {655656 await usingApi(async (api) => {657 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);658 const events = await submitTransactionAsync(sender, tx);659 const result = getGenericResult(events);660661 expect(result.success).to.be.true;662 });663}664665export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {666667 await usingApi(async (api) => {668 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);669 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;670 const result = getGenericResult(events);671672 expect(result.success).to.be.false;673 });674}675676export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {677 await usingApi(async (api) => {678 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);679 const events = await submitTransactionAsync(sender, tx);680 const result = getGenericResult(events);681682 expect(result.success).to.be.true;683 });684}685686export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {687 await usingApi(async (api) => {688 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);689 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690 const result = getGenericResult(events);691692 expect(result.success).to.be.false;693 });694}695696export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {697698 await usingApi(async (api) => {699700 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);701 const events = await submitTransactionAsync(sender, tx);702 const result = getGenericResult(events);703704 expect(result.success).to.be.true;705 });706}707708export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {709710 await usingApi(async (api) => {711712 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);713 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;714 const result = getGenericResult(events);715716 expect(result.success).to.be.false;717 });718}719720export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {721 await usingApi(async (api) => {722 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);723 const events = await submitTransactionAsync(sender, tx);724 const result = getGenericResult(events);725726 expect(result.success).to.be.true;727 });728}729730export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {731 await usingApi(async (api) => {732 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);733 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;734 const result = getGenericResult(events);735736 expect(result.success).to.be.false;737 });738}739740export async function getNextSponsored(741 api: ApiPromise,742 collectionId: number,743 account: string | CrossAccountId,744 tokenId: number,745): Promise<number> {746 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));747}748749export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {750 await usingApi(async (api) => {751 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);752 const events = await submitTransactionAsync(sender, tx);753 const result = getGenericResult(events);754755 expect(result.success).to.be.true;756 });757}758759export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {760 let allowlisted = false;761 await usingApi(async (api) => {762 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;763 });764 return allowlisted;765}766767export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {768 await usingApi(async (api) => {769 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());770 const events = await submitTransactionAsync(sender, tx);771 const result = getGenericResult(events);772773 expect(result.success).to.be.true;774 });775}776777export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {778 await usingApi(async (api) => {779 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());780 const events = await submitTransactionAsync(sender, tx);781 const result = getGenericResult(events);782783 expect(result.success).to.be.true;784 });785}786787export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {788 await usingApi(async (api) => {789 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());790 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;791 const result = getGenericResult(events);792793 expect(result.success).to.be.false;794 });795}796797export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {798 await usingApi(async (api) => {799 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));800 const events = await submitTransactionAsync(sender, tx);801 const result = getGenericResult(events);802803 expect(result.success).to.be.true;804 });805}806807export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {808 await usingApi(async (api) => {809 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));810 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;811 });812}813814export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {815 await usingApi(async (api) => {816 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));817 const events = await submitTransactionAsync(sender, tx);818 const result = getGenericResult(events);819820 expect(result.success).to.be.true;821 });822}823824export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {825 await usingApi(async (api) => {826 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));827 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;828 });829}830831export interface CreateFungibleData {832 readonly Value: bigint;833}834835export interface CreateReFungibleData { }836export interface CreateNftData { }837838export type CreateItemData = {839 NFT: CreateNftData;840} | {841 Fungible: CreateFungibleData;842} | {843 ReFungible: CreateReFungibleData;844};845846export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {847 await usingApi(async (api) => {848 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);849 850 expect(balanceBefore >= BigInt(value)).to.be.true;851852 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);853 const events = await submitTransactionAsync(sender, tx);854 const result = getGenericResult(events);855 expect(result.success).to.be.true;856857 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);858 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);859 });860}861862export async function863approveExpectSuccess(864 collectionId: number,865 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,866) {867 await usingApi(async (api: ApiPromise) => {868 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);869 const events = await submitTransactionAsync(owner, approveUniqueTx);870 const result = getGenericResult(events);871 expect(result.success).to.be.true;872873 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));874 });875}876877export async function adminApproveFromExpectSuccess(878 collectionId: number,879 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,880) {881 await usingApi(async (api: ApiPromise) => {882 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);883 const events = await submitTransactionAsync(admin, approveUniqueTx);884 const result = getGenericResult(events);885 expect(result.success).to.be.true;886887 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));888 });889}890891export async function892transferFromExpectSuccess(893 collectionId: number,894 tokenId: number,895 accountApproved: IKeyringPair,896 accountFrom: IKeyringPair | CrossAccountId,897 accountTo: IKeyringPair | CrossAccountId,898 value: number | bigint = 1,899 type = 'NFT',900) {901 await usingApi(async (api: ApiPromise) => {902 const from = normalizeAccountId(accountFrom);903 const to = normalizeAccountId(accountTo);904 let balanceBefore = 0n;905 if (type === 'Fungible' || type === 'ReFungible') {906 balanceBefore = await getBalance(api, collectionId, to, tokenId);907 }908 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);909 const events = await submitTransactionAsync(accountApproved, transferFromTx);910 const result = getCreateItemResult(events);911 912 expect(result.success).to.be.true;913 if (type === 'NFT') {914 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);915 }916 if (type === 'Fungible') {917 const balanceAfter = await getBalance(api, collectionId, to, tokenId);918 if (JSON.stringify(to) !== JSON.stringify(from)) {919 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));920 } else {921 expect(balanceAfter).to.be.equal(balanceBefore);922 }923 }924 if (type === 'ReFungible') {925 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));926 }927 });928}929930export async function931transferFromExpectFail(932 collectionId: number,933 tokenId: number,934 accountApproved: IKeyringPair,935 accountFrom: IKeyringPair,936 accountTo: IKeyringPair,937 value: number | bigint = 1,938) {939 await usingApi(async (api: ApiPromise) => {940 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);941 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;942 const result = getCreateCollectionResult(events);943 944 expect(result.success).to.be.false;945 });946}947948949async function getBlockNumber(api: ApiPromise): Promise<number> {950 return new Promise<number>(async (resolve) => {951 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {952 unsubscribe();953 resolve(head.number.toNumber());954 });955 });956}957958export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {959 await usingApi(async (api) => {960 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));961 const events = await submitTransactionAsync(sender, changeAdminTx);962 const result = getCreateCollectionResult(events);963 expect(result.success).to.be.true;964 });965}966967export async function968getFreeBalance(account: IKeyringPair): Promise<bigint> {969 let balance = 0n;970 await usingApi(async (api) => {971 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());972 });973974 return balance;975}976977export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {978 const tx = api.tx.balances.transfer(target, amount);979 const events = await submitTransactionAsync(source, tx);980 const result = getGenericResult(events);981 expect(result.success).to.be.true;982}983984export async function985scheduleTransferExpectSuccess(986 collectionId: number,987 tokenId: number,988 sender: IKeyringPair,989 recipient: IKeyringPair,990 value: number | bigint = 1,991 blockSchedule: number,992) {993 await usingApi(async (api: ApiPromise) => {994 const blockNumber: number | undefined = await getBlockNumber(api);995 const expectedBlockNumber = blockNumber + blockSchedule;996997 expect(blockNumber).to.be.greaterThan(0);998 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);999 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10001001 await submitTransactionAsync(sender, scheduleTx);10021003 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10041005 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10061007 1008 await waitNewBlocks(blockSchedule + 1);10091010 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10111012 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1013 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1014 });1015}101610171018export async function1019transferExpectSuccess(1020 collectionId: number,1021 tokenId: number,1022 sender: IKeyringPair,1023 recipient: IKeyringPair | CrossAccountId,1024 value: number | bigint = 1,1025 type = 'NFT',1026) {1027 await usingApi(async (api: ApiPromise) => {1028 const from = normalizeAccountId(sender);1029 const to = normalizeAccountId(recipient);10301031 let balanceBefore = 0n;1032 if (type === 'Fungible') {1033 balanceBefore = await getBalance(api, collectionId, to, tokenId);1034 }1035 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1036 const events = await executeTransaction(api, sender, transferTx);10371038 const result = getTransferResult(api, events);1039 expect(result.collectionId).to.be.equal(collectionId);1040 expect(result.itemId).to.be.equal(tokenId);1041 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1042 expect(result.recipient).to.be.deep.equal(to);1043 expect(result.value).to.be.equal(BigInt(value));10441045 if (type === 'NFT') {1046 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1047 }1048 if (type === 'Fungible') {1049 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1050 if (JSON.stringify(to) !== JSON.stringify(from)) {1051 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1052 } else {1053 expect(balanceAfter).to.be.equal(balanceBefore);1054 }1055 }1056 if (type === 'ReFungible') {1057 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1058 }1059 });1060}10611062export async function1063transferExpectFailure(1064 collectionId: number,1065 tokenId: number,1066 sender: IKeyringPair,1067 recipient: IKeyringPair | CrossAccountId,1068 value: number | bigint = 1,1069) {1070 await usingApi(async (api: ApiPromise) => {1071 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1072 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1073 const result = getGenericResult(events);1074 1075 1076 1077 expect(result.success).to.be.false;1078 1079 });1080}10811082export async function1083approveExpectFail(1084 collectionId: number,1085 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1086) {1087 await usingApi(async (api: ApiPromise) => {1088 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1089 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1090 const result = getCreateCollectionResult(events);1091 1092 expect(result.success).to.be.false;1093 });1094}10951096export async function getBalance(1097 api: ApiPromise,1098 collectionId: number,1099 owner: string | CrossAccountId,1100 token: number,1101): Promise<bigint> {1102 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1103}1104export async function getTokenOwner(1105 api: ApiPromise,1106 collectionId: number,1107 token: number,1108): Promise<CrossAccountId> {1109 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1110 if (owner == null) throw new Error('owner == null');1111 return normalizeAccountId(owner);1112}1113export async function getTopmostTokenOwner(1114 api: ApiPromise,1115 collectionId: number,1116 token: number,1117): Promise<CrossAccountId> {1118 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1119 if (owner == null) throw new Error('owner == null');1120 return normalizeAccountId(owner);1121}1122export async function isTokenExists(1123 api: ApiPromise,1124 collectionId: number,1125 token: number,1126): Promise<boolean> {1127 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1128}1129export async function getLastTokenId(1130 api: ApiPromise,1131 collectionId: number,1132): Promise<number> {1133 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1134}1135export async function getAdminList(1136 api: ApiPromise,1137 collectionId: number,1138): Promise<string[]> {1139 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1140}1141export async function getVariableMetadata(1142 api: ApiPromise,1143 collectionId: number,1144 tokenId: number,1145): Promise<number[]> {1146 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1147}1148export async function getConstMetadata(1149 api: ApiPromise,1150 collectionId: number,1151 tokenId: number,1152): Promise<number[]> {1153 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1154}11551156export async function createFungibleItemExpectSuccess(1157 sender: IKeyringPair,1158 collectionId: number,1159 data: CreateFungibleData,1160 owner: CrossAccountId | string = sender.address,1161) {1162 return await usingApi(async (api) => {1163 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11641165 const events = await submitTransactionAsync(sender, tx);1166 const result = getCreateItemResult(events);11671168 expect(result.success).to.be.true;1169 return result.itemId;1170 });1171}11721173export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1174 let newItemId = 0;1175 await usingApi(async (api) => {1176 const to = normalizeAccountId(owner);1177 const itemCountBefore = await getLastTokenId(api, collectionId);1178 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11791180 let tx;1181 if (createMode === 'Fungible') {1182 const createData = {fungible: {value: 10}};1183 tx = api.tx.unique.createItem(collectionId, to, createData as any);1184 } else if (createMode === 'ReFungible') {1185 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1186 tx = api.tx.unique.createItem(collectionId, to, createData as any);1187 } else {1188 const createData = {nft: {const_data: [], variable_data: []}};1189 tx = api.tx.unique.createItem(collectionId, to, createData as any);1190 }11911192 const events = await submitTransactionAsync(sender, tx);1193 const result = getCreateItemResult(events);11941195 const itemCountAfter = await getLastTokenId(api, collectionId);1196 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11971198 1199 1200 expect(result.success).to.be.true;1201 if (createMode === 'Fungible') {1202 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1203 } else {1204 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1205 }1206 expect(collectionId).to.be.equal(result.collectionId);1207 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1208 expect(to).to.be.deep.equal(result.recipient);1209 newItemId = result.itemId;1210 });1211 return newItemId;1212}12131214export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1215 await usingApi(async (api) => {1216 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12171218 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1219 const result = getCreateItemResult(events);12201221 expect(result.success).to.be.false;1222 });1223}12241225export async function setPublicAccessModeExpectSuccess(1226 sender: IKeyringPair, collectionId: number,1227 accessMode: 'Normal' | 'AllowList',1228) {1229 await usingApi(async (api) => {12301231 1232 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1233 const events = await submitTransactionAsync(sender, tx);1234 const result = getGenericResult(events);12351236 1237 const collection = await queryCollectionExpectSuccess(api, collectionId);12381239 1240 1241 expect(result.success).to.be.true;1242 expect(collection.access.toHuman()).to.be.equal(accessMode);1243 });1244}12451246export async function setPublicAccessModeExpectFail(1247 sender: IKeyringPair, collectionId: number,1248 accessMode: 'Normal' | 'AllowList',1249) {1250 await usingApi(async (api) => {12511252 1253 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1254 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1255 const result = getGenericResult(events);12561257 1258 1259 expect(result.success).to.be.false;1260 });1261}12621263export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1264 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1265}12661267export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1268 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1269}12701271export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1272 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1273}12741275export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1276 await usingApi(async (api) => {12771278 1279 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1280 const events = await submitTransactionAsync(sender, tx);1281 const result = getGenericResult(events);1282 expect(result.success).to.be.true;12831284 1285 const collection = await queryCollectionExpectSuccess(api, collectionId);12861287 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1288 });1289}12901291export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1292 await setMintPermissionExpectSuccess(sender, collectionId, true);1293}12941295export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1296 await usingApi(async (api) => {1297 1298 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1299 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1300 const result = getCreateCollectionResult(events);1301 1302 expect(result.success).to.be.false;1303 });1304}13051306export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1307 await usingApi(async (api) => {1308 1309 const tx = api.tx.unique.setChainLimits(limits);1310 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1311 const result = getCreateCollectionResult(events);1312 1313 expect(result.success).to.be.false;1314 });1315}13161317export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1318 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1319}13201321export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1322 await usingApi(async (api) => {1323 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13241325 1326 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1327 const events = await submitTransactionAsync(sender, tx);1328 const result = getGenericResult(events);1329 expect(result.success).to.be.true;13301331 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1332 });1333}13341335export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1336 await usingApi(async (api) => {13371338 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13391340 1341 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1342 const events = await submitTransactionAsync(sender, tx);1343 const result = getGenericResult(events);1344 expect(result.success).to.be.true;13451346 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1347 });1348}13491350export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1351 await usingApi(async (api) => {13521353 1354 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1355 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1356 const result = getGenericResult(events);13571358 1359 1360 expect(result.success).to.be.false;1361 });1362}13631364export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1365 await usingApi(async (api) => {1366 1367 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1368 const events = await submitTransactionAsync(sender, tx);1369 const result = getGenericResult(events);13701371 1372 1373 expect(result.success).to.be.true;1374 });1375}13761377export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1378 await usingApi(async (api) => {1379 1380 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1381 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1382 const result = getGenericResult(events);13831384 1385 1386 expect(result.success).to.be.false;1387 });1388}13891390export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1391 : Promise<UpDataStructsRpcCollection | null> => {1392 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1393};13941395export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1396 1397 return (await api.rpc.unique.collectionStats()).created.toNumber();1398};13991400export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1401 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1402}14031404export async function waitNewBlocks(blocksCount = 1): Promise<void> {1405 await usingApi(async (api) => {1406 const promise = new Promise<void>(async (resolve) => {1407 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1408 if (blocksCount > 0) {1409 blocksCount--;1410 } else {1411 unsubscribe();1412 resolve();1413 }1414 });1415 });1416 return promise;1417 });1418}