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';4647export class CrossAccountId implements ICrossAccountId {48 Substrate?: TSubstrateAccount;49 Ethereum?: TEthereumAccount;5051 constructor(account: ICrossAccountId) {52 if (account.Substrate) this.Substrate = account.Substrate;53 if (account.Ethereum) this.Ethereum = account.Ethereum;54 }5556 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {57 switch (domain) {58 case 'Substrate': return new CrossAccountId({Substrate: account.address});59 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();60 }61 }6263 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {64 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});65 }6667 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {68 return encodeAddress(decodeAddress(address), ss58Format);69 }7071 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {72 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});73 }7475 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {76 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);77 return this;78 }7980 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {81 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));82 }8384 toEthereum(): CrossAccountId {85 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});86 return this;87 }8889 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {90 return evmToAddress(address, ss58Format);91 }9293 toSubstrate(ss58Format?: number): CrossAccountId {94 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});95 return this;96 }9798 toLowerCase(): CrossAccountId {99 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();100 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();101 return this;102 }103}104105const nesting = {106 toChecksumAddress(address: string): string {107 if (typeof address === 'undefined') return '';108109 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);110111 address = address.toLowerCase().replace(/^0x/i,'');112 const addressHash = keccakAsHex(address).replace(/^0x/i,'');113 const checksumAddress = ['0x'];114115 for (let i = 0; i < address.length; i++) {116 117 if (parseInt(addressHash[i], 16) > 7) {118 checksumAddress.push(address[i].toUpperCase());119 } else {120 checksumAddress.push(address[i]);121 }122 }123 return checksumAddress.join('');124 },125 tokenIdToAddress(collectionId: number, tokenId: number) {126 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);127 },128};129130class UniqueUtil {131 static transactionStatus = {132 NOT_READY: 'NotReady',133 FAIL: 'Fail',134 SUCCESS: 'Success',135 };136137 static chainLogType = {138 EXTRINSIC: 'extrinsic',139 RPC: 'rpc',140 };141142 static getTokenAccount(token: IToken): CrossAccountId {143 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});144 }145146 static getTokenAddress(token: IToken): string {147 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);148 }149150 static getDefaultLogger(): ILogger {151 return {152 log(msg: any, level = 'INFO') {153 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));154 },155 level: {156 ERROR: 'ERROR',157 WARNING: 'WARNING',158 INFO: 'INFO',159 },160 };161 }162163 static vec2str(arr: string[] | number[]) {164 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');165 }166167 static str2vec(string: string) {168 if (typeof string !== 'string') return string;169 return Array.from(string).map(x => x.charCodeAt(0));170 }171172 static fromSeed(seed: string, ss58Format = 42) {173 const keyring = new Keyring({type: 'sr25519', ss58Format});174 return keyring.addFromUri(seed);175 }176177 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {178 if (creationResult.status !== this.transactionStatus.SUCCESS) {179 throw Error('Unable to create collection!');180 }181182 let collectionId = null;183 creationResult.result.events.forEach(({event: {data, method, section}}) => {184 if ((section === 'common') && (method === 'CollectionCreated')) {185 collectionId = parseInt(data[0].toString(), 10);186 }187 });188189 if (collectionId === null) {190 throw Error('No CollectionCreated event was found!');191 }192193 return collectionId;194 }195196 static extractTokensFromCreationResult(creationResult: ITransactionResult): {197 success: boolean,198 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],199 } {200 if (creationResult.status !== this.transactionStatus.SUCCESS) {201 throw Error('Unable to create tokens!');202 }203 let success = false;204 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];205 creationResult.result.events.forEach(({event: {data, method, section}}) => {206 if (method === 'ExtrinsicSuccess') {207 success = true;208 } else if ((section === 'common') && (method === 'ItemCreated')) {209 tokens.push({210 collectionId: parseInt(data[0].toString(), 10),211 tokenId: parseInt(data[1].toString(), 10),212 owner: data[2].toHuman(),213 amount: data[3].toBigInt(),214 });215 }216 });217 return {success, tokens};218 }219220 static extractTokensFromBurnResult(burnResult: ITransactionResult): {221 success: boolean,222 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],223 } {224 if (burnResult.status !== this.transactionStatus.SUCCESS) {225 throw Error('Unable to burn tokens!');226 }227 let success = false;228 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];229 burnResult.result.events.forEach(({event: {data, method, section}}) => {230 if (method === 'ExtrinsicSuccess') {231 success = true;232 } else if ((section === 'common') && (method === 'ItemDestroyed')) {233 tokens.push({234 collectionId: parseInt(data[0].toString(), 10),235 tokenId: parseInt(data[1].toString(), 10),236 owner: data[2].toHuman(),237 amount: data[3].toBigInt(),238 });239 }240 });241 return {success, tokens};242 }243244 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {245 let eventId = null;246 events.forEach(({event: {data, method, section}}) => {247 if ((section === expectedSection) && (method === expectedMethod)) {248 eventId = parseInt(data[0].toString(), 10);249 }250 });251252 if (eventId === null) {253 throw Error(`No ${expectedMethod} event was found!`);254 }255 return eventId === collectionId;256 }257258 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {259 const normalizeAddress = (address: string | ICrossAccountId) => {260 if(typeof address === 'string') return address;261 const obj = {} as any;262 Object.keys(address).forEach(k => {263 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];264 });265 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);266 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();267 return address;268 };269 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;270 events.forEach(({event: {data, method, section}}) => {271 if ((section === 'common') && (method === 'Transfer')) {272 const hData = (data as any).toJSON();273 transfer = {274 collectionId: hData[0],275 tokenId: hData[1],276 from: normalizeAddress(hData[2]),277 to: normalizeAddress(hData[3]),278 amount: BigInt(hData[4]),279 };280 }281 });282 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);284 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);285 isSuccess = isSuccess && amount === transfer.amount;286 return isSuccess;287 }288289 static bigIntToDecimals(number: bigint, decimals = 18) {290 const numberStr = number.toString();291 const dotPos = numberStr.length - decimals;292293 if (dotPos <= 0) {294 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;295 } else {296 const intPart = numberStr.substring(0, dotPos);297 const fractPart = numberStr.substring(dotPos);298 return intPart + '.' + fractPart;299 }300 }301}302303class UniqueEventHelper {304 private static extractIndex(index: any): [number, number] | string {305 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];306 return index.toJSON();307 }308309 private static extractSub(data: any, subTypes: any): {[key: string]: any} {310 let obj: any = {};311 let index = 0;312313 if (data.entries) {314 for(const [key, value] of data.entries()) {315 obj[key] = this.extractData(value, subTypes[index]);316 index++;317 }318 } else obj = data.toJSON();319320 return obj;321 }322323 private static extractData(data: any, type: any): any {324 if(!type) return data.toHuman();325 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();326 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();327 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);328 return data.toHuman();329 }330331 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {332 const parsedEvents: IEvent[] = [];333334 events.forEach((record) => {335 const {event, phase} = record;336 const types = event.typeDef;337338 const eventData: IEvent = {339 section: event.section.toString(),340 method: event.method.toString(),341 index: this.extractIndex(event.index),342 data: [],343 phase: phase.toJSON(),344 };345346 event.data.forEach((val: any, index: number) => {347 eventData.data.push(this.extractData(val, types[index]));348 });349350 parsedEvents.push(eventData);351 });352353 return parsedEvents;354 }355}356357export class ChainHelperBase {358 helperBase: any;359360 transactionStatus = UniqueUtil.transactionStatus;361 chainLogType = UniqueUtil.chainLogType;362 util: typeof UniqueUtil;363 eventHelper: typeof UniqueEventHelper;364 logger: ILogger;365 api: ApiPromise | null;366 forcedNetwork: TNetworks | null;367 network: TNetworks | null;368 chainLog: IUniqueHelperLog[];369 children: ChainHelperBase[];370 address: AddressGroup;371 chain: ChainGroup;372373 constructor(logger?: ILogger, helperBase?: any) {374 this.helperBase = helperBase;375376 this.util = UniqueUtil;377 this.eventHelper = UniqueEventHelper;378 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();379 this.logger = logger;380 this.api = null;381 this.forcedNetwork = null;382 this.network = null;383 this.chainLog = [];384 this.children = [];385 this.address = new AddressGroup(this);386 this.chain = new ChainGroup(this);387 }388389 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {390 Object.setPrototypeOf(helperCls.prototype, this);391 const newHelper = new helperCls(this.logger, options);392393 newHelper.api = this.api;394 newHelper.network = this.network;395 newHelper.forceNetwork = this.forceNetwork;396397 this.children.push(newHelper);398399 return newHelper;400 }401402 getApi(): ApiPromise {403 if(this.api === null) throw Error('API not initialized');404 return this.api;405 }406407 clearChainLog(): void {408 this.chainLog = [];409 }410411 forceNetwork(value: TNetworks): void {412 this.forcedNetwork = value;413 }414415 async connect(wsEndpoint: string, listeners?: IApiListeners) {416 if (this.api !== null) throw Error('Already connected');417 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);418 this.api = api;419 this.network = network;420 }421422 async disconnect() {423 for (const child of this.children) {424 child.clearApi();425 }426427 if (this.api === null) return;428 await this.api.disconnect();429 this.clearApi();430 }431432 clearApi() {433 this.api = null;434 this.network = null;435 }436437 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {438 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;439 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];440441 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;442443 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;444 return 'opal';445 }446447 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {448 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});449 await api.isReady;450451 const network = await this.detectNetwork(api);452453 await api.disconnect();454455 return network;456 }457458 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{459 api: ApiPromise;460 network: TNetworks;461 }> {462 if(typeof network === 'undefined' || network === null) network = 'opal';463 const supportedRPC = {464 opal: {465 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,466 },467 quartz: {468 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,469 },470 unique: {471 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,472 },473 rococo: {},474 westend: {},475 moonbeam: {},476 moonriver: {},477 acala: {},478 karura: {},479 westmint: {},480 };481 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);482 const rpc = supportedRPC[network];483484 485 486487 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});488489 await api.isReadyOrError;490491 if (typeof listeners === 'undefined') listeners = {};492 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {493 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;494 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);495 }496497 return {api, network};498 }499500 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {501 const {events, status} = data;502 if (status.isReady) {503 return this.transactionStatus.NOT_READY;504 }505 if (status.isBroadcast) {506 return this.transactionStatus.NOT_READY;507 }508 if (status.isInBlock || status.isFinalized) {509 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');510 if (errors.length > 0) {511 return this.transactionStatus.FAIL;512 }513 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {514 return this.transactionStatus.SUCCESS;515 }516 }517518 return this.transactionStatus.FAIL;519 }520521 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {522 const sign = (callback: any) => {523 if(options !== null) return transaction.signAndSend(sender, options, callback);524 return transaction.signAndSend(sender, callback);525 };526 527 return new Promise(async (resolve, reject) => {528 try {529 const unsub = await sign((result: any) => {530 const status = this.getTransactionStatus(result);531532 if (status === this.transactionStatus.SUCCESS) {533 this.logger.log(`${label} successful`);534 unsub();535 resolve({result, status});536 } else if (status === this.transactionStatus.FAIL) {537 let moduleError = null;538539 if (result.hasOwnProperty('dispatchError')) {540 const dispatchError = result['dispatchError'];541542 if (dispatchError) {543 if (dispatchError.isModule) {544 const modErr = dispatchError.asModule;545 const errorMeta = dispatchError.registry.findMetaError(modErr);546547 moduleError = `${errorMeta.section}.${errorMeta.name}`;548 } else {549 moduleError = dispatchError.toHuman();550 }551 } else {552 this.logger.log(result, this.logger.level.ERROR);553 }554 }555556 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);557 unsub();558 reject({status, moduleError, result});559 }560 });561 } catch (e) {562 this.logger.log(e, this.logger.level.ERROR);563 reject(e);564 }565 });566 }567568 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {569 const api = this.getApi();570 const signingInfo = await api.derive.tx.signingInfo(signer.address);571572 573 574 tx.sign(signer, {575 blockHash: api.genesisHash,576 genesisHash: api.genesisHash,577 runtimeVersion: api.runtimeVersion,578 nonce: signingInfo.nonce,579 });580581 if (len === null) {582 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;583 } else {584 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;585 }586 }587588 constructApiCall(apiCall: string, params: any[]) {589 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);590 let call = this.getApi() as any;591 for(const part of apiCall.slice(4).split('.')) {592 call = call[part];593 }594 return call(...params);595 }596597 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {598 if(this.api === null) throw Error('API not initialized');599 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);600601 const startTime = (new Date()).getTime();602 let result: ITransactionResult;603 let events: IEvent[] = [];604 try {605 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;606 events = this.eventHelper.extractEvents(result.result.events);607 }608 catch(e) {609 if(!(e as object).hasOwnProperty('status')) throw e;610 result = e as ITransactionResult;611 }612613 const endTime = (new Date()).getTime();614615 const log = {616 executedAt: endTime,617 executionTime: endTime - startTime,618 type: this.chainLogType.EXTRINSIC,619 status: result.status,620 call: extrinsic,621 signer: this.getSignerAddress(sender),622 params,623 } as IUniqueHelperLog;624625 if(result.status !== this.transactionStatus.SUCCESS) {626 if (result.moduleError) log.moduleError = result.moduleError;627 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;628 }629 if(events.length > 0) log.events = events;630631 this.chainLog.push(log);632633 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {634 if (result.moduleError) throw Error(`${result.moduleError}`);635 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));636 }637 return result;638 }639640 async callRpc(rpc: string, params?: any[]) {641 if(typeof params === 'undefined') params = [];642 if(this.api === null) throw Error('API not initialized');643 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);644645 const startTime = (new Date()).getTime();646 let result;647 let error = null;648 const log = {649 type: this.chainLogType.RPC,650 call: rpc,651 params,652 } as IUniqueHelperLog;653654 try {655 result = await this.constructApiCall(rpc, params);656 }657 catch(e) {658 error = e;659 }660661 const endTime = (new Date()).getTime();662663 log.executedAt = endTime;664 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';665 log.executionTime = endTime - startTime;666667 this.chainLog.push(log);668669 if(error !== null) throw error;670671 return result;672 }673674 getSignerAddress(signer: IKeyringPair | string): string {675 if(typeof signer === 'string') return signer;676 return signer.address;677 }678679 fetchAllPalletNames(): string[] {680 if(this.api === null) throw Error('API not initialized');681 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());682 }683684 fetchMissingPalletNames(requiredPallets: string[]): string[] {685 const palletNames = this.fetchAllPalletNames();686 return requiredPallets.filter(p => !palletNames.includes(p));687 }688}689690691class HelperGroup<T extends ChainHelperBase> {692 helper: T;693694 constructor(uniqueHelper: T) {695 this.helper = uniqueHelper;696 }697}698699700class CollectionGroup extends HelperGroup<UniqueHelper> {701 702703704705706707708709710 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {711 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();712 }713714 715716717718719 async getTotalCount(): Promise<number> {720 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();721 }722723 724725726727728729730731732 async getData(collectionId: number): Promise<{733 id: number;734 name: string;735 description: string;736 tokensCount: number;737 admins: CrossAccountId[];738 normalizedOwner: TSubstrateAccount;739 raw: any740 } | null> {741 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);742 const humanCollection = collection.toHuman(), collectionData = {743 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],744 raw: humanCollection,745 } as any, jsonCollection = collection.toJSON();746 if (humanCollection === null) return null;747 collectionData.raw.limits = jsonCollection.limits;748 collectionData.raw.permissions = jsonCollection.permissions;749 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);750 for (const key of ['name', 'description']) {751 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);752 }753754 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))755 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)756 : 0;757 collectionData.admins = await this.getAdmins(collectionId);758759 return collectionData;760 }761762 763764765766767768769770 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {771 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();772773 return normalize774 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())775 : admins;776 }777778 779780781782783784785 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {786 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();787 return normalize788 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())789 : allowListed;790 }791792 793794795796797798799 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {800 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();801 }802803 804805806807808809810811 async burn(signer: TSigner, collectionId: number): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.destroyCollection', [collectionId],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');819 }820821 822823824825826827828829830 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');838 }839840 841842843844845846847848 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.confirmSponsorship', [collectionId],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');856 }857858 859860861862863864865866 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.removeCollectionSponsor', [collectionId],870 true,871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');874 }875876 877878879880881882883884885886887888889890891892893 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {894 const result = await this.helper.executeExtrinsic(895 signer,896 'api.tx.unique.setCollectionLimits', [collectionId, limits],897 true,898 );899900 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');901 }902903 904905906907908909910911912 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {913 const result = await this.helper.executeExtrinsic(914 signer,915 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],916 true,917 );918919 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');920 }921922 923924925926927928929930931 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {932 const result = await this.helper.executeExtrinsic(933 signer,934 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],935 true,936 );937938 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');939 }940941 942943944945946947948949950 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');958 }959960 961962963964965966967968 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {969 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();970 }971972 973974975976977978979 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {980 const result = await this.helper.executeExtrinsic(981 signer,982 'api.tx.unique.addToAllowList', [collectionId, addressObj],983 true,984 );985986 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');987 }988989 990991992993994995996997 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');1005 }10061007 100810091010101110121013101410151016 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1017 const result = await this.helper.executeExtrinsic(1018 signer,1019 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1020 true,1021 );10221023 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1024 }10251026 102710281029103010311032103310341035 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1036 return await this.setPermissions(signer, collectionId, {nesting: permissions});1037 }10381039 10401041104210431044104510461047 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1048 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1049 }10501051 105210531054105510561057105810591060 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1061 const result = await this.helper.executeExtrinsic(1062 signer,1063 'api.tx.unique.setCollectionProperties', [collectionId, properties],1064 true,1065 );10661067 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1068 }10691070 10711072107310741075107610771078 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1079 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1080 }10811082 async getCollectionOptions(collectionId: number) {1083 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1084 }10851086 108710881089109010911092109310941095 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1099 true,1100 );11011102 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1103 }11041105 11061107110811091110111111121113111411151116 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1117 const result = await this.helper.executeExtrinsic(1118 signer,1119 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1120 true, 1121 );11221123 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1124 }11251126 1127112811291130113111321133113411351136113711381139 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1140 const result = await this.helper.executeExtrinsic(1141 signer,1142 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1143 true, 1144 );1145 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1146 }11471148 11491150115111521153115411551156115711581159 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1160 const burnResult = await this.helper.executeExtrinsic(1161 signer,1162 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1163 true, 1164 );1165 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1166 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1167 return burnedTokens.success;1168 }11691170 11711172117311741175117611771178117911801181 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const burnResult = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1185 true, 1186 );1187 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1188 return burnedTokens.success && burnedTokens.tokens.length > 0;1189 }11901191 1192119311941195119611971198119912001201 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1202 const approveResult = await this.helper.executeExtrinsic(1203 signer,1204 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1205 true, 1206 );12071208 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1209 }12101211 1212121312141215121612171218121912201221 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1222 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1223 }12241225 1226122712281229123012311232 async getLastTokenId(collectionId: number): Promise<number> {1233 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1234 }12351236 12371238123912401241124212431244 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1245 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1246 }1247}12481249class NFTnRFT extends CollectionGroup {1250 12511252125312541255125612571258 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1259 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1260 }12611262 1263126412651266126712681269127012711272 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1273 properties: IProperty[];1274 owner: CrossAccountId;1275 normalizedOwner: CrossAccountId;1276 }| null> {1277 let tokenData;1278 if(typeof blockHashAt === 'undefined') {1279 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1280 }1281 else {1282 if(propertyKeys.length == 0) {1283 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1284 if(!collection) return null;1285 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1286 }1287 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1288 }1289 tokenData = tokenData.toHuman();1290 if (tokenData === null || tokenData.owner === null) return null;1291 const owner = {} as any;1292 for (const key of Object.keys(tokenData.owner)) {1293 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1294 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1295 : tokenData.owner[key];1296 }1297 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1298 return tokenData;1299 }13001301 13021303130413051306130713081309131013111312 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1320 }13211322 13231324132513261327132813291330 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1331 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1332 }13331334 1335133613371338133913401341134213431344 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1352 }13531354 135513561357135813591360136113621363 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1364 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1365 }13661367 136813691370137113721373137413751376 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1377 const result = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1380 true,1381 );13821383 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1384 }13851386 138713881389139013911392139313941395 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1396 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1397 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1398 for (const key of ['name', 'description', 'tokenPrefix']) {1399 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);1400 }1401 const creationResult = await this.helper.executeExtrinsic(1402 signer,1403 'api.tx.unique.createCollectionEx', [collectionOptions],1404 true, 1405 );1406 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1407 }14081409 getCollectionObject(_collectionId: number): any {1410 return null;1411 }14121413 getTokenObject(_collectionId: number, _tokenId: number): any {1414 return null;1415 }1416}141714181419class NFTGroup extends NFTnRFT {1420 142114221423142414251426 getCollectionObject(collectionId: number): UniqueNFTCollection {1427 return new UniqueNFTCollection(collectionId, this.helper);1428 }14291430 1431143214331434143514361437 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1438 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1439 }14401441 14421443144414451446144714481449 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1450 let owner;1451 if (typeof blockHashAt === 'undefined') {1452 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1453 } else {1454 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1455 }1456 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1457 }14581459 1460146114621463146414651466 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1467 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1468 }14691470 1471147214731474147514761477147814791480 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1481 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1482 }14831484 148514861487148814891490149114921493149414951496 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1497 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1498 }14991500 15011502150315041505150615071508 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1509 let owner;1510 if (typeof blockHashAt === 'undefined') {1511 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1512 } else {1513 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1514 }15151516 if (owner === null) return null;15171518 return owner.toHuman();1519 }15201521 15221523152415251526152715281529 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1530 let children;1531 if(typeof blockHashAt === 'undefined') {1532 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1533 } else {1534 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1535 }15361537 return children.toJSON().map((x: any) => {1538 return {collectionId: x.collection, tokenId: x.token};1539 });1540 }15411542 15431544154515461547154815491550 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1551 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1552 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1553 if(!result) {1554 throw Error('Unable to nest token!');1555 }1556 return result;1557 }15581559 156015611562156315641565156615671568 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1569 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1570 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1571 if(!result) {1572 throw Error('Unable to unnest token!');1573 }1574 return result;1575 }15761577 157815791580158115821583158415851586158715881589 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1590 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1591 }15921593 159415951596159715981599 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1603 nft: {1604 properties: data.properties,1605 },1606 }],1607 true,1608 );1609 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1610 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1611 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1612 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1613 }16141615 161616171618161916201621162216231624162516261627162816291630 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1634 true,1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1638 }16391640 164116421643164416451646164716481649165016511652165316541655165616571658 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1659 const rawTokens = [];1660 for (const token of tokens) {1661 const raw = {NFT: {properties: token.properties}};1662 rawTokens.push(raw);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1667 true,1668 );1669 const collection = this.getCollectionObject(collectionId);1670 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1671 }16721673 1674167516761677167816791680168116821683 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1684 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1685 }1686}168716881689class RFTGroup extends NFTnRFT {1690 169116921693169416951696 getCollectionObject(collectionId: number): UniqueRFTCollection {1697 return new UniqueRFTCollection(collectionId, this.helper);1698 }16991700 1701170217031704170517061707 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1708 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1709 }17101711 1712171317141715171617171718 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1719 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1720 }17211722 17231724172517261727172817291730 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1731 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1732 }17331734 1735173617371738173917401741174217431744 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1745 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1746 }17471748 17491750175117521753175417551756175717581759 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1761 }17621763 176417651766176717681769177017711772177317741775 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1776 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1777 }17781779 1780178117821783178417851786 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1787 const creationResult = await this.helper.executeExtrinsic(1788 signer,1789 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790 refungible: {1791 pieces: data.pieces,1792 properties: data.properties,1793 },1794 }],1795 true,1796 );1797 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1798 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1799 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1800 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1801 }18021803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1804 throw Error('Not implemented');1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1808 true, 1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 181518161817181818191820182118221823 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1824 const rawTokens = [];1825 for (const token of tokens) {1826 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1827 rawTokens.push(raw);1828 }1829 const creationResult = await this.helper.executeExtrinsic(1830 signer,1831 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1832 true,1833 );1834 const collection = this.getCollectionObject(collectionId);1835 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1836 }18371838 183918401841184218431844184518461847 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1848 return await super.burnToken(signer, collectionId, tokenId, amount);1849 }18501851 1852185318541855185618571858185918601861 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1862 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1863 }18641865 18661867186818691870187118721873187418751876 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1877 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1878 }18791880 1881188218831884188518861887 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1888 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1889 }18901891 189218931894189518961897189818991900 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1901 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1902 const repartitionResult = await this.helper.executeExtrinsic(1903 signer,1904 'api.tx.unique.repartition', [collectionId, tokenId, amount],1905 true,1906 );1907 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1908 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1909 }1910}191119121913class FTGroup extends CollectionGroup {1914 191519161917191819191920 getCollectionObject(collectionId: number): UniqueFTCollection {1921 return new UniqueFTCollection(collectionId, this.helper);1922 }19231924 1925192619271928192919301931193219331934193519361937 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1938 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1939 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1940 collectionOptions.mode = {fungible: decimalPoints};1941 for (const key of ['name', 'description', 'tokenPrefix']) {1942 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);1943 }1944 const creationResult = await this.helper.executeExtrinsic(1945 signer,1946 'api.tx.unique.createCollectionEx', [collectionOptions],1947 true,1948 );1949 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1950 }19511952 195319541955195619571958195919601961 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1962 const creationResult = await this.helper.executeExtrinsic(1963 signer,1964 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1965 fungible: {1966 value: amount,1967 },1968 }],1969 true, 1970 );1971 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1972 }19731974 19751976197719781979198019811982 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1983 const rawTokens = [];1984 for (const token of tokens) {1985 const raw = {Fungible: {Value: token.value}};1986 rawTokens.push(raw);1987 }1988 const creationResult = await this.helper.executeExtrinsic(1989 signer,1990 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1991 true,1992 );1993 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1994 }19951996 199719981999200020012002 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2003 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2004 }20052006 2007200820092010201120122013 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2014 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2015 }20162017 201820192020202120222023202420252026 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2027 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2028 }20292030 2031203220332034203520362037203820392040 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2041 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2042 }20432044 20452046204720482049205020512052 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2053 return await super.burnToken(signer, collectionId, 0, amount);2054 }20552056 205720582059206020612062206320642065 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2066 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2067 }20682069 20702071207220732074 async getTotalPieces(collectionId: number): Promise<bigint> {2075 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2076 }20772078 2079208020812082208320842085208620872088 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2089 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2090 }20912092 2093209420952096209720982099 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2100 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2101 }2102}210321042105class ChainGroup extends HelperGroup<ChainHelperBase> {2106 21072108210921102111 getChainProperties(): IChainProperties {2112 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2113 return {2114 ss58Format: properties.ss58Format.toJSON(),2115 tokenDecimals: properties.tokenDecimals.toJSON(),2116 tokenSymbol: properties.tokenSymbol.toJSON(),2117 };2118 }21192120 21212122212321242125 async getLatestBlockNumber(): Promise<number> {2126 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2127 }21282129 213021312132213321342135 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2136 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2137 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2138 return blockHash;2139 }21402141 2142 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2143 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2144 if (!blockHash) return null;2145 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2146 }21472148 2149215021512152 async getRelayBlockNumber(): Promise<bigint> {2153 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2154 return BigInt(blockNumber);2155 }21562157 215821592160216121622163 async getNonce(address: TSubstrateAccount): Promise<number> {2164 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2165 }2166}21672168class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2169 217021712172217321742175 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2176 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2177 }21782179 21802181218221832184218521862187 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2188 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21892190 let transfer = {from: null, to: null, amount: 0n} as any;2191 result.result.events.forEach(({event: {data, method, section}}) => {2192 if ((section === 'balances') && (method === 'Transfer')) {2193 transfer = {2194 from: this.helper.address.normalizeSubstrate(data[0]),2195 to: this.helper.address.normalizeSubstrate(data[1]),2196 amount: BigInt(data[2]),2197 };2198 }2199 });2200 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2201 && this.helper.address.normalizeSubstrate(address) === transfer.to2202 && BigInt(amount) === transfer.amount;2203 return isSuccess;2204 }22052206 22072208220922102211 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2212 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2213 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2214 }22152216 async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2217 const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2218 return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2219 }2220}22212222class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2223 222422252226222722282229 async getEthereum(address: TEthereumAccount): Promise<bigint> {2230 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2231 }22322233 22342235223622372238223922402241 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2242 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22432244 let transfer = {from: null, to: null, amount: 0n} as any;2245 result.result.events.forEach(({event: {data, method, section}}) => {2246 if ((section === 'balances') && (method === 'Transfer')) {2247 transfer = {2248 from: data[0].toString(),2249 to: data[1].toString(),2250 amount: BigInt(data[2]),2251 };2252 }2253 });2254 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2255 && address === transfer.to2256 && BigInt(amount) === transfer.amount;2257 return isSuccess;2258 }2259}22602261class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2262 subBalanceGroup: SubstrateBalanceGroup<T>;2263 ethBalanceGroup: EthereumBalanceGroup<T>;22642265 constructor(helper: T) {2266 super(helper);2267 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2268 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2269 }22702271 getCollectionCreationPrice(): bigint {2272 return 2n * this.getOneTokenNominal();2273 }2274 22752276227722782279 getOneTokenNominal(): bigint {2280 const chainProperties = this.helper.chain.getChainProperties();2281 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2282 }22832284 228522862287228822892290 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2291 return this.subBalanceGroup.getSubstrate(address);2292 }22932294 22952296229722982299 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2300 return this.subBalanceGroup.getSubstrateFull(address);2301 }23022303 23042305230623072308 getLocked(address: TSubstrateAccount) {2309 return this.subBalanceGroup.getLocked(address);2310 }23112312 231323142315231623172318 getEthereum(address: TEthereumAccount): Promise<bigint> {2319 return this.ethBalanceGroup.getEthereum(address);2320 }23212322 23232324232523262327232823292330 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2331 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2332 }23332334 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2335 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23362337 let transfer = {from: null, to: null, amount: 0n} as any;2338 result.result.events.forEach(({event: {data, method, section}}) => {2339 if ((section === 'balances') && (method === 'Transfer')) {2340 transfer = {2341 from: this.helper.address.normalizeSubstrate(data[0]),2342 to: this.helper.address.normalizeSubstrate(data[1]),2343 amount: BigInt(data[2]),2344 };2345 }2346 });2347 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2348 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2349 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2350 return isSuccess;2351 }23522353 2354235523562357235823592360 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2361 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2362 const event = result.result.events2363 .find(e => e.event.section === 'vesting' &&2364 e.event.method === 'VestingScheduleAdded' &&2365 e.event.data[0].toHuman() === signer.address);2366 if (!event) throw Error('Cannot find transfer in events');2367 }23682369 23702371237223732374 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2375 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2376 return schedule.map((schedule: any) => {2377 return {2378 start: BigInt(schedule.start),2379 period: BigInt(schedule.period),2380 periodCount: BigInt(schedule.periodCount),2381 perPeriod: BigInt(schedule.perPeriod),2382 };2383 });2384 }23852386 2387238823892390 async claim(signer: TSigner) {2391 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2392 const event = result.result.events2393 .find(e => e.event.section === 'vesting' &&2394 e.event.method === 'Claimed' &&2395 e.event.data[0].toHuman() === signer.address);2396 if (!event) throw Error('Cannot find claim in events');2397 }2398}23992400class AddressGroup extends HelperGroup<ChainHelperBase> {2401 2402240324042405240624072408 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2409 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2410 }24112412 241324142415241624172418 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2419 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2420 }24212422 2423242424252426242724282429 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2430 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2431 }24322433 243424352436243724382439 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2440 return CrossAccountId.translateSubToEth(subAddress);2441 }24422443 244424452446244724482449 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2450 const u8a :Uint8Array = typeof key === 'string'2451 ? hexToU8a(key)2452 : typeof key === 'bigint'2453 ? hexToU8a(key.toString(16))2454 : key;2455 2456 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2457 throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2458 }2459 2460 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2461 if (!allowedDecodedLengths.includes(u8a.length)) {2462 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2463 }2464 2465 const u8aPrefix = ss58Format < 642466 ? new Uint8Array([ss58Format])2467 : new Uint8Array([2468 ((ss58Format & 0xfc) >> 2) | 0x40,2469 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2470 ]);24712472 const input = u8aConcat(u8aPrefix, u8a);2473 2474 return base58Encode(u8aConcat(2475 input,2476 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2477 ));2478 }24792480 24812482248324842485 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2486 if (this.helper.api === null) {2487 throw 'Not connected';2488 }2489 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2490 if (res === undefined || res === null) {2491 throw 'Restore address error';2492 }2493 return res.toString();2494 }24952496 24972498249925002501 convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2502 if (ethCrossAccount.sub === '0') {2503 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2504 }2505 2506 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2507 return {Substrate: ss58};2508 }25092510 paraSiblingSovereignAccount(paraid: number) {2511 2512 2513 const siblingPrefix = '0x7369626c';25142515 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2516 const suffix = '000000000000000000000000000000000000000000000000';25172518 return siblingPrefix + encodedParaId + suffix;2519 }2520}25212522class StakingGroup extends HelperGroup<UniqueHelper> {2523 2524252525262527252825292530 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2531 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2532 const _stakeResult = await this.helper.executeExtrinsic(2533 signer, 'api.tx.appPromotion.stake',2534 [amountToStake], true,2535 );2536 2537 return true;2538 }25392540 2541254225432544254525462547 async unstake(signer: TSigner, label?: string): Promise<number> {2548 if(typeof label === 'undefined') label = `${signer.address}`;2549 const _unstakeResult = await this.helper.executeExtrinsic(2550 signer, 'api.tx.appPromotion.unstake',2551 [], true,2552 );2553 2554 return 1;2555 }25562557 25582559256025612562 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2563 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2564 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2565 }25662567 25682569257025712572 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2573 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2574 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2575 return {2576 block: block.toBigInt(),2577 amount: amount.toBigInt(),2578 };2579 });2580 }25812582 25832584258525862587 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2588 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2589 }25902591 25922593259425952596 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2597 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2598 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2599 return {2600 block: block.toBigInt(),2601 amount: amount.toBigInt(),2602 };2603 });2604 return result;2605 }2606}26072608class SchedulerGroup extends HelperGroup<UniqueHelper> {2609 constructor(helper: UniqueHelper) {2610 super(helper);2611 }26122613 cancelScheduled(signer: TSigner, scheduledId: string) {2614 return this.helper.executeExtrinsic(2615 signer,2616 'api.tx.scheduler.cancelNamed',2617 [scheduledId],2618 true,2619 );2620 }26212622 changePriority(signer: TSigner, scheduledId: string, priority: number) {2623 return this.helper.executeExtrinsic(2624 signer,2625 'api.tx.scheduler.changeNamedPriority',2626 [scheduledId, priority],2627 true,2628 );2629 }26302631 scheduleAt<T extends UniqueHelper>(2632 executionBlockNumber: number,2633 options: ISchedulerOptions = {},2634 ) {2635 return this.schedule<T>('schedule', executionBlockNumber, options);2636 }26372638 scheduleAfter<T extends UniqueHelper>(2639 blocksBeforeExecution: number,2640 options: ISchedulerOptions = {},2641 ) {2642 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2643 }26442645 schedule<T extends UniqueHelper>(2646 scheduleFn: 'schedule' | 'scheduleAfter',2647 blocksNum: number,2648 options: ISchedulerOptions = {},2649 ) {2650 2651 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2652 return this.helper.clone(ScheduledHelperType, {2653 scheduleFn,2654 blocksNum,2655 options,2656 }) as T;2657 }2658}26592660class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2661 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2662 await this.helper.executeExtrinsic(2663 signer,2664 'api.tx.foreignAssets.registerForeignAsset',2665 [ownerAddress, location, metadata],2666 true,2667 );2668 }26692670 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2671 await this.helper.executeExtrinsic(2672 signer,2673 'api.tx.foreignAssets.updateForeignAsset',2674 [foreignAssetId, location, metadata],2675 true,2676 );2677 }2678}26792680class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2681 palletName: string;26822683 constructor(helper: T, palletName: string) {2684 super(helper);26852686 this.palletName = palletName;2687 }26882689 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2690 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2691 }2692}26932694class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2695 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2696 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2697 }26982699 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2700 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2701 }27022703 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2704 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2705 }2706}27072708class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2709 async accounts(address: string, currencyId: any) {2710 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2711 return BigInt(free);2712 }2713}27142715class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2716 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2717 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2718 }27192720 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2721 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2722 }27232724 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2725 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2726 }27272728 async account(assetId: string | number, address: string) {2729 const accountAsset = (2730 await this.helper.callRpc('api.query.assets.account', [assetId, address])2731 ).toJSON()! as any;27322733 if (accountAsset !== null) {2734 return BigInt(accountAsset['balance']);2735 } else {2736 return null;2737 }2738 }2739}27402741class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2742 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2743 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2744 }2745}27462747class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2748 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2749 const apiPrefix = 'api.tx.assetManager.';27502751 const registerTx = this.helper.constructApiCall(2752 apiPrefix + 'registerForeignAsset',2753 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2754 );27552756 const setUnitsTx = this.helper.constructApiCall(2757 apiPrefix + 'setAssetUnitsPerSecond',2758 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2759 );27602761 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2762 const encodedProposal = batchCall?.method.toHex() || '';2763 return encodedProposal;2764 }27652766 async assetTypeId(location: any) {2767 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2768 }2769}27702771class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2772 async notePreimage(signer: TSigner, encodedProposal: string) {2773 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2774 }27752776 externalProposeMajority(proposalHash: string) {2777 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2778 }27792780 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2781 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2782 }27832784 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2785 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2786 }2787}27882789class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2790 collective: string;27912792 constructor(helper: MoonbeamHelper, collective: string) {2793 super(helper);27942795 this.collective = collective;2796 }27972798 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2799 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2800 }28012802 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2803 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2804 }28052806 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2807 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2808 }28092810 async proposalCount() {2811 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2812 }2813}28142815export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2816export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28172818export class UniqueHelper extends ChainHelperBase {2819 balance: BalanceGroup<UniqueHelper>;2820 collection: CollectionGroup;2821 nft: NFTGroup;2822 rft: RFTGroup;2823 ft: FTGroup;2824 staking: StakingGroup;2825 scheduler: SchedulerGroup;2826 foreignAssets: ForeignAssetsGroup;2827 xcm: XcmGroup<UniqueHelper>;2828 xTokens: XTokensGroup<UniqueHelper>;2829 tokens: TokensGroup<UniqueHelper>;28302831 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2832 super(logger, options.helperBase ?? UniqueHelper);28332834 this.balance = new BalanceGroup(this);2835 this.collection = new CollectionGroup(this);2836 this.nft = new NFTGroup(this);2837 this.rft = new RFTGroup(this);2838 this.ft = new FTGroup(this);2839 this.staking = new StakingGroup(this);2840 this.scheduler = new SchedulerGroup(this);2841 this.foreignAssets = new ForeignAssetsGroup(this);2842 this.xcm = new XcmGroup(this, 'polkadotXcm');2843 this.xTokens = new XTokensGroup(this);2844 this.tokens = new TokensGroup(this);2845 }28462847 getSudo<T extends UniqueHelper>() {2848 2849 const SudoHelperType = SudoHelper(this.helperBase);2850 return this.clone(SudoHelperType) as T;2851 }2852}28532854export class XcmChainHelper extends ChainHelperBase {2855 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2856 const wsProvider = new WsProvider(wsEndpoint);2857 this.api = new ApiPromise({2858 provider: wsProvider,2859 });2860 await this.api.isReadyOrError;2861 this.network = await UniqueHelper.detectNetwork(this.api);2862 }2863}28642865export class RelayHelper extends XcmChainHelper {2866 xcm: XcmGroup<RelayHelper>;28672868 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2869 super(logger, options.helperBase ?? RelayHelper);28702871 this.xcm = new XcmGroup(this, 'xcmPallet');2872 }2873}28742875export class WestmintHelper extends XcmChainHelper {2876 balance: SubstrateBalanceGroup<WestmintHelper>;2877 xcm: XcmGroup<WestmintHelper>;2878 assets: AssetsGroup<WestmintHelper>;2879 xTokens: XTokensGroup<WestmintHelper>;28802881 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2882 super(logger, options.helperBase ?? WestmintHelper);28832884 this.balance = new SubstrateBalanceGroup(this);2885 this.xcm = new XcmGroup(this, 'polkadotXcm');2886 this.assets = new AssetsGroup(this);2887 this.xTokens = new XTokensGroup(this);2888 }2889}28902891export class MoonbeamHelper extends XcmChainHelper {2892 balance: EthereumBalanceGroup<MoonbeamHelper>;2893 assetManager: MoonbeamAssetManagerGroup;2894 assets: AssetsGroup<MoonbeamHelper>;2895 xTokens: XTokensGroup<MoonbeamHelper>;2896 democracy: MoonbeamDemocracyGroup;2897 collective: {2898 council: MoonbeamCollectiveGroup,2899 techCommittee: MoonbeamCollectiveGroup,2900 };29012902 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2903 super(logger, options.helperBase ?? MoonbeamHelper);29042905 this.balance = new EthereumBalanceGroup(this);2906 this.assetManager = new MoonbeamAssetManagerGroup(this);2907 this.assets = new AssetsGroup(this);2908 this.xTokens = new XTokensGroup(this);2909 this.democracy = new MoonbeamDemocracyGroup(this);2910 this.collective = {2911 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2912 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2913 };2914 }2915}29162917export class AcalaHelper extends XcmChainHelper {2918 balance: SubstrateBalanceGroup<AcalaHelper>;2919 assetRegistry: AcalaAssetRegistryGroup;2920 xTokens: XTokensGroup<AcalaHelper>;2921 tokens: TokensGroup<AcalaHelper>;29222923 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2924 super(logger, options.helperBase ?? AcalaHelper);29252926 this.balance = new SubstrateBalanceGroup(this);2927 this.assetRegistry = new AcalaAssetRegistryGroup(this);2928 this.xTokens = new XTokensGroup(this);2929 this.tokens = new TokensGroup(this);2930 }29312932 getSudo<T extends AcalaHelper>() {2933 2934 const SudoHelperType = SudoHelper(this.helperBase);2935 return this.clone(SudoHelperType) as T;2936 }2937}293829392940function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2941 return class extends Base {2942 scheduleFn: 'schedule' | 'scheduleAfter';2943 blocksNum: number;2944 options: ISchedulerOptions;29452946 constructor(...args: any[]) {2947 const logger = args[0] as ILogger;2948 const options = args[1] as {2949 scheduleFn: 'schedule' | 'scheduleAfter',2950 blocksNum: number,2951 options: ISchedulerOptions2952 };29532954 super(logger);29552956 this.scheduleFn = options.scheduleFn;2957 this.blocksNum = options.blocksNum;2958 this.options = options.options;2959 }29602961 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2962 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2963 2964 const mandatorySchedArgs = [2965 this.blocksNum,2966 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2967 this.options.priority ?? null,2968 scheduledTx,2969 ];2970 2971 let schedArgs;2972 let scheduleFn;29732974 if (this.options.scheduledId) {2975 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];29762977 if (this.scheduleFn == 'schedule') {2978 scheduleFn = 'scheduleNamed';2979 } else if (this.scheduleFn == 'scheduleAfter') {2980 scheduleFn = 'scheduleNamedAfter';2981 }2982 } else {2983 schedArgs = mandatorySchedArgs;2984 scheduleFn = this.scheduleFn;2985 }29862987 const extrinsic = 'api.tx.scheduler.' + scheduleFn;29882989 return super.executeExtrinsic(2990 sender,2991 extrinsic,2992 schedArgs,2993 expectSuccess,2994 );2995 }2996 };2997}299829993000function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3001 return class extends Base {3002 constructor(...args: any[]) {3003 super(...args);3004 }30053006 executeExtrinsic (3007 sender: IKeyringPair,3008 extrinsic: string,3009 params: any[],3010 expectSuccess?: boolean,3011 ): Promise<ITransactionResult> {3012 const call = this.constructApiCall(extrinsic, params);3013 return super.executeExtrinsic(3014 sender,3015 'api.tx.sudo.sudo',3016 [call],3017 expectSuccess,3018 );3019 }3020 };3021}30223023export class UniqueBaseCollection {3024 helper: UniqueHelper;3025 collectionId: number;30263027 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3028 this.collectionId = collectionId;3029 this.helper = uniqueHelper;3030 }30313032 async getData() {3033 return await this.helper.collection.getData(this.collectionId);3034 }30353036 async getLastTokenId() {3037 return await this.helper.collection.getLastTokenId(this.collectionId);3038 }30393040 async doesTokenExist(tokenId: number) {3041 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3042 }30433044 async getAdmins() {3045 return await this.helper.collection.getAdmins(this.collectionId);3046 }30473048 async getAllowList() {3049 return await this.helper.collection.getAllowList(this.collectionId);3050 }30513052 async getEffectiveLimits() {3053 return await this.helper.collection.getEffectiveLimits(this.collectionId);3054 }30553056 async getProperties(propertyKeys?: string[] | null) {3057 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3058 }30593060 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3061 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3062 }30633064 async getOptions() {3065 return await this.helper.collection.getCollectionOptions(this.collectionId);3066 }30673068 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3069 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3070 }30713072 async confirmSponsorship(signer: TSigner) {3073 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3074 }30753076 async removeSponsor(signer: TSigner) {3077 return await this.helper.collection.removeSponsor(signer, this.collectionId);3078 }30793080 async setLimits(signer: TSigner, limits: ICollectionLimits) {3081 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3082 }30833084 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3085 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3086 }30873088 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3089 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3090 }30913092 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3093 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3094 }30953096 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3097 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3098 }30993100 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3101 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3102 }31033104 async setProperties(signer: TSigner, properties: IProperty[]) {3105 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3106 }31073108 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3109 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3110 }31113112 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3113 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3114 }31153116 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3117 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3118 }31193120 async disableNesting(signer: TSigner) {3121 return await this.helper.collection.disableNesting(signer, this.collectionId);3122 }31233124 async burn(signer: TSigner) {3125 return await this.helper.collection.burn(signer, this.collectionId);3126 }31273128 scheduleAt<T extends UniqueHelper>(3129 executionBlockNumber: number,3130 options: ISchedulerOptions = {},3131 ) {3132 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3133 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3134 }31353136 scheduleAfter<T extends UniqueHelper>(3137 blocksBeforeExecution: number,3138 options: ISchedulerOptions = {},3139 ) {3140 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3141 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3142 }31433144 getSudo<T extends UniqueHelper>() {3145 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3146 }3147}314831493150export class UniqueNFTCollection extends UniqueBaseCollection {3151 getTokenObject(tokenId: number) {3152 return new UniqueNFToken(tokenId, this);3153 }31543155 async getTokensByAddress(addressObj: ICrossAccountId) {3156 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3157 }31583159 async getToken(tokenId: number, blockHashAt?: string) {3160 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3161 }31623163 async getTokenOwner(tokenId: number, blockHashAt?: string) {3164 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3165 }31663167 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3168 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3169 }31703171 async getTokenChildren(tokenId: number, blockHashAt?: string) {3172 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3173 }31743175 async getPropertyPermissions(propertyKeys: string[] | null = null) {3176 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3177 }31783179 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3180 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3181 }31823183 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3184 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3185 }31863187 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3188 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3189 }31903191 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3192 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3193 }31943195 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3196 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3197 }31983199 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3200 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3201 }32023203 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3204 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3205 }32063207 async burnToken(signer: TSigner, tokenId: number) {3208 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3209 }32103211 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3212 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3213 }32143215 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3216 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3217 }32183219 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3220 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3221 }32223223 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3224 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3225 }32263227 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3228 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3229 }32303231 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3232 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3233 }32343235 scheduleAt<T extends UniqueHelper>(3236 executionBlockNumber: number,3237 options: ISchedulerOptions = {},3238 ) {3239 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3240 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3241 }32423243 scheduleAfter<T extends UniqueHelper>(3244 blocksBeforeExecution: number,3245 options: ISchedulerOptions = {},3246 ) {3247 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3248 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3249 }32503251 getSudo<T extends UniqueHelper>() {3252 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3253 }3254}325532563257export class UniqueRFTCollection extends UniqueBaseCollection {3258 getTokenObject(tokenId: number) {3259 return new UniqueRFToken(tokenId, this);3260 }32613262 async getToken(tokenId: number, blockHashAt?: string) {3263 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3264 }32653266 async getTokensByAddress(addressObj: ICrossAccountId) {3267 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3268 }32693270 async getTop10TokenOwners(tokenId: number) {3271 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3272 }32733274 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3275 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3276 }32773278 async getTokenTotalPieces(tokenId: number) {3279 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3280 }32813282 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3283 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3284 }32853286 async getPropertyPermissions(propertyKeys: string[] | null = null) {3287 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3288 }32893290 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3291 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3292 }32933294 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3295 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3296 }32973298 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3299 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3300 }33013302 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3303 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3304 }33053306 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3307 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3308 }33093310 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3311 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3312 }33133314 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3315 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3316 }33173318 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3319 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3320 }33213322 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3323 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3324 }33253326 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3327 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3328 }33293330 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3331 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3332 }33333334 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3335 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3336 }33373338 scheduleAt<T extends UniqueHelper>(3339 executionBlockNumber: number,3340 options: ISchedulerOptions = {},3341 ) {3342 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3343 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3344 }33453346 scheduleAfter<T extends UniqueHelper>(3347 blocksBeforeExecution: number,3348 options: ISchedulerOptions = {},3349 ) {3350 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3351 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3352 }33533354 getSudo<T extends UniqueHelper>() {3355 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3356 }3357}335833593360export class UniqueFTCollection extends UniqueBaseCollection {3361 async getBalance(addressObj: ICrossAccountId) {3362 return await this.helper.ft.getBalance(this.collectionId, addressObj);3363 }33643365 async getTotalPieces() {3366 return await this.helper.ft.getTotalPieces(this.collectionId);3367 }33683369 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3370 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3371 }33723373 async getTop10Owners() {3374 return await this.helper.ft.getTop10Owners(this.collectionId);3375 }33763377 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3378 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3379 }33803381 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3382 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3383 }33843385 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3386 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3387 }33883389 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3390 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3391 }33923393 async burnTokens(signer: TSigner, amount=1n) {3394 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3395 }33963397 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3398 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3399 }34003401 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3402 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3403 }34043405 scheduleAt<T extends UniqueHelper>(3406 executionBlockNumber: number,3407 options: ISchedulerOptions = {},3408 ) {3409 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3410 return new UniqueFTCollection(this.collectionId, scheduledHelper);3411 }34123413 scheduleAfter<T extends UniqueHelper>(3414 blocksBeforeExecution: number,3415 options: ISchedulerOptions = {},3416 ) {3417 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3418 return new UniqueFTCollection(this.collectionId, scheduledHelper);3419 }34203421 getSudo<T extends UniqueHelper>() {3422 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3423 }3424}342534263427export class UniqueBaseToken {3428 collection: UniqueNFTCollection | UniqueRFTCollection;3429 collectionId: number;3430 tokenId: number;34313432 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3433 this.collection = collection;3434 this.collectionId = collection.collectionId;3435 this.tokenId = tokenId;3436 }34373438 async getNextSponsored(addressObj: ICrossAccountId) {3439 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3440 }34413442 async getProperties(propertyKeys?: string[] | null) {3443 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3444 }34453446 async setProperties(signer: TSigner, properties: IProperty[]) {3447 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3448 }34493450 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3451 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3452 }34533454 async doesExist() {3455 return await this.collection.doesTokenExist(this.tokenId);3456 }34573458 nestingAccount() {3459 return this.collection.helper.util.getTokenAccount(this);3460 }34613462 scheduleAt<T extends UniqueHelper>(3463 executionBlockNumber: number,3464 options: ISchedulerOptions = {},3465 ) {3466 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3467 return new UniqueBaseToken(this.tokenId, scheduledCollection);3468 }34693470 scheduleAfter<T extends UniqueHelper>(3471 blocksBeforeExecution: number,3472 options: ISchedulerOptions = {},3473 ) {3474 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3475 return new UniqueBaseToken(this.tokenId, scheduledCollection);3476 }34773478 getSudo<T extends UniqueHelper>() {3479 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3480 }3481}348234833484export class UniqueNFToken extends UniqueBaseToken {3485 collection: UniqueNFTCollection;34863487 constructor(tokenId: number, collection: UniqueNFTCollection) {3488 super(tokenId, collection);3489 this.collection = collection;3490 }34913492 async getData(blockHashAt?: string) {3493 return await this.collection.getToken(this.tokenId, blockHashAt);3494 }34953496 async getOwner(blockHashAt?: string) {3497 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3498 }34993500 async getTopmostOwner(blockHashAt?: string) {3501 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3502 }35033504 async getChildren(blockHashAt?: string) {3505 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3506 }35073508 async nest(signer: TSigner, toTokenObj: IToken) {3509 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3510 }35113512 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3513 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3514 }35153516 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3517 return await this.collection.transferToken(signer, this.tokenId, addressObj);3518 }35193520 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3521 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3522 }35233524 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3525 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3526 }35273528 async isApproved(toAddressObj: ICrossAccountId) {3529 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3530 }35313532 async burn(signer: TSigner) {3533 return await this.collection.burnToken(signer, this.tokenId);3534 }35353536 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3537 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3538 }35393540 scheduleAt<T extends UniqueHelper>(3541 executionBlockNumber: number,3542 options: ISchedulerOptions = {},3543 ) {3544 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3545 return new UniqueNFToken(this.tokenId, scheduledCollection);3546 }35473548 scheduleAfter<T extends UniqueHelper>(3549 blocksBeforeExecution: number,3550 options: ISchedulerOptions = {},3551 ) {3552 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3553 return new UniqueNFToken(this.tokenId, scheduledCollection);3554 }35553556 getSudo<T extends UniqueHelper>() {3557 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3558 }3559}35603561export class UniqueRFToken extends UniqueBaseToken {3562 collection: UniqueRFTCollection;35633564 constructor(tokenId: number, collection: UniqueRFTCollection) {3565 super(tokenId, collection);3566 this.collection = collection;3567 }35683569 async getData(blockHashAt?: string) {3570 return await this.collection.getToken(this.tokenId, blockHashAt);3571 }35723573 async getTop10Owners() {3574 return await this.collection.getTop10TokenOwners(this.tokenId);3575 }35763577 async getBalance(addressObj: ICrossAccountId) {3578 return await this.collection.getTokenBalance(this.tokenId, addressObj);3579 }35803581 async getTotalPieces() {3582 return await this.collection.getTokenTotalPieces(this.tokenId);3583 }35843585 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3586 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3587 }35883589 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3590 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3591 }35923593 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3594 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3595 }35963597 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3598 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3599 }36003601 async repartition(signer: TSigner, amount: bigint) {3602 return await this.collection.repartitionToken(signer, this.tokenId, amount);3603 }36043605 async burn(signer: TSigner, amount=1n) {3606 return await this.collection.burnToken(signer, this.tokenId, amount);3607 }36083609 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3610 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3611 }36123613 scheduleAt<T extends UniqueHelper>(3614 executionBlockNumber: number,3615 options: ISchedulerOptions = {},3616 ) {3617 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3618 return new UniqueRFToken(this.tokenId, scheduledCollection);3619 }36203621 scheduleAfter<T extends UniqueHelper>(3622 blocksBeforeExecution: number,3623 options: ISchedulerOptions = {},3624 ) {3625 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3626 return new UniqueRFToken(this.tokenId, scheduledCollection);3627 }36283629 getSudo<T extends UniqueHelper>() {3630 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3631 }3632}