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 {13 IApiListeners,14 IBlock,15 IEvent,16 IChainProperties,17 ICollectionCreationOptions,18 ICollectionLimits,19 ICollectionPermissions,20 ICrossAccountId,21 ICrossAccountIdLower,22 ILogger,23 INestingPermissions,24 IProperty,25 IStakingInfo,26 ISchedulerOptions,27 ISubstrateBalance,28 IToken,29 ITokenPropertyPermission,30 ITransactionResult,31 IUniqueHelperLog,32 TApiAllowedListeners,33 TEthereumAccount,34 TSigner,35 TSubstrateAccount,36 TNetworks,37 IForeignAssetMetadata,38 AcalaAssetMetadata,39 MoonbeamAssetInfo,40 DemocracyStandardAccountVote,41} from './types';4243export class CrossAccountId implements ICrossAccountId {44 Substrate?: TSubstrateAccount;45 Ethereum?: TEthereumAccount;4647 constructor(account: ICrossAccountId) {48 if (account.Substrate) this.Substrate = account.Substrate;49 if (account.Ethereum) this.Ethereum = account.Ethereum;50 }5152 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {53 switch (domain) {54 case 'Substrate': return new CrossAccountId({Substrate: account.address});55 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();56 }57 }5859 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {60 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});61 }6263 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {64 return encodeAddress(decodeAddress(address), ss58Format);65 }6667 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {68 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});69 }70 71 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {72 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);73 return this;74 }7576 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {77 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));78 }7980 toEthereum(): CrossAccountId {81 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});82 return this;83 }8485 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {86 return evmToAddress(address, ss58Format);87 }8889 toSubstrate(ss58Format?: number): CrossAccountId {90 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});91 return this;92 }93 94 toLowerCase(): CrossAccountId {95 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();96 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();97 return this;98 }99}100101const nesting = {102 toChecksumAddress(address: string): string {103 if (typeof address === 'undefined') return '';104105 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);106107 address = address.toLowerCase().replace(/^0x/i,'');108 const addressHash = keccakAsHex(address).replace(/^0x/i,'');109 const checksumAddress = ['0x'];110111 for (let i = 0; i < address.length; i++) {112 113 if (parseInt(addressHash[i], 16) > 7) {114 checksumAddress.push(address[i].toUpperCase());115 } else {116 checksumAddress.push(address[i]);117 }118 }119 return checksumAddress.join('');120 },121 tokenIdToAddress(collectionId: number, tokenId: number) {122 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);123 },124};125126class UniqueUtil {127 static transactionStatus = {128 NOT_READY: 'NotReady',129 FAIL: 'Fail',130 SUCCESS: 'Success',131 };132133 static chainLogType = {134 EXTRINSIC: 'extrinsic',135 RPC: 'rpc',136 };137138 static getTokenAccount(token: IToken): CrossAccountId {139 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});140 }141142 static getTokenAddress(token: IToken): string {143 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);144 }145146 static getDefaultLogger(): ILogger {147 return {148 log(msg: any, level = 'INFO') {149 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));150 },151 level: {152 ERROR: 'ERROR',153 WARNING: 'WARNING',154 INFO: 'INFO',155 },156 };157 }158159 static vec2str(arr: string[] | number[]) {160 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');161 }162163 static str2vec(string: string) {164 if (typeof string !== 'string') return string;165 return Array.from(string).map(x => x.charCodeAt(0));166 }167168 static fromSeed(seed: string, ss58Format = 42) {169 const keyring = new Keyring({type: 'sr25519', ss58Format});170 return keyring.addFromUri(seed);171 }172173 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {174 if (creationResult.status !== this.transactionStatus.SUCCESS) {175 throw Error('Unable to create collection!');176 }177178 let collectionId = null;179 creationResult.result.events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'CollectionCreated')) {181 collectionId = parseInt(data[0].toString(), 10);182 }183 });184185 if (collectionId === null) {186 throw Error('No CollectionCreated event was found!');187 }188189 return collectionId;190 }191192 static extractTokensFromCreationResult(creationResult: ITransactionResult): {193 success: boolean, 194 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],195 } {196 if (creationResult.status !== this.transactionStatus.SUCCESS) {197 throw Error('Unable to create tokens!');198 }199 let success = false;200 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];201 creationResult.result.events.forEach(({event: {data, method, section}}) => {202 if (method === 'ExtrinsicSuccess') {203 success = true;204 } else if ((section === 'common') && (method === 'ItemCreated')) {205 tokens.push({206 collectionId: parseInt(data[0].toString(), 10),207 tokenId: parseInt(data[1].toString(), 10),208 owner: data[2].toHuman(),209 amount: data[3].toBigInt(),210 });211 }212 });213 return {success, tokens};214 }215216 static extractTokensFromBurnResult(burnResult: ITransactionResult): {217 success: boolean, 218 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],219 } {220 if (burnResult.status !== this.transactionStatus.SUCCESS) {221 throw Error('Unable to burn tokens!');222 }223 let success = false;224 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];225 burnResult.result.events.forEach(({event: {data, method, section}}) => {226 if (method === 'ExtrinsicSuccess') {227 success = true;228 } else if ((section === 'common') && (method === 'ItemDestroyed')) {229 tokens.push({230 collectionId: parseInt(data[0].toString(), 10),231 tokenId: parseInt(data[1].toString(), 10),232 owner: data[2].toHuman(),233 amount: data[3].toBigInt(),234 });235 }236 });237 return {success, tokens};238 }239240 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {241 let eventId = null;242 events.forEach(({event: {data, method, section}}) => {243 if ((section === expectedSection) && (method === expectedMethod)) {244 eventId = parseInt(data[0].toString(), 10);245 }246 });247248 if (eventId === null) {249 throw Error(`No ${expectedMethod} event was found!`);250 }251 return eventId === collectionId;252 }253254 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {255 const normalizeAddress = (address: string | ICrossAccountId) => {256 if(typeof address === 'string') return address;257 const obj = {} as any;258 Object.keys(address).forEach(k => {259 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];260 });261 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);262 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();263 return address;264 };265 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;266 events.forEach(({event: {data, method, section}}) => {267 if ((section === 'common') && (method === 'Transfer')) {268 const hData = (data as any).toJSON();269 transfer = {270 collectionId: hData[0],271 tokenId: hData[1],272 from: normalizeAddress(hData[2]),273 to: normalizeAddress(hData[3]),274 amount: BigInt(hData[4]),275 };276 }277 });278 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;279 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);280 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);281 isSuccess = isSuccess && amount === transfer.amount;282 return isSuccess;283 }284285 static bigIntToDecimals(number: bigint, decimals = 18) {286 const numberStr = number.toString();287 const dotPos = numberStr.length - decimals;288 289 if (dotPos <= 0) {290 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;291 } else {292 const intPart = numberStr.substring(0, dotPos);293 const fractPart = numberStr.substring(dotPos);294 return intPart + '.' + fractPart;295 }296 }297}298299class UniqueEventHelper {300 private static extractIndex(index: any): [number, number] | string {301 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];302 return index.toJSON();303 }304305 private static extractSub(data: any, subTypes: any): {[key: string]: any} {306 let obj: any = {};307 let index = 0;308309 if (data.entries) {310 for(const [key, value] of data.entries()) {311 obj[key] = this.extractData(value, subTypes[index]);312 index++;313 }314 } else obj = data.toJSON();315316 return obj;317 }318 319 private static extractData(data: any, type: any): any {320 if(!type) return data.toHuman();321 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();322 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();323 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);324 return data.toHuman();325 }326327 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {328 const parsedEvents: IEvent[] = [];329330 events.forEach((record) => {331 const {event, phase} = record;332 const types = event.typeDef;333334 const eventData: IEvent = {335 section: event.section.toString(),336 method: event.method.toString(),337 index: this.extractIndex(event.index),338 data: [],339 phase: phase.toJSON(),340 };341342 event.data.forEach((val: any, index: number) => {343 eventData.data.push(this.extractData(val, types[index]));344 });345346 parsedEvents.push(eventData);347 });348349 return parsedEvents;350 }351}352353export class ChainHelperBase {354 helperBase: any;355356 transactionStatus = UniqueUtil.transactionStatus;357 chainLogType = UniqueUtil.chainLogType;358 util: typeof UniqueUtil;359 eventHelper: typeof UniqueEventHelper;360 logger: ILogger;361 api: ApiPromise | null;362 forcedNetwork: TNetworks | null;363 network: TNetworks | null;364 chainLog: IUniqueHelperLog[];365 children: ChainHelperBase[];366 address: AddressGroup;367 chain: ChainGroup;368369 constructor(logger?: ILogger, helperBase?: any) {370 this.helperBase = helperBase;371372 this.util = UniqueUtil;373 this.eventHelper = UniqueEventHelper;374 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();375 this.logger = logger;376 this.api = null;377 this.forcedNetwork = null;378 this.network = null;379 this.chainLog = [];380 this.children = [];381 this.address = new AddressGroup(this);382 this.chain = new ChainGroup(this);383 }384385 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {386 Object.setPrototypeOf(helperCls.prototype, this);387 const newHelper = new helperCls(this.logger, options);388389 newHelper.api = this.api;390 newHelper.network = this.network;391 newHelper.forceNetwork = this.forceNetwork;392393 this.children.push(newHelper);394395 return newHelper;396 }397398 getApi(): ApiPromise {399 if(this.api === null) throw Error('API not initialized');400 return this.api;401 }402403 clearChainLog(): void {404 this.chainLog = [];405 }406407 forceNetwork(value: TNetworks): void {408 this.forcedNetwork = value;409 }410411 async connect(wsEndpoint: string, listeners?: IApiListeners) {412 if (this.api !== null) throw Error('Already connected');413 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);414 this.api = api;415 this.network = network;416 }417418 async disconnect() {419 for (const child of this.children) {420 child.clearApi();421 }422423 if (this.api === null) return;424 await this.api.disconnect();425 this.clearApi();426 }427428 clearApi() {429 this.api = null;430 this.network = null;431 }432433 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {434 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;435 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];436437 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;438439 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;440 return 'opal';441 }442443 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {444 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});445 await api.isReady;446447 const network = await this.detectNetwork(api);448449 await api.disconnect();450451 return network;452 }453454 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{455 api: ApiPromise;456 network: TNetworks;457 }> {458 if(typeof network === 'undefined' || network === null) network = 'opal';459 const supportedRPC = {460 opal: {461 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,462 },463 quartz: {464 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,465 },466 unique: {467 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,468 },469 rococo: {},470 westend: {},471 moonbeam: {},472 moonriver: {},473 acala: {},474 karura: {},475 westmint: {},476 };477 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);478 const rpc = supportedRPC[network];479480 481 482483 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});484485 await api.isReadyOrError;486487 if (typeof listeners === 'undefined') listeners = {};488 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {489 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;490 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);491 }492493 return {api, network};494 }495496 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {497 const {events, status} = data;498 if (status.isReady) {499 return this.transactionStatus.NOT_READY;500 }501 if (status.isBroadcast) {502 return this.transactionStatus.NOT_READY;503 }504 if (status.isInBlock || status.isFinalized) {505 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');506 if (errors.length > 0) {507 return this.transactionStatus.FAIL;508 }509 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {510 return this.transactionStatus.SUCCESS;511 }512 }513514 return this.transactionStatus.FAIL;515 }516517 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {518 const sign = (callback: any) => {519 if(options !== null) return transaction.signAndSend(sender, options, callback);520 return transaction.signAndSend(sender, callback);521 };522 523 return new Promise(async (resolve, reject) => {524 try {525 const unsub = await sign((result: any) => {526 const status = this.getTransactionStatus(result);527528 if (status === this.transactionStatus.SUCCESS) {529 this.logger.log(`${label} successful`);530 unsub();531 resolve({result, status});532 } else if (status === this.transactionStatus.FAIL) {533 let moduleError = null;534535 if (result.hasOwnProperty('dispatchError')) {536 const dispatchError = result['dispatchError'];537538 if (dispatchError) {539 if (dispatchError.isModule) {540 const modErr = dispatchError.asModule;541 const errorMeta = dispatchError.registry.findMetaError(modErr);542543 moduleError = `${errorMeta.section}.${errorMeta.name}`;544 } else {545 moduleError = dispatchError.toHuman();546 }547 } else {548 this.logger.log(result, this.logger.level.ERROR);549 }550 }551552 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);553 unsub();554 reject({status, moduleError, result});555 }556 });557 } catch (e) {558 this.logger.log(e, this.logger.level.ERROR);559 reject(e);560 }561 });562 }563564 constructApiCall(apiCall: string, params: any[]) {565 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);566 let call = this.getApi() as any;567 for(const part of apiCall.slice(4).split('.')) {568 call = call[part];569 }570 return call(...params);571 }572573 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {574 if(this.api === null) throw Error('API not initialized');575 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);576577 const startTime = (new Date()).getTime();578 let result: ITransactionResult;579 let events: IEvent[] = [];580 try {581 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;582 events = this.eventHelper.extractEvents(result.result.events);583 }584 catch(e) {585 if(!(e as object).hasOwnProperty('status')) throw e;586 result = e as ITransactionResult;587 }588589 const endTime = (new Date()).getTime();590591 const log = {592 executedAt: endTime,593 executionTime: endTime - startTime,594 type: this.chainLogType.EXTRINSIC,595 status: result.status,596 call: extrinsic,597 signer: this.getSignerAddress(sender),598 params,599 } as IUniqueHelperLog;600601 if(result.status !== this.transactionStatus.SUCCESS) {602 if (result.moduleError) log.moduleError = result.moduleError;603 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;604 }605 if(events.length > 0) log.events = events;606607 this.chainLog.push(log);608609 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {610 if (result.moduleError) throw Error(`${result.moduleError}`);611 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));612 }613 return result;614 }615616 async callRpc(rpc: string, params?: any[]) {617 if(typeof params === 'undefined') params = [];618 if(this.api === null) throw Error('API not initialized');619 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);620621 const startTime = (new Date()).getTime();622 let result;623 let error = null;624 const log = {625 type: this.chainLogType.RPC,626 call: rpc,627 params,628 } as IUniqueHelperLog;629630 try {631 result = await this.constructApiCall(rpc, params);632 }633 catch(e) {634 error = e;635 }636637 const endTime = (new Date()).getTime();638639 log.executedAt = endTime;640 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';641 log.executionTime = endTime - startTime;642643 this.chainLog.push(log);644645 if(error !== null) throw error;646647 return result;648 }649650 getSignerAddress(signer: IKeyringPair | string): string {651 if(typeof signer === 'string') return signer;652 return signer.address;653 }654655 fetchAllPalletNames(): string[] {656 if(this.api === null) throw Error('API not initialized');657 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());658 }659660 fetchMissingPalletNames(requiredPallets: string[]): string[] {661 const palletNames = this.fetchAllPalletNames();662 return requiredPallets.filter(p => !palletNames.includes(p));663 }664}665666667class HelperGroup<T extends ChainHelperBase> {668 helper: T;669670 constructor(uniqueHelper: T) {671 this.helper = uniqueHelper;672 }673}674675676class CollectionGroup extends HelperGroup<UniqueHelper> {677 678679680681682683684685686 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {687 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();688 }689690 691692693694695 async getTotalCount(): Promise<number> {696 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();697 }698699 700701702703704705706707708 async getData(collectionId: number): Promise<{709 id: number;710 name: string;711 description: string;712 tokensCount: number;713 admins: CrossAccountId[];714 normalizedOwner: TSubstrateAccount;715 raw: any716 } | null> {717 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);718 const humanCollection = collection.toHuman(), collectionData = {719 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],720 raw: humanCollection,721 } as any, jsonCollection = collection.toJSON();722 if (humanCollection === null) return null;723 collectionData.raw.limits = jsonCollection.limits;724 collectionData.raw.permissions = jsonCollection.permissions;725 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);726 for (const key of ['name', 'description']) {727 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);728 }729730 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))731 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)732 : 0;733 collectionData.admins = await this.getAdmins(collectionId);734735 return collectionData;736 }737738 739740741742743744745746 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {747 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();748749 return normalize750 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())751 : admins;752 }753754 755756757758759760761 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {762 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();763 return normalize764 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())765 : allowListed;766 }767768 769770771772773774775 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {776 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();777 }778779 780781782783784785786787 async burn(signer: TSigner, collectionId: number): Promise<boolean> {788 const result = await this.helper.executeExtrinsic(789 signer,790 'api.tx.unique.destroyCollection', [collectionId],791 true,792 );793794 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');795 }796797 798799800801802803804805806 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {807 const result = await this.helper.executeExtrinsic(808 signer,809 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],810 true,811 );812813 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');814 }815816 817818819820821822823824 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {825 const result = await this.helper.executeExtrinsic(826 signer,827 'api.tx.unique.confirmSponsorship', [collectionId],828 true,829 );830831 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');832 }833834 835836837838839840841842 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.removeCollectionSponsor', [collectionId],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');850 }851852 853854855856857858859860861862863864865866867868869 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {870 const result = await this.helper.executeExtrinsic(871 signer,872 'api.tx.unique.setCollectionLimits', [collectionId, limits],873 true,874 );875876 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');877 }878879 880881882883884885886887888 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {889 const result = await this.helper.executeExtrinsic(890 signer,891 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],892 true,893 );894895 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');896 }897898 899900901902903904905906907 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {908 const result = await this.helper.executeExtrinsic(909 signer,910 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],911 true,912 );913914 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');915 }916917 918919920921922923924925926 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {927 const result = await this.helper.executeExtrinsic(928 signer,929 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],930 true,931 );932933 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');934 }935936 937938939940941942943944 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {945 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();946 }947948 949950951952953954955 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {956 const result = await this.helper.executeExtrinsic(957 signer,958 'api.tx.unique.addToAllowList', [collectionId, addressObj],959 true,960 );961962 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');963 }964965 966967968969970971972973 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {974 const result = await this.helper.executeExtrinsic(975 signer,976 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],977 true,978 );979980 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');981 }982983 984985986987988989990991992 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],996 true,997 );998999 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1000 }10011002 100310041005100610071008100910101011 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1012 return await this.setPermissions(signer, collectionId, {nesting: permissions});1013 }10141015 10161017101810191020102110221023 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1024 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1025 }10261027 102810291030103110321033103410351036 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1037 const result = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.setCollectionProperties', [collectionId, properties],1040 true,1041 );10421043 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1044 }10451046 10471048104910501051105210531054 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1055 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1056 }10571058 async getCollectionOptions(collectionId: number) {1059 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1060 }10611062 106310641065106610671068106910701071 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1072 const result = await this.helper.executeExtrinsic(1073 signer,1074 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1075 true,1076 );10771078 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1079 }10801081 10821083108410851086108710881089109010911092 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1093 const result = await this.helper.executeExtrinsic(1094 signer,1095 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1096 true, 1097 );10981099 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1100 }11011102 1103110411051106110711081109111011111112111311141115 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1116 const result = await this.helper.executeExtrinsic(1117 signer,1118 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1119 true, 1120 );1121 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1122 }11231124 11251126112711281129113011311132113311341135 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1136 const burnResult = await this.helper.executeExtrinsic(1137 signer,1138 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1139 true, 1140 );1141 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1142 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1143 return burnedTokens.success;1144 }11451146 11471148114911501151115211531154115511561157 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1158 const burnResult = await this.helper.executeExtrinsic(1159 signer,1160 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1161 true, 1162 );1163 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1164 return burnedTokens.success && burnedTokens.tokens.length > 0;1165 }11661167 1168116911701171117211731174117511761177 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1178 const approveResult = await this.helper.executeExtrinsic(1179 signer,1180 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1181 true, 1182 );11831184 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1185 }11861187 1188118911901191119211931194119511961197 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1198 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1199 }12001201 1202120312041205120612071208 async getLastTokenId(collectionId: number): Promise<number> {1209 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1210 }12111212 12131214121512161217121812191220 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1221 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1222 }1223}12241225class NFTnRFT extends CollectionGroup {1226 12271228122912301231123212331234 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1235 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1236 }12371238 1239124012411242124312441245124612471248 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1249 properties: IProperty[];1250 owner: CrossAccountId;1251 normalizedOwner: CrossAccountId;1252 }| null> {1253 let tokenData;1254 if(typeof blockHashAt === 'undefined') {1255 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1256 }1257 else {1258 if(propertyKeys.length == 0) {1259 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1260 if(!collection) return null;1261 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1262 }1263 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1264 }1265 tokenData = tokenData.toHuman();1266 if (tokenData === null || tokenData.owner === null) return null;1267 const owner = {} as any;1268 for (const key of Object.keys(tokenData.owner)) {1269 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1270 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1271 : tokenData.owner[key];1272 }1273 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1274 return tokenData;1275 }12761277 12781279128012811282128312841285128612871288 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1289 const result = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1292 true,1293 );12941295 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1296 }12971298 12991300130113021303130413051306 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1307 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1308 }13091310 1311131213131314131513161317131813191320 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1321 const result = await this.helper.executeExtrinsic(1322 signer,1323 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1324 true,1325 );13261327 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1328 }13291330 133113321333133413351336133713381339 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1340 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1341 }13421343 134413451346134713481349135013511352 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1353 const result = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1356 true,1357 );13581359 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1360 }13611362 136313641365136613671368136913701371 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1372 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1373 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1374 for (const key of ['name', 'description', 'tokenPrefix']) {1375 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);1376 }1377 const creationResult = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.createCollectionEx', [collectionOptions],1380 true, 1381 );1382 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1383 }13841385 getCollectionObject(_collectionId: number): any {1386 return null;1387 }13881389 getTokenObject(_collectionId: number, _tokenId: number): any {1390 return null;1391 }1392}139313941395class NFTGroup extends NFTnRFT {1396 139713981399140014011402 getCollectionObject(collectionId: number): UniqueNFTCollection {1403 return new UniqueNFTCollection(collectionId, this.helper);1404 }14051406 1407140814091410141114121413 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1414 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1415 }14161417 14181419142014211422142314241425 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1426 let owner;1427 if (typeof blockHashAt === 'undefined') {1428 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1429 } else {1430 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1431 }1432 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1433 }14341435 1436143714381439144014411442 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1443 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1444 }14451446 1447144814491450145114521453145414551456 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1457 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1458 }14591460 146114621463146414651466146714681469147014711472 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1473 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1474 }14751476 14771478147914801481148214831484 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1485 let owner;1486 if (typeof blockHashAt === 'undefined') {1487 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1488 } else {1489 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1490 }14911492 if (owner === null) return null;14931494 return owner.toHuman();1495 }14961497 14981499150015011502150315041505 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1506 let children;1507 if(typeof blockHashAt === 'undefined') {1508 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1509 } else {1510 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1511 }15121513 return children.toJSON().map((x: any) => {1514 return {collectionId: x.collection, tokenId: x.token};1515 });1516 }15171518 15191520152115221523152415251526 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1527 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1528 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1529 if(!result) {1530 throw Error('Unable to nest token!');1531 }1532 return result;1533 }15341535 153615371538153915401541154215431544 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1545 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1546 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1547 if(!result) {1548 throw Error('Unable to unnest token!');1549 }1550 return result;1551 }15521553 155415551556155715581559156015611562156315641565 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1566 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1567 }15681569 157015711572157315741575 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1576 const creationResult = await this.helper.executeExtrinsic(1577 signer,1578 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1579 nft: {1580 properties: data.properties,1581 },1582 }],1583 true,1584 );1585 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1586 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1587 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1588 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1589 }15901591 159215931594159515961597159815991600160116021603160416051606 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1607 const creationResult = await this.helper.executeExtrinsic(1608 signer,1609 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1610 true,1611 );1612 const collection = this.getCollectionObject(collectionId);1613 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614 }16151616 161716181619162016211622162316241625162616271628162916301631163216331634 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1635 const rawTokens = [];1636 for (const token of tokens) {1637 const raw = {NFT: {properties: token.properties}};1638 rawTokens.push(raw);1639 }1640 const creationResult = await this.helper.executeExtrinsic(1641 signer,1642 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1643 true,1644 );1645 const collection = this.getCollectionObject(collectionId);1646 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1647 }16481649 1650165116521653165416551656165716581659 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1660 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1661 }1662}166316641665class RFTGroup extends NFTnRFT {1666 166716681669167016711672 getCollectionObject(collectionId: number): UniqueRFTCollection {1673 return new UniqueRFTCollection(collectionId, this.helper);1674 }16751676 1677167816791680168116821683 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1684 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1685 }16861687 1688168916901691169216931694 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1695 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1696 }16971698 16991700170117021703170417051706 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1707 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1708 }17091710 1711171217131714171517161717171817191720 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1721 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1722 }17231724 17251726172717281729173017311732173317341735 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1736 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1737 }17381739 174017411742174317441745174617471748174917501751 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1752 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1753 }17541755 1756175717581759176017611762 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1763 const creationResult = await this.helper.executeExtrinsic(1764 signer,1765 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1766 refungible: {1767 pieces: data.pieces,1768 properties: data.properties,1769 },1770 }],1771 true,1772 );1773 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1774 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1775 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1776 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1777 }17781779 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1780 throw Error('Not implemented');1781 const creationResult = await this.helper.executeExtrinsic(1782 signer,1783 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1784 true, 1785 );1786 const collection = this.getCollectionObject(collectionId);1787 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1788 }17891790 179117921793179417951796179717981799 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1800 const rawTokens = [];1801 for (const token of tokens) {1802 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1803 rawTokens.push(raw);1804 }1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1808 true,1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 181518161817181818191820182118221823 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1824 return await super.burnToken(signer, collectionId, tokenId, amount);1825 }18261827 1828182918301831183218331834183518361837 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1838 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1839 }18401841 18421843184418451846184718481849185018511852 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1853 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1854 }18551856 1857185818591860186118621863 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1864 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1865 }18661867 186818691870187118721873187418751876 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1877 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1878 const repartitionResult = await this.helper.executeExtrinsic(1879 signer,1880 'api.tx.unique.repartition', [collectionId, tokenId, amount],1881 true,1882 );1883 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1884 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1885 }1886}188718881889class FTGroup extends CollectionGroup {1890 189118921893189418951896 getCollectionObject(collectionId: number): UniqueFTCollection {1897 return new UniqueFTCollection(collectionId, this.helper);1898 }18991900 1901190219031904190519061907190819091910191119121913 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1914 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1915 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1916 collectionOptions.mode = {fungible: decimalPoints};1917 for (const key of ['name', 'description', 'tokenPrefix']) {1918 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);1919 }1920 const creationResult = await this.helper.executeExtrinsic(1921 signer,1922 'api.tx.unique.createCollectionEx', [collectionOptions],1923 true,1924 );1925 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1926 }19271928 192919301931193219331934193519361937 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1938 const creationResult = await this.helper.executeExtrinsic(1939 signer,1940 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1941 fungible: {1942 value: amount,1943 },1944 }],1945 true, 1946 );1947 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1948 }19491950 19511952195319541955195619571958 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1959 const rawTokens = [];1960 for (const token of tokens) {1961 const raw = {Fungible: {Value: token.value}};1962 rawTokens.push(raw);1963 }1964 const creationResult = await this.helper.executeExtrinsic(1965 signer,1966 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1967 true,1968 );1969 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1970 }19711972 197319741975197619771978 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1979 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1980 }19811982 1983198419851986198719881989 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1990 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1991 }19921993 199419951996199719981999200020012002 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2003 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2004 }20052006 2007200820092010201120122013201420152016 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2017 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2018 }20192020 20212022202320242025202620272028 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2029 return await super.burnToken(signer, collectionId, 0, amount);2030 }20312032 203320342035203620372038203920402041 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2042 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2043 }20442045 20462047204820492050 async getTotalPieces(collectionId: number): Promise<bigint> {2051 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2052 }20532054 2055205620572058205920602061206220632064 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2065 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2066 }20672068 2069207020712072207320742075 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2076 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2077 }2078}207920802081class ChainGroup extends HelperGroup<ChainHelperBase> {2082 20832084208520862087 getChainProperties(): IChainProperties {2088 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2089 return {2090 ss58Format: properties.ss58Format.toJSON(),2091 tokenDecimals: properties.tokenDecimals.toJSON(),2092 tokenSymbol: properties.tokenSymbol.toJSON(),2093 };2094 }20952096 20972098209921002101 async getLatestBlockNumber(): Promise<number> {2102 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2103 }21042105 210621072108210921102111 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2112 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2113 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2114 return blockHash;2115 }21162117 2118 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2119 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2120 if (!blockHash) return null;2121 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2122 }21232124 212521262127212821292130 async getNonce(address: TSubstrateAccount): Promise<number> {2131 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2132 }2133}21342135class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2136 213721382139214021412142 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2143 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2144 }21452146 21472148214921502151215221532154 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2155 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21562157 let transfer = {from: null, to: null, amount: 0n} as any;2158 result.result.events.forEach(({event: {data, method, section}}) => {2159 if ((section === 'balances') && (method === 'Transfer')) {2160 transfer = {2161 from: this.helper.address.normalizeSubstrate(data[0]),2162 to: this.helper.address.normalizeSubstrate(data[1]),2163 amount: BigInt(data[2]),2164 };2165 }2166 });2167 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2168 && this.helper.address.normalizeSubstrate(address) === transfer.to 2169 && BigInt(amount) === transfer.amount;2170 return isSuccess;2171 }21722173 21742175217621772178 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2179 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2180 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2181 }2182}21832184class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2185 218621872188218921902191 async getEthereum(address: TEthereumAccount): Promise<bigint> {2192 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2193 }21942195 21962197219821992200220122022203 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2204 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22052206 let transfer = {from: null, to: null, amount: 0n} as any;2207 result.result.events.forEach(({event: {data, method, section}}) => {2208 if ((section === 'balances') && (method === 'Transfer')) {2209 transfer = {2210 from: data[0].toString(),2211 to: data[1].toString(),2212 amount: BigInt(data[2]),2213 };2214 }2215 });2216 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2217 && address === transfer.to 2218 && BigInt(amount) === transfer.amount;2219 return isSuccess;2220 }2221}22222223class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2224 subBalanceGroup: SubstrateBalanceGroup<T>;2225 ethBalanceGroup: EthereumBalanceGroup<T>;22262227 constructor(helper: T) {2228 super(helper);2229 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2230 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2231 }22322233 getCollectionCreationPrice(): bigint {2234 return 2n * this.getOneTokenNominal();2235 }2236 22372238223922402241 getOneTokenNominal(): bigint {2242 const chainProperties = this.helper.chain.getChainProperties();2243 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2244 }22452246 224722482249225022512252 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2253 return this.subBalanceGroup.getSubstrate(address);2254 }22552256 22572258225922602261 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2262 return this.subBalanceGroup.getSubstrateFull(address);2263 }22642265 226622672268226922702271 async getEthereum(address: TEthereumAccount): Promise<bigint> {2272 return this.ethBalanceGroup.getEthereum(address);2273 }22742275 22762277227822792280228122822283 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2284 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2285 }2286}22872288class AddressGroup extends HelperGroup<ChainHelperBase> {2289 2290229122922293229422952296 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2297 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2298 }22992300 230123022303230423052306 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2307 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2308 }23092310 2311231223132314231523162317 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2318 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2319 }23202321 232223232324232523262327 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2328 return CrossAccountId.translateSubToEth(subAddress);2329 }23302331 paraSiblingSovereignAccount(paraid: number) {2332 2333 2334 const siblingPrefix = '0x7369626c';23352336 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2337 const suffix = '000000000000000000000000000000000000000000000000';23382339 return siblingPrefix + encodedParaId + suffix;2340 }2341}23422343class StakingGroup extends HelperGroup<UniqueHelper> {2344 2345234623472348234923502351 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2352 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2353 const _stakeResult = await this.helper.executeExtrinsic(2354 signer, 'api.tx.appPromotion.stake',2355 [amountToStake], true,2356 );2357 2358 return true;2359 }23602361 2362236323642365236623672368 async unstake(signer: TSigner, label?: string): Promise<number> {2369 if(typeof label === 'undefined') label = `${signer.address}`;2370 const _unstakeResult = await this.helper.executeExtrinsic(2371 signer, 'api.tx.appPromotion.unstake',2372 [], true,2373 );2374 2375 return 1;2376 }23772378 23792380238123822383 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2384 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2385 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2386 }23872388 23892390239123922393 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2394 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2395 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2396 return { 2397 block: block.toBigInt(),2398 amount: amount.toBigInt(),2399 };2400 });2401 }24022403 24042405240624072408 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2409 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2410 }24112412 24132414241524162417 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2418 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2419 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2420 return {2421 block: block.toBigInt(),2422 amount: amount.toBigInt(),2423 };2424 });2425 return result;2426 }2427}24282429class SchedulerGroup extends HelperGroup<UniqueHelper> {2430 constructor(helper: UniqueHelper) {2431 super(helper);2432 }24332434 async cancelScheduled(signer: TSigner, scheduledId: string) {2435 return this.helper.executeExtrinsic(2436 signer,2437 'api.tx.scheduler.cancelNamed',2438 [scheduledId],2439 true,2440 );2441 }24422443 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2444 return this.helper.executeExtrinsic(2445 signer,2446 'api.tx.scheduler.changeNamedPriority',2447 [scheduledId, priority],2448 true,2449 );2450 }24512452 scheduleAt<T extends UniqueHelper>(2453 scheduledId: string,2454 executionBlockNumber: number,2455 options: ISchedulerOptions = {},2456 ) {2457 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2458 }24592460 scheduleAfter<T extends UniqueHelper>(2461 scheduledId: string,2462 blocksBeforeExecution: number,2463 options: ISchedulerOptions = {},2464 ) {2465 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2466 }24672468 schedule<T extends UniqueHelper>(2469 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2470 scheduledId: string,2471 blocksNum: number,2472 options: ISchedulerOptions = {},2473 ) {2474 2475 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2476 return this.helper.clone(ScheduledHelperType, {2477 scheduleFn,2478 scheduledId,2479 blocksNum,2480 options,2481 }) as T;2482 }2483}24842485class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2486 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2487 await this.helper.executeExtrinsic(2488 signer,2489 'api.tx.foreignAssets.registerForeignAsset',2490 [ownerAddress, location, metadata],2491 true,2492 );2493 }24942495 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2496 await this.helper.executeExtrinsic(2497 signer,2498 'api.tx.foreignAssets.updateForeignAsset',2499 [foreignAssetId, location, metadata],2500 true,2501 );2502 }2503}25042505class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2506 palletName: string;25072508 constructor(helper: T, palletName: string) {2509 super(helper);25102511 this.palletName = palletName;2512 }25132514 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2515 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2516 }2517}25182519class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2520 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2521 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2522 }25232524 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2525 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2526 }25272528 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2529 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2530 }2531}25322533class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2534 async accounts(address: string, currencyId: any) {2535 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2536 return BigInt(free);2537 }2538}25392540class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2541 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2542 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2543 }25442545 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2546 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2547 }25482549 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2550 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2551 }25522553 async account(assetId: string | number, address: string) {2554 const accountAsset = (2555 await this.helper.callRpc('api.query.assets.account', [assetId, address])2556 ).toJSON()! as any;25572558 if (accountAsset !== null) {2559 return BigInt(accountAsset['balance']);2560 } else {2561 return null;2562 }2563 }2564}25652566class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2567 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2568 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2569 }2570}25712572class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2573 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2574 const apiPrefix = 'api.tx.assetManager.';25752576 const registerTx = this.helper.constructApiCall(2577 apiPrefix + 'registerForeignAsset',2578 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2579 );25802581 const setUnitsTx = this.helper.constructApiCall(2582 apiPrefix + 'setAssetUnitsPerSecond',2583 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2584 );25852586 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2587 const encodedProposal = batchCall?.method.toHex() || '';2588 return encodedProposal;2589 }25902591 async assetTypeId(location: any) {2592 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2593 }2594}25952596class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2597 async notePreimage(signer: TSigner, encodedProposal: string) {2598 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2599 }26002601 externalProposeMajority(proposalHash: string) {2602 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2603 }26042605 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2606 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2607 }26082609 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2610 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2611 }2612}26132614class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2615 collective: string;26162617 constructor(helper: MoonbeamHelper, collective: string) {2618 super(helper);26192620 this.collective = collective;2621 }26222623 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2624 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2625 }26262627 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2628 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2629 }26302631 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2632 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2633 }26342635 async proposalCount() {2636 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2637 }2638}26392640export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2641export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26422643export class UniqueHelper extends ChainHelperBase {2644 balance: BalanceGroup<UniqueHelper>;2645 collection: CollectionGroup;2646 nft: NFTGroup;2647 rft: RFTGroup;2648 ft: FTGroup;2649 staking: StakingGroup;2650 scheduler: SchedulerGroup;2651 foreignAssets: ForeignAssetsGroup;2652 xcm: XcmGroup<UniqueHelper>;2653 xTokens: XTokensGroup<UniqueHelper>;2654 tokens: TokensGroup<UniqueHelper>;26552656 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2657 super(logger, options.helperBase ?? UniqueHelper);26582659 this.balance = new BalanceGroup(this);2660 this.collection = new CollectionGroup(this);2661 this.nft = new NFTGroup(this);2662 this.rft = new RFTGroup(this);2663 this.ft = new FTGroup(this);2664 this.staking = new StakingGroup(this);2665 this.scheduler = new SchedulerGroup(this);2666 this.foreignAssets = new ForeignAssetsGroup(this);2667 this.xcm = new XcmGroup(this, 'polkadotXcm');2668 this.xTokens = new XTokensGroup(this);2669 this.tokens = new TokensGroup(this);2670 }26712672 getSudo<T extends UniqueHelper>() {2673 2674 const SudoHelperType = SudoHelper(this.helperBase);2675 return this.clone(SudoHelperType) as T;2676 }2677}26782679export class XcmChainHelper extends ChainHelperBase {2680 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2681 const wsProvider = new WsProvider(wsEndpoint);2682 this.api = new ApiPromise({2683 provider: wsProvider,2684 });2685 await this.api.isReadyOrError;2686 this.network = await UniqueHelper.detectNetwork(this.api);2687 }2688}26892690export class RelayHelper extends XcmChainHelper {2691 xcm: XcmGroup<RelayHelper>;26922693 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2694 super(logger, options.helperBase ?? RelayHelper);26952696 this.xcm = new XcmGroup(this, 'xcmPallet');2697 }2698}26992700export class WestmintHelper extends XcmChainHelper {2701 balance: SubstrateBalanceGroup<WestmintHelper>;2702 xcm: XcmGroup<WestmintHelper>;2703 assets: AssetsGroup<WestmintHelper>;2704 xTokens: XTokensGroup<WestmintHelper>;27052706 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2707 super(logger, options.helperBase ?? WestmintHelper);27082709 this.balance = new SubstrateBalanceGroup(this);2710 this.xcm = new XcmGroup(this, 'polkadotXcm');2711 this.assets = new AssetsGroup(this);2712 this.xTokens = new XTokensGroup(this);2713 }2714}27152716export class MoonbeamHelper extends XcmChainHelper {2717 balance: EthereumBalanceGroup<MoonbeamHelper>;2718 assetManager: MoonbeamAssetManagerGroup;2719 assets: AssetsGroup<MoonbeamHelper>;2720 xTokens: XTokensGroup<MoonbeamHelper>;2721 democracy: MoonbeamDemocracyGroup;2722 collective: {2723 council: MoonbeamCollectiveGroup,2724 techCommittee: MoonbeamCollectiveGroup,2725 };27262727 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2728 super(logger, options.helperBase ?? MoonbeamHelper);27292730 this.balance = new EthereumBalanceGroup(this);2731 this.assetManager = new MoonbeamAssetManagerGroup(this);2732 this.assets = new AssetsGroup(this);2733 this.xTokens = new XTokensGroup(this);2734 this.democracy = new MoonbeamDemocracyGroup(this);2735 this.collective = {2736 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2737 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2738 };2739 }2740}27412742export class AcalaHelper extends XcmChainHelper {2743 balance: SubstrateBalanceGroup<AcalaHelper>;2744 assetRegistry: AcalaAssetRegistryGroup;2745 xTokens: XTokensGroup<AcalaHelper>;2746 tokens: TokensGroup<AcalaHelper>;27472748 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2749 super(logger, options.helperBase ?? AcalaHelper);27502751 this.balance = new SubstrateBalanceGroup(this);2752 this.assetRegistry = new AcalaAssetRegistryGroup(this);2753 this.xTokens = new XTokensGroup(this);2754 this.tokens = new TokensGroup(this);2755 }27562757 getSudo<T extends AcalaHelper>() {2758 2759 const SudoHelperType = SudoHelper(this.helperBase);2760 return this.clone(SudoHelperType) as T;2761 }2762}276327642765function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2766 return class extends Base {2767 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2768 scheduledId: string;2769 blocksNum: number;2770 options: ISchedulerOptions;27712772 constructor(...args: any[]) {2773 const logger = args[0] as ILogger;2774 const options = args[1] as {2775 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2776 scheduledId: string,2777 blocksNum: number,2778 options: ISchedulerOptions2779 };27802781 super(logger);27822783 this.scheduleFn = options.scheduleFn;2784 this.scheduledId = options.scheduledId;2785 this.blocksNum = options.blocksNum;2786 this.options = options.options;2787 }27882789 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2790 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2791 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;27922793 return super.executeExtrinsic(2794 sender,2795 extrinsic,2796 [2797 this.scheduledId,2798 this.blocksNum,2799 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2800 this.options.priority ?? null,2801 {Value: scheduledTx},2802 ],2803 expectSuccess,2804 );2805 }2806 };2807}280828092810function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2811 return class extends Base {2812 constructor(...args: any[]) {2813 super(...args);2814 }28152816 executeExtrinsic (2817 sender: IKeyringPair,2818 extrinsic: string,2819 params: any[],2820 expectSuccess?: boolean,2821 ): Promise<ITransactionResult> {2822 const call = this.constructApiCall(extrinsic, params);28232824 return super.executeExtrinsic(2825 sender,2826 'api.tx.sudo.sudo',2827 [call],2828 expectSuccess,2829 );2830 }2831 };2832}28332834export class UniqueBaseCollection {2835 helper: UniqueHelper;2836 collectionId: number;28372838 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2839 this.collectionId = collectionId;2840 this.helper = uniqueHelper;2841 }28422843 async getData() {2844 return await this.helper.collection.getData(this.collectionId);2845 }28462847 async getLastTokenId() {2848 return await this.helper.collection.getLastTokenId(this.collectionId);2849 }28502851 async doesTokenExist(tokenId: number) {2852 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2853 }28542855 async getAdmins() {2856 return await this.helper.collection.getAdmins(this.collectionId);2857 }28582859 async getAllowList() {2860 return await this.helper.collection.getAllowList(this.collectionId);2861 }28622863 async getEffectiveLimits() {2864 return await this.helper.collection.getEffectiveLimits(this.collectionId);2865 }28662867 async getProperties(propertyKeys?: string[] | null) {2868 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2869 }28702871 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2872 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2873 }28742875 async getOptions() {2876 return await this.helper.collection.getCollectionOptions(this.collectionId);2877 }28782879 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2880 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2881 }28822883 async confirmSponsorship(signer: TSigner) {2884 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2885 }28862887 async removeSponsor(signer: TSigner) {2888 return await this.helper.collection.removeSponsor(signer, this.collectionId);2889 }28902891 async setLimits(signer: TSigner, limits: ICollectionLimits) {2892 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2893 }28942895 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2896 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2897 }28982899 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2900 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2901 }29022903 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2904 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2905 }29062907 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2908 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2909 }29102911 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2912 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2913 }29142915 async setProperties(signer: TSigner, properties: IProperty[]) {2916 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2917 }29182919 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2920 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2921 }29222923 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2924 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2925 }29262927 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2928 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2929 }29302931 async disableNesting(signer: TSigner) {2932 return await this.helper.collection.disableNesting(signer, this.collectionId);2933 }29342935 async burn(signer: TSigner) {2936 return await this.helper.collection.burn(signer, this.collectionId);2937 }29382939 scheduleAt<T extends UniqueHelper>(2940 scheduledId: string,2941 executionBlockNumber: number,2942 options: ISchedulerOptions = {},2943 ) {2944 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2945 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2946 }29472948 scheduleAfter<T extends UniqueHelper>(2949 scheduledId: string,2950 blocksBeforeExecution: number,2951 options: ISchedulerOptions = {},2952 ) {2953 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2954 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2955 }29562957 getSudo<T extends UniqueHelper>() {2958 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2959 }2960}296129622963export class UniqueNFTCollection extends UniqueBaseCollection {2964 getTokenObject(tokenId: number) {2965 return new UniqueNFToken(tokenId, this);2966 }29672968 async getTokensByAddress(addressObj: ICrossAccountId) {2969 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2970 }29712972 async getToken(tokenId: number, blockHashAt?: string) {2973 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2974 }29752976 async getTokenOwner(tokenId: number, blockHashAt?: string) {2977 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2978 }29792980 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2981 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2982 }29832984 async getTokenChildren(tokenId: number, blockHashAt?: string) {2985 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2986 }29872988 async getPropertyPermissions(propertyKeys: string[] | null = null) {2989 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2990 }29912992 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2993 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2994 }29952996 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2997 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2998 }29993000 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3001 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3002 }30033004 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3005 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3006 }30073008 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3009 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3010 }30113012 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3013 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3014 }30153016 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3017 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3018 }30193020 async burnToken(signer: TSigner, tokenId: number) {3021 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3022 }30233024 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3025 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3026 }30273028 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3029 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3030 }30313032 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3033 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3034 }30353036 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3037 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3038 }30393040 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3041 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3042 }30433044 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3045 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3046 }30473048 scheduleAt<T extends UniqueHelper>(3049 scheduledId: string,3050 executionBlockNumber: number,3051 options: ISchedulerOptions = {},3052 ) {3053 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3054 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3055 }30563057 scheduleAfter<T extends UniqueHelper>(3058 scheduledId: string,3059 blocksBeforeExecution: number,3060 options: ISchedulerOptions = {},3061 ) {3062 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3063 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3064 }30653066 getSudo<T extends UniqueHelper>() {3067 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3068 }3069}307030713072export class UniqueRFTCollection extends UniqueBaseCollection {3073 getTokenObject(tokenId: number) {3074 return new UniqueRFToken(tokenId, this);3075 }30763077 async getToken(tokenId: number, blockHashAt?: string) {3078 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3079 }30803081 async getTokensByAddress(addressObj: ICrossAccountId) {3082 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3083 }30843085 async getTop10TokenOwners(tokenId: number) {3086 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3087 }30883089 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3090 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3091 }30923093 async getTokenTotalPieces(tokenId: number) {3094 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3095 }30963097 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3098 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3099 }31003101 async getPropertyPermissions(propertyKeys: string[] | null = null) {3102 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3103 }31043105 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3106 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3107 }31083109 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3110 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3111 }31123113 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3114 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3115 }31163117 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3118 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3119 }31203121 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3122 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3123 }31243125 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3126 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3127 }31283129 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3130 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3131 }31323133 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3134 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3135 }31363137 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3138 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3139 }31403141 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3142 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3143 }31443145 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3146 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3147 }31483149 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3150 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3151 }31523153 scheduleAt<T extends UniqueHelper>(3154 scheduledId: string,3155 executionBlockNumber: number,3156 options: ISchedulerOptions = {},3157 ) {3158 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3159 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3160 }31613162 scheduleAfter<T extends UniqueHelper>(3163 scheduledId: string,3164 blocksBeforeExecution: number,3165 options: ISchedulerOptions = {},3166 ) {3167 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3168 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3169 }31703171 getSudo<T extends UniqueHelper>() {3172 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3173 }3174}317531763177export class UniqueFTCollection extends UniqueBaseCollection {3178 async getBalance(addressObj: ICrossAccountId) {3179 return await this.helper.ft.getBalance(this.collectionId, addressObj);3180 }31813182 async getTotalPieces() {3183 return await this.helper.ft.getTotalPieces(this.collectionId);3184 }31853186 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3187 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3188 }31893190 async getTop10Owners() {3191 return await this.helper.ft.getTop10Owners(this.collectionId);3192 }31933194 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3195 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3196 }31973198 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3199 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3200 }32013202 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3203 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3204 }32053206 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3207 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3208 }32093210 async burnTokens(signer: TSigner, amount=1n) {3211 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3212 }32133214 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3215 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3216 }32173218 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3219 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3220 }32213222 scheduleAt<T extends UniqueHelper>(3223 scheduledId: string,3224 executionBlockNumber: number,3225 options: ISchedulerOptions = {},3226 ) {3227 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3228 return new UniqueFTCollection(this.collectionId, scheduledHelper);3229 }32303231 scheduleAfter<T extends UniqueHelper>(3232 scheduledId: string,3233 blocksBeforeExecution: number,3234 options: ISchedulerOptions = {},3235 ) {3236 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3237 return new UniqueFTCollection(this.collectionId, scheduledHelper);3238 }32393240 getSudo<T extends UniqueHelper>() {3241 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3242 }3243}324432453246export class UniqueBaseToken {3247 collection: UniqueNFTCollection | UniqueRFTCollection;3248 collectionId: number;3249 tokenId: number;32503251 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3252 this.collection = collection;3253 this.collectionId = collection.collectionId;3254 this.tokenId = tokenId;3255 }32563257 async getNextSponsored(addressObj: ICrossAccountId) {3258 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3259 }32603261 async getProperties(propertyKeys?: string[] | null) {3262 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3263 }32643265 async setProperties(signer: TSigner, properties: IProperty[]) {3266 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3267 }32683269 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3270 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3271 }32723273 async doesExist() {3274 return await this.collection.doesTokenExist(this.tokenId);3275 }32763277 nestingAccount() {3278 return this.collection.helper.util.getTokenAccount(this);3279 }32803281 scheduleAt<T extends UniqueHelper>(3282 scheduledId: string,3283 executionBlockNumber: number,3284 options: ISchedulerOptions = {},3285 ) {3286 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3287 return new UniqueBaseToken(this.tokenId, scheduledCollection);3288 }32893290 scheduleAfter<T extends UniqueHelper>(3291 scheduledId: string,3292 blocksBeforeExecution: number,3293 options: ISchedulerOptions = {},3294 ) {3295 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3296 return new UniqueBaseToken(this.tokenId, scheduledCollection);3297 }32983299 getSudo<T extends UniqueHelper>() {3300 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3301 }3302}330333043305export class UniqueNFToken extends UniqueBaseToken {3306 collection: UniqueNFTCollection;33073308 constructor(tokenId: number, collection: UniqueNFTCollection) {3309 super(tokenId, collection);3310 this.collection = collection;3311 }33123313 async getData(blockHashAt?: string) {3314 return await this.collection.getToken(this.tokenId, blockHashAt);3315 }33163317 async getOwner(blockHashAt?: string) {3318 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3319 }33203321 async getTopmostOwner(blockHashAt?: string) {3322 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3323 }33243325 async getChildren(blockHashAt?: string) {3326 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3327 }33283329 async nest(signer: TSigner, toTokenObj: IToken) {3330 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3331 }33323333 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3334 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3335 }33363337 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3338 return await this.collection.transferToken(signer, this.tokenId, addressObj);3339 }33403341 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3342 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3343 }33443345 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3346 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3347 }33483349 async isApproved(toAddressObj: ICrossAccountId) {3350 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3351 }33523353 async burn(signer: TSigner) {3354 return await this.collection.burnToken(signer, this.tokenId);3355 }33563357 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3358 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3359 }33603361 scheduleAt<T extends UniqueHelper>(3362 scheduledId: string,3363 executionBlockNumber: number,3364 options: ISchedulerOptions = {},3365 ) {3366 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3367 return new UniqueNFToken(this.tokenId, scheduledCollection);3368 }33693370 scheduleAfter<T extends UniqueHelper>(3371 scheduledId: string,3372 blocksBeforeExecution: number,3373 options: ISchedulerOptions = {},3374 ) {3375 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3376 return new UniqueNFToken(this.tokenId, scheduledCollection);3377 }33783379 getSudo<T extends UniqueHelper>() {3380 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3381 }3382}33833384export class UniqueRFToken extends UniqueBaseToken {3385 collection: UniqueRFTCollection;33863387 constructor(tokenId: number, collection: UniqueRFTCollection) {3388 super(tokenId, collection);3389 this.collection = collection;3390 }33913392 async getData(blockHashAt?: string) {3393 return await this.collection.getToken(this.tokenId, blockHashAt);3394 }33953396 async getTop10Owners() {3397 return await this.collection.getTop10TokenOwners(this.tokenId);3398 }33993400 async getBalance(addressObj: ICrossAccountId) {3401 return await this.collection.getTokenBalance(this.tokenId, addressObj);3402 }34033404 async getTotalPieces() {3405 return await this.collection.getTokenTotalPieces(this.tokenId);3406 }34073408 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3409 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3410 }34113412 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3413 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3414 }34153416 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3417 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3418 }34193420 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3421 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3422 }34233424 async repartition(signer: TSigner, amount: bigint) {3425 return await this.collection.repartitionToken(signer, this.tokenId, amount);3426 }34273428 async burn(signer: TSigner, amount=1n) {3429 return await this.collection.burnToken(signer, this.tokenId, amount);3430 }34313432 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3433 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3434 }34353436 scheduleAt<T extends UniqueHelper>(3437 scheduledId: string,3438 executionBlockNumber: number,3439 options: ISchedulerOptions = {},3440 ) {3441 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3442 return new UniqueRFToken(this.tokenId, scheduledCollection);3443 }34443445 scheduleAfter<T extends UniqueHelper>(3446 scheduledId: string,3447 blocksBeforeExecution: number,3448 options: ISchedulerOptions = {},3449 ) {3450 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3451 return new UniqueRFToken(this.tokenId, scheduledCollection);3452 }34533454 getSudo<T extends UniqueHelper>() {3455 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3456 }3457}