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 {13 IApiListeners,14 IBlock,15 IEvent,16 IChainProperties,17 ICollectionCreationOptions,18 ICollectionLimits,19 ICollectionPermissions,20 ICrossAccountId,21 ICrossAccountIdLower,22 ILogger,23 INestingPermissions,24 IProperty,25 IStakingInfo,26 ISchedulerOptions,27 ISubstrateBalance,28 IToken,29 ITokenPropertyPermission,30 ITransactionResult,31 IUniqueHelperLog,32 TApiAllowedListeners,33 TEthereumAccount,34 TSigner,35 TSubstrateAccount,36 IEthCrossAccountId,37 TNetworks,38 IForeignAssetMetadata,39 AcalaAssetMetadata,40 MoonbeamAssetInfo,41 DemocracyStandardAccountVote,42} from './types';43import {hexToU8a} from '@polkadot/util/hex';44import {u8aConcat} from '@polkadot/util/u8a';4546export class CrossAccountId implements ICrossAccountId {47 Substrate?: TSubstrateAccount;48 Ethereum?: TEthereumAccount;4950 constructor(account: ICrossAccountId) {51 if (account.Substrate) this.Substrate = account.Substrate;52 if (account.Ethereum) this.Ethereum = account.Ethereum;53 }5455 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {56 switch (domain) {57 case 'Substrate': return new CrossAccountId({Substrate: account.address});58 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();59 }60 }6162 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {63 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});64 }6566 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {67 return encodeAddress(decodeAddress(address), ss58Format);68 }6970 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {71 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});72 }73 74 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {75 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);76 return this;77 }7879 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {80 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));81 }8283 toEthereum(): CrossAccountId {84 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});85 return this;86 }8788 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {89 return evmToAddress(address, ss58Format);90 }9192 toSubstrate(ss58Format?: number): CrossAccountId {93 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});94 return this;95 }96 97 toLowerCase(): CrossAccountId {98 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();99 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();100 return this;101 }102}103104const nesting = {105 toChecksumAddress(address: string): string {106 if (typeof address === 'undefined') return '';107108 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);109110 address = address.toLowerCase().replace(/^0x/i,'');111 const addressHash = keccakAsHex(address).replace(/^0x/i,'');112 const checksumAddress = ['0x'];113114 for (let i = 0; i < address.length; i++) {115 116 if (parseInt(addressHash[i], 16) > 7) {117 checksumAddress.push(address[i].toUpperCase());118 } else {119 checksumAddress.push(address[i]);120 }121 }122 return checksumAddress.join('');123 },124 tokenIdToAddress(collectionId: number, tokenId: number) {125 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);126 },127};128129class UniqueUtil {130 static transactionStatus = {131 NOT_READY: 'NotReady',132 FAIL: 'Fail',133 SUCCESS: 'Success',134 };135136 static chainLogType = {137 EXTRINSIC: 'extrinsic',138 RPC: 'rpc',139 };140141 static getTokenAccount(token: IToken): CrossAccountId {142 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});143 }144145 static getTokenAddress(token: IToken): string {146 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);147 }148149 static getDefaultLogger(): ILogger {150 return {151 log(msg: any, level = 'INFO') {152 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));153 },154 level: {155 ERROR: 'ERROR',156 WARNING: 'WARNING',157 INFO: 'INFO',158 },159 };160 }161162 static vec2str(arr: string[] | number[]) {163 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');164 }165166 static str2vec(string: string) {167 if (typeof string !== 'string') return string;168 return Array.from(string).map(x => x.charCodeAt(0));169 }170171 static fromSeed(seed: string, ss58Format = 42) {172 const keyring = new Keyring({type: 'sr25519', ss58Format});173 return keyring.addFromUri(seed);174 }175176 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {177 if (creationResult.status !== this.transactionStatus.SUCCESS) {178 throw Error('Unable to create collection!');179 }180181 let collectionId = null;182 creationResult.result.events.forEach(({event: {data, method, section}}) => {183 if ((section === 'common') && (method === 'CollectionCreated')) {184 collectionId = parseInt(data[0].toString(), 10);185 }186 });187188 if (collectionId === null) {189 throw Error('No CollectionCreated event was found!');190 }191192 return collectionId;193 }194195 static extractTokensFromCreationResult(creationResult: ITransactionResult): {196 success: boolean, 197 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],198 } {199 if (creationResult.status !== this.transactionStatus.SUCCESS) {200 throw Error('Unable to create tokens!');201 }202 let success = false;203 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];204 creationResult.result.events.forEach(({event: {data, method, section}}) => {205 if (method === 'ExtrinsicSuccess') {206 success = true;207 } else if ((section === 'common') && (method === 'ItemCreated')) {208 tokens.push({209 collectionId: parseInt(data[0].toString(), 10),210 tokenId: parseInt(data[1].toString(), 10),211 owner: data[2].toHuman(),212 amount: data[3].toBigInt(),213 });214 }215 });216 return {success, tokens};217 }218219 static extractTokensFromBurnResult(burnResult: ITransactionResult): {220 success: boolean, 221 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],222 } {223 if (burnResult.status !== this.transactionStatus.SUCCESS) {224 throw Error('Unable to burn tokens!');225 }226 let success = false;227 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];228 burnResult.result.events.forEach(({event: {data, method, section}}) => {229 if (method === 'ExtrinsicSuccess') {230 success = true;231 } else if ((section === 'common') && (method === 'ItemDestroyed')) {232 tokens.push({233 collectionId: parseInt(data[0].toString(), 10),234 tokenId: parseInt(data[1].toString(), 10),235 owner: data[2].toHuman(),236 amount: data[3].toBigInt(),237 });238 }239 });240 return {success, tokens};241 }242243 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {244 let eventId = null;245 events.forEach(({event: {data, method, section}}) => {246 if ((section === expectedSection) && (method === expectedMethod)) {247 eventId = parseInt(data[0].toString(), 10);248 }249 });250251 if (eventId === null) {252 throw Error(`No ${expectedMethod} event was found!`);253 }254 return eventId === collectionId;255 }256257 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {258 const normalizeAddress = (address: string | ICrossAccountId) => {259 if(typeof address === 'string') return address;260 const obj = {} as any;261 Object.keys(address).forEach(k => {262 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];263 });264 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);265 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();266 return address;267 };268 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;269 events.forEach(({event: {data, method, section}}) => {270 if ((section === 'common') && (method === 'Transfer')) {271 const hData = (data as any).toJSON();272 transfer = {273 collectionId: hData[0],274 tokenId: hData[1],275 from: normalizeAddress(hData[2]),276 to: normalizeAddress(hData[3]),277 amount: BigInt(hData[4]),278 };279 }280 });281 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;282 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);284 isSuccess = isSuccess && amount === transfer.amount;285 return isSuccess;286 }287288 static bigIntToDecimals(number: bigint, decimals = 18) {289 const numberStr = number.toString();290 const dotPos = numberStr.length - decimals;291 292 if (dotPos <= 0) {293 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;294 } else {295 const intPart = numberStr.substring(0, dotPos);296 const fractPart = numberStr.substring(dotPos);297 return intPart + '.' + fractPart;298 }299 }300}301302class UniqueEventHelper {303 private static extractIndex(index: any): [number, number] | string {304 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];305 return index.toJSON();306 }307308 private static extractSub(data: any, subTypes: any): {[key: string]: any} {309 let obj: any = {};310 let index = 0;311312 if (data.entries) {313 for(const [key, value] of data.entries()) {314 obj[key] = this.extractData(value, subTypes[index]);315 index++;316 }317 } else obj = data.toJSON();318319 return obj;320 }321 322 private static extractData(data: any, type: any): any {323 if(!type) return data.toHuman();324 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();325 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();326 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);327 return data.toHuman();328 }329330 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {331 const parsedEvents: IEvent[] = [];332333 events.forEach((record) => {334 const {event, phase} = record;335 const types = event.typeDef;336337 const eventData: IEvent = {338 section: event.section.toString(),339 method: event.method.toString(),340 index: this.extractIndex(event.index),341 data: [],342 phase: phase.toJSON(),343 };344345 event.data.forEach((val: any, index: number) => {346 eventData.data.push(this.extractData(val, types[index]));347 });348349 parsedEvents.push(eventData);350 });351352 return parsedEvents;353 }354}355356export class ChainHelperBase {357 helperBase: any;358359 transactionStatus = UniqueUtil.transactionStatus;360 chainLogType = UniqueUtil.chainLogType;361 util: typeof UniqueUtil;362 eventHelper: typeof UniqueEventHelper;363 logger: ILogger;364 api: ApiPromise | null;365 forcedNetwork: TNetworks | null;366 network: TNetworks | null;367 chainLog: IUniqueHelperLog[];368 children: ChainHelperBase[];369 address: AddressGroup;370 chain: ChainGroup;371372 constructor(logger?: ILogger, helperBase?: any) {373 this.helperBase = helperBase;374375 this.util = UniqueUtil;376 this.eventHelper = UniqueEventHelper;377 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();378 this.logger = logger;379 this.api = null;380 this.forcedNetwork = null;381 this.network = null;382 this.chainLog = [];383 this.children = [];384 this.address = new AddressGroup(this);385 this.chain = new ChainGroup(this);386 }387388 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {389 Object.setPrototypeOf(helperCls.prototype, this);390 const newHelper = new helperCls(this.logger, options);391392 newHelper.api = this.api;393 newHelper.network = this.network;394 newHelper.forceNetwork = this.forceNetwork;395396 this.children.push(newHelper);397398 return newHelper;399 }400401 getApi(): ApiPromise {402 if(this.api === null) throw Error('API not initialized');403 return this.api;404 }405406 clearChainLog(): void {407 this.chainLog = [];408 }409410 forceNetwork(value: TNetworks): void {411 this.forcedNetwork = value;412 }413414 async connect(wsEndpoint: string, listeners?: IApiListeners) {415 if (this.api !== null) throw Error('Already connected');416 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);417 this.api = api;418 this.network = network;419 }420421 async disconnect() {422 for (const child of this.children) {423 child.clearApi();424 }425426 if (this.api === null) return;427 await this.api.disconnect();428 this.clearApi();429 }430431 clearApi() {432 this.api = null;433 this.network = null;434 }435436 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {437 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;438 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];439440 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;441442 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;443 return 'opal';444 }445446 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {447 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});448 await api.isReady;449450 const network = await this.detectNetwork(api);451452 await api.disconnect();453454 return network;455 }456457 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{458 api: ApiPromise;459 network: TNetworks;460 }> {461 if(typeof network === 'undefined' || network === null) network = 'opal';462 const supportedRPC = {463 opal: {464 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,465 },466 quartz: {467 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,468 },469 unique: {470 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,471 },472 rococo: {},473 westend: {},474 moonbeam: {},475 moonriver: {},476 acala: {},477 karura: {},478 westmint: {},479 };480 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);481 const rpc = supportedRPC[network];482483 484 485486 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});487488 await api.isReadyOrError;489490 if (typeof listeners === 'undefined') listeners = {};491 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {492 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;493 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);494 }495496 return {api, network};497 }498499 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {500 const {events, status} = data;501 if (status.isReady) {502 return this.transactionStatus.NOT_READY;503 }504 if (status.isBroadcast) {505 return this.transactionStatus.NOT_READY;506 }507 if (status.isInBlock || status.isFinalized) {508 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');509 if (errors.length > 0) {510 return this.transactionStatus.FAIL;511 }512 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {513 return this.transactionStatus.SUCCESS;514 }515 }516517 return this.transactionStatus.FAIL;518 }519520 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {521 const sign = (callback: any) => {522 if(options !== null) return transaction.signAndSend(sender, options, callback);523 return transaction.signAndSend(sender, callback);524 };525 526 return new Promise(async (resolve, reject) => {527 try {528 const unsub = await sign((result: any) => {529 const status = this.getTransactionStatus(result);530531 if (status === this.transactionStatus.SUCCESS) {532 this.logger.log(`${label} successful`);533 unsub();534 resolve({result, status});535 } else if (status === this.transactionStatus.FAIL) {536 let moduleError = null;537538 if (result.hasOwnProperty('dispatchError')) {539 const dispatchError = result['dispatchError'];540541 if (dispatchError) {542 if (dispatchError.isModule) {543 const modErr = dispatchError.asModule;544 const errorMeta = dispatchError.registry.findMetaError(modErr);545546 moduleError = `${errorMeta.section}.${errorMeta.name}`;547 } else {548 moduleError = dispatchError.toHuman();549 }550 } else {551 this.logger.log(result, this.logger.level.ERROR);552 }553 }554555 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);556 unsub();557 reject({status, moduleError, result});558 }559 });560 } catch (e) {561 this.logger.log(e, this.logger.level.ERROR);562 reject(e);563 }564 });565 }566567 constructApiCall(apiCall: string, params: any[]) {568 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);569 let call = this.getApi() as any;570 for(const part of apiCall.slice(4).split('.')) {571 call = call[part];572 }573 return call(...params);574 }575576 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {577 if(this.api === null) throw Error('API not initialized');578 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);579580 const startTime = (new Date()).getTime();581 let result: ITransactionResult;582 let events: IEvent[] = [];583 try {584 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;585 events = this.eventHelper.extractEvents(result.result.events);586 }587 catch(e) {588 if(!(e as object).hasOwnProperty('status')) throw e;589 result = e as ITransactionResult;590 }591592 const endTime = (new Date()).getTime();593594 const log = {595 executedAt: endTime,596 executionTime: endTime - startTime,597 type: this.chainLogType.EXTRINSIC,598 status: result.status,599 call: extrinsic,600 signer: this.getSignerAddress(sender),601 params,602 } as IUniqueHelperLog;603604 if(result.status !== this.transactionStatus.SUCCESS) {605 if (result.moduleError) log.moduleError = result.moduleError;606 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;607 }608 if(events.length > 0) log.events = events;609610 this.chainLog.push(log);611612 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {613 if (result.moduleError) throw Error(`${result.moduleError}`);614 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));615 }616 return result;617 }618619 async callRpc(rpc: string, params?: any[]) {620 if(typeof params === 'undefined') params = [];621 if(this.api === null) throw Error('API not initialized');622 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);623624 const startTime = (new Date()).getTime();625 let result;626 let error = null;627 const log = {628 type: this.chainLogType.RPC,629 call: rpc,630 params,631 } as IUniqueHelperLog;632633 try {634 result = await this.constructApiCall(rpc, params);635 }636 catch(e) {637 error = e;638 }639640 const endTime = (new Date()).getTime();641642 log.executedAt = endTime;643 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';644 log.executionTime = endTime - startTime;645646 this.chainLog.push(log);647648 if(error !== null) throw error;649650 return result;651 }652653 getSignerAddress(signer: IKeyringPair | string): string {654 if(typeof signer === 'string') return signer;655 return signer.address;656 }657658 fetchAllPalletNames(): string[] {659 if(this.api === null) throw Error('API not initialized');660 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());661 }662663 fetchMissingPalletNames(requiredPallets: string[]): string[] {664 const palletNames = this.fetchAllPalletNames();665 return requiredPallets.filter(p => !palletNames.includes(p));666 }667}668669670class HelperGroup<T extends ChainHelperBase> {671 helper: T;672673 constructor(uniqueHelper: T) {674 this.helper = uniqueHelper;675 }676}677678679class CollectionGroup extends HelperGroup<UniqueHelper> {680 681682683684685686687688689 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {690 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();691 }692693 694695696697698 async getTotalCount(): Promise<number> {699 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();700 }701702 703704705706707708709710711 async getData(collectionId: number): Promise<{712 id: number;713 name: string;714 description: string;715 tokensCount: number;716 admins: CrossAccountId[];717 normalizedOwner: TSubstrateAccount;718 raw: any719 } | null> {720 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);721 const humanCollection = collection.toHuman(), collectionData = {722 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],723 raw: humanCollection,724 } as any, jsonCollection = collection.toJSON();725 if (humanCollection === null) return null;726 collectionData.raw.limits = jsonCollection.limits;727 collectionData.raw.permissions = jsonCollection.permissions;728 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);729 for (const key of ['name', 'description']) {730 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);731 }732733 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))734 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)735 : 0;736 collectionData.admins = await this.getAdmins(collectionId);737738 return collectionData;739 }740741 742743744745746747748749 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {750 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();751752 return normalize753 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())754 : admins;755 }756757 758759760761762763764 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {765 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();766 return normalize767 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())768 : allowListed;769 }770771 772773774775776777778 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {779 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();780 }781782 783784785786787788789790 async burn(signer: TSigner, collectionId: number): Promise<boolean> {791 const result = await this.helper.executeExtrinsic(792 signer,793 'api.tx.unique.destroyCollection', [collectionId],794 true,795 );796797 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');798 }799800 801802803804805806807808809 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {810 const result = await this.helper.executeExtrinsic(811 signer,812 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],813 true,814 );815816 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');817 }818819 820821822823824825826827 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {828 const result = await this.helper.executeExtrinsic(829 signer,830 'api.tx.unique.confirmSponsorship', [collectionId],831 true,832 );833834 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');835 }836837 838839840841842843844845 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {846 const result = await this.helper.executeExtrinsic(847 signer,848 'api.tx.unique.removeCollectionSponsor', [collectionId],849 true,850 );851852 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');853 }854855 856857858859860861862863864865866867868869870871872 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {873 const result = await this.helper.executeExtrinsic(874 signer,875 'api.tx.unique.setCollectionLimits', [collectionId, limits],876 true,877 );878879 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');880 }881882 883884885886887888889890891 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {892 const result = await this.helper.executeExtrinsic(893 signer,894 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],895 true,896 );897898 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');899 }900901 902903904905906907908909910 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {911 const result = await this.helper.executeExtrinsic(912 signer,913 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],914 true,915 );916917 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');918 }919920 921922923924925926927928929 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {930 const result = await this.helper.executeExtrinsic(931 signer,932 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],933 true,934 );935936 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');937 }938939 940941942943944945946947 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {948 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();949 }950951 952953954955956957958 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {959 const result = await this.helper.executeExtrinsic(960 signer,961 'api.tx.unique.addToAllowList', [collectionId, addressObj],962 true,963 );964965 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');966 }967968 969970971972973974975976 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {977 const result = await this.helper.executeExtrinsic(978 signer,979 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],980 true,981 );982983 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');984 }985986 987988989990991992993994995 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {996 const result = await this.helper.executeExtrinsic(997 signer,998 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],999 true,1000 );10011002 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1003 }10041005 100610071008100910101011101210131014 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1015 return await this.setPermissions(signer, collectionId, {nesting: permissions});1016 }10171018 10191020102110221023102410251026 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1027 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1028 }10291030 103110321033103410351036103710381039 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1040 const result = await this.helper.executeExtrinsic(1041 signer,1042 'api.tx.unique.setCollectionProperties', [collectionId, properties],1043 true,1044 );10451046 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1047 }10481049 10501051105210531054105510561057 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1058 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1059 }10601061 async getCollectionOptions(collectionId: number) {1062 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1063 }10641065 106610671068106910701071107210731074 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1075 const result = await this.helper.executeExtrinsic(1076 signer,1077 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1078 true,1079 );10801081 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1082 }10831084 10851086108710881089109010911092109310941095 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1099 true, 1100 );11011102 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1103 }11041105 1106110711081109111011111112111311141115111611171118 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1119 const result = await this.helper.executeExtrinsic(1120 signer,1121 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1122 true, 1123 );1124 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1125 }11261127 11281129113011311132113311341135113611371138 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1139 const burnResult = await this.helper.executeExtrinsic(1140 signer,1141 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1142 true, 1143 );1144 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1145 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1146 return burnedTokens.success;1147 }11481149 11501151115211531154115511561157115811591160 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1161 const burnResult = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1164 true, 1165 );1166 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1167 return burnedTokens.success && burnedTokens.tokens.length > 0;1168 }11691170 1171117211731174117511761177117811791180 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1181 const approveResult = await this.helper.executeExtrinsic(1182 signer,1183 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1184 true, 1185 );11861187 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1188 }11891190 1191119211931194119511961197119811991200 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1201 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1202 }12031204 1205120612071208120912101211 async getLastTokenId(collectionId: number): Promise<number> {1212 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1213 }12141215 12161217121812191220122112221223 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1224 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1225 }1226}12271228class NFTnRFT extends CollectionGroup {1229 12301231123212331234123512361237 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1238 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1239 }12401241 1242124312441245124612471248124912501251 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1252 properties: IProperty[];1253 owner: CrossAccountId;1254 normalizedOwner: CrossAccountId;1255 }| null> {1256 let tokenData;1257 if(typeof blockHashAt === 'undefined') {1258 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1259 }1260 else {1261 if(propertyKeys.length == 0) {1262 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1263 if(!collection) return null;1264 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1265 }1266 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1267 }1268 tokenData = tokenData.toHuman();1269 if (tokenData === null || tokenData.owner === null) return null;1270 const owner = {} as any;1271 for (const key of Object.keys(tokenData.owner)) {1272 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1273 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1274 : tokenData.owner[key];1275 }1276 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1277 return tokenData;1278 }12791280 12811282128312841285128612871288128912901291 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1292 const result = await this.helper.executeExtrinsic(1293 signer,1294 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1295 true,1296 );12971298 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1299 }13001301 13021303130413051306130713081309 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1310 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1311 }13121313 1314131513161317131813191320132113221323 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1324 const result = await this.helper.executeExtrinsic(1325 signer,1326 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1327 true,1328 );13291330 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1331 }13321333 133413351336133713381339134013411342 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1343 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1344 }13451346 134713481349135013511352135313541355 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1356 const result = await this.helper.executeExtrinsic(1357 signer,1358 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1359 true,1360 );13611362 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1363 }13641365 136613671368136913701371137213731374 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1375 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1376 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1377 for (const key of ['name', 'description', 'tokenPrefix']) {1378 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);1379 }1380 const creationResult = await this.helper.executeExtrinsic(1381 signer,1382 'api.tx.unique.createCollectionEx', [collectionOptions],1383 true, 1384 );1385 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1386 }13871388 getCollectionObject(_collectionId: number): any {1389 return null;1390 }13911392 getTokenObject(_collectionId: number, _tokenId: number): any {1393 return null;1394 }1395}139613971398class NFTGroup extends NFTnRFT {1399 140014011402140314041405 getCollectionObject(collectionId: number): UniqueNFTCollection {1406 return new UniqueNFTCollection(collectionId, this.helper);1407 }14081409 1410141114121413141414151416 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1417 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1418 }14191420 14211422142314241425142614271428 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1429 let owner;1430 if (typeof blockHashAt === 'undefined') {1431 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1432 } else {1433 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1434 }1435 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1436 }14371438 1439144014411442144314441445 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1446 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1447 }14481449 1450145114521453145414551456145714581459 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1460 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1461 }14621463 146414651466146714681469147014711472147314741475 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1476 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1477 }14781479 14801481148214831484148514861487 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1488 let owner;1489 if (typeof blockHashAt === 'undefined') {1490 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1491 } else {1492 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1493 }14941495 if (owner === null) return null;14961497 return owner.toHuman();1498 }14991500 15011502150315041505150615071508 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1509 let children;1510 if(typeof blockHashAt === 'undefined') {1511 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1512 } else {1513 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1514 }15151516 return children.toJSON().map((x: any) => {1517 return {collectionId: x.collection, tokenId: x.token};1518 });1519 }15201521 15221523152415251526152715281529 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1530 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1531 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1532 if(!result) {1533 throw Error('Unable to nest token!');1534 }1535 return result;1536 }15371538 153915401541154215431544154515461547 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1548 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1549 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1550 if(!result) {1551 throw Error('Unable to unnest token!');1552 }1553 return result;1554 }15551556 155715581559156015611562156315641565156615671568 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1569 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1570 }15711572 157315741575157615771578 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1579 const creationResult = await this.helper.executeExtrinsic(1580 signer,1581 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1582 nft: {1583 properties: data.properties,1584 },1585 }],1586 true,1587 );1588 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1589 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1590 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1591 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592 }15931594 159515961597159815991600160116021603160416051606160716081609 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1610 const creationResult = await this.helper.executeExtrinsic(1611 signer,1612 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1613 true,1614 );1615 const collection = this.getCollectionObject(collectionId);1616 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1617 }16181619 162016211622162316241625162616271628162916301631163216331634163516361637 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1638 const rawTokens = [];1639 for (const token of tokens) {1640 const raw = {NFT: {properties: token.properties}};1641 rawTokens.push(raw);1642 }1643 const creationResult = await this.helper.executeExtrinsic(1644 signer,1645 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1646 true,1647 );1648 const collection = this.getCollectionObject(collectionId);1649 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1650 }16511652 1653165416551656165716581659166016611662 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1663 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1664 }1665}166616671668class RFTGroup extends NFTnRFT {1669 167016711672167316741675 getCollectionObject(collectionId: number): UniqueRFTCollection {1676 return new UniqueRFTCollection(collectionId, this.helper);1677 }16781679 1680168116821683168416851686 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1687 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1688 }16891690 1691169216931694169516961697 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1698 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1699 }17001701 17021703170417051706170717081709 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1710 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1711 }17121713 1714171517161717171817191720172117221723 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1724 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1725 }17261727 17281729173017311732173317341735173617371738 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1739 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1740 }17411742 174317441745174617471748174917501751175217531754 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1755 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1756 }17571758 1759176017611762176317641765 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1766 const creationResult = await this.helper.executeExtrinsic(1767 signer,1768 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1769 refungible: {1770 pieces: data.pieces,1771 properties: data.properties,1772 },1773 }],1774 true,1775 );1776 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1777 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1778 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1779 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1780 }17811782 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1783 throw Error('Not implemented');1784 const creationResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1787 true, 1788 );1789 const collection = this.getCollectionObject(collectionId);1790 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1791 }17921793 179417951796179717981799180018011802 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1803 const rawTokens = [];1804 for (const token of tokens) {1805 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1806 rawTokens.push(raw);1807 }1808 const creationResult = await this.helper.executeExtrinsic(1809 signer,1810 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1811 true,1812 );1813 const collection = this.getCollectionObject(collectionId);1814 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1815 }18161817 181818191820182118221823182418251826 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1827 return await super.burnToken(signer, collectionId, tokenId, amount);1828 }18291830 1831183218331834183518361837183818391840 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1841 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1842 }18431844 18451846184718481849185018511852185318541855 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1856 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1857 }18581859 1860186118621863186418651866 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1867 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1868 }18691870 187118721873187418751876187718781879 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1880 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1881 const repartitionResult = await this.helper.executeExtrinsic(1882 signer,1883 'api.tx.unique.repartition', [collectionId, tokenId, amount],1884 true,1885 );1886 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1887 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1888 }1889}189018911892class FTGroup extends CollectionGroup {1893 189418951896189718981899 getCollectionObject(collectionId: number): UniqueFTCollection {1900 return new UniqueFTCollection(collectionId, this.helper);1901 }19021903 1904190519061907190819091910191119121913191419151916 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1917 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1918 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1919 collectionOptions.mode = {fungible: decimalPoints};1920 for (const key of ['name', 'description', 'tokenPrefix']) {1921 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);1922 }1923 const creationResult = await this.helper.executeExtrinsic(1924 signer,1925 'api.tx.unique.createCollectionEx', [collectionOptions],1926 true,1927 );1928 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1929 }19301931 193219331934193519361937193819391940 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1941 const creationResult = await this.helper.executeExtrinsic(1942 signer,1943 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1944 fungible: {1945 value: amount,1946 },1947 }],1948 true, 1949 );1950 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1951 }19521953 19541955195619571958195919601961 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1962 const rawTokens = [];1963 for (const token of tokens) {1964 const raw = {Fungible: {Value: token.value}};1965 rawTokens.push(raw);1966 }1967 const creationResult = await this.helper.executeExtrinsic(1968 signer,1969 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1970 true,1971 );1972 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1973 }19741975 197619771978197919801981 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1982 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1983 }19841985 1986198719881989199019911992 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1993 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1994 }19951996 199719981999200020012002200320042005 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2006 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2007 }20082009 2010201120122013201420152016201720182019 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2020 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2021 }20222023 20242025202620272028202920302031 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2032 return await super.burnToken(signer, collectionId, 0, amount);2033 }20342035 203620372038203920402041204220432044 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2045 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2046 }20472048 20492050205120522053 async getTotalPieces(collectionId: number): Promise<bigint> {2054 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2055 }20562057 2058205920602061206220632064206520662067 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2068 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2069 }20702071 2072207320742075207620772078 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2079 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2080 }2081}208220832084class ChainGroup extends HelperGroup<ChainHelperBase> {2085 20862087208820892090 getChainProperties(): IChainProperties {2091 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2092 return {2093 ss58Format: properties.ss58Format.toJSON(),2094 tokenDecimals: properties.tokenDecimals.toJSON(),2095 tokenSymbol: properties.tokenSymbol.toJSON(),2096 };2097 }20982099 21002101210221032104 async getLatestBlockNumber(): Promise<number> {2105 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2106 }21072108 210921102111211221132114 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2115 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2116 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2117 return blockHash;2118 }21192120 2121 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2122 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2123 if (!blockHash) return null;2124 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2125 }21262127 212821292130213121322133 async getNonce(address: TSubstrateAccount): Promise<number> {2134 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2135 }2136}21372138class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2139 214021412142214321442145 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2146 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2147 }21482149 21502151215221532154215521562157 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2158 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21592160 let transfer = {from: null, to: null, amount: 0n} as any;2161 result.result.events.forEach(({event: {data, method, section}}) => {2162 if ((section === 'balances') && (method === 'Transfer')) {2163 transfer = {2164 from: this.helper.address.normalizeSubstrate(data[0]),2165 to: this.helper.address.normalizeSubstrate(data[1]),2166 amount: BigInt(data[2]),2167 };2168 }2169 });2170 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2171 && this.helper.address.normalizeSubstrate(address) === transfer.to 2172 && BigInt(amount) === transfer.amount;2173 return isSuccess;2174 }21752176 21772178217921802181 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2182 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2183 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2184 }2185}21862187class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2188 218921902191219221932194 async getEthereum(address: TEthereumAccount): Promise<bigint> {2195 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2196 }21972198 21992200220122022203220422052206 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2207 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22082209 let transfer = {from: null, to: null, amount: 0n} as any;2210 result.result.events.forEach(({event: {data, method, section}}) => {2211 if ((section === 'balances') && (method === 'Transfer')) {2212 transfer = {2213 from: data[0].toString(),2214 to: data[1].toString(),2215 amount: BigInt(data[2]),2216 };2217 }2218 });2219 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2220 && address === transfer.to 2221 && BigInt(amount) === transfer.amount;2222 return isSuccess;2223 }2224}22252226class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2227 subBalanceGroup: SubstrateBalanceGroup<T>;2228 ethBalanceGroup: EthereumBalanceGroup<T>;22292230 constructor(helper: T) {2231 super(helper);2232 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2233 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2234 }22352236 getCollectionCreationPrice(): bigint {2237 return 2n * this.getOneTokenNominal();2238 }2239 22402241224222432244 getOneTokenNominal(): bigint {2245 const chainProperties = this.helper.chain.getChainProperties();2246 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2247 }22482249 225022512252225322542255 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2256 return this.subBalanceGroup.getSubstrate(address);2257 }22582259 22602261226222632264 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2265 return this.subBalanceGroup.getSubstrateFull(address);2266 }22672268 226922702271227222732274 async getEthereum(address: TEthereumAccount): Promise<bigint> {2275 return this.ethBalanceGroup.getEthereum(address);2276 }22772278 22792280228122822283228422852286 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2287 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2288 }2289}22902291class AddressGroup extends HelperGroup<ChainHelperBase> {2292 2293229422952296229722982299 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2300 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2301 }23022303 230423052306230723082309 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2310 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2311 }23122313 2314231523162317231823192320 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2321 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2322 }23232324 232523262327232823292330 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2331 return CrossAccountId.translateSubToEth(subAddress);2332 }23332334 paraSiblingSovereignAccount(paraid: number) {2335 2336 2337 const siblingPrefix = '0x7369626c';23382339 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2340 const suffix = '000000000000000000000000000000000000000000000000';23412342 return siblingPrefix + encodedParaId + suffix;2343 }2344}23452346class StakingGroup extends HelperGroup<UniqueHelper> {2347 2348234923502351235223532354 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2355 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2356 const _stakeResult = await this.helper.executeExtrinsic(2357 signer, 'api.tx.appPromotion.stake',2358 [amountToStake], true,2359 );2360 2361 return true;2362 }23632364 2365236623672368236923702371 async unstake(signer: TSigner, label?: string): Promise<number> {2372 if(typeof label === 'undefined') label = `${signer.address}`;2373 const _unstakeResult = await this.helper.executeExtrinsic(2374 signer, 'api.tx.appPromotion.unstake',2375 [], true,2376 );2377 2378 return 1;2379 }23802381 23822383238423852386 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2387 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2388 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2389 }23902391 23922393239423952396 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2397 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2398 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2399 return { 2400 block: block.toBigInt(),2401 amount: amount.toBigInt(),2402 };2403 });2404 }24052406 24072408240924102411 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2412 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2413 }24142415 24162417241824192420 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2421 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2422 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2423 return {2424 block: block.toBigInt(),2425 amount: amount.toBigInt(),2426 };2427 });2428 return result;2429 }2430}24312432class SchedulerGroup extends HelperGroup<UniqueHelper> {2433 constructor(helper: UniqueHelper) {2434 super(helper);2435 }24362437 async cancelScheduled(signer: TSigner, scheduledId: string) {2438 return this.helper.executeExtrinsic(2439 signer,2440 'api.tx.scheduler.cancelNamed',2441 [scheduledId],2442 true,2443 );2444 }24452446 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2447 return this.helper.executeExtrinsic(2448 signer,2449 'api.tx.scheduler.changeNamedPriority',2450 [scheduledId, priority],2451 true,2452 );2453 }24542455 scheduleAt<T extends UniqueHelper>(2456 scheduledId: string,2457 executionBlockNumber: number,2458 options: ISchedulerOptions = {},2459 ) {2460 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2461 }24622463 scheduleAfter<T extends UniqueHelper>(2464 scheduledId: string,2465 blocksBeforeExecution: number,2466 options: ISchedulerOptions = {},2467 ) {2468 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2469 }24702471 schedule<T extends UniqueHelper>(2472 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2473 scheduledId: string,2474 blocksNum: number,2475 options: ISchedulerOptions = {},2476 ) {2477 2478 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2479 return this.helper.clone(ScheduledHelperType, {2480 scheduleFn,2481 scheduledId,2482 blocksNum,2483 options,2484 }) as T;2485 }2486}24872488class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2489 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2490 await this.helper.executeExtrinsic(2491 signer,2492 'api.tx.foreignAssets.registerForeignAsset',2493 [ownerAddress, location, metadata],2494 true,2495 );2496 }24972498 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2499 await this.helper.executeExtrinsic(2500 signer,2501 'api.tx.foreignAssets.updateForeignAsset',2502 [foreignAssetId, location, metadata],2503 true,2504 );2505 }2506}25072508class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2509 palletName: string;25102511 constructor(helper: T, palletName: string) {2512 super(helper);25132514 this.palletName = palletName;2515 }25162517 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2518 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2519 }2520}25212522class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2523 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2524 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2525 }25262527 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2528 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2529 }25302531 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2532 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2533 }2534}25352536class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2537 async accounts(address: string, currencyId: any) {2538 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2539 return BigInt(free);2540 }2541}25422543class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2544 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2545 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2546 }25472548 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2549 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2550 }25512552 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2553 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2554 }25552556 async account(assetId: string | number, address: string) {2557 const accountAsset = (2558 await this.helper.callRpc('api.query.assets.account', [assetId, address])2559 ).toJSON()! as any;25602561 if (accountAsset !== null) {2562 return BigInt(accountAsset['balance']);2563 } else {2564 return null;2565 }2566 }2567}25682569class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2570 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2571 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2572 }2573}25742575class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2576 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2577 const apiPrefix = 'api.tx.assetManager.';25782579 const registerTx = this.helper.constructApiCall(2580 apiPrefix + 'registerForeignAsset',2581 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2582 );25832584 const setUnitsTx = this.helper.constructApiCall(2585 apiPrefix + 'setAssetUnitsPerSecond',2586 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2587 );25882589 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2590 const encodedProposal = batchCall?.method.toHex() || '';2591 return encodedProposal;2592 }25932594 async assetTypeId(location: any) {2595 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2596 }2597}25982599class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2600 async notePreimage(signer: TSigner, encodedProposal: string) {2601 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2602 }26032604 externalProposeMajority(proposalHash: string) {2605 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2606 }26072608 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2609 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2610 }26112612 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2613 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2614 }2615}26162617class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2618 collective: string;26192620 constructor(helper: MoonbeamHelper, collective: string) {2621 super(helper);26222623 this.collective = collective;2624 }26252626 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2627 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2628 }26292630 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2631 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2632 }26332634 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2635 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2636 }26372638 async proposalCount() {2639 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2640 }2641}26422643export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2644export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26452646export class UniqueHelper extends ChainHelperBase {2647 balance: BalanceGroup<UniqueHelper>;2648 collection: CollectionGroup;2649 nft: NFTGroup;2650 rft: RFTGroup;2651 ft: FTGroup;2652 staking: StakingGroup;2653 scheduler: SchedulerGroup;2654 foreignAssets: ForeignAssetsGroup;2655 xcm: XcmGroup<UniqueHelper>;2656 xTokens: XTokensGroup<UniqueHelper>;2657 tokens: TokensGroup<UniqueHelper>;26582659 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2660 super(logger, options.helperBase ?? UniqueHelper);26612662 this.balance = new BalanceGroup(this);2663 this.collection = new CollectionGroup(this);2664 this.nft = new NFTGroup(this);2665 this.rft = new RFTGroup(this);2666 this.ft = new FTGroup(this);2667 this.staking = new StakingGroup(this);2668 this.scheduler = new SchedulerGroup(this);2669 this.foreignAssets = new ForeignAssetsGroup(this);2670 this.xcm = new XcmGroup(this, 'polkadotXcm');2671 this.xTokens = new XTokensGroup(this);2672 this.tokens = new TokensGroup(this);2673 }26742675 getSudo<T extends UniqueHelper>() {2676 2677 const SudoHelperType = SudoHelper(this.helperBase);2678 return this.clone(SudoHelperType) as T;2679 }2680}26812682export class XcmChainHelper extends ChainHelperBase {2683 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2684 const wsProvider = new WsProvider(wsEndpoint);2685 this.api = new ApiPromise({2686 provider: wsProvider,2687 });2688 await this.api.isReadyOrError;2689 this.network = await UniqueHelper.detectNetwork(this.api);2690 }2691}26922693export class RelayHelper extends XcmChainHelper {2694 xcm: XcmGroup<RelayHelper>;26952696 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2697 super(logger, options.helperBase ?? RelayHelper);26982699 this.xcm = new XcmGroup(this, 'xcmPallet');2700 }2701}27022703export class WestmintHelper extends XcmChainHelper {2704 balance: SubstrateBalanceGroup<WestmintHelper>;2705 xcm: XcmGroup<WestmintHelper>;2706 assets: AssetsGroup<WestmintHelper>;2707 xTokens: XTokensGroup<WestmintHelper>;27082709 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2710 super(logger, options.helperBase ?? WestmintHelper);27112712 this.balance = new SubstrateBalanceGroup(this);2713 this.xcm = new XcmGroup(this, 'polkadotXcm');2714 this.assets = new AssetsGroup(this);2715 this.xTokens = new XTokensGroup(this);2716 }2717}27182719export class MoonbeamHelper extends XcmChainHelper {2720 balance: EthereumBalanceGroup<MoonbeamHelper>;2721 assetManager: MoonbeamAssetManagerGroup;2722 assets: AssetsGroup<MoonbeamHelper>;2723 xTokens: XTokensGroup<MoonbeamHelper>;2724 democracy: MoonbeamDemocracyGroup;2725 collective: {2726 council: MoonbeamCollectiveGroup,2727 techCommittee: MoonbeamCollectiveGroup,2728 };27292730 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2731 super(logger, options.helperBase ?? MoonbeamHelper);27322733 this.balance = new EthereumBalanceGroup(this);2734 this.assetManager = new MoonbeamAssetManagerGroup(this);2735 this.assets = new AssetsGroup(this);2736 this.xTokens = new XTokensGroup(this);2737 this.democracy = new MoonbeamDemocracyGroup(this);2738 this.collective = {2739 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2740 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2741 };2742 }2743}27442745export class AcalaHelper extends XcmChainHelper {2746 balance: SubstrateBalanceGroup<AcalaHelper>;2747 assetRegistry: AcalaAssetRegistryGroup;2748 xTokens: XTokensGroup<AcalaHelper>;2749 tokens: TokensGroup<AcalaHelper>;27502751 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2752 super(logger, options.helperBase ?? AcalaHelper);27532754 this.balance = new SubstrateBalanceGroup(this);2755 this.assetRegistry = new AcalaAssetRegistryGroup(this);2756 this.xTokens = new XTokensGroup(this);2757 this.tokens = new TokensGroup(this);2758 }27592760 getSudo<T extends AcalaHelper>() {2761 2762 const SudoHelperType = SudoHelper(this.helperBase);2763 return this.clone(SudoHelperType) as T;2764 }2765}276627672768function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2769 return class extends Base {2770 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2771 scheduledId: string;2772 blocksNum: number;2773 options: ISchedulerOptions;27742775 constructor(...args: any[]) {2776 const logger = args[0] as ILogger;2777 const options = args[1] as {2778 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2779 scheduledId: string,2780 blocksNum: number,2781 options: ISchedulerOptions2782 };27832784 super(logger);27852786 this.scheduleFn = options.scheduleFn;2787 this.scheduledId = options.scheduledId;2788 this.blocksNum = options.blocksNum;2789 this.options = options.options;2790 }27912792 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2793 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2794 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27952796 return super.executeExtrinsic(2797 sender,2798 extrinsic,2799 [2800 this.scheduledId,2801 this.blocksNum,2802 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2803 this.options.priority ?? null,2804 {Value: scheduledTx},2805 ],2806 expectSuccess,2807 );2808 }2809 };2810}281128122813function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2814 return class extends Base {2815 constructor(...args: any[]) {2816 super(...args);2817 }28182819 executeExtrinsic (2820 sender: IKeyringPair,2821 extrinsic: string,2822 params: any[],2823 expectSuccess?: boolean,2824 ): Promise<ITransactionResult> {2825 const call = this.constructApiCall(extrinsic, params);28262827 return super.executeExtrinsic(2828 sender,2829 'api.tx.sudo.sudo',2830 [call],2831 expectSuccess,2832 );2833 }2834 };2835}28362837export class UniqueBaseCollection {2838 helper: UniqueHelper;2839 collectionId: number;28402841 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2842 this.collectionId = collectionId;2843 this.helper = uniqueHelper;2844 }28452846 async getData() {2847 return await this.helper.collection.getData(this.collectionId);2848 }28492850 async getLastTokenId() {2851 return await this.helper.collection.getLastTokenId(this.collectionId);2852 }28532854 async doesTokenExist(tokenId: number) {2855 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2856 }28572858 async getAdmins() {2859 return await this.helper.collection.getAdmins(this.collectionId);2860 }28612862 async getAllowList() {2863 return await this.helper.collection.getAllowList(this.collectionId);2864 }28652866 async getEffectiveLimits() {2867 return await this.helper.collection.getEffectiveLimits(this.collectionId);2868 }28692870 async getProperties(propertyKeys?: string[] | null) {2871 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2872 }28732874 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2875 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2876 }28772878 async getOptions() {2879 return await this.helper.collection.getCollectionOptions(this.collectionId);2880 }28812882 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2883 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2884 }28852886 async confirmSponsorship(signer: TSigner) {2887 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2888 }28892890 async removeSponsor(signer: TSigner) {2891 return await this.helper.collection.removeSponsor(signer, this.collectionId);2892 }28932894 async setLimits(signer: TSigner, limits: ICollectionLimits) {2895 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2896 }28972898 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2899 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2900 }29012902 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2903 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2904 }29052906 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2907 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2908 }29092910 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2911 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2912 }29132914 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2915 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2916 }29172918 async setProperties(signer: TSigner, properties: IProperty[]) {2919 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2920 }29212922 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2923 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2924 }29252926 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2927 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2928 }29292930 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2931 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2932 }29332934 async disableNesting(signer: TSigner) {2935 return await this.helper.collection.disableNesting(signer, this.collectionId);2936 }29372938 async burn(signer: TSigner) {2939 return await this.helper.collection.burn(signer, this.collectionId);2940 }29412942 scheduleAt<T extends UniqueHelper>(2943 scheduledId: string,2944 executionBlockNumber: number,2945 options: ISchedulerOptions = {},2946 ) {2947 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2948 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2949 }29502951 scheduleAfter<T extends UniqueHelper>(2952 scheduledId: string,2953 blocksBeforeExecution: number,2954 options: ISchedulerOptions = {},2955 ) {2956 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2957 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2958 }29592960 getSudo<T extends UniqueHelper>() {2961 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2962 }2963}296429652966export class UniqueNFTCollection extends UniqueBaseCollection {2967 getTokenObject(tokenId: number) {2968 return new UniqueNFToken(tokenId, this);2969 }29702971 async getTokensByAddress(addressObj: ICrossAccountId) {2972 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2973 }29742975 async getToken(tokenId: number, blockHashAt?: string) {2976 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2977 }29782979 async getTokenOwner(tokenId: number, blockHashAt?: string) {2980 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2981 }29822983 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2984 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2985 }29862987 async getTokenChildren(tokenId: number, blockHashAt?: string) {2988 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2989 }29902991 async getPropertyPermissions(propertyKeys: string[] | null = null) {2992 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2993 }29942995 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2996 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2997 }29982999 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3000 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3001 }30023003 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3004 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3005 }30063007 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3008 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3009 }30103011 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3012 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3013 }30143015 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3016 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3017 }30183019 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3020 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3021 }30223023 async burnToken(signer: TSigner, tokenId: number) {3024 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3025 }30263027 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3028 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3029 }30303031 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3032 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3033 }30343035 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3036 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3037 }30383039 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3040 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3041 }30423043 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3044 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3045 }30463047 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3048 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3049 }30503051 scheduleAt<T extends UniqueHelper>(3052 scheduledId: string,3053 executionBlockNumber: number,3054 options: ISchedulerOptions = {},3055 ) {3056 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3057 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3058 }30593060 scheduleAfter<T extends UniqueHelper>(3061 scheduledId: string,3062 blocksBeforeExecution: number,3063 options: ISchedulerOptions = {},3064 ) {3065 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3066 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3067 }30683069 getSudo<T extends UniqueHelper>() {3070 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3071 }3072}307330743075export class UniqueRFTCollection extends UniqueBaseCollection {3076 getTokenObject(tokenId: number) {3077 return new UniqueRFToken(tokenId, this);3078 }30793080 async getToken(tokenId: number, blockHashAt?: string) {3081 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3082 }30833084 async getTokensByAddress(addressObj: ICrossAccountId) {3085 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3086 }30873088 async getTop10TokenOwners(tokenId: number) {3089 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3090 }30913092 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3093 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3094 }30953096 async getTokenTotalPieces(tokenId: number) {3097 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3098 }30993100 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3101 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3102 }31033104 async getPropertyPermissions(propertyKeys: string[] | null = null) {3105 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3106 }31073108 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3109 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3110 }31113112 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3113 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3114 }31153116 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3117 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3118 }31193120 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3121 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3122 }31233124 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3125 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3126 }31273128 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3129 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3130 }31313132 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3133 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3134 }31353136 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3137 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3138 }31393140 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3141 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3142 }31433144 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3145 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3146 }31473148 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3149 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3150 }31513152 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3153 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3154 }31553156 scheduleAt<T extends UniqueHelper>(3157 scheduledId: string,3158 executionBlockNumber: number,3159 options: ISchedulerOptions = {},3160 ) {3161 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3162 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3163 }31643165 scheduleAfter<T extends UniqueHelper>(3166 scheduledId: string,3167 blocksBeforeExecution: number,3168 options: ISchedulerOptions = {},3169 ) {3170 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3171 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3172 }31733174 getSudo<T extends UniqueHelper>() {3175 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3176 }3177}317831793180export class UniqueFTCollection extends UniqueBaseCollection {3181 async getBalance(addressObj: ICrossAccountId) {3182 return await this.helper.ft.getBalance(this.collectionId, addressObj);3183 }31843185 async getTotalPieces() {3186 return await this.helper.ft.getTotalPieces(this.collectionId);3187 }31883189 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3190 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3191 }31923193 async getTop10Owners() {3194 return await this.helper.ft.getTop10Owners(this.collectionId);3195 }31963197 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3198 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3199 }32003201 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3202 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3203 }32043205 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3206 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3207 }32083209 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3210 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3211 }32123213 async burnTokens(signer: TSigner, amount=1n) {3214 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3215 }32163217 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3218 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3219 }32203221 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3222 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3223 }32243225 scheduleAt<T extends UniqueHelper>(3226 scheduledId: string,3227 executionBlockNumber: number,3228 options: ISchedulerOptions = {},3229 ) {3230 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3231 return new UniqueFTCollection(this.collectionId, scheduledHelper);3232 }32333234 scheduleAfter<T extends UniqueHelper>(3235 scheduledId: string,3236 blocksBeforeExecution: number,3237 options: ISchedulerOptions = {},3238 ) {3239 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3240 return new UniqueFTCollection(this.collectionId, scheduledHelper);3241 }32423243 getSudo<T extends UniqueHelper>() {3244 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3245 }3246}324732483249export class UniqueBaseToken {3250 collection: UniqueNFTCollection | UniqueRFTCollection;3251 collectionId: number;3252 tokenId: number;32533254 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3255 this.collection = collection;3256 this.collectionId = collection.collectionId;3257 this.tokenId = tokenId;3258 }32593260 async getNextSponsored(addressObj: ICrossAccountId) {3261 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3262 }32633264 async getProperties(propertyKeys?: string[] | null) {3265 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3266 }32673268 async setProperties(signer: TSigner, properties: IProperty[]) {3269 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3270 }32713272 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3273 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3274 }32753276 async doesExist() {3277 return await this.collection.doesTokenExist(this.tokenId);3278 }32793280 nestingAccount() {3281 return this.collection.helper.util.getTokenAccount(this);3282 }32833284 scheduleAt<T extends UniqueHelper>(3285 scheduledId: string,3286 executionBlockNumber: number,3287 options: ISchedulerOptions = {},3288 ) {3289 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3290 return new UniqueBaseToken(this.tokenId, scheduledCollection);3291 }32923293 scheduleAfter<T extends UniqueHelper>(3294 scheduledId: string,3295 blocksBeforeExecution: number,3296 options: ISchedulerOptions = {},3297 ) {3298 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3299 return new UniqueBaseToken(this.tokenId, scheduledCollection);3300 }33013302 getSudo<T extends UniqueHelper>() {3303 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3304 }3305}330633073308export class UniqueNFToken extends UniqueBaseToken {3309 collection: UniqueNFTCollection;33103311 constructor(tokenId: number, collection: UniqueNFTCollection) {3312 super(tokenId, collection);3313 this.collection = collection;3314 }33153316 async getData(blockHashAt?: string) {3317 return await this.collection.getToken(this.tokenId, blockHashAt);3318 }33193320 async getOwner(blockHashAt?: string) {3321 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3322 }33233324 async getTopmostOwner(blockHashAt?: string) {3325 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3326 }33273328 async getChildren(blockHashAt?: string) {3329 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3330 }33313332 async nest(signer: TSigner, toTokenObj: IToken) {3333 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3334 }33353336 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3337 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3338 }33393340 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3341 return await this.collection.transferToken(signer, this.tokenId, addressObj);3342 }33433344 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3345 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3346 }33473348 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3349 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3350 }33513352 async isApproved(toAddressObj: ICrossAccountId) {3353 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3354 }33553356 async burn(signer: TSigner) {3357 return await this.collection.burnToken(signer, this.tokenId);3358 }33593360 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3361 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3362 }33633364 scheduleAt<T extends UniqueHelper>(3365 scheduledId: string,3366 executionBlockNumber: number,3367 options: ISchedulerOptions = {},3368 ) {3369 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3370 return new UniqueNFToken(this.tokenId, scheduledCollection);3371 }33723373 scheduleAfter<T extends UniqueHelper>(3374 scheduledId: string,3375 blocksBeforeExecution: number,3376 options: ISchedulerOptions = {},3377 ) {3378 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3379 return new UniqueNFToken(this.tokenId, scheduledCollection);3380 }33813382 getSudo<T extends UniqueHelper>() {3383 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3384 }3385}33863387export class UniqueRFToken extends UniqueBaseToken {3388 collection: UniqueRFTCollection;33893390 constructor(tokenId: number, collection: UniqueRFTCollection) {3391 super(tokenId, collection);3392 this.collection = collection;3393 }33943395 async getData(blockHashAt?: string) {3396 return await this.collection.getToken(this.tokenId, blockHashAt);3397 }33983399 async getTop10Owners() {3400 return await this.collection.getTop10TokenOwners(this.tokenId);3401 }34023403 async getBalance(addressObj: ICrossAccountId) {3404 return await this.collection.getTokenBalance(this.tokenId, addressObj);3405 }34063407 async getTotalPieces() {3408 return await this.collection.getTokenTotalPieces(this.tokenId);3409 }34103411 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3412 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3413 }34143415 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3416 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3417 }34183419 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3420 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3421 }34223423 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3424 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3425 }34263427 async repartition(signer: TSigner, amount: bigint) {3428 return await this.collection.repartitionToken(signer, this.tokenId, amount);3429 }34303431 async burn(signer: TSigner, amount=1n) {3432 return await this.collection.burnToken(signer, this.tokenId, amount);3433 }34343435 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3436 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3437 }34383439 scheduleAt<T extends UniqueHelper>(3440 scheduledId: string,3441 executionBlockNumber: number,3442 options: ISchedulerOptions = {},3443 ) {3444 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3445 return new UniqueRFToken(this.tokenId, scheduledCollection);3446 }34473448 scheduleAfter<T extends UniqueHelper>(3449 scheduledId: string,3450 blocksBeforeExecution: number,3451 options: ISchedulerOptions = {},3452 ) {3453 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3454 return new UniqueRFToken(this.tokenId, scheduledCollection);3455 }34563457 getSudo<T extends UniqueHelper>() {3458 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3459 }3460}