12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50 Substrate?: TSubstrateAccount;51 Ethereum?: TEthereumAccount;5253 constructor(account: ICrossAccountId) {54 if (account.Substrate) this.Substrate = account.Substrate;55 if (account.Ethereum) this.Ethereum = account.Ethereum;56 }5758 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59 switch (domain) {60 case 'Substrate': return new CrossAccountId({Substrate: account.address});61 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62 }63 }6465 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67 }6869 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70 return encodeAddress(decodeAddress(address), ss58Format);71 }7273 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75 }7677 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79 return this;80 }8182 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84 }8586 toEthereum(): CrossAccountId {87 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88 return this;89 }9091 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92 return evmToAddress(address, ss58Format);93 }9495 toSubstrate(ss58Format?: number): CrossAccountId {96 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97 return this;98 }99100 toLowerCase(): CrossAccountId {101 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103 return this;104 }105}106107const nesting = {108 toChecksumAddress(address: string): string {109 if (typeof address === 'undefined') return '';110111 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113 address = address.toLowerCase().replace(/^0x/i,'');114 const addressHash = keccakAsHex(address).replace(/^0x/i,'');115 const checksumAddress = ['0x'];116117 for (let i = 0; i < address.length; i++) {118 119 if (parseInt(addressHash[i], 16) > 7) {120 checksumAddress.push(address[i].toUpperCase());121 } else {122 checksumAddress.push(address[i]);123 }124 }125 return checksumAddress.join('');126 },127 tokenIdToAddress(collectionId: number, tokenId: number) {128 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129 },130};131132class UniqueUtil {133 static transactionStatus = {134 NOT_READY: 'NotReady',135 FAIL: 'Fail',136 SUCCESS: 'Success',137 };138139 static chainLogType = {140 EXTRINSIC: 'extrinsic',141 RPC: 'rpc',142 };143144 static getTokenAccount(token: IToken): CrossAccountId {145 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146 }147148 static getTokenAddress(token: IToken): string {149 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150 }151152 static getDefaultLogger(): ILogger {153 return {154 log(msg: any, level = 'INFO') {155 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156 },157 level: {158 ERROR: 'ERROR',159 WARNING: 'WARNING',160 INFO: 'INFO',161 },162 };163 }164165 static vec2str(arr: string[] | number[]) {166 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167 }168169 static str2vec(string: string) {170 if (typeof string !== 'string') return string;171 return Array.from(string).map(x => x.charCodeAt(0));172 }173174 static fromSeed(seed: string, ss58Format = 42) {175 const keyring = new Keyring({type: 'sr25519', ss58Format});176 return keyring.addFromUri(seed);177 }178179 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180 if (creationResult.status !== this.transactionStatus.SUCCESS) {181 throw Error('Unable to create collection!');182 }183184 let collectionId = null;185 creationResult.result.events.forEach(({event: {data, method, section}}) => {186 if ((section === 'common') && (method === 'CollectionCreated')) {187 collectionId = parseInt(data[0].toString(), 10);188 }189 });190191 if (collectionId === null) {192 throw Error('No CollectionCreated event was found!');193 }194195 return collectionId;196 }197198 static extractTokensFromCreationResult(creationResult: ITransactionResult): {199 success: boolean,200 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201 } {202 if (creationResult.status !== this.transactionStatus.SUCCESS) {203 throw Error('Unable to create tokens!');204 }205 let success = false;206 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207 creationResult.result.events.forEach(({event: {data, method, section}}) => {208 if (method === 'ExtrinsicSuccess') {209 success = true;210 } else if ((section === 'common') && (method === 'ItemCreated')) {211 tokens.push({212 collectionId: parseInt(data[0].toString(), 10),213 tokenId: parseInt(data[1].toString(), 10),214 owner: data[2].toHuman(),215 amount: data[3].toBigInt(),216 });217 }218 });219 return {success, tokens};220 }221222 static extractTokensFromBurnResult(burnResult: ITransactionResult): {223 success: boolean,224 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225 } {226 if (burnResult.status !== this.transactionStatus.SUCCESS) {227 throw Error('Unable to burn tokens!');228 }229 let success = false;230 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231 burnResult.result.events.forEach(({event: {data, method, section}}) => {232 if (method === 'ExtrinsicSuccess') {233 success = true;234 } else if ((section === 'common') && (method === 'ItemDestroyed')) {235 tokens.push({236 collectionId: parseInt(data[0].toString(), 10),237 tokenId: parseInt(data[1].toString(), 10),238 owner: data[2].toHuman(),239 amount: data[3].toBigInt(),240 });241 }242 });243 return {success, tokens};244 }245246 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247 let eventId = null;248 events.forEach(({event: {data, method, section}}) => {249 if ((section === expectedSection) && (method === expectedMethod)) {250 eventId = parseInt(data[0].toString(), 10);251 }252 });253254 if (eventId === null) {255 throw Error(`No ${expectedMethod} event was found!`);256 }257 return eventId === collectionId;258 }259260 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261 const normalizeAddress = (address: string | ICrossAccountId) => {262 if(typeof address === 'string') return address;263 const obj = {} as any;264 Object.keys(address).forEach(k => {265 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266 });267 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269 return address;270 };271 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272 events.forEach(({event: {data, method, section}}) => {273 if ((section === 'common') && (method === 'Transfer')) {274 const hData = (data as any).toJSON();275 transfer = {276 collectionId: hData[0],277 tokenId: hData[1],278 from: normalizeAddress(hData[2]),279 to: normalizeAddress(hData[3]),280 amount: BigInt(hData[4]),281 };282 }283 });284 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287 isSuccess = isSuccess && amount === transfer.amount;288 return isSuccess;289 }290291 static bigIntToDecimals(number: bigint, decimals = 18) {292 const numberStr = number.toString();293 const dotPos = numberStr.length - decimals;294295 if (dotPos <= 0) {296 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297 } else {298 const intPart = numberStr.substring(0, dotPos);299 const fractPart = numberStr.substring(dotPos);300 return intPart + '.' + fractPart;301 }302 }303}304305class UniqueEventHelper {306 private static extractIndex(index: any): [number, number] | string {307 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308 return index.toJSON();309 }310311 private static extractSub(data: any, subTypes: any): {[key: string]: any} {312 let obj: any = {};313 let index = 0;314315 if (data.entries) {316 for(const [key, value] of data.entries()) {317 obj[key] = this.extractData(value, subTypes[index]);318 index++;319 }320 } else obj = data.toJSON();321322 return obj;323 }324325 private static toHuman(data: any) {326 return data && data.toHuman ? data.toHuman() : `${data}`;327 }328329 private static extractData(data: any, type: any): any {330 if(!type) return this.toHuman(data);331 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334 return this.toHuman(data);335 }336337 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338 const parsedEvents: IEvent[] = [];339340 events.forEach((record) => {341 const {event, phase} = record;342 const types = event.typeDef;343344 const eventData: IEvent = {345 section: event.section.toString(),346 method: event.method.toString(),347 index: this.extractIndex(event.index),348 data: [],349 phase: phase.toJSON(),350 };351352 event.data.forEach((val: any, index: number) => {353 eventData.data.push(this.extractData(val, types[index]));354 });355356 parsedEvents.push(eventData);357 });358359 return parsedEvents;360 }361}362363export class ChainHelperBase {364 helperBase: any;365366 transactionStatus = UniqueUtil.transactionStatus;367 chainLogType = UniqueUtil.chainLogType;368 util: typeof UniqueUtil;369 eventHelper: typeof UniqueEventHelper;370 logger: ILogger;371 api: ApiPromise | null;372 forcedNetwork: TNetworks | null;373 network: TNetworks | null;374 chainLog: IUniqueHelperLog[];375 children: ChainHelperBase[];376 address: AddressGroup;377 chain: ChainGroup;378379 constructor(logger?: ILogger, helperBase?: any) {380 this.helperBase = helperBase;381382 this.util = UniqueUtil;383 this.eventHelper = UniqueEventHelper;384 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();385 this.logger = logger;386 this.api = null;387 this.forcedNetwork = null;388 this.network = null;389 this.chainLog = [];390 this.children = [];391 this.address = new AddressGroup(this);392 this.chain = new ChainGroup(this);393 }394395 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {396 Object.setPrototypeOf(helperCls.prototype, this);397 const newHelper = new helperCls(this.logger, options);398399 newHelper.api = this.api;400 newHelper.network = this.network;401 newHelper.forceNetwork = this.forceNetwork;402403 this.children.push(newHelper);404405 return newHelper;406 }407408 getApi(): ApiPromise {409 if(this.api === null) throw Error('API not initialized');410 return this.api;411 }412413 async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {414 const collectedEvents: IEvent[] = [];415 const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {416 const ievents = this.eventHelper.extractEvents(events);417 ievents.forEach((event) => {418 expectedEvents.forEach((e => {419 if (event.section === e.section && e.names.includes(event.method)) {420 collectedEvents.push(event);421 }422 }));423 });424 });425 return {unsubscribe: unsubscribe as any, collectedEvents};426 }427428 clearChainLog(): void {429 this.chainLog = [];430 }431432 forceNetwork(value: TNetworks): void {433 this.forcedNetwork = value;434 }435436 async connect(wsEndpoint: string, listeners?: IApiListeners) {437 if (this.api !== null) throw Error('Already connected');438 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);439 this.api = api;440 this.network = network;441 }442443 async disconnect() {444 for (const child of this.children) {445 child.clearApi();446 }447448 if (this.api === null) return;449 await this.api.disconnect();450 this.clearApi();451 }452453 clearApi() {454 this.api = null;455 this.network = null;456 }457458 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {459 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;460 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];461462 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;463464 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;465 return 'opal';466 }467468 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {469 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});470 await api.isReady;471472 const network = await this.detectNetwork(api);473474 await api.disconnect();475476 return network;477 }478479 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{480 api: ApiPromise;481 network: TNetworks;482 }> {483 if(typeof network === 'undefined' || network === null) network = 'opal';484 const supportedRPC = {485 opal: {486 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,487 },488 quartz: {489 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,490 },491 unique: {492 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,493 },494 rococo: {},495 westend: {},496 moonbeam: {},497 moonriver: {},498 acala: {},499 karura: {},500 westmint: {},501 };502 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);503 const rpc = supportedRPC[network];504505 506 507508 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});509510 await api.isReadyOrError;511512 if (typeof listeners === 'undefined') listeners = {};513 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {514 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;515 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);516 }517518 return {api, network};519 }520521 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {522 const {events, status} = data;523 if (status.isReady) {524 return this.transactionStatus.NOT_READY;525 }526 if (status.isBroadcast) {527 return this.transactionStatus.NOT_READY;528 }529 if (status.isInBlock || status.isFinalized) {530 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');531 if (errors.length > 0) {532 return this.transactionStatus.FAIL;533 }534 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {535 return this.transactionStatus.SUCCESS;536 }537 }538539 return this.transactionStatus.FAIL;540 }541542 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {543 const sign = (callback: any) => {544 if(options !== null) return transaction.signAndSend(sender, options, callback);545 return transaction.signAndSend(sender, callback);546 };547 548 return new Promise(async (resolve, reject) => {549 try {550 const unsub = await sign((result: any) => {551 const status = this.getTransactionStatus(result);552553 if (status === this.transactionStatus.SUCCESS) {554 this.logger.log(`${label} successful`);555 unsub();556 resolve({result, status});557 } else if (status === this.transactionStatus.FAIL) {558 let moduleError = null;559560 if (result.hasOwnProperty('dispatchError')) {561 const dispatchError = result['dispatchError'];562563 if (dispatchError) {564 if (dispatchError.isModule) {565 const modErr = dispatchError.asModule;566 const errorMeta = dispatchError.registry.findMetaError(modErr);567568 moduleError = `${errorMeta.section}.${errorMeta.name}`;569 } else {570 moduleError = dispatchError.toHuman();571 }572 } else {573 this.logger.log(result, this.logger.level.ERROR);574 }575 }576577 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);578 unsub();579 reject({status, moduleError, result});580 }581 });582 } catch (e) {583 this.logger.log(e, this.logger.level.ERROR);584 reject(e);585 }586 });587 }588589 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {590 const api = this.getApi();591 const signingInfo = await api.derive.tx.signingInfo(signer.address);592593 594 595 tx.sign(signer, {596 blockHash: api.genesisHash,597 genesisHash: api.genesisHash,598 runtimeVersion: api.runtimeVersion,599 nonce: signingInfo.nonce,600 });601602 if (len === null) {603 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;604 } else {605 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;606 }607 }608609 constructApiCall(apiCall: string, params: any[]) {610 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);611 let call = this.getApi() as any;612 for(const part of apiCall.slice(4).split('.')) {613 call = call[part];614 }615 return call(...params);616 }617618 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {619 if(this.api === null) throw Error('API not initialized');620 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);621622 const startTime = (new Date()).getTime();623 let result: ITransactionResult;624 let events: IEvent[] = [];625 try {626 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;627 events = this.eventHelper.extractEvents(result.result.events);628 }629 catch(e) {630 if(!(e as object).hasOwnProperty('status')) throw e;631 result = e as ITransactionResult;632 }633634 const endTime = (new Date()).getTime();635636 const log = {637 executedAt: endTime,638 executionTime: endTime - startTime,639 type: this.chainLogType.EXTRINSIC,640 status: result.status,641 call: extrinsic,642 signer: this.getSignerAddress(sender),643 params,644 } as IUniqueHelperLog;645646 if(result.status !== this.transactionStatus.SUCCESS) {647 if (result.moduleError) log.moduleError = result.moduleError;648 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;649 }650 if(events.length > 0) log.events = events;651652 this.chainLog.push(log);653654 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {655 if (result.moduleError) throw Error(`${result.moduleError}`);656 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));657 }658 return result;659 }660661 async callRpc(rpc: string, params?: any[]) {662 if(typeof params === 'undefined') params = [];663 if(this.api === null) throw Error('API not initialized');664 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);665666 const startTime = (new Date()).getTime();667 let result;668 let error = null;669 const log = {670 type: this.chainLogType.RPC,671 call: rpc,672 params,673 } as IUniqueHelperLog;674675 try {676 result = await this.constructApiCall(rpc, params);677 }678 catch(e) {679 error = e;680 }681682 const endTime = (new Date()).getTime();683684 log.executedAt = endTime;685 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';686 log.executionTime = endTime - startTime;687688 this.chainLog.push(log);689690 if(error !== null) throw error;691692 return result;693 }694695 getSignerAddress(signer: IKeyringPair | string): string {696 if(typeof signer === 'string') return signer;697 return signer.address;698 }699700 fetchAllPalletNames(): string[] {701 if(this.api === null) throw Error('API not initialized');702 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());703 }704705 fetchMissingPalletNames(requiredPallets: string[]): string[] {706 const palletNames = this.fetchAllPalletNames();707 return requiredPallets.filter(p => !palletNames.includes(p));708 }709}710711712class HelperGroup<T extends ChainHelperBase> {713 helper: T;714715 constructor(uniqueHelper: T) {716 this.helper = uniqueHelper;717 }718}719720721class CollectionGroup extends HelperGroup<UniqueHelper> {722 723724725726727728729730731 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {732 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();733 }734735 736737738739740 async getTotalCount(): Promise<number> {741 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();742 }743744 745746747748749750751752753 async getData(collectionId: number): Promise<{754 id: number;755 name: string;756 description: string;757 tokensCount: number;758 admins: CrossAccountId[];759 normalizedOwner: TSubstrateAccount;760 raw: any761 } | null> {762 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);763 const humanCollection = collection.toHuman(), collectionData = {764 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],765 raw: humanCollection,766 } as any, jsonCollection = collection.toJSON();767 if (humanCollection === null) return null;768 collectionData.raw.limits = jsonCollection.limits;769 collectionData.raw.permissions = jsonCollection.permissions;770 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);771 for (const key of ['name', 'description']) {772 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);773 }774775 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))776 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)777 : 0;778 collectionData.admins = await this.getAdmins(collectionId);779780 return collectionData;781 }782783 784785786787788789790791 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {792 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();793794 return normalize795 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())796 : admins;797 }798799 800801802803804805806 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {807 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();808 return normalize809 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())810 : allowListed;811 }812813 814815816817818819820 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {821 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();822 }823824 825826827828829830831832 async burn(signer: TSigner, collectionId: number): Promise<boolean> {833 const result = await this.helper.executeExtrinsic(834 signer,835 'api.tx.unique.destroyCollection', [collectionId],836 true,837 );838839 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');840 }841842 843844845846847848849850851 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');859 }860861 862863864865866867868869 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.confirmSponsorship', [collectionId],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');877 }878879 880881882883884885886887 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {888 const result = await this.helper.executeExtrinsic(889 signer,890 'api.tx.unique.removeCollectionSponsor', [collectionId],891 true,892 );893894 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');895 }896897 898899900901902903904905906907908909910911912913914 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {915 const result = await this.helper.executeExtrinsic(916 signer,917 'api.tx.unique.setCollectionLimits', [collectionId, limits],918 true,919 );920921 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');922 }923924 925926927928929930931932933 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {934 const result = await this.helper.executeExtrinsic(935 signer,936 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],937 true,938 );939940 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');941 }942943 944945946947948949950951952 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');960 }961962 963964965966967968969970971 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');979 }980981 982983984985986987988989 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {990 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();991 }992993 9949959969979989991000 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1001 const result = await this.helper.executeExtrinsic(1002 signer,1003 'api.tx.unique.addToAllowList', [collectionId, addressObj],1004 true,1005 );10061007 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1008 }10091010 10111012101310141015101610171018 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1026 }10271028 102910301031103210331034103510361037 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1041 true,1042 );10431044 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1045 }10461047 104810491050105110521053105410551056 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1057 return await this.setPermissions(signer, collectionId, {nesting: permissions});1058 }10591060 10611062106310641065106610671068 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1069 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1070 }10711072 107310741075107610771078107910801081 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1082 const result = await this.helper.executeExtrinsic(1083 signer,1084 'api.tx.unique.setCollectionProperties', [collectionId, properties],1085 true,1086 );10871088 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1089 }10901091 10921093109410951096109710981099 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1100 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1101 }11021103 async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1104 const api = this.helper.getApi();1105 const props = (await api.query.common.collectionProperties(collectionId)).toJSON();1106 1107 return (props! as any).consumedSpace;1108 }11091110 async getCollectionOptions(collectionId: number) {1111 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112 }11131114 111511161117111811191120112111221123 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1124 const result = await this.helper.executeExtrinsic(1125 signer,1126 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1127 true,1128 );11291130 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1131 }11321133 11341135113611371138113911401141114211431144 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1145 const result = await this.helper.executeExtrinsic(1146 signer,1147 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1148 true, 1149 );11501151 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1152 }11531154 1155115611571158115911601161116211631164116511661167 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1171 true, 1172 );1173 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1174 }11751176 11771178117911801181118211831184118511861187 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1188 const burnResult = await this.helper.executeExtrinsic(1189 signer,1190 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1191 true, 1192 );1193 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1194 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1195 return burnedTokens.success;1196 }11971198 11991200120112021203120412051206120712081209 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1210 const burnResult = await this.helper.executeExtrinsic(1211 signer,1212 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1213 true, 1214 );1215 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216 return burnedTokens.success && burnedTokens.tokens.length > 0;1217 }12181219 1220122112221223122412251226122712281229 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1230 const approveResult = await this.helper.executeExtrinsic(1231 signer,1232 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1233 true, 1234 );12351236 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1237 }12381239 1240124112421243124412451246124712481249 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1250 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1251 }12521253 1254125512561257125812591260 async getLastTokenId(collectionId: number): Promise<number> {1261 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1262 }12631264 12651266126712681269127012711272 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1273 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1274 }1275}12761277class NFTnRFT extends CollectionGroup {1278 12791280128112821283128412851286 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1287 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1288 }12891290 1291129212931294129512961297129812991300 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1301 properties: IProperty[];1302 owner: CrossAccountId;1303 normalizedOwner: CrossAccountId;1304 }| null> {1305 let tokenData;1306 if(typeof blockHashAt === 'undefined') {1307 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1308 }1309 else {1310 if(propertyKeys.length == 0) {1311 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1312 if(!collection) return null;1313 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1314 }1315 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1316 }1317 tokenData = tokenData.toHuman();1318 if (tokenData === null || tokenData.owner === null) return null;1319 const owner = {} as any;1320 for (const key of Object.keys(tokenData.owner)) {1321 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1322 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1323 : tokenData.owner[key];1324 }1325 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1326 return tokenData;1327 }13281329 13301331133213331334133513361337133813391340 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1341 const result = await this.helper.executeExtrinsic(1342 signer,1343 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1344 true,1345 );13461347 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1348 }13491350 13511352135313541355135613571358 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1359 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1360 }13611362 1363136413651366136713681369137013711372 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1373 const result = await this.helper.executeExtrinsic(1374 signer,1375 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1376 true,1377 );13781379 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1380 }13811382 138313841385138613871388138913901391 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1392 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1393 }13941395 139613971398139914001401140214031404 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1405 const result = await this.helper.executeExtrinsic(1406 signer,1407 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1408 true,1409 );14101411 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1412 }14131414 141514161417141814191420142114221423 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1424 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1425 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1426 for (const key of ['name', 'description', 'tokenPrefix']) {1427 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1428 }1429 const creationResult = await this.helper.executeExtrinsic(1430 signer,1431 'api.tx.unique.createCollectionEx', [collectionOptions],1432 true, 1433 );1434 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1435 }14361437 getCollectionObject(_collectionId: number): any {1438 return null;1439 }14401441 getTokenObject(_collectionId: number, _tokenId: number): any {1442 return null;1443 }14441445 1446144714481449145014511452 async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1453 return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1454 }14551456 145714581459146014611462 async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1463 const result = await this.helper.executeExtrinsic(1464 signer,1465 'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1466 true,1467 );1468 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1469 }1470}147114721473class NFTGroup extends NFTnRFT {1474 147514761477147814791480 getCollectionObject(collectionId: number): UniqueNFTCollection {1481 return new UniqueNFTCollection(collectionId, this.helper);1482 }14831484 1485148614871488148914901491 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1492 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1493 }14941495 14961497149814991500150115021503 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1504 let owner;1505 if (typeof blockHashAt === 'undefined') {1506 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1507 } else {1508 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1509 }1510 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1511 }15121513 1514151515161517151815191520 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1521 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1522 }15231524 1525152615271528152915301531153215331534 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1535 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1536 }15371538 153915401541154215431544154515461547154815491550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1552 }15531554 15551556155715581559156015611562 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1563 let owner;1564 if (typeof blockHashAt === 'undefined') {1565 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1566 } else {1567 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1568 }15691570 if (owner === null) return null;15711572 return owner.toHuman();1573 }15741575 15761577157815791580158115821583 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1584 let children;1585 if(typeof blockHashAt === 'undefined') {1586 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1587 } else {1588 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1589 }15901591 return children.toJSON().map((x: any) => {1592 return {collectionId: x.collection, tokenId: x.token};1593 });1594 }15951596 15971598159916001601160216031604 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1605 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1606 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1607 if(!result) {1608 throw Error('Unable to nest token!');1609 }1610 return result;1611 }16121613 161416151616161716181619162016211622 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1623 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1624 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1625 if(!result) {1626 throw Error('Unable to unnest token!');1627 }1628 return result;1629 }16301631 163216331634163516361637163816391640164116421643 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1644 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1645 }16461647 164816491650165116521653 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1654 const creationResult = await this.helper.executeExtrinsic(1655 signer,1656 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1657 nft: {1658 properties: data.properties,1659 },1660 }],1661 true,1662 );1663 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1664 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1665 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1666 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1667 }16681669 167016711672167316741675167616771678167916801681168216831684 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1688 true,1689 );1690 const collection = this.getCollectionObject(collectionId);1691 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1692 }16931694 169516961697169816991700170117021703170417051706170717081709171017111712 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1713 const rawTokens = [];1714 for (const token of tokens) {1715 const raw = {NFT: {properties: token.properties}};1716 rawTokens.push(raw);1717 }1718 const creationResult = await this.helper.executeExtrinsic(1719 signer,1720 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1721 true,1722 );1723 const collection = this.getCollectionObject(collectionId);1724 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1725 }17261727 1728172917301731173217331734173517361737 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1738 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1739 }1740}174117421743class RFTGroup extends NFTnRFT {1744 174517461747174817491750 getCollectionObject(collectionId: number): UniqueRFTCollection {1751 return new UniqueRFTCollection(collectionId, this.helper);1752 }17531754 1755175617571758175917601761 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1762 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1763 }17641765 1766176717681769177017711772 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1773 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1774 }17751776 17771778177917801781178217831784 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1785 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1786 }17871788 1789179017911792179317941795179617971798 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1799 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1800 }18011802 18031804180518061807180818091810181118121813 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1814 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1815 }18161817 181818191820182118221823182418251826182718281829 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1830 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1831 }18321833 1834183518361837183818391840 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1841 const creationResult = await this.helper.executeExtrinsic(1842 signer,1843 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1844 refungible: {1845 pieces: data.pieces,1846 properties: data.properties,1847 },1848 }],1849 true,1850 );1851 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1852 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1853 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1854 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1855 }18561857 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1858 throw Error('Not implemented');1859 const creationResult = await this.helper.executeExtrinsic(1860 signer,1861 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1862 true, 1863 );1864 const collection = this.getCollectionObject(collectionId);1865 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1866 }18671868 186918701871187218731874187518761877 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1878 const rawTokens = [];1879 for (const token of tokens) {1880 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1881 rawTokens.push(raw);1882 }1883 const creationResult = await this.helper.executeExtrinsic(1884 signer,1885 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1886 true,1887 );1888 const collection = this.getCollectionObject(collectionId);1889 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1890 }18911892 189318941895189618971898189919001901 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1902 return await super.burnToken(signer, collectionId, tokenId, amount);1903 }19041905 1906190719081909191019111912191319141915 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1916 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1917 }19181919 19201921192219231924192519261927192819291930 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1931 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1932 }19331934 1935193619371938193919401941 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1942 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1943 }19441945 194619471948194919501951195219531954 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1955 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1956 const repartitionResult = await this.helper.executeExtrinsic(1957 signer,1958 'api.tx.unique.repartition', [collectionId, tokenId, amount],1959 true,1960 );1961 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1962 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1963 }1964}196519661967class FTGroup extends CollectionGroup {1968 196919701971197219731974 getCollectionObject(collectionId: number): UniqueFTCollection {1975 return new UniqueFTCollection(collectionId, this.helper);1976 }19771978 1979198019811982198319841985198619871988198919901991 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1992 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1993 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1994 collectionOptions.mode = {fungible: decimalPoints};1995 for (const key of ['name', 'description', 'tokenPrefix']) {1996 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1997 }1998 const creationResult = await this.helper.executeExtrinsic(1999 signer,2000 'api.tx.unique.createCollectionEx', [collectionOptions],2001 true,2002 );2003 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2004 }20052006 200720082009201020112012201320142015 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2016 const creationResult = await this.helper.executeExtrinsic(2017 signer,2018 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2019 fungible: {2020 value: amount,2021 },2022 }],2023 true, 2024 );2025 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2026 }20272028 20292030203120322033203420352036 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2037 const rawTokens = [];2038 for (const token of tokens) {2039 const raw = {Fungible: {Value: token.value}};2040 rawTokens.push(raw);2041 }2042 const creationResult = await this.helper.executeExtrinsic(2043 signer,2044 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2045 true,2046 );2047 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048 }20492050 205120522053205420552056 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2057 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2058 }20592060 2061206220632064206520662067 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2068 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2069 }20702071 207220732074207520762077207820792080 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2081 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2082 }20832084 2085208620872088208920902091209220932094 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2095 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2096 }20972098 20992100210121022103210421052106 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2107 return await super.burnToken(signer, collectionId, 0, amount);2108 }21092110 211121122113211421152116211721182119 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2120 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2121 }21222123 21242125212621272128 async getTotalPieces(collectionId: number): Promise<bigint> {2129 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2130 }21312132 2133213421352136213721382139214021412142 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2144 }21452146 2147214821492150215121522153 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2154 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2155 }2156}215721582159class ChainGroup extends HelperGroup<ChainHelperBase> {2160 21612162216321642165 getChainProperties(): IChainProperties {2166 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2167 return {2168 ss58Format: properties.ss58Format.toJSON(),2169 tokenDecimals: properties.tokenDecimals.toJSON(),2170 tokenSymbol: properties.tokenSymbol.toJSON(),2171 };2172 }21732174 21752176217721782179 async getLatestBlockNumber(): Promise<number> {2180 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2181 }21822183 218421852186218721882189 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2190 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2191 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2192 return blockHash;2193 }21942195 2196 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2197 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2198 if (!blockHash) return null;2199 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2200 }22012202 220322042205220622072208 async getNonce(address: TSubstrateAccount): Promise<number> {2209 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2210 }2211}22122213class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2214 221522162217221822192220 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2221 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2222 }22232224 22252226222722282229223022312232 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2233 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22342235 let transfer = {from: null, to: null, amount: 0n} as any;2236 result.result.events.forEach(({event: {data, method, section}}) => {2237 if ((section === 'balances') && (method === 'Transfer')) {2238 transfer = {2239 from: this.helper.address.normalizeSubstrate(data[0]),2240 to: this.helper.address.normalizeSubstrate(data[1]),2241 amount: BigInt(data[2]),2242 };2243 }2244 });2245 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2246 && this.helper.address.normalizeSubstrate(address) === transfer.to2247 && BigInt(amount) === transfer.amount;2248 return isSuccess;2249 }22502251 22522253225422552256 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2257 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2258 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2259 }2260}22612262class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2263 226422652266226722682269 async getEthereum(address: TEthereumAccount): Promise<bigint> {2270 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2271 }22722273 22742275227622772278227922802281 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2282 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22832284 let transfer = {from: null, to: null, amount: 0n} as any;2285 result.result.events.forEach(({event: {data, method, section}}) => {2286 if ((section === 'balances') && (method === 'Transfer')) {2287 transfer = {2288 from: data[0].toString(),2289 to: data[1].toString(),2290 amount: BigInt(data[2]),2291 };2292 }2293 });2294 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2295 && address === transfer.to2296 && BigInt(amount) === transfer.amount;2297 return isSuccess;2298 }2299}23002301class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2302 subBalanceGroup: SubstrateBalanceGroup<T>;2303 ethBalanceGroup: EthereumBalanceGroup<T>;23042305 constructor(helper: T) {2306 super(helper);2307 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2308 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2309 }23102311 getCollectionCreationPrice(): bigint {2312 return 2n * this.getOneTokenNominal();2313 }2314 23152316231723182319 getOneTokenNominal(): bigint {2320 const chainProperties = this.helper.chain.getChainProperties();2321 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2322 }23232324 232523262327232823292330 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2331 return this.subBalanceGroup.getSubstrate(address);2332 }23332334 23352336233723382339 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2340 return this.subBalanceGroup.getSubstrateFull(address);2341 }23422343 234423452346234723482349 getEthereum(address: TEthereumAccount): Promise<bigint> {2350 return this.ethBalanceGroup.getEthereum(address);2351 }23522353 23542355235623572358235923602361 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2362 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2363 }23642365 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2366 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23672368 let transfer = {from: null, to: null, amount: 0n} as any;2369 result.result.events.forEach(({event: {data, method, section}}) => {2370 if ((section === 'balances') && (method === 'Transfer')) {2371 transfer = {2372 from: this.helper.address.normalizeSubstrate(data[0]),2373 to: this.helper.address.normalizeSubstrate(data[1]),2374 amount: BigInt(data[2]),2375 };2376 }2377 });2378 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2379 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2380 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2381 return isSuccess;2382 }2383}23842385class AddressGroup extends HelperGroup<ChainHelperBase> {2386 2387238823892390239123922393 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2394 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2395 }23962397 239823992400240124022403 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2404 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2405 }24062407 2408240924102411241224132414 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2415 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2416 }24172418 241924202421242224232424 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2425 return CrossAccountId.translateSubToEth(subAddress);2426 }24272428 242924302431243224332434 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2435 const u8a :Uint8Array = typeof key === 'string'2436 ? hexToU8a(key)2437 : typeof key === 'bigint'2438 ? hexToU8a(key.toString(16))2439 : key;2440 2441 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2442 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2443 }2444 2445 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2446 if (!allowedDecodedLengths.includes(u8a.length)) {2447 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2448 }2449 2450 const u8aPrefix = ss58Format < 642451 ? new Uint8Array([ss58Format])2452 : new Uint8Array([2453 ((ss58Format & 0xfc) >> 2) | 0x40,2454 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2455 ]);24562457 const input = u8aConcat(u8aPrefix, u8a);2458 2459 return base58Encode(u8aConcat(2460 input,2461 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2462 ));2463 }24642465 24662467246824692470 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2471 if (this.helper.api === null) {2472 throw 'Not connected';2473 }2474 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2475 if (res === undefined || res === null) {2476 throw 'Restore address error';2477 }2478 return res.toString();2479 }24802481 24822483248424852486 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2487 if (ethCrossAccount.sub === '0') {2488 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2489 }2490 2491 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2492 return {Substrate: ss58};2493 }24942495 paraSiblingSovereignAccount(paraid: number) {2496 2497 2498 const siblingPrefix = '0x7369626c';24992500 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2501 const suffix = '000000000000000000000000000000000000000000000000';25022503 return siblingPrefix + encodedParaId + suffix;2504 }2505}25062507class StakingGroup extends HelperGroup<UniqueHelper> {2508 2509251025112512251325142515 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2516 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2517 const _stakeResult = await this.helper.executeExtrinsic(2518 signer, 'api.tx.appPromotion.stake',2519 [amountToStake], true,2520 );2521 2522 return true;2523 }25242525 2526252725282529253025312532 async unstake(signer: TSigner, label?: string): Promise<number> {2533 if(typeof label === 'undefined') label = `${signer.address}`;2534 const _unstakeResult = await this.helper.executeExtrinsic(2535 signer, 'api.tx.appPromotion.unstake',2536 [], true,2537 );2538 2539 return 1;2540 }25412542 25432544254525462547 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2548 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2549 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2550 }25512552 25532554255525562557 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2558 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2559 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2560 return {2561 block: block.toBigInt(),2562 amount: amount.toBigInt(),2563 };2564 });2565 }25662567 25682569257025712572 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2573 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2574 }25752576 25772578257925802581 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2582 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2583 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2584 return {2585 block: block.toBigInt(),2586 amount: amount.toBigInt(),2587 };2588 });2589 return result;2590 }2591}25922593class SchedulerGroup extends HelperGroup<UniqueHelper> {2594 constructor(helper: UniqueHelper) {2595 super(helper);2596 }25972598 cancelScheduled(signer: TSigner, scheduledId: string) {2599 return this.helper.executeExtrinsic(2600 signer,2601 'api.tx.scheduler.cancelNamed',2602 [scheduledId],2603 true,2604 );2605 }26062607 changePriority(signer: TSigner, scheduledId: string, priority: number) {2608 return this.helper.executeExtrinsic(2609 signer,2610 'api.tx.scheduler.changeNamedPriority',2611 [scheduledId, priority],2612 true,2613 );2614 }26152616 scheduleAt<T extends UniqueHelper>(2617 executionBlockNumber: number,2618 options: ISchedulerOptions = {},2619 ) {2620 return this.schedule<T>('schedule', executionBlockNumber, options);2621 }26222623 scheduleAfter<T extends UniqueHelper>(2624 blocksBeforeExecution: number,2625 options: ISchedulerOptions = {},2626 ) {2627 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2628 }26292630 schedule<T extends UniqueHelper>(2631 scheduleFn: 'schedule' | 'scheduleAfter',2632 blocksNum: number,2633 options: ISchedulerOptions = {},2634 ) {2635 2636 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2637 return this.helper.clone(ScheduledHelperType, {2638 scheduleFn,2639 blocksNum,2640 options,2641 }) as T;2642 }2643}26442645class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2646 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2647 await this.helper.executeExtrinsic(2648 signer,2649 'api.tx.foreignAssets.registerForeignAsset',2650 [ownerAddress, location, metadata],2651 true,2652 );2653 }26542655 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2656 await this.helper.executeExtrinsic(2657 signer,2658 'api.tx.foreignAssets.updateForeignAsset',2659 [foreignAssetId, location, metadata],2660 true,2661 );2662 }2663}26642665class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2666 palletName: string;26672668 constructor(helper: T, palletName: string) {2669 super(helper);26702671 this.palletName = palletName;2672 }26732674 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2675 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2676 }2677}26782679class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2680 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2681 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2682 }26832684 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2685 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2686 }26872688 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2689 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2690 }2691}26922693class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2694 async accounts(address: string, currencyId: any) {2695 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2696 return BigInt(free);2697 }2698}26992700class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2701 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2702 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2703 }27042705 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2706 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2707 }27082709 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2710 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2711 }27122713 async account(assetId: string | number, address: string) {2714 const accountAsset = (2715 await this.helper.callRpc('api.query.assets.account', [assetId, address])2716 ).toJSON()! as any;27172718 if (accountAsset !== null) {2719 return BigInt(accountAsset['balance']);2720 } else {2721 return null;2722 }2723 }2724}27252726class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2727 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2728 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2729 }2730}27312732class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2733 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2734 const apiPrefix = 'api.tx.assetManager.';27352736 const registerTx = this.helper.constructApiCall(2737 apiPrefix + 'registerForeignAsset',2738 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2739 );27402741 const setUnitsTx = this.helper.constructApiCall(2742 apiPrefix + 'setAssetUnitsPerSecond',2743 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2744 );27452746 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2747 const encodedProposal = batchCall?.method.toHex() || '';2748 return encodedProposal;2749 }27502751 async assetTypeId(location: any) {2752 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2753 }2754}27552756class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2757 async notePreimage(signer: TSigner, encodedProposal: string) {2758 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2759 }27602761 externalProposeMajority(proposalHash: string) {2762 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2763 }27642765 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2766 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2767 }27682769 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2770 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2771 }2772}27732774class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2775 collective: string;27762777 constructor(helper: MoonbeamHelper, collective: string) {2778 super(helper);27792780 this.collective = collective;2781 }27822783 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2784 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2785 }27862787 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2788 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2789 }27902791 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2792 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2793 }27942795 async proposalCount() {2796 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2797 }2798}27992800export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2801export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28022803export class UniqueHelper extends ChainHelperBase {2804 balance: BalanceGroup<UniqueHelper>;2805 collection: CollectionGroup;2806 nft: NFTGroup;2807 rft: RFTGroup;2808 ft: FTGroup;2809 staking: StakingGroup;2810 scheduler: SchedulerGroup;2811 foreignAssets: ForeignAssetsGroup;2812 xcm: XcmGroup<UniqueHelper>;2813 xTokens: XTokensGroup<UniqueHelper>;2814 tokens: TokensGroup<UniqueHelper>;28152816 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2817 super(logger, options.helperBase ?? UniqueHelper);28182819 this.balance = new BalanceGroup(this);2820 this.collection = new CollectionGroup(this);2821 this.nft = new NFTGroup(this);2822 this.rft = new RFTGroup(this);2823 this.ft = new FTGroup(this);2824 this.staking = new StakingGroup(this);2825 this.scheduler = new SchedulerGroup(this);2826 this.foreignAssets = new ForeignAssetsGroup(this);2827 this.xcm = new XcmGroup(this, 'polkadotXcm');2828 this.xTokens = new XTokensGroup(this);2829 this.tokens = new TokensGroup(this);2830 }28312832 getSudo<T extends UniqueHelper>() {2833 2834 const SudoHelperType = SudoHelper(this.helperBase);2835 return this.clone(SudoHelperType) as T;2836 }2837}28382839export class XcmChainHelper extends ChainHelperBase {2840 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2841 const wsProvider = new WsProvider(wsEndpoint);2842 this.api = new ApiPromise({2843 provider: wsProvider,2844 });2845 await this.api.isReadyOrError;2846 this.network = await UniqueHelper.detectNetwork(this.api);2847 }2848}28492850export class RelayHelper extends XcmChainHelper {2851 xcm: XcmGroup<RelayHelper>;28522853 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2854 super(logger, options.helperBase ?? RelayHelper);28552856 this.xcm = new XcmGroup(this, 'xcmPallet');2857 }2858}28592860export class WestmintHelper extends XcmChainHelper {2861 balance: SubstrateBalanceGroup<WestmintHelper>;2862 xcm: XcmGroup<WestmintHelper>;2863 assets: AssetsGroup<WestmintHelper>;2864 xTokens: XTokensGroup<WestmintHelper>;28652866 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2867 super(logger, options.helperBase ?? WestmintHelper);28682869 this.balance = new SubstrateBalanceGroup(this);2870 this.xcm = new XcmGroup(this, 'polkadotXcm');2871 this.assets = new AssetsGroup(this);2872 this.xTokens = new XTokensGroup(this);2873 }2874}28752876export class MoonbeamHelper extends XcmChainHelper {2877 balance: EthereumBalanceGroup<MoonbeamHelper>;2878 assetManager: MoonbeamAssetManagerGroup;2879 assets: AssetsGroup<MoonbeamHelper>;2880 xTokens: XTokensGroup<MoonbeamHelper>;2881 democracy: MoonbeamDemocracyGroup;2882 collective: {2883 council: MoonbeamCollectiveGroup,2884 techCommittee: MoonbeamCollectiveGroup,2885 };28862887 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2888 super(logger, options.helperBase ?? MoonbeamHelper);28892890 this.balance = new EthereumBalanceGroup(this);2891 this.assetManager = new MoonbeamAssetManagerGroup(this);2892 this.assets = new AssetsGroup(this);2893 this.xTokens = new XTokensGroup(this);2894 this.democracy = new MoonbeamDemocracyGroup(this);2895 this.collective = {2896 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2897 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2898 };2899 }2900}29012902export class AcalaHelper extends XcmChainHelper {2903 balance: SubstrateBalanceGroup<AcalaHelper>;2904 assetRegistry: AcalaAssetRegistryGroup;2905 xTokens: XTokensGroup<AcalaHelper>;2906 tokens: TokensGroup<AcalaHelper>;29072908 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2909 super(logger, options.helperBase ?? AcalaHelper);29102911 this.balance = new SubstrateBalanceGroup(this);2912 this.assetRegistry = new AcalaAssetRegistryGroup(this);2913 this.xTokens = new XTokensGroup(this);2914 this.tokens = new TokensGroup(this);2915 }29162917 getSudo<T extends AcalaHelper>() {2918 2919 const SudoHelperType = SudoHelper(this.helperBase);2920 return this.clone(SudoHelperType) as T;2921 }2922}292329242925function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2926 return class extends Base {2927 scheduleFn: 'schedule' | 'scheduleAfter';2928 blocksNum: number;2929 options: ISchedulerOptions;29302931 constructor(...args: any[]) {2932 const logger = args[0] as ILogger;2933 const options = args[1] as {2934 scheduleFn: 'schedule' | 'scheduleAfter',2935 blocksNum: number,2936 options: ISchedulerOptions2937 };29382939 super(logger);29402941 this.scheduleFn = options.scheduleFn;2942 this.blocksNum = options.blocksNum;2943 this.options = options.options;2944 }29452946 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2947 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2948 2949 const mandatorySchedArgs = [2950 this.blocksNum,2951 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2952 this.options.priority ?? null,2953 scheduledTx,2954 ];2955 2956 let schedArgs;2957 let scheduleFn;29582959 if (this.options.scheduledId) {2960 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];29612962 if (this.scheduleFn == 'schedule') {2963 scheduleFn = 'scheduleNamed';2964 } else if (this.scheduleFn == 'scheduleAfter') {2965 scheduleFn = 'scheduleNamedAfter';2966 }2967 } else {2968 schedArgs = mandatorySchedArgs;2969 scheduleFn = this.scheduleFn;2970 }29712972 const extrinsic = 'api.tx.scheduler.' + scheduleFn;29732974 return super.executeExtrinsic(2975 sender,2976 extrinsic,2977 schedArgs,2978 expectSuccess,2979 );2980 }2981 };2982}298329842985function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2986 return class extends Base {2987 constructor(...args: any[]) {2988 super(...args);2989 }29902991 executeExtrinsic (2992 sender: IKeyringPair,2993 extrinsic: string,2994 params: any[],2995 expectSuccess?: boolean,2996 ): Promise<ITransactionResult> {2997 const call = this.constructApiCall(extrinsic, params);2998 return super.executeExtrinsic(2999 sender,3000 'api.tx.sudo.sudo',3001 [call],3002 expectSuccess,3003 );3004 }3005 };3006}30073008export class UniqueBaseCollection {3009 helper: UniqueHelper;3010 collectionId: number;30113012 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3013 this.collectionId = collectionId;3014 this.helper = uniqueHelper;3015 }30163017 async getData() {3018 return await this.helper.collection.getData(this.collectionId);3019 }30203021 async getLastTokenId() {3022 return await this.helper.collection.getLastTokenId(this.collectionId);3023 }30243025 async doesTokenExist(tokenId: number) {3026 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3027 }30283029 async getAdmins() {3030 return await this.helper.collection.getAdmins(this.collectionId);3031 }30323033 async getAllowList() {3034 return await this.helper.collection.getAllowList(this.collectionId);3035 }30363037 async getEffectiveLimits() {3038 return await this.helper.collection.getEffectiveLimits(this.collectionId);3039 }30403041 async getProperties(propertyKeys?: string[] | null) {3042 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3043 }30443045 async getPropertiesConsumedSpace() {3046 return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3047 }30483049 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3050 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3051 }30523053 async getOptions() {3054 return await this.helper.collection.getCollectionOptions(this.collectionId);3055 }30563057 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3058 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3059 }30603061 async confirmSponsorship(signer: TSigner) {3062 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3063 }30643065 async removeSponsor(signer: TSigner) {3066 return await this.helper.collection.removeSponsor(signer, this.collectionId);3067 }30683069 async setLimits(signer: TSigner, limits: ICollectionLimits) {3070 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3071 }30723073 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3074 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3075 }30763077 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3078 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3079 }30803081 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3082 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3083 }30843085 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3086 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3087 }30883089 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3090 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3091 }30923093 async setProperties(signer: TSigner, properties: IProperty[]) {3094 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3095 }30963097 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3098 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3099 }31003101 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3102 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3103 }31043105 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3106 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3107 }31083109 async disableNesting(signer: TSigner) {3110 return await this.helper.collection.disableNesting(signer, this.collectionId);3111 }31123113 async burn(signer: TSigner) {3114 return await this.helper.collection.burn(signer, this.collectionId);3115 }31163117 scheduleAt<T extends UniqueHelper>(3118 executionBlockNumber: number,3119 options: ISchedulerOptions = {},3120 ) {3121 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3122 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3123 }31243125 scheduleAfter<T extends UniqueHelper>(3126 blocksBeforeExecution: number,3127 options: ISchedulerOptions = {},3128 ) {3129 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3130 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3131 }31323133 getSudo<T extends UniqueHelper>() {3134 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3135 }3136}313731383139export class UniqueNFTCollection extends UniqueBaseCollection {3140 getTokenObject(tokenId: number) {3141 return new UniqueNFToken(tokenId, this);3142 }31433144 async getTokensByAddress(addressObj: ICrossAccountId) {3145 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3146 }31473148 async getToken(tokenId: number, blockHashAt?: string) {3149 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3150 }31513152 async getTokenOwner(tokenId: number, blockHashAt?: string) {3153 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3154 }31553156 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3157 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3158 }31593160 async getTokenChildren(tokenId: number, blockHashAt?: string) {3161 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3162 }31633164 async getPropertyPermissions(propertyKeys: string[] | null = null) {3165 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3166 }31673168 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3169 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3170 }31713172 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3173 const api = this.helper.getApi();3174 const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();3175 3176 return (props! as any).consumedSpace;3177 }31783179 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3180 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3181 }31823183 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3184 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3185 }31863187 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3188 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3189 }31903191 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3192 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3193 }31943195 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3196 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3197 }31983199 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3200 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3201 }32023203 async burnToken(signer: TSigner, tokenId: number) {3204 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3205 }32063207 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3208 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3209 }32103211 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3212 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3213 }32143215 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3216 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3217 }32183219 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3220 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3221 }32223223 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3224 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3225 }32263227 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3228 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3229 }32303231 scheduleAt<T extends UniqueHelper>(3232 executionBlockNumber: number,3233 options: ISchedulerOptions = {},3234 ) {3235 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3236 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3237 }32383239 scheduleAfter<T extends UniqueHelper>(3240 blocksBeforeExecution: number,3241 options: ISchedulerOptions = {},3242 ) {3243 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3244 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3245 }32463247 getSudo<T extends UniqueHelper>() {3248 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3249 }3250}325132523253export class UniqueRFTCollection extends UniqueBaseCollection {3254 getTokenObject(tokenId: number) {3255 return new UniqueRFToken(tokenId, this);3256 }32573258 async getToken(tokenId: number, blockHashAt?: string) {3259 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3260 }32613262 async getTokensByAddress(addressObj: ICrossAccountId) {3263 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3264 }32653266 async getTop10TokenOwners(tokenId: number) {3267 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3268 }32693270 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3271 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3272 }32733274 async getTokenTotalPieces(tokenId: number) {3275 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3276 }32773278 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3279 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3280 }32813282 async getPropertyPermissions(propertyKeys: string[] | null = null) {3283 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3284 }32853286 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3287 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3288 }32893290 async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3291 const api = this.helper.getApi();3292 const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();3293 3294 return (props! as any).consumedSpace;3295 }32963297 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3298 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3299 }33003301 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3302 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3303 }33043305 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3306 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3307 }33083309 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3310 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3311 }33123313 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3314 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3315 }33163317 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3318 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3319 }33203321 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3322 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3323 }33243325 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3326 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3327 }33283329 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3330 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3331 }33323333 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3334 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3335 }33363337 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3338 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3339 }33403341 scheduleAt<T extends UniqueHelper>(3342 executionBlockNumber: number,3343 options: ISchedulerOptions = {},3344 ) {3345 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3346 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3347 }33483349 scheduleAfter<T extends UniqueHelper>(3350 blocksBeforeExecution: number,3351 options: ISchedulerOptions = {},3352 ) {3353 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3354 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3355 }33563357 getSudo<T extends UniqueHelper>() {3358 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3359 }3360}336133623363export class UniqueFTCollection extends UniqueBaseCollection {3364 async getBalance(addressObj: ICrossAccountId) {3365 return await this.helper.ft.getBalance(this.collectionId, addressObj);3366 }33673368 async getTotalPieces() {3369 return await this.helper.ft.getTotalPieces(this.collectionId);3370 }33713372 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3373 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3374 }33753376 async getTop10Owners() {3377 return await this.helper.ft.getTop10Owners(this.collectionId);3378 }33793380 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3381 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3382 }33833384 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3385 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3386 }33873388 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3389 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3390 }33913392 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3393 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3394 }33953396 async burnTokens(signer: TSigner, amount=1n) {3397 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3398 }33993400 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3401 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3402 }34033404 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3405 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3406 }34073408 scheduleAt<T extends UniqueHelper>(3409 executionBlockNumber: number,3410 options: ISchedulerOptions = {},3411 ) {3412 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3413 return new UniqueFTCollection(this.collectionId, scheduledHelper);3414 }34153416 scheduleAfter<T extends UniqueHelper>(3417 blocksBeforeExecution: number,3418 options: ISchedulerOptions = {},3419 ) {3420 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3421 return new UniqueFTCollection(this.collectionId, scheduledHelper);3422 }34233424 getSudo<T extends UniqueHelper>() {3425 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3426 }3427}342834293430export class UniqueBaseToken {3431 collection: UniqueNFTCollection | UniqueRFTCollection;3432 collectionId: number;3433 tokenId: number;34343435 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3436 this.collection = collection;3437 this.collectionId = collection.collectionId;3438 this.tokenId = tokenId;3439 }34403441 async getNextSponsored(addressObj: ICrossAccountId) {3442 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3443 }34443445 async getProperties(propertyKeys?: string[] | null) {3446 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3447 }34483449 async getTokenPropertiesConsumedSpace() {3450 return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3451 }34523453 async setProperties(signer: TSigner, properties: IProperty[]) {3454 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3455 }34563457 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3458 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3459 }34603461 async doesExist() {3462 return await this.collection.doesTokenExist(this.tokenId);3463 }34643465 nestingAccount() {3466 return this.collection.helper.util.getTokenAccount(this);3467 }34683469 scheduleAt<T extends UniqueHelper>(3470 executionBlockNumber: number,3471 options: ISchedulerOptions = {},3472 ) {3473 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3474 return new UniqueBaseToken(this.tokenId, scheduledCollection);3475 }34763477 scheduleAfter<T extends UniqueHelper>(3478 blocksBeforeExecution: number,3479 options: ISchedulerOptions = {},3480 ) {3481 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3482 return new UniqueBaseToken(this.tokenId, scheduledCollection);3483 }34843485 getSudo<T extends UniqueHelper>() {3486 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3487 }3488}348934903491export class UniqueNFToken extends UniqueBaseToken {3492 collection: UniqueNFTCollection;34933494 constructor(tokenId: number, collection: UniqueNFTCollection) {3495 super(tokenId, collection);3496 this.collection = collection;3497 }34983499 async getData(blockHashAt?: string) {3500 return await this.collection.getToken(this.tokenId, blockHashAt);3501 }35023503 async getOwner(blockHashAt?: string) {3504 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3505 }35063507 async getTopmostOwner(blockHashAt?: string) {3508 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3509 }35103511 async getChildren(blockHashAt?: string) {3512 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3513 }35143515 async nest(signer: TSigner, toTokenObj: IToken) {3516 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3517 }35183519 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3520 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3521 }35223523 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3524 return await this.collection.transferToken(signer, this.tokenId, addressObj);3525 }35263527 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3528 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3529 }35303531 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3532 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3533 }35343535 async isApproved(toAddressObj: ICrossAccountId) {3536 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3537 }35383539 async burn(signer: TSigner) {3540 return await this.collection.burnToken(signer, this.tokenId);3541 }35423543 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3544 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3545 }35463547 scheduleAt<T extends UniqueHelper>(3548 executionBlockNumber: number,3549 options: ISchedulerOptions = {},3550 ) {3551 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3552 return new UniqueNFToken(this.tokenId, scheduledCollection);3553 }35543555 scheduleAfter<T extends UniqueHelper>(3556 blocksBeforeExecution: number,3557 options: ISchedulerOptions = {},3558 ) {3559 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3560 return new UniqueNFToken(this.tokenId, scheduledCollection);3561 }35623563 getSudo<T extends UniqueHelper>() {3564 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3565 }3566}35673568export class UniqueRFToken extends UniqueBaseToken {3569 collection: UniqueRFTCollection;35703571 constructor(tokenId: number, collection: UniqueRFTCollection) {3572 super(tokenId, collection);3573 this.collection = collection;3574 }35753576 async getData(blockHashAt?: string) {3577 return await this.collection.getToken(this.tokenId, blockHashAt);3578 }35793580 async getTop10Owners() {3581 return await this.collection.getTop10TokenOwners(this.tokenId);3582 }35833584 async getBalance(addressObj: ICrossAccountId) {3585 return await this.collection.getTokenBalance(this.tokenId, addressObj);3586 }35873588 async getTotalPieces() {3589 return await this.collection.getTokenTotalPieces(this.tokenId);3590 }35913592 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3593 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3594 }35953596 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3597 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3598 }35993600 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3601 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3602 }36033604 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3605 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3606 }36073608 async repartition(signer: TSigner, amount: bigint) {3609 return await this.collection.repartitionToken(signer, this.tokenId, amount);3610 }36113612 async burn(signer: TSigner, amount=1n) {3613 return await this.collection.burnToken(signer, this.tokenId, amount);3614 }36153616 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3617 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3618 }36193620 scheduleAt<T extends UniqueHelper>(3621 executionBlockNumber: number,3622 options: ISchedulerOptions = {},3623 ) {3624 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3625 return new UniqueRFToken(this.tokenId, scheduledCollection);3626 }36273628 scheduleAfter<T extends UniqueHelper>(3629 blocksBeforeExecution: number,3630 options: ISchedulerOptions = {},3631 ) {3632 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3633 return new UniqueRFToken(this.tokenId, scheduledCollection);3634 }36353636 getSudo<T extends UniqueHelper>() {3637 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3638 }3639}