12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255256 static bigIntToDecimals(number: bigint, decimals = 18) {257 const numberStr = number.toString();258 const dotPos = numberStr.length - decimals;259 260 if (dotPos <= 0) {261 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262 } else {263 const intPart = numberStr.substring(0, dotPos);264 const fractPart = numberStr.substring(dotPos);265 return intPart + '.' + fractPart;266 }267 }268}269270class UniqueEventHelper {271 private static extractIndex(index: any): [number, number] | string {272 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273 return index.toJSON();274 }275276 private static extractSub(data: any, subTypes: any): {[key: string]: any} {277 let obj: any = {};278 let index = 0;279280 if (data.entries) {281 for(const [key, value] of data.entries()) {282 obj[key] = this.extractData(value, subTypes[index]);283 index++;284 }285 } else obj = data.toJSON();286287 return obj;288 }289 290 private static extractData(data: any, type: any): any {291 if(!type) return data.toHuman();292 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295 return data.toHuman();296 }297298 public static extractEvents(records: ITransactionResult): IEvent[] {299 const parsedEvents: IEvent[] = [];300301 records.result.events.forEach((record) => {302 const {event, phase} = record;303 const types = (event as any).typeDef;304305 const eventData: IEvent = {306 section: event.section.toString(),307 method: event.method.toString(),308 index: this.extractIndex(event.index),309 data: [],310 phase: phase.toJSON(),311 };312313 event.data.forEach((val: any, index: number) => {314 eventData.data.push(this.extractData(val, types[index]));315 });316317 parsedEvents.push(eventData);318 });319320 return parsedEvents;321 }322}323324export class ChainHelperBase {325 helperBase: any;326327 transactionStatus = UniqueUtil.transactionStatus;328 chainLogType = UniqueUtil.chainLogType;329 util: typeof UniqueUtil;330 eventHelper: typeof UniqueEventHelper;331 logger: ILogger;332 api: ApiPromise | null;333 forcedNetwork: TNetworks | null;334 network: TNetworks | null;335 chainLog: IUniqueHelperLog[];336 children: ChainHelperBase[];337 address: AddressGroup;338 chain: ChainGroup;339340 constructor(logger?: ILogger, helperBase?: any) {341 this.helperBase = helperBase;342343 this.util = UniqueUtil;344 this.eventHelper = UniqueEventHelper;345 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346 this.logger = logger;347 this.api = null;348 this.forcedNetwork = null;349 this.network = null;350 this.chainLog = [];351 this.children = [];352 this.address = new AddressGroup(this);353 this.chain = new ChainGroup(this);354 }355356 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357 Object.setPrototypeOf(helperCls.prototype, this);358 const newHelper = new helperCls(this.logger, options);359360 newHelper.api = this.api;361 newHelper.network = this.network;362 newHelper.forceNetwork = this.forceNetwork;363364 this.children.push(newHelper);365366 return newHelper;367 }368369 getApi(): ApiPromise {370 if(this.api === null) throw Error('API not initialized');371 return this.api;372 }373374 clearChainLog(): void {375 this.chainLog = [];376 }377378 forceNetwork(value: TNetworks): void {379 this.forcedNetwork = value;380 }381382 async connect(wsEndpoint: string, listeners?: IApiListeners) {383 if (this.api !== null) throw Error('Already connected');384 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385 this.api = api;386 this.network = network;387 }388389 async disconnect() {390 for (const child of this.children) {391 child.clearApi();392 }393394 if (this.api === null) return;395 await this.api.disconnect();396 this.clearApi();397 }398399 clearApi() {400 this.api = null;401 this.network = null;402 }403404 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411 return 'opal';412 }413414 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416 await api.isReady;417418 const network = await this.detectNetwork(api);419420 await api.disconnect();421422 return network;423 }424425 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426 api: ApiPromise;427 network: TNetworks;428 }> {429 console.log('createConnection network = ', network);430 if(typeof network === 'undefined' || network === null) network = 'opal';431 const supportedRPC = {432 opal: {433 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,434 },435 quartz: {436 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,437 },438 unique: {439 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,440 },441 rococo: {},442 westend: {},443 moonbeam: {},444 moonriver: {},445 acala: {},446 karura: {},447 westmint: {},448 };449 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);450 const rpc = supportedRPC[network];451452 453 454455 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});456457 await api.isReadyOrError;458459 if (typeof listeners === 'undefined') listeners = {};460 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {461 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;462 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);463 }464465 return {api, network};466 }467468 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {469 const {events, status} = data;470 if (status.isReady) {471 return this.transactionStatus.NOT_READY;472 }473 if (status.isBroadcast) {474 return this.transactionStatus.NOT_READY;475 }476 if (status.isInBlock || status.isFinalized) {477 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');478 if (errors.length > 0) {479 return this.transactionStatus.FAIL;480 }481 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {482 return this.transactionStatus.SUCCESS;483 }484 }485486 return this.transactionStatus.FAIL;487 }488489 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {490 const sign = (callback: any) => {491 if(options !== null) return transaction.signAndSend(sender, options, callback);492 return transaction.signAndSend(sender, callback);493 };494 495 return new Promise(async (resolve, reject) => {496 try {497 const unsub = await sign((result: any) => {498 const status = this.getTransactionStatus(result);499500 if (status === this.transactionStatus.SUCCESS) {501 this.logger.log(`${label} successful`);502 unsub();503 resolve({result, status});504 } else if (status === this.transactionStatus.FAIL) {505 let moduleError = null;506507 if (result.hasOwnProperty('dispatchError')) {508 const dispatchError = result['dispatchError'];509510 if (dispatchError) {511 if (dispatchError.isModule) {512 const modErr = dispatchError.asModule;513 const errorMeta = dispatchError.registry.findMetaError(modErr);514515 moduleError = `${errorMeta.section}.${errorMeta.name}`;516 } else {517 moduleError = dispatchError.toHuman();518 }519 } else {520 this.logger.log(result, this.logger.level.ERROR);521 }522 }523524 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);525 unsub();526 reject({status, moduleError, result});527 }528 });529 } catch (e) {530 this.logger.log(e, this.logger.level.ERROR);531 reject(e);532 }533 });534 }535536 constructApiCall(apiCall: string, params: any[]) {537 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);538 let call = this.getApi() as any;539 for(const part of apiCall.slice(4).split('.')) {540 call = call[part];541 }542 return call(...params);543 }544545 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {546 if(this.api === null) throw Error('API not initialized');547 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);548549 const startTime = (new Date()).getTime();550 let result: ITransactionResult;551 let events: IEvent[] = [];552 try {553 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;554 events = this.eventHelper.extractEvents(result);555 }556 catch(e) {557 if(!(e as object).hasOwnProperty('status')) throw e;558 result = e as ITransactionResult;559 }560561 const endTime = (new Date()).getTime();562563 const log = {564 executedAt: endTime,565 executionTime: endTime - startTime,566 type: this.chainLogType.EXTRINSIC,567 status: result.status,568 call: extrinsic,569 signer: this.getSignerAddress(sender),570 params,571 } as IUniqueHelperLog;572573 if(result.status !== this.transactionStatus.SUCCESS) {574 if (result.moduleError) log.moduleError = result.moduleError;575 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;576 }577 if(events.length > 0) log.events = events;578579 this.chainLog.push(log);580581 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {582 if (result.moduleError) throw Error(`${result.moduleError}`);583 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));584 }585 return result;586 }587588 async callRpc(rpc: string, params?: any[]) {589 if(typeof params === 'undefined') params = [];590 if(this.api === null) throw Error('API not initialized');591 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);592593 const startTime = (new Date()).getTime();594 let result;595 let error = null;596 const log = {597 type: this.chainLogType.RPC,598 call: rpc,599 params,600 } as IUniqueHelperLog;601602 try {603 result = await this.constructApiCall(rpc, params);604 }605 catch(e) {606 error = e;607 }608609 const endTime = (new Date()).getTime();610611 log.executedAt = endTime;612 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';613 log.executionTime = endTime - startTime;614615 this.chainLog.push(log);616617 if(error !== null) throw error;618619 return result;620 }621622 getSignerAddress(signer: IKeyringPair | string): string {623 if(typeof signer === 'string') return signer;624 return signer.address;625 }626627 fetchAllPalletNames(): string[] {628 if(this.api === null) throw Error('API not initialized');629 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());630 }631632 fetchMissingPalletNames(requiredPallets: string[]): string[] {633 const palletNames = this.fetchAllPalletNames();634 return requiredPallets.filter(p => !palletNames.includes(p));635 }636}637638639class HelperGroup<T extends ChainHelperBase> {640 helper: T;641642 constructor(uniqueHelper: T) {643 this.helper = uniqueHelper;644 }645}646647648class CollectionGroup extends HelperGroup<UniqueHelper> {649 650651652653654655656657658 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {659 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();660 }661662 663664665666667 async getTotalCount(): Promise<number> {668 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();669 }670671 672673674675676677678679680 async getData(collectionId: number): Promise<{681 id: number;682 name: string;683 description: string;684 tokensCount: number;685 admins: CrossAccountId[];686 normalizedOwner: TSubstrateAccount;687 raw: any688 } | null> {689 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);690 const humanCollection = collection.toHuman(), collectionData = {691 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],692 raw: humanCollection,693 } as any, jsonCollection = collection.toJSON();694 if (humanCollection === null) return null;695 collectionData.raw.limits = jsonCollection.limits;696 collectionData.raw.permissions = jsonCollection.permissions;697 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);698 for (const key of ['name', 'description']) {699 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);700 }701702 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))703 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)704 : 0;705 collectionData.admins = await this.getAdmins(collectionId);706707 return collectionData;708 }709710 711712713714715716717718 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {719 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();720721 return normalize722 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())723 : admins;724 }725726 727728729730731732733 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {734 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();735 return normalize736 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())737 : allowListed;738 }739740 741742743744745746747 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {748 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();749 }750751 752753754755756757758759 async burn(signer: TSigner, collectionId: number): Promise<boolean> {760 const result = await this.helper.executeExtrinsic(761 signer,762 'api.tx.unique.destroyCollection', [collectionId],763 true,764 );765766 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');767 }768769 770771772773774775776777778 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {779 const result = await this.helper.executeExtrinsic(780 signer,781 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],782 true,783 );784785 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');786 }787788 789790791792793794795796 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {797 const result = await this.helper.executeExtrinsic(798 signer,799 'api.tx.unique.confirmSponsorship', [collectionId],800 true,801 );802803 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');804 }805806 807808809810811812813814 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {815 const result = await this.helper.executeExtrinsic(816 signer,817 'api.tx.unique.removeCollectionSponsor', [collectionId],818 true,819 );820821 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');822 }823824 825826827828829830831832833834835836837838839840841 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {842 const result = await this.helper.executeExtrinsic(843 signer,844 'api.tx.unique.setCollectionLimits', [collectionId, limits],845 true,846 );847848 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');849 }850851 852853854855856857858859860 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],864 true,865 );866867 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');868 }869870 871872873874875876877878879 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {880 const result = await this.helper.executeExtrinsic(881 signer,882 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],883 true,884 );885886 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');887 }888889 890891892893894895896897898 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {899 const result = await this.helper.executeExtrinsic(900 signer,901 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],902 true,903 );904905 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');906 }907908 909910911912913914915916 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {917 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();918 }919920 921922923924925926927 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {928 const result = await this.helper.executeExtrinsic(929 signer,930 'api.tx.unique.addToAllowList', [collectionId, addressObj],931 true,932 );933934 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');935 }936937 938939940941942943944945 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {946 const result = await this.helper.executeExtrinsic(947 signer,948 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],949 true,950 );951952 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');953 }954955 956957958959960961962963964 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {965 const result = await this.helper.executeExtrinsic(966 signer,967 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],968 true,969 );970971 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');972 }973974 975976977978979980981982983 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {984 return await this.setPermissions(signer, collectionId, {nesting: permissions});985 }986987 988989990991992993994995 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {996 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});997 }998999 100010011002100310041005100610071008 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1009 const result = await this.helper.executeExtrinsic(1010 signer,1011 'api.tx.unique.setCollectionProperties', [collectionId, properties],1012 true,1013 );10141015 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1016 }10171018 10191020102110221023102410251026 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1027 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1028 }10291030 103110321033103410351036103710381039 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1040 const result = await this.helper.executeExtrinsic(1041 signer,1042 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1043 true,1044 );10451046 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1047 }10481049 10501051105210531054105510561057105810591060 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1061 const result = await this.helper.executeExtrinsic(1062 signer,1063 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1064 true, 1065 );10661067 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1068 }10691070 1071107210731074107510761077107810791080108110821083 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1084 const result = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1087 true, 1088 );1089 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1090 }10911092 10931094109510961097109810991100110111021103 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1104 const burnResult = await this.helper.executeExtrinsic(1105 signer,1106 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1107 true, 1108 );1109 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1110 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1111 return burnedTokens.success;1112 }11131114 11151116111711181119112011211122112311241125 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1126 const burnResult = await this.helper.executeExtrinsic(1127 signer,1128 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1129 true, 1130 );1131 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1132 return burnedTokens.success && burnedTokens.tokens.length > 0;1133 }11341135 1136113711381139114011411142114311441145 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1146 const approveResult = await this.helper.executeExtrinsic(1147 signer,1148 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1149 true, 1150 );11511152 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1153 }11541155 1156115711581159116011611162116311641165 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1166 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1167 }11681169 1170117111721173117411751176 async getLastTokenId(collectionId: number): Promise<number> {1177 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1178 }11791180 11811182118311841185118611871188 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1189 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1190 }1191}11921193class NFTnRFT extends CollectionGroup {1194 11951196119711981199120012011202 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1203 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1204 }12051206 1207120812091210121112121213121412151216 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1217 properties: IProperty[];1218 owner: CrossAccountId;1219 normalizedOwner: CrossAccountId;1220 }| null> {1221 let tokenData;1222 if(typeof blockHashAt === 'undefined') {1223 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1224 }1225 else {1226 if(propertyKeys.length == 0) {1227 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1228 if(!collection) return null;1229 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1230 }1231 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1232 }1233 tokenData = tokenData.toHuman();1234 if (tokenData === null || tokenData.owner === null) return null;1235 const owner = {} as any;1236 for (const key of Object.keys(tokenData.owner)) {1237 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1238 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1239 : tokenData.owner[key];1240 }1241 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1242 return tokenData;1243 }12441245 12461247124812491250125112521253125412551256 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1257 const result = await this.helper.executeExtrinsic(1258 signer,1259 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1260 true,1261 );12621263 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1264 }12651266 12671268126912701271127212731274 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1275 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1276 }12771278 1279128012811282128312841285128612871288 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1289 const result = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1292 true,1293 );12941295 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1296 }12971298 129913001301130213031304130513061307 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1308 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1309 }13101311 131213131314131513161317131813191320 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1321 const result = await this.helper.executeExtrinsic(1322 signer,1323 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1324 true,1325 );13261327 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1328 }13291330 133113321333133413351336133713381339 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1340 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1341 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1342 for (const key of ['name', 'description', 'tokenPrefix']) {1343 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);1344 }1345 const creationResult = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.createCollectionEx', [collectionOptions],1348 true, 1349 );1350 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1351 }13521353 getCollectionObject(_collectionId: number): any {1354 return null;1355 }13561357 getTokenObject(_collectionId: number, _tokenId: number): any {1358 return null;1359 }1360}136113621363class NFTGroup extends NFTnRFT {1364 136513661367136813691370 getCollectionObject(collectionId: number): UniqueNFTCollection {1371 return new UniqueNFTCollection(collectionId, this.helper);1372 }13731374 1375137613771378137913801381 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1382 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1383 }13841385 13861387138813891390139113921393 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1394 let owner;1395 if (typeof blockHashAt === 'undefined') {1396 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1397 } else {1398 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1399 }1400 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1401 }14021403 1404140514061407140814091410 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1411 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1412 }14131414 1415141614171418141914201421142214231424 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1425 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1426 }14271428 142914301431143214331434143514361437143814391440 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1441 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1442 }14431444 14451446144714481449145014511452 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1453 let owner;1454 if (typeof blockHashAt === 'undefined') {1455 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1456 } else {1457 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1458 }14591460 if (owner === null) return null;14611462 return owner.toHuman();1463 }14641465 14661467146814691470147114721473 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1474 let children;1475 if(typeof blockHashAt === 'undefined') {1476 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1477 } else {1478 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1479 }14801481 return children.toJSON().map((x: any) => {1482 return {collectionId: x.collection, tokenId: x.token};1483 });1484 }14851486 14871488148914901491149214931494 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1495 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1496 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1497 if(!result) {1498 throw Error('Unable to nest token!');1499 }1500 return result;1501 }15021503 150415051506150715081509151015111512 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1513 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1514 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1515 if(!result) {1516 throw Error('Unable to unnest token!');1517 }1518 return result;1519 }15201521 152215231524152515261527152815291530153115321533 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1534 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1535 }15361537 153815391540154115421543 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1544 const creationResult = await this.helper.executeExtrinsic(1545 signer,1546 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1547 nft: {1548 properties: data.properties,1549 },1550 }],1551 true,1552 );1553 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1554 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1555 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1556 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1557 }15581559 156015611562156315641565156615671568156915701571157215731574 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1575 const creationResult = await this.helper.executeExtrinsic(1576 signer,1577 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1578 true,1579 );1580 const collection = this.getCollectionObject(collectionId);1581 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1582 }15831584 158515861587158815891590159115921593159415951596159715981599160016011602 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1603 const rawTokens = [];1604 for (const token of tokens) {1605 const raw = {NFT: {properties: token.properties}};1606 rawTokens.push(raw);1607 }1608 const creationResult = await this.helper.executeExtrinsic(1609 signer,1610 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1611 true,1612 );1613 const collection = this.getCollectionObject(collectionId);1614 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1615 }16161617 1618161916201621162216231624162516261627 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1628 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1629 }1630}163116321633class RFTGroup extends NFTnRFT {1634 163516361637163816391640 getCollectionObject(collectionId: number): UniqueRFTCollection {1641 return new UniqueRFTCollection(collectionId, this.helper);1642 }16431644 1645164616471648164916501651 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1652 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1653 }16541655 1656165716581659166016611662 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1663 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1664 }16651666 16671668166916701671167216731674 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1675 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1676 }16771678 1679168016811682168316841685168616871688 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1689 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1690 }16911692 16931694169516961697169816991700170117021703 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1704 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1705 }17061707 170817091710171117121713171417151716171717181719 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1720 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1721 }17221723 1724172517261727172817291730 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1731 const creationResult = await this.helper.executeExtrinsic(1732 signer,1733 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1734 refungible: {1735 pieces: data.pieces,1736 properties: data.properties,1737 },1738 }],1739 true,1740 );1741 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1742 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1743 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1744 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1745 }17461747 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1748 throw Error('Not implemented');1749 const creationResult = await this.helper.executeExtrinsic(1750 signer,1751 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1752 true, 1753 );1754 const collection = this.getCollectionObject(collectionId);1755 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1756 }17571758 175917601761176217631764176517661767 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1768 const rawTokens = [];1769 for (const token of tokens) {1770 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1771 rawTokens.push(raw);1772 }1773 const creationResult = await this.helper.executeExtrinsic(1774 signer,1775 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1776 true,1777 );1778 const collection = this.getCollectionObject(collectionId);1779 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1780 }17811782 178317841785178617871788178917901791 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1792 return await super.burnToken(signer, collectionId, tokenId, amount);1793 }17941795 1796179717981799180018011802180318041805 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1806 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1807 }18081809 18101811181218131814181518161817181818191820 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1821 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1822 }18231824 1825182618271828182918301831 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1832 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1833 }18341835 183618371838183918401841184218431844 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1845 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1846 const repartitionResult = await this.helper.executeExtrinsic(1847 signer,1848 'api.tx.unique.repartition', [collectionId, tokenId, amount],1849 true,1850 );1851 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1852 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1853 }1854}185518561857class FTGroup extends CollectionGroup {1858 185918601861186218631864 getCollectionObject(collectionId: number): UniqueFTCollection {1865 return new UniqueFTCollection(collectionId, this.helper);1866 }18671868 1869187018711872187318741875187618771878187918801881 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1882 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1883 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1884 collectionOptions.mode = {fungible: decimalPoints};1885 for (const key of ['name', 'description', 'tokenPrefix']) {1886 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);1887 }1888 const creationResult = await this.helper.executeExtrinsic(1889 signer,1890 'api.tx.unique.createCollectionEx', [collectionOptions],1891 true,1892 );1893 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1894 }18951896 189718981899190019011902190319041905 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1906 const creationResult = await this.helper.executeExtrinsic(1907 signer,1908 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1909 fungible: {1910 value: amount,1911 },1912 }],1913 true, 1914 );1915 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1916 }19171918 19191920192119221923192419251926 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1927 const rawTokens = [];1928 for (const token of tokens) {1929 const raw = {Fungible: {Value: token.value}};1930 rawTokens.push(raw);1931 }1932 const creationResult = await this.helper.executeExtrinsic(1933 signer,1934 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1935 true,1936 );1937 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1938 }19391940 194119421943194419451946 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1947 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1948 }19491950 1951195219531954195519561957 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1958 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1959 }19601961 196219631964196519661967196819691970 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1971 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1972 }19731974 1975197619771978197919801981198219831984 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1985 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1986 }19871988 19891990199119921993199419951996 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1997 return await super.burnToken(signer, collectionId, 0, amount);1998 }19992000 200120022003200420052006200720082009 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2010 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2011 }20122013 20142015201620172018 async getTotalPieces(collectionId: number): Promise<bigint> {2019 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2020 }20212022 2023202420252026202720282029203020312032 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2033 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2034 }20352036 2037203820392040204120422043 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2044 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2045 }2046}204720482049class ChainGroup extends HelperGroup<ChainHelperBase> {2050 20512052205320542055 getChainProperties(): IChainProperties {2056 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2057 return {2058 ss58Format: properties.ss58Format.toJSON(),2059 tokenDecimals: properties.tokenDecimals.toJSON(),2060 tokenSymbol: properties.tokenSymbol.toJSON(),2061 };2062 }20632064 20652066206720682069 async getLatestBlockNumber(): Promise<number> {2070 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2071 }20722073 207420752076207720782079 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2080 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2081 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2082 return blockHash;2083 }20842085 2086 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2087 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2088 if (!blockHash) return null;2089 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2090 }20912092 209320942095209620972098 async getNonce(address: TSubstrateAccount): Promise<number> {2099 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2100 }2101}21022103class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2104 210521062107210821092110 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2111 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2112 }21132114 21152116211721182119212021212122 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2123 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21242125 let transfer = {from: null, to: null, amount: 0n} as any;2126 result.result.events.forEach(({event: {data, method, section}}) => {2127 if ((section === 'balances') && (method === 'Transfer')) {2128 transfer = {2129 from: this.helper.address.normalizeSubstrate(data[0]),2130 to: this.helper.address.normalizeSubstrate(data[1]),2131 amount: BigInt(data[2]),2132 };2133 }2134 });2135 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2136 && this.helper.address.normalizeSubstrate(address) === transfer.to 2137 && BigInt(amount) === transfer.amount;2138 return isSuccess;2139 }21402141 21422143214421452146 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2147 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2148 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2149 }2150}21512152class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2153 215421552156215721582159 async getEthereum(address: TEthereumAccount): Promise<bigint> {2160 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2161 }21622163 21642165216621672168216921702171 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2172 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21732174 let transfer = {from: null, to: null, amount: 0n} as any;2175 result.result.events.forEach(({event: {data, method, section}}) => {2176 if ((section === 'balances') && (method === 'Transfer')) {2177 transfer = {2178 from: data[0].toString(),2179 to: data[1].toString(),2180 amount: BigInt(data[2]),2181 };2182 }2183 });2184 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2185 && address === transfer.to 2186 && BigInt(amount) === transfer.amount;2187 return isSuccess;2188 }2189}21902191class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2192 subBalanceGroup: SubstrateBalanceGroup<T>;2193 ethBalanceGroup: EthereumBalanceGroup<T>;21942195 constructor(helper: T) {2196 super(helper);2197 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2198 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2199 }22002201 getCollectionCreationPrice(): bigint {2202 return 2n * this.getOneTokenNominal();2203 }2204 22052206220722082209 getOneTokenNominal(): bigint {2210 const chainProperties = this.helper.chain.getChainProperties();2211 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2212 }22132214 221522162217221822192220 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2221 return this.subBalanceGroup.getSubstrate(address);2222 }22232224 22252226222722282229 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2230 return this.subBalanceGroup.getSubstrateFull(address);2231 }22322233 223422352236223722382239 async getEthereum(address: TEthereumAccount): Promise<bigint> {2240 return this.ethBalanceGroup.getEthereum(address);2241 }22422243 22442245224622472248224922502251 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2252 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2253 }2254}22552256class AddressGroup extends HelperGroup<ChainHelperBase> {2257 2258225922602261226222632264 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2265 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2266 }22672268 226922702271227222732274 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2275 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2276 }22772278 2279228022812282228322842285 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2286 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2287 }22882289 229022912292229322942295 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2296 return CrossAccountId.translateSubToEth(subAddress);2297 }22982299 paraSiblingSovereignAccount(paraid: number) {2300 2301 2302 const siblingPrefix = '0x7369626c';23032304 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2305 const suffix = '000000000000000000000000000000000000000000000000';23062307 return siblingPrefix + encodedParaId + suffix;2308 }2309}23102311class StakingGroup extends HelperGroup<UniqueHelper> {2312 2313231423152316231723182319 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2320 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2321 const _stakeResult = await this.helper.executeExtrinsic(2322 signer, 'api.tx.appPromotion.stake',2323 [amountToStake], true,2324 );2325 2326 return true;2327 }23282329 2330233123322333233423352336 async unstake(signer: TSigner, label?: string): Promise<number> {2337 if(typeof label === 'undefined') label = `${signer.address}`;2338 const _unstakeResult = await this.helper.executeExtrinsic(2339 signer, 'api.tx.appPromotion.unstake',2340 [], true,2341 );2342 2343 return 1;2344 }23452346 23472348234923502351 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2352 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2353 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2354 }23552356 23572358235923602361 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2362 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2363 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2364 return { 2365 block: block.toBigInt(),2366 amount: amount.toBigInt(),2367 };2368 });2369 }23702371 23722373237423752376 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2377 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2378 }23792380 23812382238323842385 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2386 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2387 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2388 return {2389 block: block.toBigInt(),2390 amount: amount.toBigInt(),2391 };2392 });2393 return result;2394 }2395}23962397class SchedulerGroup extends HelperGroup<UniqueHelper> {2398 constructor(helper: UniqueHelper) {2399 super(helper);2400 }24012402 async cancelScheduled(signer: TSigner, scheduledId: string) {2403 return this.helper.executeExtrinsic(2404 signer,2405 'api.tx.scheduler.cancelNamed',2406 [scheduledId],2407 true,2408 );2409 }24102411 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2412 return this.helper.executeExtrinsic(2413 signer,2414 'api.tx.scheduler.changeNamedPriority',2415 [scheduledId, priority],2416 true,2417 );2418 }24192420 scheduleAt<T extends UniqueHelper>(2421 scheduledId: string,2422 executionBlockNumber: number,2423 options: ISchedulerOptions = {},2424 ) {2425 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2426 }24272428 scheduleAfter<T extends UniqueHelper>(2429 scheduledId: string,2430 blocksBeforeExecution: number,2431 options: ISchedulerOptions = {},2432 ) {2433 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2434 }24352436 schedule<T extends UniqueHelper>(2437 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2438 scheduledId: string,2439 blocksNum: number,2440 options: ISchedulerOptions = {},2441 ) {2442 2443 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2444 return this.helper.clone(ScheduledHelperType, {2445 scheduleFn,2446 scheduledId,2447 blocksNum,2448 options,2449 }) as T;2450 }2451}24522453class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2454 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2455 await this.helper.executeExtrinsic(2456 signer,2457 'api.tx.foreignAssets.registerForeignAsset',2458 [ownerAddress, location, metadata],2459 true,2460 );2461 }24622463 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2464 await this.helper.executeExtrinsic(2465 signer,2466 'api.tx.foreignAssets.updateForeignAsset',2467 [foreignAssetId, location, metadata],2468 true,2469 );2470 }2471}24722473class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2474 palletName: string;24752476 constructor(helper: T, palletName: string) {2477 super(helper);24782479 this.palletName = palletName;2480 }24812482 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2483 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2484 }2485}24862487class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2488 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2489 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2490 }24912492 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2493 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2494 }24952496 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2497 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2498 }2499}25002501class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2502 async accounts(address: string, currencyId: any) {2503 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2504 return BigInt(free);2505 }2506}25072508class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2509 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2510 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2511 }25122513 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2514 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2515 }25162517 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2518 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2519 }25202521 async account(assetId: string | number, address: string) {2522 const accountAsset = (2523 await this.helper.callRpc('api.query.assets.account', [assetId, address])2524 ).toJSON()! as any;25252526 if (accountAsset !== null) {2527 return BigInt(accountAsset['balance']);2528 } else {2529 return null;2530 }2531 }2532}25332534class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2535 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2536 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2537 }2538}25392540class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2541 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2542 const apiPrefix = 'api.tx.assetManager.';25432544 const registerTx = this.helper.constructApiCall(2545 apiPrefix + 'registerForeignAsset',2546 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2547 );25482549 const setUnitsTx = this.helper.constructApiCall(2550 apiPrefix + 'setAssetUnitsPerSecond',2551 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2552 );25532554 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2555 const encodedProposal = batchCall?.method.toHex() || '';2556 return encodedProposal;2557 }25582559 async assetTypeId(location: any) {2560 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2561 }2562}25632564class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2565 async notePreimage(signer: TSigner, encodedProposal: string) {2566 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2567 }25682569 externalProposeMajority(proposalHash: string) {2570 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2571 }25722573 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2574 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2575 }25762577 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2578 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2579 }2580}25812582class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2583 collective: string;25842585 constructor(helper: MoonbeamHelper, collective: string) {2586 super(helper);25872588 this.collective = collective;2589 }25902591 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2592 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2593 }25942595 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2596 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2597 }25982599 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2600 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2601 }26022603 async proposalCount() {2604 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2605 }2606}26072608export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2609export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26102611export class UniqueHelper extends ChainHelperBase {2612 balance: BalanceGroup<UniqueHelper>;2613 collection: CollectionGroup;2614 nft: NFTGroup;2615 rft: RFTGroup;2616 ft: FTGroup;2617 staking: StakingGroup;2618 scheduler: SchedulerGroup;2619 foreignAssets: ForeignAssetsGroup;2620 xcm: XcmGroup<UniqueHelper>;2621 xTokens: XTokensGroup<UniqueHelper>;2622 tokens: TokensGroup<UniqueHelper>;26232624 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2625 super(logger, options.helperBase ?? UniqueHelper);26262627 this.balance = new BalanceGroup(this);2628 this.collection = new CollectionGroup(this);2629 this.nft = new NFTGroup(this);2630 this.rft = new RFTGroup(this);2631 this.ft = new FTGroup(this);2632 this.staking = new StakingGroup(this);2633 this.scheduler = new SchedulerGroup(this);2634 this.foreignAssets = new ForeignAssetsGroup(this);2635 this.xcm = new XcmGroup(this, 'polkadotXcm');2636 this.xTokens = new XTokensGroup(this);2637 this.tokens = new TokensGroup(this);2638 }26392640 getSudo<T extends UniqueHelper>() {2641 2642 const SudoHelperType = SudoHelper(this.helperBase);2643 return this.clone(SudoHelperType) as T;2644 }2645}26462647export class XcmChainHelper extends ChainHelperBase {2648 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2649 const wsProvider = new WsProvider(wsEndpoint);2650 this.api = new ApiPromise({2651 provider: wsProvider,2652 });2653 await this.api.isReadyOrError;2654 this.network = await UniqueHelper.detectNetwork(this.api);2655 }2656}26572658export class RelayHelper extends XcmChainHelper {2659 xcm: XcmGroup<RelayHelper>;26602661 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2662 super(logger, options.helperBase ?? RelayHelper);26632664 this.xcm = new XcmGroup(this, 'xcmPallet');2665 }2666}26672668export class WestmintHelper extends XcmChainHelper {2669 balance: SubstrateBalanceGroup<WestmintHelper>;2670 xcm: XcmGroup<WestmintHelper>;2671 assets: AssetsGroup<WestmintHelper>;2672 xTokens: XTokensGroup<WestmintHelper>;26732674 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2675 super(logger, options.helperBase ?? WestmintHelper);26762677 this.balance = new SubstrateBalanceGroup(this);2678 this.xcm = new XcmGroup(this, 'polkadotXcm');2679 this.assets = new AssetsGroup(this);2680 this.xTokens = new XTokensGroup(this);2681 }2682}26832684export class MoonbeamHelper extends XcmChainHelper {2685 balance: EthereumBalanceGroup<MoonbeamHelper>;2686 assetManager: MoonbeamAssetManagerGroup;2687 assets: AssetsGroup<MoonbeamHelper>;2688 xTokens: XTokensGroup<MoonbeamHelper>;2689 democracy: MoonbeamDemocracyGroup;2690 collective: {2691 council: MoonbeamCollectiveGroup,2692 techCommittee: MoonbeamCollectiveGroup,2693 };26942695 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2696 super(logger, options.helperBase ?? MoonbeamHelper);26972698 this.balance = new EthereumBalanceGroup(this);2699 this.assetManager = new MoonbeamAssetManagerGroup(this);2700 this.assets = new AssetsGroup(this);2701 this.xTokens = new XTokensGroup(this);2702 this.democracy = new MoonbeamDemocracyGroup(this);2703 this.collective = {2704 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2705 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2706 };2707 }2708}27092710export class AcalaHelper extends XcmChainHelper {2711 balance: SubstrateBalanceGroup<AcalaHelper>;2712 assetRegistry: AcalaAssetRegistryGroup;2713 xTokens: XTokensGroup<AcalaHelper>;2714 tokens: TokensGroup<AcalaHelper>;27152716 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2717 super(logger, options.helperBase ?? AcalaHelper);27182719 this.balance = new SubstrateBalanceGroup(this);2720 this.assetRegistry = new AcalaAssetRegistryGroup(this);2721 this.xTokens = new XTokensGroup(this);2722 this.tokens = new TokensGroup(this);2723 }27242725 getSudo<T extends AcalaHelper>() {2726 2727 const SudoHelperType = SudoHelper(this.helperBase);2728 return this.clone(SudoHelperType) as T;2729 }2730}273127322733function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2734 return class extends Base {2735 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2736 scheduledId: string;2737 blocksNum: number;2738 options: ISchedulerOptions;27392740 constructor(...args: any[]) {2741 const logger = args[0] as ILogger;2742 const options = args[1] as {2743 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2744 scheduledId: string,2745 blocksNum: number,2746 options: ISchedulerOptions2747 };27482749 super(logger);27502751 this.scheduleFn = options.scheduleFn;2752 this.scheduledId = options.scheduledId;2753 this.blocksNum = options.blocksNum;2754 this.options = options.options;2755 }27562757 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2758 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2759 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27602761 return super.executeExtrinsic(2762 sender,2763 extrinsic,2764 [2765 this.scheduledId,2766 this.blocksNum,2767 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2768 this.options.priority ?? null,2769 {Value: scheduledTx},2770 ],2771 expectSuccess,2772 );2773 }2774 };2775}277627772778function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2779 return class extends Base {2780 constructor(...args: any[]) {2781 super(...args);2782 }27832784 executeExtrinsic (2785 sender: IKeyringPair,2786 extrinsic: string,2787 params: any[],2788 expectSuccess?: boolean,2789 ): Promise<ITransactionResult> {2790 const call = this.constructApiCall(extrinsic, params);27912792 return super.executeExtrinsic(2793 sender,2794 'api.tx.sudo.sudo',2795 [call],2796 expectSuccess,2797 );2798 }2799 };2800}28012802export class UniqueBaseCollection {2803 helper: UniqueHelper;2804 collectionId: number;28052806 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2807 this.collectionId = collectionId;2808 this.helper = uniqueHelper;2809 }28102811 async getData() {2812 return await this.helper.collection.getData(this.collectionId);2813 }28142815 async getLastTokenId() {2816 return await this.helper.collection.getLastTokenId(this.collectionId);2817 }28182819 async doesTokenExist(tokenId: number) {2820 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2821 }28222823 async getAdmins() {2824 return await this.helper.collection.getAdmins(this.collectionId);2825 }28262827 async getAllowList() {2828 return await this.helper.collection.getAllowList(this.collectionId);2829 }28302831 async getEffectiveLimits() {2832 return await this.helper.collection.getEffectiveLimits(this.collectionId);2833 }28342835 async getProperties(propertyKeys?: string[] | null) {2836 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2837 }28382839 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2840 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2841 }28422843 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2844 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2845 }28462847 async confirmSponsorship(signer: TSigner) {2848 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2849 }28502851 async removeSponsor(signer: TSigner) {2852 return await this.helper.collection.removeSponsor(signer, this.collectionId);2853 }28542855 async setLimits(signer: TSigner, limits: ICollectionLimits) {2856 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2857 }28582859 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2860 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2861 }28622863 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2864 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2865 }28662867 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2868 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2869 }28702871 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2872 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2873 }28742875 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2876 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2877 }28782879 async setProperties(signer: TSigner, properties: IProperty[]) {2880 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2881 }28822883 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2884 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2885 }28862887 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2888 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2889 }28902891 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2892 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2893 }28942895 async disableNesting(signer: TSigner) {2896 return await this.helper.collection.disableNesting(signer, this.collectionId);2897 }28982899 async burn(signer: TSigner) {2900 return await this.helper.collection.burn(signer, this.collectionId);2901 }29022903 scheduleAt<T extends UniqueHelper>(2904 scheduledId: string,2905 executionBlockNumber: number,2906 options: ISchedulerOptions = {},2907 ) {2908 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2909 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2910 }29112912 scheduleAfter<T extends UniqueHelper>(2913 scheduledId: string,2914 blocksBeforeExecution: number,2915 options: ISchedulerOptions = {},2916 ) {2917 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2918 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2919 }29202921 getSudo<T extends UniqueHelper>() {2922 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2923 }2924}292529262927export class UniqueNFTCollection extends UniqueBaseCollection {2928 getTokenObject(tokenId: number) {2929 return new UniqueNFToken(tokenId, this);2930 }29312932 async getTokensByAddress(addressObj: ICrossAccountId) {2933 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2934 }29352936 async getToken(tokenId: number, blockHashAt?: string) {2937 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2938 }29392940 async getTokenOwner(tokenId: number, blockHashAt?: string) {2941 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2942 }29432944 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2945 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2946 }29472948 async getTokenChildren(tokenId: number, blockHashAt?: string) {2949 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2950 }29512952 async getPropertyPermissions(propertyKeys: string[] | null = null) {2953 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2954 }29552956 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2957 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2958 }29592960 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2961 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2962 }29632964 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2965 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2966 }29672968 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2969 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2970 }29712972 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2973 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2974 }29752976 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2977 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2978 }29792980 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2981 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2982 }29832984 async burnToken(signer: TSigner, tokenId: number) {2985 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2986 }29872988 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2989 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2990 }29912992 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2993 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2994 }29952996 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2997 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2998 }29993000 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3001 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3002 }30033004 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3005 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3006 }30073008 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3009 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3010 }30113012 scheduleAt<T extends UniqueHelper>(3013 scheduledId: string,3014 executionBlockNumber: number,3015 options: ISchedulerOptions = {},3016 ) {3017 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3018 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3019 }30203021 scheduleAfter<T extends UniqueHelper>(3022 scheduledId: string,3023 blocksBeforeExecution: number,3024 options: ISchedulerOptions = {},3025 ) {3026 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3027 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3028 }30293030 getSudo<T extends UniqueHelper>() {3031 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3032 }3033}303430353036export class UniqueRFTCollection extends UniqueBaseCollection {3037 getTokenObject(tokenId: number) {3038 return new UniqueRFToken(tokenId, this);3039 }30403041 async getToken(tokenId: number, blockHashAt?: string) {3042 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3043 }30443045 async getTokensByAddress(addressObj: ICrossAccountId) {3046 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3047 }30483049 async getTop10TokenOwners(tokenId: number) {3050 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3051 }30523053 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3054 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3055 }30563057 async getTokenTotalPieces(tokenId: number) {3058 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3059 }30603061 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3062 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3063 }30643065 async getPropertyPermissions(propertyKeys: string[] | null = null) {3066 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3067 }30683069 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3070 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3071 }30723073 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3074 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3075 }30763077 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3078 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3079 }30803081 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3082 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3083 }30843085 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3086 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3087 }30883089 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3090 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3091 }30923093 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3094 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3095 }30963097 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3098 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3099 }31003101 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3102 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3103 }31043105 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3106 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3107 }31083109 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3110 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3111 }31123113 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3114 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3115 }31163117 scheduleAt<T extends UniqueHelper>(3118 scheduledId: string,3119 executionBlockNumber: number,3120 options: ISchedulerOptions = {},3121 ) {3122 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3123 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3124 }31253126 scheduleAfter<T extends UniqueHelper>(3127 scheduledId: string,3128 blocksBeforeExecution: number,3129 options: ISchedulerOptions = {},3130 ) {3131 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3132 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3133 }31343135 getSudo<T extends UniqueHelper>() {3136 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3137 }3138}313931403141export class UniqueFTCollection extends UniqueBaseCollection {3142 async getBalance(addressObj: ICrossAccountId) {3143 return await this.helper.ft.getBalance(this.collectionId, addressObj);3144 }31453146 async getTotalPieces() {3147 return await this.helper.ft.getTotalPieces(this.collectionId);3148 }31493150 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3151 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3152 }31533154 async getTop10Owners() {3155 return await this.helper.ft.getTop10Owners(this.collectionId);3156 }31573158 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3159 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3160 }31613162 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3163 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3164 }31653166 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3167 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3168 }31693170 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3171 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3172 }31733174 async burnTokens(signer: TSigner, amount=1n) {3175 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3176 }31773178 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3179 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3180 }31813182 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3183 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3184 }31853186 scheduleAt<T extends UniqueHelper>(3187 scheduledId: string,3188 executionBlockNumber: number,3189 options: ISchedulerOptions = {},3190 ) {3191 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3192 return new UniqueFTCollection(this.collectionId, scheduledHelper);3193 }31943195 scheduleAfter<T extends UniqueHelper>(3196 scheduledId: string,3197 blocksBeforeExecution: number,3198 options: ISchedulerOptions = {},3199 ) {3200 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3201 return new UniqueFTCollection(this.collectionId, scheduledHelper);3202 }32033204 getSudo<T extends UniqueHelper>() {3205 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3206 }3207}320832093210export class UniqueBaseToken {3211 collection: UniqueNFTCollection | UniqueRFTCollection;3212 collectionId: number;3213 tokenId: number;32143215 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3216 this.collection = collection;3217 this.collectionId = collection.collectionId;3218 this.tokenId = tokenId;3219 }32203221 async getNextSponsored(addressObj: ICrossAccountId) {3222 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3223 }32243225 async getProperties(propertyKeys?: string[] | null) {3226 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3227 }32283229 async setProperties(signer: TSigner, properties: IProperty[]) {3230 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3231 }32323233 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3234 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3235 }32363237 async doesExist() {3238 return await this.collection.doesTokenExist(this.tokenId);3239 }32403241 nestingAccount() {3242 return this.collection.helper.util.getTokenAccount(this);3243 }32443245 scheduleAt<T extends UniqueHelper>(3246 scheduledId: string,3247 executionBlockNumber: number,3248 options: ISchedulerOptions = {},3249 ) {3250 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3251 return new UniqueBaseToken(this.tokenId, scheduledCollection);3252 }32533254 scheduleAfter<T extends UniqueHelper>(3255 scheduledId: string,3256 blocksBeforeExecution: number,3257 options: ISchedulerOptions = {},3258 ) {3259 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3260 return new UniqueBaseToken(this.tokenId, scheduledCollection);3261 }32623263 getSudo<T extends UniqueHelper>() {3264 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3265 }3266}326732683269export class UniqueNFToken extends UniqueBaseToken {3270 collection: UniqueNFTCollection;32713272 constructor(tokenId: number, collection: UniqueNFTCollection) {3273 super(tokenId, collection);3274 this.collection = collection;3275 }32763277 async getData(blockHashAt?: string) {3278 return await this.collection.getToken(this.tokenId, blockHashAt);3279 }32803281 async getOwner(blockHashAt?: string) {3282 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3283 }32843285 async getTopmostOwner(blockHashAt?: string) {3286 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3287 }32883289 async getChildren(blockHashAt?: string) {3290 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3291 }32923293 async nest(signer: TSigner, toTokenObj: IToken) {3294 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3295 }32963297 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3298 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3299 }33003301 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3302 return await this.collection.transferToken(signer, this.tokenId, addressObj);3303 }33043305 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3306 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3307 }33083309 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3310 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3311 }33123313 async isApproved(toAddressObj: ICrossAccountId) {3314 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3315 }33163317 async burn(signer: TSigner) {3318 return await this.collection.burnToken(signer, this.tokenId);3319 }33203321 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3322 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3323 }33243325 scheduleAt<T extends UniqueHelper>(3326 scheduledId: string,3327 executionBlockNumber: number,3328 options: ISchedulerOptions = {},3329 ) {3330 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3331 return new UniqueNFToken(this.tokenId, scheduledCollection);3332 }33333334 scheduleAfter<T extends UniqueHelper>(3335 scheduledId: string,3336 blocksBeforeExecution: number,3337 options: ISchedulerOptions = {},3338 ) {3339 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3340 return new UniqueNFToken(this.tokenId, scheduledCollection);3341 }33423343 getSudo<T extends UniqueHelper>() {3344 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3345 }3346}33473348export class UniqueRFToken extends UniqueBaseToken {3349 collection: UniqueRFTCollection;33503351 constructor(tokenId: number, collection: UniqueRFTCollection) {3352 super(tokenId, collection);3353 this.collection = collection;3354 }33553356 async getData(blockHashAt?: string) {3357 return await this.collection.getToken(this.tokenId, blockHashAt);3358 }33593360 async getTop10Owners() {3361 return await this.collection.getTop10TokenOwners(this.tokenId);3362 }33633364 async getBalance(addressObj: ICrossAccountId) {3365 return await this.collection.getTokenBalance(this.tokenId, addressObj);3366 }33673368 async getTotalPieces() {3369 return await this.collection.getTokenTotalPieces(this.tokenId);3370 }33713372 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3373 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3374 }33753376 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3377 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3378 }33793380 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3381 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3382 }33833384 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3385 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3386 }33873388 async repartition(signer: TSigner, amount: bigint) {3389 return await this.collection.repartitionToken(signer, this.tokenId, amount);3390 }33913392 async burn(signer: TSigner, amount=1n) {3393 return await this.collection.burnToken(signer, this.tokenId, amount);3394 }33953396 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3397 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3398 }33993400 scheduleAt<T extends UniqueHelper>(3401 scheduledId: string,3402 executionBlockNumber: number,3403 options: ISchedulerOptions = {},3404 ) {3405 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3406 return new UniqueRFToken(this.tokenId, scheduledCollection);3407 }34083409 scheduleAfter<T extends UniqueHelper>(3410 scheduledId: string,3411 blocksBeforeExecution: number,3412 options: ISchedulerOptions = {},3413 ) {3414 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3415 return new UniqueRFToken(this.tokenId, scheduledCollection);3416 }34173418 getSudo<T extends UniqueHelper>() {3419 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3420 }3421}