1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {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 success: boolean;109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 offchainSchemaLimit: number;140 variableOnChainSchemaLimit: number;141 constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146 constData: number[];147 variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151 let checkMsgUnqMethod = '';152 let checkMsgTrsMethod = '';153 let checkMsgSysMethod = '';154 events.forEach(({event: {method, section}}) => {155 if (section === 'common') {156 checkMsgUnqMethod = method;157 } else if (section === 'treasury') {158 checkMsgTrsMethod = method;159 } else if (section === 'system') {160 checkMsgSysMethod = method;161 } else { return null; }162 });163 const result: IGetMessage = {164 checkMsgUnqMethod,165 checkMsgTrsMethod,166 checkMsgSysMethod,167 };168 return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172 const result: GenericResult = {173 success: false,174 };175 events.forEach(({event: {method}}) => {176 177 if (method === 'ExtrinsicSuccess') {178 result.success = true;179 }180 });181 return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187 let success = false;188 let collectionId = 0;189 events.forEach(({event: {data, method, section}}) => {190 191 if (method == 'ExtrinsicSuccess') {192 success = true;193 } else if ((section == 'common') && (method == 'CollectionCreated')) {194 collectionId = parseInt(data[0].toString(), 10);195 }196 });197 const result: CreateCollectionResult = {198 success,199 collectionId,200 };201 return result;202}203204export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {205 let success = false;206 let collectionId = 0;207 let itemId = 0;208 let recipient;209210 const results : CreateItemResult[] = [];211212 events.forEach(({event: {data, method, section}}) => {213 214 if (method == 'ExtrinsicSuccess') {215 success = true;216 } else if ((section == 'common') && (method == 'ItemCreated')) {217 collectionId = parseInt(data[0].toString(), 10);218 itemId = parseInt(data[1].toString(), 10);219 recipient = normalizeAccountId(data[2].toJSON() as any);220221 const itemRes: CreateItemResult = {222 success,223 collectionId,224 itemId,225 recipient,226 };227228 results.push(itemRes);229 }230 });231232 return results;233}234235export function getCreateItemResult(events: EventRecord[]): CreateItemResult {236 let success = false;237 let collectionId = 0;238 let itemId = 0;239 let recipient;240 events.forEach(({event: {data, method, section}}) => {241 242 if (method == 'ExtrinsicSuccess') {243 success = true;244 } else if ((section == 'common') && (method == 'ItemCreated')) {245 collectionId = parseInt(data[0].toString(), 10);246 itemId = parseInt(data[1].toString(), 10);247 recipient = normalizeAccountId(data[2].toJSON() as any);248 }249 });250 const result: CreateItemResult = {251 success,252 collectionId,253 itemId,254 recipient,255 };256 return result;257}258259export function getTransferResult(events: EventRecord[]): TransferResult {260 const result: TransferResult = {261 success: false,262 collectionId: 0,263 itemId: 0,264 value: 0n,265 };266267 events.forEach(({event: {data, method, section}}) => {268 if (method === 'ExtrinsicSuccess') {269 result.success = true;270 } else if (section === 'common' && method === 'Transfer') {271 result.collectionId = +data[0].toString();272 result.itemId = +data[1].toString();273 result.sender = normalizeAccountId(data[2].toJSON() as any);274 result.recipient = normalizeAccountId(data[3].toJSON() as any);275 result.value = BigInt(data[4].toString());276 }277 });278279 return result;280}281282interface Nft {283 type: 'NFT';284}285286interface Fungible {287 type: 'Fungible';288 decimalPoints: number;289}290291interface ReFungible {292 type: 'ReFungible';293}294295type CollectionMode = Nft | Fungible | ReFungible;296297export type Property = {298 key: any,299 value: any,300};301302type PropertyPermission = {303 key: any,304 mutable: boolean;305 collectionAdmin: boolean;306 tokenOwner: boolean;307}308309export type CreateCollectionParams = {310 mode: CollectionMode,311 name: string,312 description: string,313 tokenPrefix: string,314 schemaVersion: string,315 properties?: Array<Property>,316 propPerm?: Array<PropertyPermission>317};318319const defaultCreateCollectionParams: CreateCollectionParams = {320 description: 'description',321 mode: {type: 'NFT'},322 name: 'name',323 tokenPrefix: 'prefix',324 schemaVersion: 'ImageURL',325};326327export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {328 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};329330 let collectionId = 0;331 await usingApi(async (api) => {332 333 const collectionCountBefore = await getCreatedCollectionCount(api);334335 336 const alicePrivateKey = privateKey('//Alice');337338 let modeprm = {};339 if (mode.type === 'NFT') {340 modeprm = {nft: null};341 } else if (mode.type === 'Fungible') {342 modeprm = {fungible: mode.decimalPoints};343 } else if (mode.type === 'ReFungible') {344 modeprm = {refungible: null};345 }346347 const tx = api.tx.unique.createCollectionEx({348 name: strToUTF16(name), 349 description: strToUTF16(description), 350 tokenPrefix: strToUTF16(tokenPrefix), 351 mode: modeprm as any,352 schemaVersion: schemaVersion,353 });354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getCreateCollectionResult(events);356357 358 const collectionCountAfter = await getCreatedCollectionCount(api);359360 361 const collection = await queryCollectionExpectSuccess(api, result.collectionId);362363 364 365 expect(result.success).to.be.true;366 expect(result.collectionId).to.be.equal(collectionCountAfter);367 368 expect(collection).to.be.not.null;369 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');370 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));371 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);372 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);373 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);374375 collectionId = result.collectionId;376 });377378 return collectionId;379}380381export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {382 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};383384 let collectionId = 0;385 await usingApi(async (api) => {386 387 const collectionCountBefore = await getCreatedCollectionCount(api);388389 390 const alicePrivateKey = privateKey('//Alice');391392 let modeprm = {};393 if (mode.type === 'NFT') {394 modeprm = {nft: null};395 } else if (mode.type === 'Fungible') {396 modeprm = {fungible: mode.decimalPoints};397 } else if (mode.type === 'ReFungible') {398 modeprm = {refungible: null};399 }400401 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});402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getCreateCollectionResult(events);404405 406 const collectionCountAfter = await getCreatedCollectionCount(api);407408 409 const collection = await queryCollectionExpectSuccess(api, result.collectionId);410411 412 413 expect(result.success).to.be.true;414 expect(result.collectionId).to.be.equal(collectionCountAfter);415 416 expect(collection).to.be.not.null;417 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');418 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));419 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);420 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);421 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);422423424 collectionId = result.collectionId;425 });426427 return collectionId;428}429430export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {431 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433 const collectionId = 0;434 await usingApi(async (api) => {435 436 const collectionCountBefore = await getCreatedCollectionCount(api);437438 439 const alicePrivateKey = privateKey('//Alice');440441 let modeprm = {};442 if (mode.type === 'NFT') {443 modeprm = {nft: null};444 } else if (mode.type === 'Fungible') {445 modeprm = {fungible: mode.decimalPoints};446 } else if (mode.type === 'ReFungible') {447 modeprm = {refungible: null};448 }449450 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});451 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;452453454 455 const collectionCountAfter = await getCreatedCollectionCount(api);456457 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');458 });459}460461export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {462 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};463464 let modeprm = {};465 if (mode.type === 'NFT') {466 modeprm = {nft: null};467 } else if (mode.type === 'Fungible') {468 modeprm = {fungible: mode.decimalPoints};469 } else if (mode.type === 'ReFungible') {470 modeprm = {refungible: null};471 }472473 await usingApi(async (api) => {474 475 const collectionCountBefore = await getCreatedCollectionCount(api);476477 478 const alicePrivateKey = privateKey('//Alice');479 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});480 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;481482 483 const collectionCountAfter = await getCreatedCollectionCount(api);484485 486 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');487 });488}489490export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {491 let bal = 0n;492 let unused;493 do {494 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;495 const keyring = new Keyring({type: 'sr25519'});496 unused = keyring.addFromUri(`//${randomSeed}`);497 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();498 } while (bal !== 0n);499 return unused;500}501502export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {503 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();504}505506export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {507 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));508}509510export async function findNotExistingCollection(api: ApiPromise): Promise<number> {511 const totalNumber = await getCreatedCollectionCount(api);512 const newCollection: number = totalNumber + 1;513 return newCollection;514}515516function getDestroyResult(events: EventRecord[]): boolean {517 let success = false;518 events.forEach(({event: {method}}) => {519 if (method == 'ExtrinsicSuccess') {520 success = true;521 }522 });523 return success;524}525526export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {527 await usingApi(async (api) => {528 529 const alicePrivateKey = privateKey(senderSeed);530 const tx = api.tx.unique.destroyCollection(collectionId);531 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;532 });533}534535export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {536 await usingApi(async (api) => {537 538 const alicePrivateKey = privateKey(senderSeed);539 const tx = api.tx.unique.destroyCollection(collectionId);540 const events = await submitTransactionAsync(alicePrivateKey, tx);541 const result = getDestroyResult(events);542 expect(result).to.be.true;543544 545 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;546 });547}548549export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {550 await usingApi(async (api) => {551 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);552 const events = await submitTransactionAsync(sender, tx);553 const result = getGenericResult(events);554555 expect(result.success).to.be.true;556 });557}558559export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {560 await usingApi(async (api) => {561 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);562 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;563 const result = getGenericResult(events);564565 expect(result.success).to.be.false;566 });567}568569export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {570 await usingApi(async (api) => {571572 573 const senderPrivateKey = privateKey(sender);574 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);575 const events = await submitTransactionAsync(senderPrivateKey, tx);576 const result = getGenericResult(events);577578 579 const collection = await queryCollectionExpectSuccess(api, collectionId);580581 582 expect(result.success).to.be.true;583 expect(collection.sponsorship.toJSON()).to.deep.equal({584 unconfirmed: sponsor,585 });586 });587}588589export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {590 await usingApi(async (api) => {591592 593 const alicePrivateKey = privateKey(sender);594 const tx = api.tx.unique.removeCollectionSponsor(collectionId);595 const events = await submitTransactionAsync(alicePrivateKey, tx);596 const result = getGenericResult(events);597598 599 const collection = await queryCollectionExpectSuccess(api, collectionId);600601 602 expect(result.success).to.be.true;603 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});604 });605}606607export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {608 await usingApi(async (api) => {609610 611 const alicePrivateKey = privateKey(senderSeed);612 const tx = api.tx.unique.removeCollectionSponsor(collectionId);613 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;614 });615}616617export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {618 await usingApi(async (api) => {619620 621 const alicePrivateKey = privateKey(senderSeed);622 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);623 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;624 });625}626627export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {628 await usingApi(async (api) => {629630 631 const sender = privateKey(senderSeed);632 const tx = api.tx.unique.confirmSponsorship(collectionId);633 const events = await submitTransactionAsync(sender, tx);634 const result = getGenericResult(events);635636 637 const collection = await queryCollectionExpectSuccess(api, collectionId);638639 640 expect(result.success).to.be.true;641 expect(collection.sponsorship.toJSON()).to.be.deep.equal({642 confirmed: sender.address,643 });644 });645}646647648export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {649 await usingApi(async (api) => {650651 652 const sender = privateKey(senderSeed);653 const tx = api.tx.unique.confirmSponsorship(collectionId);654 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;655 });656}657658export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {659660 await usingApi(async (api) => {661 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);662 const events = await submitTransactionAsync(sender, tx);663 const result = getGenericResult(events);664665 expect(result.success).to.be.true;666 });667}668669export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {670671 await usingApi(async (api) => {672 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);673 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;674 const result = getGenericResult(events);675676 expect(result.success).to.be.false;677 });678}679680export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683 const events = await submitTransactionAsync(sender, tx);684 const result = getGenericResult(events);685686 expect(result.success).to.be.true;687 });688}689690export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {691 await usingApi(async (api) => {692 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);693 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;694 const result = getGenericResult(events);695696 expect(result.success).to.be.false;697 });698}699700export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {701702 await usingApi(async (api) => {703704 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);705 const events = await submitTransactionAsync(sender, tx);706 const result = getGenericResult(events);707708 expect(result.success).to.be.true;709 });710}711712export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {713714 await usingApi(async (api) => {715716 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);717 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;718 const result = getGenericResult(events);719720 expect(result.success).to.be.false;721 });722}723724export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725 await usingApi(async (api) => {726 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727 const events = await submitTransactionAsync(sender, tx);728 const result = getGenericResult(events);729730 expect(result.success).to.be.true;731 });732}733734export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {735 await usingApi(async (api) => {736 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);737 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;738 const result = getGenericResult(events);739740 expect(result.success).to.be.false;741 });742}743744export async function getNextSponsored(745 api: ApiPromise,746 collectionId: number,747 account: string | CrossAccountId,748 tokenId: number,749): Promise<number> {750 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));751}752753export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {754 await usingApi(async (api) => {755 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);756 const events = await submitTransactionAsync(sender, tx);757 const result = getGenericResult(events);758759 expect(result.success).to.be.true;760 });761}762763export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {764 let allowlisted = false;765 await usingApi(async (api) => {766 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;767 });768 return allowlisted;769}770771export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772 await usingApi(async (api) => {773 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());774 const events = await submitTransactionAsync(sender, tx);775 const result = getGenericResult(events);776777 expect(result.success).to.be.true;778 });779}780781export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782 await usingApi(async (api) => {783 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784 const events = await submitTransactionAsync(sender, tx);785 const result = getGenericResult(events);786787 expect(result.success).to.be.true;788 });789}790791export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {792 await usingApi(async (api) => {793 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());794 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795 const result = getGenericResult(events);796797 expect(result.success).to.be.false;798 });799}800801export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {802 await usingApi(async (api) => {803 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));804 const events = await submitTransactionAsync(sender, tx);805 const result = getGenericResult(events);806807 expect(result.success).to.be.true;808 });809}810811export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {812 await usingApi(async (api) => {813 const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));814 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;815 });816}817818export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {819 await usingApi(async (api) => {820 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));821 const events = await submitTransactionAsync(sender, tx);822 const result = getGenericResult(events);823824 expect(result.success).to.be.true;825 });826}827828export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {829 await usingApi(async (api) => {830 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));831 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;832 });833}834835export interface CreateFungibleData {836 readonly Value: bigint;837}838839export interface CreateReFungibleData { }840export interface CreateNftData { }841842export type CreateItemData = {843 NFT: CreateNftData;844} | {845 Fungible: CreateFungibleData;846} | {847 ReFungible: CreateReFungibleData;848};849850export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {851 await usingApi(async (api) => {852 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);853 854 expect(balanceBefore >= BigInt(value)).to.be.true;855856 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);857 const events = await submitTransactionAsync(sender, tx);858 const result = getGenericResult(events);859 expect(result.success).to.be.true;860861 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);862 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);863 });864}865866export async function867approveExpectSuccess(868 collectionId: number,869 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,870) {871 await usingApi(async (api: ApiPromise) => {872 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);873 const events = await submitTransactionAsync(owner, approveUniqueTx);874 const result = getGenericResult(events);875 expect(result.success).to.be.true;876877 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));878 });879}880881export async function adminApproveFromExpectSuccess(882 collectionId: number,883 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,884) {885 await usingApi(async (api: ApiPromise) => {886 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);887 const events = await submitTransactionAsync(admin, approveUniqueTx);888 const result = getGenericResult(events);889 expect(result.success).to.be.true;890891 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));892 });893}894895export async function896transferFromExpectSuccess(897 collectionId: number,898 tokenId: number,899 accountApproved: IKeyringPair,900 accountFrom: IKeyringPair | CrossAccountId,901 accountTo: IKeyringPair | CrossAccountId,902 value: number | bigint = 1,903 type = 'NFT',904) {905 await usingApi(async (api: ApiPromise) => {906 const from = normalizeAccountId(accountFrom);907 const to = normalizeAccountId(accountTo);908 let balanceBefore = 0n;909 if (type === 'Fungible') {910 balanceBefore = await getBalance(api, collectionId, to, tokenId);911 }912 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);913 const events = await submitTransactionAsync(accountApproved, transferFromTx);914 const result = getCreateItemResult(events);915 916 expect(result.success).to.be.true;917 if (type === 'NFT') {918 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);919 }920 if (type === 'Fungible') {921 const balanceAfter = await getBalance(api, collectionId, to, tokenId);922 if (JSON.stringify(to) !== JSON.stringify(from)) {923 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));924 } else {925 expect(balanceAfter).to.be.equal(balanceBefore);926 }927 }928 if (type === 'ReFungible') {929 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));930 }931 });932}933934export async function935transferFromExpectFail(936 collectionId: number,937 tokenId: number,938 accountApproved: IKeyringPair,939 accountFrom: IKeyringPair,940 accountTo: IKeyringPair,941 value: number | bigint = 1,942) {943 await usingApi(async (api: ApiPromise) => {944 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);945 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;946 const result = getCreateCollectionResult(events);947 948 expect(result.success).to.be.false;949 });950}951952953async function getBlockNumber(api: ApiPromise): Promise<number> {954 return new Promise<number>(async (resolve) => {955 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {956 unsubscribe();957 resolve(head.number.toNumber());958 });959 });960}961962export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {963 await usingApi(async (api) => {964 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));965 const events = await submitTransactionAsync(sender, changeAdminTx);966 const result = getCreateCollectionResult(events);967 expect(result.success).to.be.true;968 });969}970971export async function972getFreeBalance(account: IKeyringPair): Promise<bigint> {973 let balance = 0n;974 await usingApi(async (api) => {975 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());976 });977978 return balance;979}980981export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {982 const tx = api.tx.balances.transfer(target, amount);983 const events = await submitTransactionAsync(source, tx);984 const result = getGenericResult(events);985 expect(result.success).to.be.true;986}987988export async function989scheduleTransferExpectSuccess(990 collectionId: number,991 tokenId: number,992 sender: IKeyringPair,993 recipient: IKeyringPair,994 value: number | bigint = 1,995 blockSchedule: number,996) {997 await usingApi(async (api: ApiPromise) => {998 const blockNumber: number | undefined = await getBlockNumber(api);999 const expectedBlockNumber = blockNumber + blockSchedule;10001001 expect(blockNumber).to.be.greaterThan(0);1002 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1003 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10041005 await submitTransactionAsync(sender, scheduleTx);10061007 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10081009 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10101011 1012 await waitNewBlocks(blockSchedule + 1);10131014 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10151016 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1017 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1018 });1019}102010211022export async function1023transferExpectSuccess(1024 collectionId: number,1025 tokenId: number,1026 sender: IKeyringPair,1027 recipient: IKeyringPair | CrossAccountId,1028 value: number | bigint = 1,1029 type = 'NFT',1030) {1031 await usingApi(async (api: ApiPromise) => {1032 const from = normalizeAccountId(sender);1033 const to = normalizeAccountId(recipient);10341035 let balanceBefore = 0n;1036 if (type === 'Fungible') {1037 balanceBefore = await getBalance(api, collectionId, to, tokenId);1038 }1039 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1040 const events = await submitTransactionAsync(sender, transferTx);1041 const result = getTransferResult(events);1042 1043 expect(result.success).to.be.true;1044 expect(result.collectionId).to.be.equal(collectionId);1045 expect(result.itemId).to.be.equal(tokenId);1046 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1047 expect(result.recipient).to.be.deep.equal(to);1048 expect(result.value).to.be.equal(BigInt(value));1049 if (type === 'NFT') {1050 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1051 }1052 if (type === 'Fungible') {1053 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1054 if (JSON.stringify(to) !== JSON.stringify(from)) {1055 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1056 } else {1057 expect(balanceAfter).to.be.equal(balanceBefore);1058 }1059 }1060 if (type === 'ReFungible') {1061 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1062 }1063 });1064}10651066export async function1067transferExpectFailure(1068 collectionId: number,1069 tokenId: number,1070 sender: IKeyringPair,1071 recipient: IKeyringPair | CrossAccountId,1072 value: number | bigint = 1,1073) {1074 await usingApi(async (api: ApiPromise) => {1075 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1076 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1077 const result = getGenericResult(events);1078 1079 1080 1081 expect(result.success).to.be.false;1082 1083 });1084}10851086export async function1087approveExpectFail(1088 collectionId: number,1089 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1090) {1091 await usingApi(async (api: ApiPromise) => {1092 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1093 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1094 const result = getCreateCollectionResult(events);1095 1096 expect(result.success).to.be.false;1097 });1098}10991100export async function getBalance(1101 api: ApiPromise,1102 collectionId: number,1103 owner: string | CrossAccountId,1104 token: number,1105): Promise<bigint> {1106 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1107}1108export async function getTokenOwner(1109 api: ApiPromise,1110 collectionId: number,1111 token: number,1112): Promise<CrossAccountId> {1113 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1114 if (owner == null) throw new Error('owner == null');1115 return normalizeAccountId(owner);1116}1117export async function getTopmostTokenOwner(1118 api: ApiPromise,1119 collectionId: number,1120 token: number,1121): Promise<CrossAccountId> {1122 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1123 if (owner == null) throw new Error('owner == null');1124 return normalizeAccountId(owner);1125}1126export async function isTokenExists(1127 api: ApiPromise,1128 collectionId: number,1129 token: number,1130): Promise<boolean> {1131 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1132}1133export async function getLastTokenId(1134 api: ApiPromise,1135 collectionId: number,1136): Promise<number> {1137 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1138}1139export async function getAdminList(1140 api: ApiPromise,1141 collectionId: number,1142): Promise<string[]> {1143 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1144}1145export async function getVariableMetadata(1146 api: ApiPromise,1147 collectionId: number,1148 tokenId: number,1149): Promise<number[]> {1150 return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1151}1152export async function getConstMetadata(1153 api: ApiPromise,1154 collectionId: number,1155 tokenId: number,1156): Promise<number[]> {1157 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1158}11591160export async function createFungibleItemExpectSuccess(1161 sender: IKeyringPair,1162 collectionId: number,1163 data: CreateFungibleData,1164 owner: CrossAccountId | string = sender.address,1165) {1166 return await usingApi(async (api) => {1167 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11681169 const events = await submitTransactionAsync(sender, tx);1170 const result = getCreateItemResult(events);11711172 expect(result.success).to.be.true;1173 return result.itemId;1174 });1175}11761177export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1178 let newItemId = 0;1179 await usingApi(async (api) => {1180 const to = normalizeAccountId(owner);1181 const itemCountBefore = await getLastTokenId(api, collectionId);1182 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11831184 let tx;1185 if (createMode === 'Fungible') {1186 const createData = {fungible: {value: 10}};1187 tx = api.tx.unique.createItem(collectionId, to, createData as any);1188 } else if (createMode === 'ReFungible') {1189 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1190 tx = api.tx.unique.createItem(collectionId, to, createData as any);1191 } else {1192 const createData = {nft: {const_data: [], variable_data: []}};1193 tx = api.tx.unique.createItem(collectionId, to, createData as any);1194 }11951196 const events = await submitTransactionAsync(sender, tx);1197 const result = getCreateItemResult(events);11981199 const itemCountAfter = await getLastTokenId(api, collectionId);1200 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12011202 1203 1204 expect(result.success).to.be.true;1205 if (createMode === 'Fungible') {1206 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1207 } else {1208 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1209 }1210 expect(collectionId).to.be.equal(result.collectionId);1211 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1212 expect(to).to.be.deep.equal(result.recipient);1213 newItemId = result.itemId;1214 });1215 return newItemId;1216}12171218export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1219 await usingApi(async (api) => {1220 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12211222 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1223 const result = getCreateItemResult(events);12241225 expect(result.success).to.be.false;1226 });1227}12281229export async function setPublicAccessModeExpectSuccess(1230 sender: IKeyringPair, collectionId: number,1231 accessMode: 'Normal' | 'AllowList',1232) {1233 await usingApi(async (api) => {12341235 1236 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1237 const events = await submitTransactionAsync(sender, tx);1238 const result = getGenericResult(events);12391240 1241 const collection = await queryCollectionExpectSuccess(api, collectionId);12421243 1244 1245 expect(result.success).to.be.true;1246 expect(collection.access.toHuman()).to.be.equal(accessMode);1247 });1248}12491250export async function setPublicAccessModeExpectFail(1251 sender: IKeyringPair, collectionId: number,1252 accessMode: 'Normal' | 'AllowList',1253) {1254 await usingApi(async (api) => {12551256 1257 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1258 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1259 const result = getGenericResult(events);12601261 1262 1263 expect(result.success).to.be.false;1264 });1265}12661267export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1268 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1269}12701271export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1272 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1273}12741275export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1276 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1277}12781279export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1280 await usingApi(async (api) => {12811282 1283 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1284 const events = await submitTransactionAsync(sender, tx);1285 const result = getGenericResult(events);1286 expect(result.success).to.be.true;12871288 1289 const collection = await queryCollectionExpectSuccess(api, collectionId);12901291 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1292 });1293}12941295export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1296 await setMintPermissionExpectSuccess(sender, collectionId, true);1297}12981299export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1300 await usingApi(async (api) => {1301 1302 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1303 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1304 const result = getCreateCollectionResult(events);1305 1306 expect(result.success).to.be.false;1307 });1308}13091310export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1311 await usingApi(async (api) => {1312 1313 const tx = api.tx.unique.setChainLimits(limits);1314 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1315 const result = getCreateCollectionResult(events);1316 1317 expect(result.success).to.be.false;1318 });1319}13201321export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1322 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1323}13241325export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1326 await usingApi(async (api) => {1327 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13281329 1330 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1331 const events = await submitTransactionAsync(sender, tx);1332 const result = getGenericResult(events);1333 expect(result.success).to.be.true;13341335 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1336 });1337}13381339export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1340 await usingApi(async (api) => {13411342 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13431344 1345 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1346 const events = await submitTransactionAsync(sender, tx);1347 const result = getGenericResult(events);1348 expect(result.success).to.be.true;13491350 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1351 });1352}13531354export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1355 await usingApi(async (api) => {13561357 1358 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1359 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1360 const result = getGenericResult(events);13611362 1363 1364 expect(result.success).to.be.false;1365 });1366}13671368export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1369 await usingApi(async (api) => {1370 1371 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1372 const events = await submitTransactionAsync(sender, tx);1373 const result = getGenericResult(events);13741375 1376 1377 expect(result.success).to.be.true;1378 });1379}13801381export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1382 await usingApi(async (api) => {1383 1384 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1385 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1386 const result = getGenericResult(events);13871388 1389 1390 expect(result.success).to.be.false;1391 });1392}13931394export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1395 : Promise<UpDataStructsRpcCollection | null> => {1396 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1397};13981399export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1400 1401 return (await api.rpc.unique.collectionStats()).created.toNumber();1402};14031404export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1405 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1406}14071408export async function waitNewBlocks(blocksCount = 1): Promise<void> {1409 await usingApi(async (api) => {1410 const promise = new Promise<void>(async (resolve) => {1411 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1412 if (blocksCount > 0) {1413 blocksCount--;1414 } else {1415 unsubscribe();1416 resolve();1417 }1418 });1419 });1420 return promise;1421 });1422}