difftreelog
Fix helpers and tests
in: master
2 files changed
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15 IApiListeners,16 IBlock,17 IEvent,18 IChainProperties,19 ICollectionCreationOptions,20 ICollectionLimits,21 ICollectionPermissions,22 ICrossAccountId,23 ICrossAccountIdLower,24 ILogger,25 INestingPermissions,26 IProperty,27 IStakingInfo,28 ISchedulerOptions,29 ISubstrateBalance,30 IToken,31 ITokenPropertyPermission,32 ITransactionResult,33 IUniqueHelperLog,34 TApiAllowedListeners,35 TEthereumAccount,36 TSigner,37 TSubstrateAccount,38 TNetworks,39 IForeignAssetMetadata,40 AcalaAssetMetadata,41 MoonbeamAssetInfo,42 DemocracyStandardAccountVote,43 IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';4647export class CrossAccountId implements ICrossAccountId {48 Substrate?: TSubstrateAccount;49 Ethereum?: TEthereumAccount;5051 constructor(account: ICrossAccountId) {52 if (account.Substrate) this.Substrate = account.Substrate;53 if (account.Ethereum) this.Ethereum = account.Ethereum;54 }5556 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {57 switch (domain) {58 case 'Substrate': return new CrossAccountId({Substrate: account.address});59 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();60 }61 }6263 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {64 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});65 }6667 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {68 return encodeAddress(decodeAddress(address), ss58Format);69 }7071 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {72 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});73 }7475 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {76 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);77 return this;78 }7980 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {81 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));82 }8384 toEthereum(): CrossAccountId {85 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});86 return this;87 }8889 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {90 return evmToAddress(address, ss58Format);91 }9293 toSubstrate(ss58Format?: number): CrossAccountId {94 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});95 return this;96 }9798 toLowerCase(): CrossAccountId {99 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();100 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();101 return this;102 }103}104105const nesting = {106 toChecksumAddress(address: string): string {107 if (typeof address === 'undefined') return '';108109 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);110111 address = address.toLowerCase().replace(/^0x/i,'');112 const addressHash = keccakAsHex(address).replace(/^0x/i,'');113 const checksumAddress = ['0x'];114115 for (let i = 0; i < address.length; i++) {116 // If ith character is 8 to f then make it uppercase117 if (parseInt(addressHash[i], 16) > 7) {118 checksumAddress.push(address[i].toUpperCase());119 } else {120 checksumAddress.push(address[i]);121 }122 }123 return checksumAddress.join('');124 },125 tokenIdToAddress(collectionId: number, tokenId: number) {126 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);127 },128};129130class UniqueUtil {131 static transactionStatus = {132 NOT_READY: 'NotReady',133 FAIL: 'Fail',134 SUCCESS: 'Success',135 };136137 static chainLogType = {138 EXTRINSIC: 'extrinsic',139 RPC: 'rpc',140 };141142 static getTokenAccount(token: IToken): CrossAccountId {143 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});144 }145146 static getTokenAddress(token: IToken): string {147 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);148 }149150 static getDefaultLogger(): ILogger {151 return {152 log(msg: any, level = 'INFO') {153 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));154 },155 level: {156 ERROR: 'ERROR',157 WARNING: 'WARNING',158 INFO: 'INFO',159 },160 };161 }162163 static vec2str(arr: string[] | number[]) {164 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');165 }166167 static str2vec(string: string) {168 if (typeof string !== 'string') return string;169 return Array.from(string).map(x => x.charCodeAt(0));170 }171172 static fromSeed(seed: string, ss58Format = 42) {173 const keyring = new Keyring({type: 'sr25519', ss58Format});174 return keyring.addFromUri(seed);175 }176177 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {178 if (creationResult.status !== this.transactionStatus.SUCCESS) {179 throw Error('Unable to create collection!');180 }181182 let collectionId = null;183 creationResult.result.events.forEach(({event: {data, method, section}}) => {184 if ((section === 'common') && (method === 'CollectionCreated')) {185 collectionId = parseInt(data[0].toString(), 10);186 }187 });188189 if (collectionId === null) {190 throw Error('No CollectionCreated event was found!');191 }192193 return collectionId;194 }195196 static extractTokensFromCreationResult(creationResult: ITransactionResult): {197 success: boolean,198 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],199 } {200 if (creationResult.status !== this.transactionStatus.SUCCESS) {201 throw Error('Unable to create tokens!');202 }203 let success = false;204 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];205 creationResult.result.events.forEach(({event: {data, method, section}}) => {206 if (method === 'ExtrinsicSuccess') {207 success = true;208 } else if ((section === 'common') && (method === 'ItemCreated')) {209 tokens.push({210 collectionId: parseInt(data[0].toString(), 10),211 tokenId: parseInt(data[1].toString(), 10),212 owner: data[2].toHuman(),213 amount: data[3].toBigInt(),214 });215 }216 });217 return {success, tokens};218 }219220 static extractTokensFromBurnResult(burnResult: ITransactionResult): {221 success: boolean,222 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],223 } {224 if (burnResult.status !== this.transactionStatus.SUCCESS) {225 throw Error('Unable to burn tokens!');226 }227 let success = false;228 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];229 burnResult.result.events.forEach(({event: {data, method, section}}) => {230 if (method === 'ExtrinsicSuccess') {231 success = true;232 } else if ((section === 'common') && (method === 'ItemDestroyed')) {233 tokens.push({234 collectionId: parseInt(data[0].toString(), 10),235 tokenId: parseInt(data[1].toString(), 10),236 owner: data[2].toHuman(),237 amount: data[3].toBigInt(),238 });239 }240 });241 return {success, tokens};242 }243244 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {245 let eventId = null;246 events.forEach(({event: {data, method, section}}) => {247 if ((section === expectedSection) && (method === expectedMethod)) {248 eventId = parseInt(data[0].toString(), 10);249 }250 });251252 if (eventId === null) {253 throw Error(`No ${expectedMethod} event was found!`);254 }255 return eventId === collectionId;256 }257258 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {259 const normalizeAddress = (address: string | ICrossAccountId) => {260 if(typeof address === 'string') return address;261 const obj = {} as any;262 Object.keys(address).forEach(k => {263 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];264 });265 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);266 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();267 return address;268 };269 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;270 events.forEach(({event: {data, method, section}}) => {271 if ((section === 'common') && (method === 'Transfer')) {272 const hData = (data as any).toJSON();273 transfer = {274 collectionId: hData[0],275 tokenId: hData[1],276 from: normalizeAddress(hData[2]),277 to: normalizeAddress(hData[3]),278 amount: BigInt(hData[4]),279 };280 }281 });282 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;283 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);284 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);285 isSuccess = isSuccess && amount === transfer.amount;286 return isSuccess;287 }288289 static bigIntToDecimals(number: bigint, decimals = 18) {290 const numberStr = number.toString();291 const dotPos = numberStr.length - decimals;292293 if (dotPos <= 0) {294 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;295 } else {296 const intPart = numberStr.substring(0, dotPos);297 const fractPart = numberStr.substring(dotPos);298 return intPart + '.' + fractPart;299 }300 }301}302303class UniqueEventHelper {304 private static extractIndex(index: any): [number, number] | string {305 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];306 return index.toJSON();307 }308309 private static extractSub(data: any, subTypes: any): {[key: string]: any} {310 let obj: any = {};311 let index = 0;312313 if (data.entries) {314 for(const [key, value] of data.entries()) {315 obj[key] = this.extractData(value, subTypes[index]);316 index++;317 }318 } else obj = data.toJSON();319320 return obj;321 }322323 private static extractData(data: any, type: any): any {324 if(!type) return data.toHuman();325 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();326 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();327 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);328 return data.toHuman();329 }330331 public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {332 const parsedEvents: IEvent[] = [];333334 events.forEach((record) => {335 const {event, phase} = record;336 const types = event.typeDef;337338 const eventData: IEvent = {339 section: event.section.toString(),340 method: event.method.toString(),341 index: this.extractIndex(event.index),342 data: [],343 phase: phase.toJSON(),344 };345346 event.data.forEach((val: any, index: number) => {347 eventData.data.push(this.extractData(val, types[index]));348 });349350 parsedEvents.push(eventData);351 });352353 return parsedEvents;354 }355}356357export class ChainHelperBase {358 helperBase: any;359360 transactionStatus = UniqueUtil.transactionStatus;361 chainLogType = UniqueUtil.chainLogType;362 util: typeof UniqueUtil;363 eventHelper: typeof UniqueEventHelper;364 logger: ILogger;365 api: ApiPromise | null;366 forcedNetwork: TNetworks | null;367 network: TNetworks | null;368 chainLog: IUniqueHelperLog[];369 children: ChainHelperBase[];370 address: AddressGroup;371 chain: ChainGroup;372373 constructor(logger?: ILogger, helperBase?: any) {374 this.helperBase = helperBase;375376 this.util = UniqueUtil;377 this.eventHelper = UniqueEventHelper;378 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();379 this.logger = logger;380 this.api = null;381 this.forcedNetwork = null;382 this.network = null;383 this.chainLog = [];384 this.children = [];385 this.address = new AddressGroup(this);386 this.chain = new ChainGroup(this);387 }388389 clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {390 Object.setPrototypeOf(helperCls.prototype, this);391 const newHelper = new helperCls(this.logger, options);392393 newHelper.api = this.api;394 newHelper.network = this.network;395 newHelper.forceNetwork = this.forceNetwork;396397 this.children.push(newHelper);398399 return newHelper;400 }401402 getApi(): ApiPromise {403 if(this.api === null) throw Error('API not initialized');404 return this.api;405 }406407 clearChainLog(): void {408 this.chainLog = [];409 }410411 forceNetwork(value: TNetworks): void {412 this.forcedNetwork = value;413 }414415 async connect(wsEndpoint: string, listeners?: IApiListeners) {416 if (this.api !== null) throw Error('Already connected');417 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);418 this.api = api;419 this.network = network;420 }421422 async disconnect() {423 for (const child of this.children) {424 child.clearApi();425 }426427 if (this.api === null) return;428 await this.api.disconnect();429 this.clearApi();430 }431432 clearApi() {433 this.api = null;434 this.network = null;435 }436437 static async detectNetwork(api: ApiPromise): Promise<TNetworks> {438 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;439 const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];440441 if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;442443 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;444 return 'opal';445 }446447 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {448 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});449 await api.isReady;450451 const network = await this.detectNetwork(api);452453 await api.disconnect();454455 return network;456 }457458 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{459 api: ApiPromise;460 network: TNetworks;461 }> {462 if(typeof network === 'undefined' || network === null) network = 'opal';463 const supportedRPC = {464 opal: {465 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,466 },467 quartz: {468 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,469 },470 unique: {471 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,472 },473 rococo: {},474 westend: {},475 moonbeam: {},476 moonriver: {},477 acala: {},478 karura: {},479 westmint: {},480 };481 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);482 const rpc = supportedRPC[network];483484 // TODO: investigate how to replace rpc in runtime485 // api._rpcCore.addUserInterfaces(rpc);486487 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});488489 await api.isReadyOrError;490491 if (typeof listeners === 'undefined') listeners = {};492 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {493 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;494 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);495 }496497 return {api, network};498 }499500 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {501 const {events, status} = data;502 if (status.isReady) {503 return this.transactionStatus.NOT_READY;504 }505 if (status.isBroadcast) {506 return this.transactionStatus.NOT_READY;507 }508 if (status.isInBlock || status.isFinalized) {509 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');510 if (errors.length > 0) {511 return this.transactionStatus.FAIL;512 }513 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {514 return this.transactionStatus.SUCCESS;515 }516 }517518 return this.transactionStatus.FAIL;519 }520521 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {522 const sign = (callback: any) => {523 if(options !== null) return transaction.signAndSend(sender, options, callback);524 return transaction.signAndSend(sender, callback);525 };526 // eslint-disable-next-line no-async-promise-executor527 return new Promise(async (resolve, reject) => {528 try {529 const unsub = await sign((result: any) => {530 const status = this.getTransactionStatus(result);531532 if (status === this.transactionStatus.SUCCESS) {533 this.logger.log(`${label} successful`);534 unsub();535 resolve({result, status});536 } else if (status === this.transactionStatus.FAIL) {537 let moduleError = null;538539 if (result.hasOwnProperty('dispatchError')) {540 const dispatchError = result['dispatchError'];541542 if (dispatchError) {543 if (dispatchError.isModule) {544 const modErr = dispatchError.asModule;545 const errorMeta = dispatchError.registry.findMetaError(modErr);546547 moduleError = `${errorMeta.section}.${errorMeta.name}`;548 } else {549 moduleError = dispatchError.toHuman();550 }551 } else {552 this.logger.log(result, this.logger.level.ERROR);553 }554 }555556 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);557 unsub();558 reject({status, moduleError, result});559 }560 });561 } catch (e) {562 this.logger.log(e, this.logger.level.ERROR);563 reject(e);564 }565 });566 }567568 async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {569 const api = this.getApi();570 const signingInfo = await api.derive.tx.signingInfo(signer.address);571572 // We need to sign the tx because573 // unsigned transactions does not have an inclusion fee574 tx.sign(signer, {575 blockHash: api.genesisHash,576 genesisHash: api.genesisHash,577 runtimeVersion: api.runtimeVersion,578 nonce: signingInfo.nonce,579 });580581 if (len === null) {582 return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;583 } else {584 return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;585 }586 }587588 constructApiCall(apiCall: string, params: any[]) {589 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);590 let call = this.getApi() as any;591 for(const part of apiCall.slice(4).split('.')) {592 call = call[part];593 }594 return call(...params);595 }596597 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {598 if(this.api === null) throw Error('API not initialized');599 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);600601 const startTime = (new Date()).getTime();602 let result: ITransactionResult;603 let events: IEvent[] = [];604 try {605 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;606 events = this.eventHelper.extractEvents(result.result.events);607 }608 catch(e) {609 if(!(e as object).hasOwnProperty('status')) throw e;610 result = e as ITransactionResult;611 }612613 const endTime = (new Date()).getTime();614615 const log = {616 executedAt: endTime,617 executionTime: endTime - startTime,618 type: this.chainLogType.EXTRINSIC,619 status: result.status,620 call: extrinsic,621 signer: this.getSignerAddress(sender),622 params,623 } as IUniqueHelperLog;624625 if(result.status !== this.transactionStatus.SUCCESS) {626 if (result.moduleError) log.moduleError = result.moduleError;627 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;628 }629 if(events.length > 0) log.events = events;630631 this.chainLog.push(log);632633 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {634 if (result.moduleError) throw Error(`${result.moduleError}`);635 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));636 }637 return result;638 }639640 async callRpc(rpc: string, params?: any[]) {641 if(typeof params === 'undefined') params = [];642 if(this.api === null) throw Error('API not initialized');643 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);644645 const startTime = (new Date()).getTime();646 let result;647 let error = null;648 const log = {649 type: this.chainLogType.RPC,650 call: rpc,651 params,652 } as IUniqueHelperLog;653654 try {655 result = await this.constructApiCall(rpc, params);656 }657 catch(e) {658 error = e;659 }660661 const endTime = (new Date()).getTime();662663 log.executedAt = endTime;664 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';665 log.executionTime = endTime - startTime;666667 this.chainLog.push(log);668669 if(error !== null) throw error;670671 return result;672 }673674 getSignerAddress(signer: IKeyringPair | string): string {675 if(typeof signer === 'string') return signer;676 return signer.address;677 }678679 fetchAllPalletNames(): string[] {680 if(this.api === null) throw Error('API not initialized');681 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());682 }683684 fetchMissingPalletNames(requiredPallets: string[]): string[] {685 const palletNames = this.fetchAllPalletNames();686 return requiredPallets.filter(p => !palletNames.includes(p));687 }688}689690691class HelperGroup<T extends ChainHelperBase> {692 helper: T;693694 constructor(uniqueHelper: T) {695 this.helper = uniqueHelper;696 }697}698699700class CollectionGroup extends HelperGroup<UniqueHelper> {701 /**702 * Get number of blocks when sponsored transaction is available.703 *704 * @param collectionId ID of collection705 * @param tokenId ID of token706 * @param addressObj address for which the sponsorship is checked707 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});708 * @returns number of blocks or null if sponsorship hasn't been set709 */710 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {711 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();712 }713714 /**715 * Get the number of created collections.716 *717 * @returns number of created collections718 */719 async getTotalCount(): Promise<number> {720 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();721 }722723 /**724 * Get information about the collection with additional data,725 * including the number of tokens it contains, its administrators,726 * the normalized address of the collection's owner, and decoded name and description.727 *728 * @param collectionId ID of collection729 * @example await getData(2)730 * @returns collection information object731 */732 async getData(collectionId: number): Promise<{733 id: number;734 name: string;735 description: string;736 tokensCount: number;737 admins: CrossAccountId[];738 normalizedOwner: TSubstrateAccount;739 raw: any740 } | null> {741 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);742 const humanCollection = collection.toHuman(), collectionData = {743 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],744 raw: humanCollection,745 } as any, jsonCollection = collection.toJSON();746 if (humanCollection === null) return null;747 collectionData.raw.limits = jsonCollection.limits;748 collectionData.raw.permissions = jsonCollection.permissions;749 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);750 for (const key of ['name', 'description']) {751 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);752 }753754 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))755 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)756 : 0;757 collectionData.admins = await this.getAdmins(collectionId);758759 return collectionData;760 }761762 /**763 * Get the addresses of the collection's administrators, optionally normalized.764 *765 * @param collectionId ID of collection766 * @param normalize whether to normalize the addresses to the default ss58 format767 * @example await getAdmins(1)768 * @returns array of administrators769 */770 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {771 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();772773 return normalize774 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())775 : admins;776 }777778 /**779 * Get the addresses added to the collection allow-list, optionally normalized.780 * @param collectionId ID of collection781 * @param normalize whether to normalize the addresses to the default ss58 format782 * @example await getAllowList(1)783 * @returns array of allow-listed addresses784 */785 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {786 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();787 return normalize788 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())789 : allowListed;790 }791792 /**793 * Get the effective limits of the collection instead of null for default values794 *795 * @param collectionId ID of collection796 * @example await getEffectiveLimits(2)797 * @returns object of collection limits798 */799 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {800 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();801 }802803 /**804 * Burns the collection if the signer has sufficient permissions and collection is empty.805 *806 * @param signer keyring of signer807 * @param collectionId ID of collection808 * @example await helper.collection.burn(aliceKeyring, 3);809 * @returns ```true``` if extrinsic success, otherwise ```false```810 */811 async burn(signer: TSigner, collectionId: number): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.destroyCollection', [collectionId],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');819 }820821 /**822 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.823 *824 * @param signer keyring of signer825 * @param collectionId ID of collection826 * @param sponsorAddress Sponsor substrate address827 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")828 * @returns ```true``` if extrinsic success, otherwise ```false```829 */830 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');838 }839840 /**841 * Confirms consent to sponsor the collection on behalf of the signer.842 *843 * @param signer keyring of signer844 * @param collectionId ID of collection845 * @example confirmSponsorship(aliceKeyring, 10)846 * @returns ```true``` if extrinsic success, otherwise ```false```847 */848 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.confirmSponsorship', [collectionId],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');856 }857858 /**859 * Removes the sponsor of a collection, regardless if it consented or not.860 *861 * @param signer keyring of signer862 * @param collectionId ID of collection863 * @example removeSponsor(aliceKeyring, 10)864 * @returns ```true``` if extrinsic success, otherwise ```false```865 */866 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {867 const result = await this.helper.executeExtrinsic(868 signer,869 'api.tx.unique.removeCollectionSponsor', [collectionId],870 true,871 );872873 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');874 }875876 /**877 * Sets the limits of the collection. At least one limit must be specified for a correct call.878 *879 * @param signer keyring of signer880 * @param collectionId ID of collection881 * @param limits collection limits object882 * @example883 * await setLimits(884 * aliceKeyring,885 * 10,886 * {887 * sponsorTransferTimeout: 0,888 * ownerCanDestroy: false889 * }890 * )891 * @returns ```true``` if extrinsic success, otherwise ```false```892 */893 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {894 const result = await this.helper.executeExtrinsic(895 signer,896 'api.tx.unique.setCollectionLimits', [collectionId, limits],897 true,898 );899900 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');901 }902903 /**904 * Changes the owner of the collection to the new Substrate address.905 *906 * @param signer keyring of signer907 * @param collectionId ID of collection908 * @param ownerAddress substrate address of new owner909 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")910 * @returns ```true``` if extrinsic success, otherwise ```false```911 */912 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {913 const result = await this.helper.executeExtrinsic(914 signer,915 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],916 true,917 );918919 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');920 }921922 /**923 * Adds a collection administrator.924 *925 * @param signer keyring of signer926 * @param collectionId ID of collection927 * @param adminAddressObj Administrator address (substrate or ethereum)928 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})929 * @returns ```true``` if extrinsic success, otherwise ```false```930 */931 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {932 const result = await this.helper.executeExtrinsic(933 signer,934 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],935 true,936 );937938 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');939 }940941 /**942 * Removes a collection administrator.943 *944 * @param signer keyring of signer945 * @param collectionId ID of collection946 * @param adminAddressObj Administrator address (substrate or ethereum)947 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})948 * @returns ```true``` if extrinsic success, otherwise ```false```949 */950 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');958 }959960 /**961 * Check if user is in allow list.962 *963 * @param collectionId ID of collection964 * @param user Account to check965 * @example await getAdmins(1)966 * @returns is user in allow list967 */968 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {969 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();970 }971972 /**973 * Adds an address to allow list974 * @param signer keyring of signer975 * @param collectionId ID of collection976 * @param addressObj address to add to the allow list977 * @returns ```true``` if extrinsic success, otherwise ```false```978 */979 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {980 const result = await this.helper.executeExtrinsic(981 signer,982 'api.tx.unique.addToAllowList', [collectionId, addressObj],983 true,984 );985986 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');987 }988989 /**990 * Removes an address from allow list991 *992 * @param signer keyring of signer993 * @param collectionId ID of collection994 * @param addressObj address to remove from the allow list995 * @returns ```true``` if extrinsic success, otherwise ```false```996 */997 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {998 const result = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1001 true,1002 );10031004 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');1005 }10061007 /**1008 * Sets onchain permissions for selected collection.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @param permissions collection permissions object1013 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1014 * @returns ```true``` if extrinsic success, otherwise ```false```1015 */1016 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1017 const result = await this.helper.executeExtrinsic(1018 signer,1019 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1020 true,1021 );10221023 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');1024 }10251026 /**1027 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1028 *1029 * @param signer keyring of signer1030 * @param collectionId ID of collection1031 * @param permissions nesting permissions object1032 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1033 * @returns ```true``` if extrinsic success, otherwise ```false```1034 */1035 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1036 return await this.setPermissions(signer, collectionId, {nesting: permissions});1037 }10381039 /**1040 * Disables nesting for selected collection.1041 *1042 * @param signer keyring of signer1043 * @param collectionId ID of collection1044 * @example disableNesting(aliceKeyring, 10);1045 * @returns ```true``` if extrinsic success, otherwise ```false```1046 */1047 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1048 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1049 }10501051 /**1052 * Sets onchain properties to the collection.1053 *1054 * @param signer keyring of signer1055 * @param collectionId ID of collection1056 * @param properties array of property objects1057 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1058 * @returns ```true``` if extrinsic success, otherwise ```false```1059 */1060 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1061 const result = await this.helper.executeExtrinsic(1062 signer,1063 'api.tx.unique.setCollectionProperties', [collectionId, properties],1064 true,1065 );10661067 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1068 }10691070 /**1071 * Get collection properties.1072 *1073 * @param collectionId ID of collection1074 * @param propertyKeys optionally filter the returned properties to only these keys1075 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1076 * @returns array of key-value pairs1077 */1078 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1079 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1080 }10811082 async getCollectionOptions(collectionId: number) {1083 return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1084 }10851086 /**1087 * Deletes onchain properties from the collection.1088 *1089 * @param signer keyring of signer1090 * @param collectionId ID of collection1091 * @param propertyKeys array of property keys to delete1092 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1093 * @returns ```true``` if extrinsic success, otherwise ```false```1094 */1095 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1096 const result = await this.helper.executeExtrinsic(1097 signer,1098 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1099 true,1100 );11011102 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1103 }11041105 /**1106 * Changes the owner of the token.1107 *1108 * @param signer keyring of signer1109 * @param collectionId ID of collection1110 * @param tokenId ID of token1111 * @param addressObj address of a new owner1112 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1113 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1114 * @returns true if the token success, otherwise false1115 */1116 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1117 const result = await this.helper.executeExtrinsic(1118 signer,1119 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1120 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1121 );11221123 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1124 }11251126 /**1127 *1128 * Change ownership of a token(s) on behalf of the owner.1129 *1130 * @param signer keyring of signer1131 * @param collectionId ID of collection1132 * @param tokenId ID of token1133 * @param fromAddressObj address on behalf of which the token will be sent1134 * @param toAddressObj new token owner1135 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1136 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1137 * @returns true if the token success, otherwise false1138 */1139 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1140 const result = await this.helper.executeExtrinsic(1141 signer,1142 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1143 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1144 );1145 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1146 }11471148 /**1149 *1150 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1151 *1152 * @param signer keyring of signer1153 * @param collectionId ID of collection1154 * @param tokenId ID of token1155 * @param amount amount of tokens to be burned. For NFT must be set to 1n1156 * @example burnToken(aliceKeyring, 10, 5);1157 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1158 */1159 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1160 const burnResult = await this.helper.executeExtrinsic(1161 signer,1162 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1163 true, // `Unable to burn token for ${label}`,1164 );1165 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1166 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1167 return burnedTokens.success;1168 }11691170 /**1171 * Destroys a concrete instance of NFT on behalf of the owner1172 *1173 * @param signer keyring of signer1174 * @param collectionId ID of collection1175 * @param tokenId ID of token1176 * @param fromAddressObj address on behalf of which the token will be burnt1177 * @param amount amount of tokens to be burned. For NFT must be set to 1n1178 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1179 * @returns ```true``` if extrinsic success, otherwise ```false```1180 */1181 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1182 const burnResult = await this.helper.executeExtrinsic(1183 signer,1184 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1185 true, // `Unable to burn token from for ${label}`,1186 );1187 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1188 return burnedTokens.success && burnedTokens.tokens.length > 0;1189 }11901191 /**1192 * Set, change, or remove approved address to transfer the ownership of the NFT.1193 *1194 * @param signer keyring of signer1195 * @param collectionId ID of collection1196 * @param tokenId ID of token1197 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1198 * @param amount amount of token to be approved. For NFT must be set to 1n1199 * @returns ```true``` if extrinsic success, otherwise ```false```1200 */1201 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1202 const approveResult = await this.helper.executeExtrinsic(1203 signer,1204 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1205 true, // `Unable to approve token for ${label}`,1206 );12071208 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1209 }12101211 /**1212 * Get the amount of token pieces approved to transfer or burn. Normally 0.1213 *1214 * @param collectionId ID of collection1215 * @param tokenId ID of token1216 * @param toAccountObj address which is approved to use token pieces1217 * @param fromAccountObj address which may have allowed the use of its owned tokens1218 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1219 * @returns number of approved to transfer pieces1220 */1221 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1222 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1223 }12241225 /**1226 * Get the last created token ID in a collection1227 *1228 * @param collectionId ID of collection1229 * @example getLastTokenId(10);1230 * @returns id of the last created token1231 */1232 async getLastTokenId(collectionId: number): Promise<number> {1233 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1234 }12351236 /**1237 * Check if token exists1238 *1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @example doesTokenExist(10, 20);1242 * @returns true if the token exists, otherwise false1243 */1244 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1245 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1246 }1247}12481249class NFTnRFT extends CollectionGroup {1250 /**1251 * Get tokens owned by account1252 *1253 * @param collectionId ID of collection1254 * @param addressObj tokens owner1255 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1256 * @returns array of token ids owned by account1257 */1258 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1259 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1260 }12611262 /**1263 * Get token data1264 *1265 * @param collectionId ID of collection1266 * @param tokenId ID of token1267 * @param propertyKeys optionally filter the token properties to only these keys1268 * @param blockHashAt optionally query the data at some block with this hash1269 * @example getToken(10, 5);1270 * @returns human readable token data1271 */1272 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1273 properties: IProperty[];1274 owner: CrossAccountId;1275 normalizedOwner: CrossAccountId;1276 }| null> {1277 let tokenData;1278 if(typeof blockHashAt === 'undefined') {1279 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1280 }1281 else {1282 if(propertyKeys.length == 0) {1283 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1284 if(!collection) return null;1285 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1286 }1287 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1288 }1289 tokenData = tokenData.toHuman();1290 if (tokenData === null || tokenData.owner === null) return null;1291 const owner = {} as any;1292 for (const key of Object.keys(tokenData.owner)) {1293 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1294 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1295 : tokenData.owner[key];1296 }1297 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1298 return tokenData;1299 }13001301 /**1302 * Set permissions to change token properties1303 *1304 * @param signer keyring of signer1305 * @param collectionId ID of collection1306 * @param permissions permissions to change a property by the collection admin or token owner1307 * @example setTokenPropertyPermissions(1308 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1309 * )1310 * @returns true if extrinsic success otherwise false1311 */1312 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1313 const result = await this.helper.executeExtrinsic(1314 signer,1315 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1316 true,1317 );13181319 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1320 }13211322 /**1323 * Get token property permissions.1324 *1325 * @param collectionId ID of collection1326 * @param propertyKeys optionally filter the returned property permissions to only these keys1327 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1328 * @returns array of key-permission pairs1329 */1330 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1331 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1332 }13331334 /**1335 * Set token properties1336 *1337 * @param signer keyring of signer1338 * @param collectionId ID of collection1339 * @param tokenId ID of token1340 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1341 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1342 * @returns ```true``` if extrinsic success, otherwise ```false```1343 */1344 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1345 const result = await this.helper.executeExtrinsic(1346 signer,1347 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1348 true,1349 );13501351 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1352 }13531354 /**1355 * Get properties, metadata assigned to a token.1356 *1357 * @param collectionId ID of collection1358 * @param tokenId ID of token1359 * @param propertyKeys optionally filter the returned properties to only these keys1360 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1361 * @returns array of key-value pairs1362 */1363 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1364 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1365 }13661367 /**1368 * Delete the provided properties of a token1369 * @param signer keyring of signer1370 * @param collectionId ID of collection1371 * @param tokenId ID of token1372 * @param propertyKeys property keys to be deleted1373 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1374 * @returns ```true``` if extrinsic success, otherwise ```false```1375 */1376 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1377 const result = await this.helper.executeExtrinsic(1378 signer,1379 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1380 true,1381 );13821383 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1384 }13851386 /**1387 * Mint new collection1388 *1389 * @param signer keyring of signer1390 * @param collectionOptions basic collection options and properties1391 * @param mode NFT or RFT type of a collection1392 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1393 * @returns object of the created collection1394 */1395 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1396 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1397 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1398 for (const key of ['name', 'description', 'tokenPrefix']) {1399 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1400 }1401 const creationResult = await this.helper.executeExtrinsic(1402 signer,1403 'api.tx.unique.createCollectionEx', [collectionOptions],1404 true, // errorLabel,1405 );1406 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1407 }14081409 getCollectionObject(_collectionId: number): any {1410 return null;1411 }14121413 getTokenObject(_collectionId: number, _tokenId: number): any {1414 return null;1415 }1416}141714181419class NFTGroup extends NFTnRFT {1420 /**1421 * Get collection object1422 * @param collectionId ID of collection1423 * @example getCollectionObject(2);1424 * @returns instance of UniqueNFTCollection1425 */1426 getCollectionObject(collectionId: number): UniqueNFTCollection {1427 return new UniqueNFTCollection(collectionId, this.helper);1428 }14291430 /**1431 * Get token object1432 * @param collectionId ID of collection1433 * @param tokenId ID of token1434 * @example getTokenObject(10, 5);1435 * @returns instance of UniqueNFTToken1436 */1437 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1438 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1439 }14401441 /**1442 * Get token's owner1443 * @param collectionId ID of collection1444 * @param tokenId ID of token1445 * @param blockHashAt optionally query the data at the block with this hash1446 * @example getTokenOwner(10, 5);1447 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1448 */1449 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1450 let owner;1451 if (typeof blockHashAt === 'undefined') {1452 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1453 } else {1454 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1455 }1456 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1457 }14581459 /**1460 * Is token approved to transfer1461 * @param collectionId ID of collection1462 * @param tokenId ID of token1463 * @param toAccountObj address to be approved1464 * @returns ```true``` if extrinsic success, otherwise ```false```1465 */1466 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1467 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1468 }14691470 /**1471 * Changes the owner of the token.1472 *1473 * @param signer keyring of signer1474 * @param collectionId ID of collection1475 * @param tokenId ID of token1476 * @param addressObj address of a new owner1477 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1478 * @returns ```true``` if extrinsic success, otherwise ```false```1479 */1480 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1481 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1482 }14831484 /**1485 *1486 * Change ownership of a NFT on behalf of the owner.1487 *1488 * @param signer keyring of signer1489 * @param collectionId ID of collection1490 * @param tokenId ID of token1491 * @param fromAddressObj address on behalf of which the token will be sent1492 * @param toAddressObj new token owner1493 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1494 * @returns ```true``` if extrinsic success, otherwise ```false```1495 */1496 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1497 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1498 }14991500 /**1501 * Recursively find the address that owns the token1502 * @param collectionId ID of collection1503 * @param tokenId ID of token1504 * @param blockHashAt1505 * @example getTokenTopmostOwner(10, 5);1506 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1507 */1508 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1509 let owner;1510 if (typeof blockHashAt === 'undefined') {1511 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1512 } else {1513 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1514 }15151516 if (owner === null) return null;15171518 return owner.toHuman();1519 }15201521 /**1522 * Get tokens nested in the provided token1523 * @param collectionId ID of collection1524 * @param tokenId ID of token1525 * @param blockHashAt optionally query the data at the block with this hash1526 * @example getTokenChildren(10, 5);1527 * @returns tokens whose depth of nesting is <= 51528 */1529 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1530 let children;1531 if(typeof blockHashAt === 'undefined') {1532 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1533 } else {1534 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1535 }15361537 return children.toJSON().map((x: any) => {1538 return {collectionId: x.collection, tokenId: x.token};1539 });1540 }15411542 /**1543 * Nest one token into another1544 * @param signer keyring of signer1545 * @param tokenObj token to be nested1546 * @param rootTokenObj token to be parent1547 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1551 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1552 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1553 if(!result) {1554 throw Error('Unable to nest token!');1555 }1556 return result;1557 }15581559 /**1560 * Remove token from nested state1561 * @param signer keyring of signer1562 * @param tokenObj token to unnest1563 * @param rootTokenObj parent of a token1564 * @param toAddressObj address of a new token owner1565 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1566 * @returns ```true``` if extrinsic success, otherwise ```false```1567 */1568 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1569 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1570 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1571 if(!result) {1572 throw Error('Unable to unnest token!');1573 }1574 return result;1575 }15761577 /**1578 * Mint new collection1579 * @param signer keyring of signer1580 * @param collectionOptions Collection options1581 * @example1582 * mintCollection(aliceKeyring, {1583 * name: 'New',1584 * description: 'New collection',1585 * tokenPrefix: 'NEW',1586 * })1587 * @returns object of the created collection1588 */1589 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1590 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1591 }15921593 /**1594 * Mint new token1595 * @param signer keyring of signer1596 * @param data token data1597 * @returns created token object1598 */1599 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1600 const creationResult = await this.helper.executeExtrinsic(1601 signer,1602 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1603 nft: {1604 properties: data.properties,1605 },1606 }],1607 true,1608 );1609 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1610 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1611 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1612 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1613 }16141615 /**1616 * Mint multiple NFT tokens1617 * @param signer keyring of signer1618 * @param collectionId ID of collection1619 * @param tokens array of tokens with owner and properties1620 * @example1621 * mintMultipleTokens(aliceKeyring, 10, [{1622 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1623 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1624 * },{1625 * owner: {Ethereum: "0x9F0583DbB855d..."},1626 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1627 * }]);1628 * @returns ```true``` if extrinsic success, otherwise ```false```1629 */1630 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1634 true,1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1638 }16391640 /**1641 * Mint multiple NFT tokens with one owner1642 * @param signer keyring of signer1643 * @param collectionId ID of collection1644 * @param owner tokens owner1645 * @param tokens array of tokens with owner and properties1646 * @example1647 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1648 * properties: [{1649 * key: "gender",1650 * value: "female",1651 * },{1652 * key: "age",1653 * value: "33",1654 * }],1655 * }]);1656 * @returns array of newly created tokens1657 */1658 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1659 const rawTokens = [];1660 for (const token of tokens) {1661 const raw = {NFT: {properties: token.properties}};1662 rawTokens.push(raw);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1667 true,1668 );1669 const collection = this.getCollectionObject(collectionId);1670 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1671 }16721673 /**1674 * Set, change, or remove approved address to transfer the ownership of the NFT.1675 *1676 * @param signer keyring of signer1677 * @param collectionId ID of collection1678 * @param tokenId ID of token1679 * @param toAddressObj address to approve1680 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1681 * @returns ```true``` if extrinsic success, otherwise ```false```1682 */1683 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1684 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1685 }1686}168716881689class RFTGroup extends NFTnRFT {1690 /**1691 * Get collection object1692 * @param collectionId ID of collection1693 * @example getCollectionObject(2);1694 * @returns instance of UniqueRFTCollection1695 */1696 getCollectionObject(collectionId: number): UniqueRFTCollection {1697 return new UniqueRFTCollection(collectionId, this.helper);1698 }16991700 /**1701 * Get token object1702 * @param collectionId ID of collection1703 * @param tokenId ID of token1704 * @example getTokenObject(10, 5);1705 * @returns instance of UniqueNFTToken1706 */1707 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1708 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1709 }17101711 /**1712 * Get top 10 token owners with the largest number of pieces1713 * @param collectionId ID of collection1714 * @param tokenId ID of token1715 * @example getTokenTop10Owners(10, 5);1716 * @returns array of top 10 owners1717 */1718 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1719 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1720 }17211722 /**1723 * Get number of pieces owned by address1724 * @param collectionId ID of collection1725 * @param tokenId ID of token1726 * @param addressObj address token owner1727 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1728 * @returns number of pieces ownerd by address1729 */1730 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1731 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1732 }17331734 /**1735 * Transfer pieces of token to another address1736 * @param signer keyring of signer1737 * @param collectionId ID of collection1738 * @param tokenId ID of token1739 * @param addressObj address of a new owner1740 * @param amount number of pieces to be transfered1741 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1742 * @returns ```true``` if extrinsic success, otherwise ```false```1743 */1744 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1745 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1746 }17471748 /**1749 * Change ownership of some pieces of RFT on behalf of the owner.1750 * @param signer keyring of signer1751 * @param collectionId ID of collection1752 * @param tokenId ID of token1753 * @param fromAddressObj address on behalf of which the token will be sent1754 * @param toAddressObj new token owner1755 * @param amount number of pieces to be transfered1756 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1757 * @returns ```true``` if extrinsic success, otherwise ```false```1758 */1759 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1761 }17621763 /**1764 * Mint new collection1765 * @param signer keyring of signer1766 * @param collectionOptions Collection options1767 * @example1768 * mintCollection(aliceKeyring, {1769 * name: 'New',1770 * description: 'New collection',1771 * tokenPrefix: 'NEW',1772 * })1773 * @returns object of the created collection1774 */1775 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1776 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1777 }17781779 /**1780 * Mint new token1781 * @param signer keyring of signer1782 * @param data token data1783 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1784 * @returns created token object1785 */1786 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1787 const creationResult = await this.helper.executeExtrinsic(1788 signer,1789 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790 refungible: {1791 pieces: data.pieces,1792 properties: data.properties,1793 },1794 }],1795 true,1796 );1797 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1798 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1799 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1800 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1801 }18021803 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1804 throw Error('Not implemented');1805 const creationResult = await this.helper.executeExtrinsic(1806 signer,1807 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1808 true, // `Unable to mint RFT tokens for ${label}`,1809 );1810 const collection = this.getCollectionObject(collectionId);1811 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1812 }18131814 /**1815 * Mint multiple RFT tokens with one owner1816 * @param signer keyring of signer1817 * @param collectionId ID of collection1818 * @param owner tokens owner1819 * @param tokens array of tokens with properties and pieces1820 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1821 * @returns array of newly created RFT tokens1822 */1823 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1824 const rawTokens = [];1825 for (const token of tokens) {1826 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1827 rawTokens.push(raw);1828 }1829 const creationResult = await this.helper.executeExtrinsic(1830 signer,1831 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1832 true,1833 );1834 const collection = this.getCollectionObject(collectionId);1835 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1836 }18371838 /**1839 * Destroys a concrete instance of RFT.1840 * @param signer keyring of signer1841 * @param collectionId ID of collection1842 * @param tokenId ID of token1843 * @param amount number of pieces to be burnt1844 * @example burnToken(aliceKeyring, 10, 5);1845 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1846 */1847 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1848 return await super.burnToken(signer, collectionId, tokenId, amount);1849 }18501851 /**1852 * Destroys a concrete instance of RFT on behalf of the owner.1853 * @param signer keyring of signer1854 * @param collectionId ID of collection1855 * @param tokenId ID of token1856 * @param fromAddressObj address on behalf of which the token will be burnt1857 * @param amount number of pieces to be burnt1858 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1859 * @returns ```true``` if extrinsic success, otherwise ```false```1860 */1861 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1862 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1863 }18641865 /**1866 * Set, change, or remove approved address to transfer the ownership of the RFT.1867 *1868 * @param signer keyring of signer1869 * @param collectionId ID of collection1870 * @param tokenId ID of token1871 * @param toAddressObj address to approve1872 * @param amount number of pieces to be approved1873 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1874 * @returns true if the token success, otherwise false1875 */1876 approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1877 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1878 }18791880 /**1881 * Get total number of pieces1882 * @param collectionId ID of collection1883 * @param tokenId ID of token1884 * @example getTokenTotalPieces(10, 5);1885 * @returns number of pieces1886 */1887 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1888 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1889 }18901891 /**1892 * Change number of token pieces. Signer must be the owner of all token pieces.1893 * @param signer keyring of signer1894 * @param collectionId ID of collection1895 * @param tokenId ID of token1896 * @param amount new number of pieces1897 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1898 * @returns true if the repartion was success, otherwise false1899 */1900 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1901 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1902 const repartitionResult = await this.helper.executeExtrinsic(1903 signer,1904 'api.tx.unique.repartition', [collectionId, tokenId, amount],1905 true,1906 );1907 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1908 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1909 }1910}191119121913class FTGroup extends CollectionGroup {1914 /**1915 * Get collection object1916 * @param collectionId ID of collection1917 * @example getCollectionObject(2);1918 * @returns instance of UniqueFTCollection1919 */1920 getCollectionObject(collectionId: number): UniqueFTCollection {1921 return new UniqueFTCollection(collectionId, this.helper);1922 }19231924 /**1925 * Mint new fungible collection1926 * @param signer keyring of signer1927 * @param collectionOptions Collection options1928 * @param decimalPoints number of token decimals1929 * @example1930 * mintCollection(aliceKeyring, {1931 * name: 'New',1932 * description: 'New collection',1933 * tokenPrefix: 'NEW',1934 * }, 18)1935 * @returns newly created fungible collection1936 */1937 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1938 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1939 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1940 collectionOptions.mode = {fungible: decimalPoints};1941 for (const key of ['name', 'description', 'tokenPrefix']) {1942 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1943 }1944 const creationResult = await this.helper.executeExtrinsic(1945 signer,1946 'api.tx.unique.createCollectionEx', [collectionOptions],1947 true,1948 );1949 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1950 }19511952 /**1953 * Mint tokens1954 * @param signer keyring of signer1955 * @param collectionId ID of collection1956 * @param owner address owner of new tokens1957 * @param amount amount of tokens to be meanted1958 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1959 * @returns ```true``` if extrinsic success, otherwise ```false```1960 */1961 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1962 const creationResult = await this.helper.executeExtrinsic(1963 signer,1964 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1965 fungible: {1966 value: amount,1967 },1968 }],1969 true, // `Unable to mint fungible tokens for ${label}`,1970 );1971 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1972 }19731974 /**1975 * Mint multiple Fungible tokens with one owner1976 * @param signer keyring of signer1977 * @param collectionId ID of collection1978 * @param owner tokens owner1979 * @param tokens array of tokens with properties and pieces1980 * @returns ```true``` if extrinsic success, otherwise ```false```1981 */1982 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1983 const rawTokens = [];1984 for (const token of tokens) {1985 const raw = {Fungible: {Value: token.value}};1986 rawTokens.push(raw);1987 }1988 const creationResult = await this.helper.executeExtrinsic(1989 signer,1990 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1991 true,1992 );1993 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1994 }19951996 /**1997 * Get the top 10 owners with the largest balance for the Fungible collection1998 * @param collectionId ID of collection1999 * @example getTop10Owners(10);2000 * @returns array of ```ICrossAccountId```2001 */2002 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2003 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2004 }20052006 /**2007 * Get account balance2008 * @param collectionId ID of collection2009 * @param addressObj address of owner2010 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2011 * @returns amount of fungible tokens owned by address2012 */2013 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2014 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2015 }20162017 /**2018 * Transfer tokens to address2019 * @param signer keyring of signer2020 * @param collectionId ID of collection2021 * @param toAddressObj address recipient2022 * @param amount amount of tokens to be sent2023 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2024 * @returns ```true``` if extrinsic success, otherwise ```false```2025 */2026 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2027 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2028 }20292030 /**2031 * Transfer some tokens on behalf of the owner.2032 * @param signer keyring of signer2033 * @param collectionId ID of collection2034 * @param fromAddressObj address on behalf of which tokens will be sent2035 * @param toAddressObj address where token to be sent2036 * @param amount number of tokens to be sent2037 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2038 * @returns ```true``` if extrinsic success, otherwise ```false```2039 */2040 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2041 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2042 }20432044 /**2045 * Destroy some amount of tokens2046 * @param signer keyring of signer2047 * @param collectionId ID of collection2048 * @param amount amount of tokens to be destroyed2049 * @example burnTokens(aliceKeyring, 10, 1000n);2050 * @returns ```true``` if extrinsic success, otherwise ```false```2051 */2052 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2053 return await super.burnToken(signer, collectionId, 0, amount);2054 }20552056 /**2057 * Burn some tokens on behalf of the owner.2058 * @param signer keyring of signer2059 * @param collectionId ID of collection2060 * @param fromAddressObj address on behalf of which tokens will be burnt2061 * @param amount amount of tokens to be burnt2062 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2063 * @returns ```true``` if extrinsic success, otherwise ```false```2064 */2065 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2066 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2067 }20682069 /**2070 * Get total collection supply2071 * @param collectionId2072 * @returns2073 */2074 async getTotalPieces(collectionId: number): Promise<bigint> {2075 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2076 }20772078 /**2079 * Set, change, or remove approved address to transfer tokens.2080 *2081 * @param signer keyring of signer2082 * @param collectionId ID of collection2083 * @param toAddressObj address to be approved2084 * @param amount amount of tokens to be approved2085 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2086 * @returns ```true``` if extrinsic success, otherwise ```false```2087 */2088 approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2089 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2090 }20912092 /**2093 * Get amount of fungible tokens approved to transfer2094 * @param collectionId ID of collection2095 * @param fromAddressObj owner of tokens2096 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2097 * @returns number of tokens approved for the transfer2098 */2099 getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2100 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2101 }2102}210321042105class ChainGroup extends HelperGroup<ChainHelperBase> {2106 /**2107 * Get system properties of a chain2108 * @example getChainProperties();2109 * @returns ss58Format, token decimals, and token symbol2110 */2111 getChainProperties(): IChainProperties {2112 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2113 return {2114 ss58Format: properties.ss58Format.toJSON(),2115 tokenDecimals: properties.tokenDecimals.toJSON(),2116 tokenSymbol: properties.tokenSymbol.toJSON(),2117 };2118 }21192120 /**2121 * Get chain header2122 * @example getLatestBlockNumber();2123 * @returns the number of the last block2124 */2125 async getLatestBlockNumber(): Promise<number> {2126 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2127 }21282129 /**2130 * Get block hash by block number2131 * @param blockNumber number of block2132 * @example getBlockHashByNumber(12345);2133 * @returns hash of a block2134 */2135 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2136 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2137 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2138 return blockHash;2139 }21402141 // TODO add docs2142 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2143 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2144 if (!blockHash) return null;2145 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2146 }21472148 /**2149 * Get latest relay block2150 * @returns {number} relay block2151 */2152 async getRelayBlockNumber(): Promise<bigint> {2153 const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2154 return BigInt(blockNumber);2155 }21562157 /**2158 * Get account nonce2159 * @param address substrate address2160 * @example getNonce("5GrwvaEF5zXb26Fz...");2161 * @returns number, account's nonce2162 */2163 async getNonce(address: TSubstrateAccount): Promise<number> {2164 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2165 }2166}21672168class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2169 /**2170 * Get substrate address balance2171 * @param address substrate address2172 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2173 * @returns amount of tokens on address2174 */2175 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2176 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2177 }21782179 /**2180 * Transfer tokens to substrate address2181 * @param signer keyring of signer2182 * @param address substrate address of a recipient2183 * @param amount amount of tokens to be transfered2184 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2185 * @returns ```true``` if extrinsic success, otherwise ```false```2186 */2187 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2188 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21892190 let transfer = {from: null, to: null, amount: 0n} as any;2191 result.result.events.forEach(({event: {data, method, section}}) => {2192 if ((section === 'balances') && (method === 'Transfer')) {2193 transfer = {2194 from: this.helper.address.normalizeSubstrate(data[0]),2195 to: this.helper.address.normalizeSubstrate(data[1]),2196 amount: BigInt(data[2]),2197 };2198 }2199 });2200 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2201 && this.helper.address.normalizeSubstrate(address) === transfer.to2202 && BigInt(amount) === transfer.amount;2203 return isSuccess;2204 }22052206 /**2207 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2208 * @param address substrate address2209 * @returns2210 */2211 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2212 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2213 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2214 }2215}22162217class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2218 /**2219 * Get ethereum address balance2220 * @param address ethereum address2221 * @example getEthereum("0x9F0583DbB855d...")2222 * @returns amount of tokens on address2223 */2224 async getEthereum(address: TEthereumAccount): Promise<bigint> {2225 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2226 }22272228 /**2229 * Transfer tokens to address2230 * @param signer keyring of signer2231 * @param address Ethereum address of a recipient2232 * @param amount amount of tokens to be transfered2233 * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2234 * @returns ```true``` if extrinsic success, otherwise ```false```2235 */2236 async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2237 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);22382239 let transfer = {from: null, to: null, amount: 0n} as any;2240 result.result.events.forEach(({event: {data, method, section}}) => {2241 if ((section === 'balances') && (method === 'Transfer')) {2242 transfer = {2243 from: data[0].toString(),2244 to: data[1].toString(),2245 amount: BigInt(data[2]),2246 };2247 }2248 });2249 const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2250 && address === transfer.to2251 && BigInt(amount) === transfer.amount;2252 return isSuccess;2253 }2254}22552256class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2257 subBalanceGroup: SubstrateBalanceGroup<T>;2258 ethBalanceGroup: EthereumBalanceGroup<T>;22592260 constructor(helper: T) {2261 super(helper);2262 this.subBalanceGroup = new SubstrateBalanceGroup(helper);2263 this.ethBalanceGroup = new EthereumBalanceGroup(helper);2264 }22652266 getCollectionCreationPrice(): bigint {2267 return 2n * this.getOneTokenNominal();2268 }2269 /**2270 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2271 * @example getOneTokenNominal()2272 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2273 */2274 getOneTokenNominal(): bigint {2275 const chainProperties = this.helper.chain.getChainProperties();2276 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2277 }22782279 /**2280 * Get substrate address balance2281 * @param address substrate address2282 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2283 * @returns amount of tokens on address2284 */2285 getSubstrate(address: TSubstrateAccount): Promise<bigint> {2286 return this.subBalanceGroup.getSubstrate(address);2287 }22882289 /**2290 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2291 * @param address substrate address2292 * @returns2293 */2294 getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2295 return this.subBalanceGroup.getSubstrateFull(address);2296 }22972298 /**2299 * Get ethereum address balance2300 * @param address ethereum address2301 * @example getEthereum("0x9F0583DbB855d...")2302 * @returns amount of tokens on address2303 */2304 getEthereum(address: TEthereumAccount): Promise<bigint> {2305 return this.ethBalanceGroup.getEthereum(address);2306 }23072308 /**2309 * Transfer tokens to substrate address2310 * @param signer keyring of signer2311 * @param address substrate address of a recipient2312 * @param amount amount of tokens to be transfered2313 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2314 * @returns ```true``` if extrinsic success, otherwise ```false```2315 */2316 transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2317 return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2318 }23192320 async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2321 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);23222323 let transfer = {from: null, to: null, amount: 0n} as any;2324 result.result.events.forEach(({event: {data, method, section}}) => {2325 if ((section === 'balances') && (method === 'Transfer')) {2326 transfer = {2327 from: this.helper.address.normalizeSubstrate(data[0]),2328 to: this.helper.address.normalizeSubstrate(data[1]),2329 amount: BigInt(data[2]),2330 };2331 }2332 });2333 let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2334 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2335 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2336 return isSuccess;2337 }23382339 /**2340 * Transfer tokens with the unlock period2341 * @param signer signers Keyring2342 * @param address Substrate address of recipient2343 * @param schedule Schedule params2344 * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002345 */2346 async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2347 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2348 const event = result.result.events2349 .find(e => e.event.section === 'vesting' &&2350 e.event.method === 'VestingScheduleAdded' &&2351 e.event.data[0].toHuman() === signer.address);2352 if (!event) throw Error('Cannot find transfer in events');2353 }23542355 /**2356 * Get schedule for recepient of vested transfer2357 * @param address Substrate address of recipient2358 * @returns 2359 */2360 async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2361 const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2362 return schedule.map((schedule: any) => {2363 return {2364 start: BigInt(schedule.start),2365 period: BigInt(schedule.period),2366 periodCount: BigInt(schedule.periodCount),2367 perPeriod: BigInt(schedule.perPeriod),2368 };2369 });2370 }23712372 /**2373 * Claim vested tokens2374 * @param signer signers Keyring2375 */2376 async claim(signer: TSigner) {2377 const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2378 const event = result.result.events2379 .find(e => e.event.section === 'vesting' &&2380 e.event.method === 'Claimed' &&2381 e.event.data[0].toHuman() === signer.address);2382 if (!event) throw Error('Cannot find claim in events');2383 }2384}23852386class AddressGroup extends HelperGroup<ChainHelperBase> {2387 /**2388 * Normalizes the address to the specified ss58 format, by default ```42```.2389 * @param address substrate address2390 * @param ss58Format format for address conversion, by default ```42```2391 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2392 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2393 */2394 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2395 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2396 }23972398 /**2399 * Get address in the connected chain format2400 * @param address substrate address2401 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2402 * @returns address in chain format2403 */2404 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2405 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2406 }24072408 /**2409 * Get substrate mirror of an ethereum address2410 * @param ethAddress ethereum address2411 * @param toChainFormat false for normalized account2412 * @example ethToSubstrate('0x9F0583DbB855d...')2413 * @returns substrate mirror of a provided ethereum address2414 */2415 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2416 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2417 }24182419 /**2420 * Get ethereum mirror of a substrate address2421 * @param subAddress substrate account2422 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2423 * @returns ethereum mirror of a provided substrate address2424 */2425 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2426 return CrossAccountId.translateSubToEth(subAddress);2427 }24282429 /**2430 * Encode key to substrate address2431 * @param key key for encoding address2432 * @param ss58Format prefix for encoding to the address of the corresponding network2433 * @returns encoded substrate address2434 */2435 encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2436 const u8a :Uint8Array = typeof key === 'string'2437 ? hexToU8a(key)2438 : typeof key === 'bigint'2439 ? hexToU8a(key.toString(16))2440 : key;2441 2442 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2443 throw new Error(`ss58Format is not valid, received ${typeofss58Format} "${ss58Format}"`);2444 }2445 2446 const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2447 if (!allowedDecodedLengths.includes(u8a.length)) {2448 throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2449 }2450 2451 const u8aPrefix = ss58Format < 642452 ? new Uint8Array([ss58Format])2453 : new Uint8Array([2454 ((ss58Format & 0xfc) >> 2) | 0x40,2455 (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2456 ]);24572458 const input = u8aConcat(u8aPrefix, u8a);2459 2460 return base58Encode(u8aConcat(2461 input,2462 blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2463 ));2464 }24652466 /**2467 * Restore substrate address from bigint representation2468 * @param number decimal representation of substrate address2469 * @returns substrate address2470 */2471 restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2472 if (this.helper.api === null) {2473 throw 'Not connected';2474 }2475 const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2476 if (res === undefined || res === null) {2477 throw 'Restore address error';2478 }2479 return res.toString();2480 }24812482 /**2483 * Convert etherium cross account id to substrate cross account id2484 * @param ethCrossAccount etherium cross account2485 * @returns substrate cross account id2486 */2487 convertCrossAccountFromEthCrossAcoount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2488 if (ethCrossAccount.sub === '0') {2489 return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2490 }2491 2492 const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2493 return {Substrate: ss58};2494 }24952496 paraSiblingSovereignAccount(paraid: number) {2497 // We are getting a *sibling* parachain sovereign account,2498 // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2499 const siblingPrefix = '0x7369626c';25002501 const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2502 const suffix = '000000000000000000000000000000000000000000000000';25032504 return siblingPrefix + encodedParaId + suffix;2505 }2506}25072508class StakingGroup extends HelperGroup<UniqueHelper> {2509 /**2510 * Stake tokens for App Promotion2511 * @param signer keyring of signer2512 * @param amountToStake amount of tokens to stake2513 * @param label extra label for log2514 * @returns2515 */2516 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2517 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2518 const _stakeResult = await this.helper.executeExtrinsic(2519 signer, 'api.tx.appPromotion.stake',2520 [amountToStake], true,2521 );2522 // TODO extract info from stakeResult2523 return true;2524 }25252526 /**2527 * Unstake tokens for App Promotion2528 * @param signer keyring of signer2529 * @param amountToUnstake amount of tokens to unstake2530 * @param label extra label for log2531 * @returns block number where balances will be unlocked2532 */2533 async unstake(signer: TSigner, label?: string): Promise<number> {2534 if(typeof label === 'undefined') label = `${signer.address}`;2535 const _unstakeResult = await this.helper.executeExtrinsic(2536 signer, 'api.tx.appPromotion.unstake',2537 [], true,2538 );2539 // TODO extract block number fron events2540 return 1;2541 }25422543 /**2544 * Get total staked amount for address2545 * @param address substrate or ethereum address2546 * @returns total staked amount2547 */2548 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2549 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2550 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2551 }25522553 /**2554 * Get total staked per block2555 * @param address substrate or ethereum address2556 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2557 */2558 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2559 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2560 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2561 return {2562 block: block.toBigInt(),2563 amount: amount.toBigInt(),2564 };2565 });2566 }25672568 /**2569 * Get total pending unstake amount for address2570 * @param address substrate or ethereum address2571 * @returns total pending unstake amount2572 */2573 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2574 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2575 }25762577 /**2578 * Get pending unstake amount per block for address2579 * @param address substrate or ethereum address2580 * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2581 */2582 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2583 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2584 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2585 return {2586 block: block.toBigInt(),2587 amount: amount.toBigInt(),2588 };2589 });2590 return result;2591 }2592}25932594class SchedulerGroup extends HelperGroup<UniqueHelper> {2595 constructor(helper: UniqueHelper) {2596 super(helper);2597 }25982599 cancelScheduled(signer: TSigner, scheduledId: string) {2600 return this.helper.executeExtrinsic(2601 signer,2602 'api.tx.scheduler.cancelNamed',2603 [scheduledId],2604 true,2605 );2606 }26072608 changePriority(signer: TSigner, scheduledId: string, priority: number) {2609 return this.helper.executeExtrinsic(2610 signer,2611 'api.tx.scheduler.changeNamedPriority',2612 [scheduledId, priority],2613 true,2614 );2615 }26162617 scheduleAt<T extends UniqueHelper>(2618 executionBlockNumber: number,2619 options: ISchedulerOptions = {},2620 ) {2621 return this.schedule<T>('schedule', executionBlockNumber, options);2622 }26232624 scheduleAfter<T extends UniqueHelper>(2625 blocksBeforeExecution: number,2626 options: ISchedulerOptions = {},2627 ) {2628 return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2629 }26302631 schedule<T extends UniqueHelper>(2632 scheduleFn: 'schedule' | 'scheduleAfter',2633 blocksNum: number,2634 options: ISchedulerOptions = {},2635 ) {2636 // eslint-disable-next-line @typescript-eslint/naming-convention2637 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2638 return this.helper.clone(ScheduledHelperType, {2639 scheduleFn,2640 blocksNum,2641 options,2642 }) as T;2643 }2644}26452646class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2647 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2648 await this.helper.executeExtrinsic(2649 signer,2650 'api.tx.foreignAssets.registerForeignAsset',2651 [ownerAddress, location, metadata],2652 true,2653 );2654 }26552656 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2657 await this.helper.executeExtrinsic(2658 signer,2659 'api.tx.foreignAssets.updateForeignAsset',2660 [foreignAssetId, location, metadata],2661 true,2662 );2663 }2664}26652666class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2667 palletName: string;26682669 constructor(helper: T, palletName: string) {2670 super(helper);26712672 this.palletName = palletName;2673 }26742675 async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2676 await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2677 }2678}26792680class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2681 async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2682 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2683 }26842685 async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2686 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2687 }26882689 async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2690 await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2691 }2692}26932694class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2695 async accounts(address: string, currencyId: any) {2696 const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2697 return BigInt(free);2698 }2699}27002701class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2702 async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2703 await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2704 }27052706 async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2707 await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2708 }27092710 async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2711 await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2712 }27132714 async account(assetId: string | number, address: string) {2715 const accountAsset = (2716 await this.helper.callRpc('api.query.assets.account', [assetId, address])2717 ).toJSON()! as any;27182719 if (accountAsset !== null) {2720 return BigInt(accountAsset['balance']);2721 } else {2722 return null;2723 }2724 }2725}27262727class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2728 async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2729 await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2730 }2731}27322733class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2734 makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2735 const apiPrefix = 'api.tx.assetManager.';27362737 const registerTx = this.helper.constructApiCall(2738 apiPrefix + 'registerForeignAsset',2739 [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2740 );27412742 const setUnitsTx = this.helper.constructApiCall(2743 apiPrefix + 'setAssetUnitsPerSecond',2744 [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2745 );27462747 const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2748 const encodedProposal = batchCall?.method.toHex() || '';2749 return encodedProposal;2750 }27512752 async assetTypeId(location: any) {2753 return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2754 }2755}27562757class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2758 async notePreimage(signer: TSigner, encodedProposal: string) {2759 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2760 }27612762 externalProposeMajority(proposalHash: string) {2763 return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2764 }27652766 fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2767 return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2768 }27692770 async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2771 await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2772 }2773}27742775class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2776 collective: string;27772778 constructor(helper: MoonbeamHelper, collective: string) {2779 super(helper);27802781 this.collective = collective;2782 }27832784 async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2785 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2786 }27872788 async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2789 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2790 }27912792 async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2793 await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2794 }27952796 async proposalCount() {2797 return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2798 }2799}28002801export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2802export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;28032804export class UniqueHelper extends ChainHelperBase {2805 balance: BalanceGroup<UniqueHelper>;2806 collection: CollectionGroup;2807 nft: NFTGroup;2808 rft: RFTGroup;2809 ft: FTGroup;2810 staking: StakingGroup;2811 scheduler: SchedulerGroup;2812 foreignAssets: ForeignAssetsGroup;2813 xcm: XcmGroup<UniqueHelper>;2814 xTokens: XTokensGroup<UniqueHelper>;2815 tokens: TokensGroup<UniqueHelper>;28162817 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2818 super(logger, options.helperBase ?? UniqueHelper);28192820 this.balance = new BalanceGroup(this);2821 this.collection = new CollectionGroup(this);2822 this.nft = new NFTGroup(this);2823 this.rft = new RFTGroup(this);2824 this.ft = new FTGroup(this);2825 this.staking = new StakingGroup(this);2826 this.scheduler = new SchedulerGroup(this);2827 this.foreignAssets = new ForeignAssetsGroup(this);2828 this.xcm = new XcmGroup(this, 'polkadotXcm');2829 this.xTokens = new XTokensGroup(this);2830 this.tokens = new TokensGroup(this);2831 }28322833 getSudo<T extends UniqueHelper>() {2834 // eslint-disable-next-line @typescript-eslint/naming-convention2835 const SudoHelperType = SudoHelper(this.helperBase);2836 return this.clone(SudoHelperType) as T;2837 }2838}28392840export class XcmChainHelper extends ChainHelperBase {2841 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2842 const wsProvider = new WsProvider(wsEndpoint);2843 this.api = new ApiPromise({2844 provider: wsProvider,2845 });2846 await this.api.isReadyOrError;2847 this.network = await UniqueHelper.detectNetwork(this.api);2848 }2849}28502851export class RelayHelper extends XcmChainHelper {2852 xcm: XcmGroup<RelayHelper>;28532854 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2855 super(logger, options.helperBase ?? RelayHelper);28562857 this.xcm = new XcmGroup(this, 'xcmPallet');2858 }2859}28602861export class WestmintHelper extends XcmChainHelper {2862 balance: SubstrateBalanceGroup<WestmintHelper>;2863 xcm: XcmGroup<WestmintHelper>;2864 assets: AssetsGroup<WestmintHelper>;2865 xTokens: XTokensGroup<WestmintHelper>;28662867 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2868 super(logger, options.helperBase ?? WestmintHelper);28692870 this.balance = new SubstrateBalanceGroup(this);2871 this.xcm = new XcmGroup(this, 'polkadotXcm');2872 this.assets = new AssetsGroup(this);2873 this.xTokens = new XTokensGroup(this);2874 }2875}28762877export class MoonbeamHelper extends XcmChainHelper {2878 balance: EthereumBalanceGroup<MoonbeamHelper>;2879 assetManager: MoonbeamAssetManagerGroup;2880 assets: AssetsGroup<MoonbeamHelper>;2881 xTokens: XTokensGroup<MoonbeamHelper>;2882 democracy: MoonbeamDemocracyGroup;2883 collective: {2884 council: MoonbeamCollectiveGroup,2885 techCommittee: MoonbeamCollectiveGroup,2886 };28872888 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2889 super(logger, options.helperBase ?? MoonbeamHelper);28902891 this.balance = new EthereumBalanceGroup(this);2892 this.assetManager = new MoonbeamAssetManagerGroup(this);2893 this.assets = new AssetsGroup(this);2894 this.xTokens = new XTokensGroup(this);2895 this.democracy = new MoonbeamDemocracyGroup(this);2896 this.collective = {2897 council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2898 techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2899 };2900 }2901}29022903export class AcalaHelper extends XcmChainHelper {2904 balance: SubstrateBalanceGroup<AcalaHelper>;2905 assetRegistry: AcalaAssetRegistryGroup;2906 xTokens: XTokensGroup<AcalaHelper>;2907 tokens: TokensGroup<AcalaHelper>;29082909 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2910 super(logger, options.helperBase ?? AcalaHelper);29112912 this.balance = new SubstrateBalanceGroup(this);2913 this.assetRegistry = new AcalaAssetRegistryGroup(this);2914 this.xTokens = new XTokensGroup(this);2915 this.tokens = new TokensGroup(this);2916 }29172918 getSudo<T extends AcalaHelper>() {2919 // eslint-disable-next-line @typescript-eslint/naming-convention2920 const SudoHelperType = SudoHelper(this.helperBase);2921 return this.clone(SudoHelperType) as T;2922 }2923}29242925// eslint-disable-next-line @typescript-eslint/naming-convention2926function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2927 return class extends Base {2928 scheduleFn: 'schedule' | 'scheduleAfter';2929 blocksNum: number;2930 options: ISchedulerOptions;29312932 constructor(...args: any[]) {2933 const logger = args[0] as ILogger;2934 const options = args[1] as {2935 scheduleFn: 'schedule' | 'scheduleAfter',2936 blocksNum: number,2937 options: ISchedulerOptions2938 };29392940 super(logger);29412942 this.scheduleFn = options.scheduleFn;2943 this.blocksNum = options.blocksNum;2944 this.options = options.options;2945 }29462947 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2948 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2949 2950 const mandatorySchedArgs = [2951 this.blocksNum,2952 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2953 this.options.priority ?? null,2954 scheduledTx,2955 ];2956 2957 let schedArgs;2958 let scheduleFn;29592960 if (this.options.scheduledId) {2961 schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];29622963 if (this.scheduleFn == 'schedule') {2964 scheduleFn = 'scheduleNamed';2965 } else if (this.scheduleFn == 'scheduleAfter') {2966 scheduleFn = 'scheduleNamedAfter';2967 }2968 } else {2969 schedArgs = mandatorySchedArgs;2970 scheduleFn = this.scheduleFn;2971 }29722973 const extrinsic = 'api.tx.scheduler.' + scheduleFn;29742975 return super.executeExtrinsic(2976 sender,2977 extrinsic,2978 schedArgs,2979 expectSuccess,2980 );2981 }2982 };2983}29842985// eslint-disable-next-line @typescript-eslint/naming-convention2986function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2987 return class extends Base {2988 constructor(...args: any[]) {2989 super(...args);2990 }29912992 executeExtrinsic (2993 sender: IKeyringPair,2994 extrinsic: string,2995 params: any[],2996 expectSuccess?: boolean,2997 ): Promise<ITransactionResult> {2998 const call = this.constructApiCall(extrinsic, params);2999 return super.executeExtrinsic(3000 sender,3001 'api.tx.sudo.sudo',3002 [call],3003 expectSuccess,3004 );3005 }3006 };3007}30083009export class UniqueBaseCollection {3010 helper: UniqueHelper;3011 collectionId: number;30123013 constructor(collectionId: number, uniqueHelper: UniqueHelper) {3014 this.collectionId = collectionId;3015 this.helper = uniqueHelper;3016 }30173018 async getData() {3019 return await this.helper.collection.getData(this.collectionId);3020 }30213022 async getLastTokenId() {3023 return await this.helper.collection.getLastTokenId(this.collectionId);3024 }30253026 async doesTokenExist(tokenId: number) {3027 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3028 }30293030 async getAdmins() {3031 return await this.helper.collection.getAdmins(this.collectionId);3032 }30333034 async getAllowList() {3035 return await this.helper.collection.getAllowList(this.collectionId);3036 }30373038 async getEffectiveLimits() {3039 return await this.helper.collection.getEffectiveLimits(this.collectionId);3040 }30413042 async getProperties(propertyKeys?: string[] | null) {3043 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3044 }30453046 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3047 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3048 }30493050 async getOptions() {3051 return await this.helper.collection.getCollectionOptions(this.collectionId);3052 }30533054 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3055 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3056 }30573058 async confirmSponsorship(signer: TSigner) {3059 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3060 }30613062 async removeSponsor(signer: TSigner) {3063 return await this.helper.collection.removeSponsor(signer, this.collectionId);3064 }30653066 async setLimits(signer: TSigner, limits: ICollectionLimits) {3067 return await this.helper.collection.setLimits(signer, this.collectionId, limits);3068 }30693070 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3071 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3072 }30733074 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3075 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3076 }30773078 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3079 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3080 }30813082 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3083 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3084 }30853086 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3087 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3088 }30893090 async setProperties(signer: TSigner, properties: IProperty[]) {3091 return await this.helper.collection.setProperties(signer, this.collectionId, properties);3092 }30933094 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3095 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3096 }30973098 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3099 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3100 }31013102 async enableNesting(signer: TSigner, permissions: INestingPermissions) {3103 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3104 }31053106 async disableNesting(signer: TSigner) {3107 return await this.helper.collection.disableNesting(signer, this.collectionId);3108 }31093110 async burn(signer: TSigner) {3111 return await this.helper.collection.burn(signer, this.collectionId);3112 }31133114 scheduleAt<T extends UniqueHelper>(3115 executionBlockNumber: number,3116 options: ISchedulerOptions = {},3117 ) {3118 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3119 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3120 }31213122 scheduleAfter<T extends UniqueHelper>(3123 blocksBeforeExecution: number,3124 options: ISchedulerOptions = {},3125 ) {3126 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3127 return new UniqueBaseCollection(this.collectionId, scheduledHelper);3128 }31293130 getSudo<T extends UniqueHelper>() {3131 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3132 }3133}313431353136export class UniqueNFTCollection extends UniqueBaseCollection {3137 getTokenObject(tokenId: number) {3138 return new UniqueNFToken(tokenId, this);3139 }31403141 async getTokensByAddress(addressObj: ICrossAccountId) {3142 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3143 }31443145 async getToken(tokenId: number, blockHashAt?: string) {3146 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3147 }31483149 async getTokenOwner(tokenId: number, blockHashAt?: string) {3150 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3151 }31523153 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3154 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3155 }31563157 async getTokenChildren(tokenId: number, blockHashAt?: string) {3158 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3159 }31603161 async getPropertyPermissions(propertyKeys: string[] | null = null) {3162 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3163 }31643165 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3166 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3167 }31683169 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3170 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3171 }31723173 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3174 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3175 }31763177 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3178 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3179 }31803181 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3182 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3183 }31843185 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3186 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3187 }31883189 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3190 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3191 }31923193 async burnToken(signer: TSigner, tokenId: number) {3194 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3195 }31963197 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3198 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3199 }32003201 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3202 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3203 }32043205 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3206 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3207 }32083209 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3210 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3211 }32123213 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3214 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3215 }32163217 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3218 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3219 }32203221 scheduleAt<T extends UniqueHelper>(3222 executionBlockNumber: number,3223 options: ISchedulerOptions = {},3224 ) {3225 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3226 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3227 }32283229 scheduleAfter<T extends UniqueHelper>(3230 blocksBeforeExecution: number,3231 options: ISchedulerOptions = {},3232 ) {3233 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3234 return new UniqueNFTCollection(this.collectionId, scheduledHelper);3235 }32363237 getSudo<T extends UniqueHelper>() {3238 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3239 }3240}324132423243export class UniqueRFTCollection extends UniqueBaseCollection {3244 getTokenObject(tokenId: number) {3245 return new UniqueRFToken(tokenId, this);3246 }32473248 async getToken(tokenId: number, blockHashAt?: string) {3249 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3250 }32513252 async getTokensByAddress(addressObj: ICrossAccountId) {3253 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3254 }32553256 async getTop10TokenOwners(tokenId: number) {3257 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3258 }32593260 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3261 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3262 }32633264 async getTokenTotalPieces(tokenId: number) {3265 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3266 }32673268 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3269 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3270 }32713272 async getPropertyPermissions(propertyKeys: string[] | null = null) {3273 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3274 }32753276 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3277 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3278 }32793280 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3281 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3282 }32833284 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3285 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3286 }32873288 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3289 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3290 }32913292 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3293 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3294 }32953296 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3297 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3298 }32993300 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3301 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3302 }33033304 async burnToken(signer: TSigner, tokenId: number, amount=1n) {3305 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3306 }33073308 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {3309 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3310 }33113312 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3313 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3314 }33153316 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3317 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3318 }33193320 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3321 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3322 }33233324 scheduleAt<T extends UniqueHelper>(3325 executionBlockNumber: number,3326 options: ISchedulerOptions = {},3327 ) {3328 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3329 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3330 }33313332 scheduleAfter<T extends UniqueHelper>(3333 blocksBeforeExecution: number,3334 options: ISchedulerOptions = {},3335 ) {3336 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3337 return new UniqueRFTCollection(this.collectionId, scheduledHelper);3338 }33393340 getSudo<T extends UniqueHelper>() {3341 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3342 }3343}334433453346export class UniqueFTCollection extends UniqueBaseCollection {3347 async getBalance(addressObj: ICrossAccountId) {3348 return await this.helper.ft.getBalance(this.collectionId, addressObj);3349 }33503351 async getTotalPieces() {3352 return await this.helper.ft.getTotalPieces(this.collectionId);3353 }33543355 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3356 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3357 }33583359 async getTop10Owners() {3360 return await this.helper.ft.getTop10Owners(this.collectionId);3361 }33623363 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3364 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3365 }33663367 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3368 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3369 }33703371 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3372 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3373 }33743375 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3376 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3377 }33783379 async burnTokens(signer: TSigner, amount=1n) {3380 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3381 }33823383 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3384 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3385 }33863387 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3388 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3389 }33903391 scheduleAt<T extends UniqueHelper>(3392 executionBlockNumber: number,3393 options: ISchedulerOptions = {},3394 ) {3395 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3396 return new UniqueFTCollection(this.collectionId, scheduledHelper);3397 }33983399 scheduleAfter<T extends UniqueHelper>(3400 blocksBeforeExecution: number,3401 options: ISchedulerOptions = {},3402 ) {3403 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3404 return new UniqueFTCollection(this.collectionId, scheduledHelper);3405 }34063407 getSudo<T extends UniqueHelper>() {3408 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3409 }3410}341134123413export class UniqueBaseToken {3414 collection: UniqueNFTCollection | UniqueRFTCollection;3415 collectionId: number;3416 tokenId: number;34173418 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3419 this.collection = collection;3420 this.collectionId = collection.collectionId;3421 this.tokenId = tokenId;3422 }34233424 async getNextSponsored(addressObj: ICrossAccountId) {3425 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3426 }34273428 async getProperties(propertyKeys?: string[] | null) {3429 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3430 }34313432 async setProperties(signer: TSigner, properties: IProperty[]) {3433 return await this.collection.setTokenProperties(signer, this.tokenId, properties);3434 }34353436 async deleteProperties(signer: TSigner, propertyKeys: string[]) {3437 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3438 }34393440 async doesExist() {3441 return await this.collection.doesTokenExist(this.tokenId);3442 }34433444 nestingAccount() {3445 return this.collection.helper.util.getTokenAccount(this);3446 }34473448 scheduleAt<T extends UniqueHelper>(3449 executionBlockNumber: number,3450 options: ISchedulerOptions = {},3451 ) {3452 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3453 return new UniqueBaseToken(this.tokenId, scheduledCollection);3454 }34553456 scheduleAfter<T extends UniqueHelper>(3457 blocksBeforeExecution: number,3458 options: ISchedulerOptions = {},3459 ) {3460 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3461 return new UniqueBaseToken(this.tokenId, scheduledCollection);3462 }34633464 getSudo<T extends UniqueHelper>() {3465 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3466 }3467}346834693470export class UniqueNFToken extends UniqueBaseToken {3471 collection: UniqueNFTCollection;34723473 constructor(tokenId: number, collection: UniqueNFTCollection) {3474 super(tokenId, collection);3475 this.collection = collection;3476 }34773478 async getData(blockHashAt?: string) {3479 return await this.collection.getToken(this.tokenId, blockHashAt);3480 }34813482 async getOwner(blockHashAt?: string) {3483 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3484 }34853486 async getTopmostOwner(blockHashAt?: string) {3487 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3488 }34893490 async getChildren(blockHashAt?: string) {3491 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3492 }34933494 async nest(signer: TSigner, toTokenObj: IToken) {3495 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3496 }34973498 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3499 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3500 }35013502 async transfer(signer: TSigner, addressObj: ICrossAccountId) {3503 return await this.collection.transferToken(signer, this.tokenId, addressObj);3504 }35053506 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3507 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3508 }35093510 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3511 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3512 }35133514 async isApproved(toAddressObj: ICrossAccountId) {3515 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3516 }35173518 async burn(signer: TSigner) {3519 return await this.collection.burnToken(signer, this.tokenId);3520 }35213522 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3523 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3524 }35253526 scheduleAt<T extends UniqueHelper>(3527 executionBlockNumber: number,3528 options: ISchedulerOptions = {},3529 ) {3530 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3531 return new UniqueNFToken(this.tokenId, scheduledCollection);3532 }35333534 scheduleAfter<T extends UniqueHelper>(3535 blocksBeforeExecution: number,3536 options: ISchedulerOptions = {},3537 ) {3538 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3539 return new UniqueNFToken(this.tokenId, scheduledCollection);3540 }35413542 getSudo<T extends UniqueHelper>() {3543 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3544 }3545}35463547export class UniqueRFToken extends UniqueBaseToken {3548 collection: UniqueRFTCollection;35493550 constructor(tokenId: number, collection: UniqueRFTCollection) {3551 super(tokenId, collection);3552 this.collection = collection;3553 }35543555 async getData(blockHashAt?: string) {3556 return await this.collection.getToken(this.tokenId, blockHashAt);3557 }35583559 async getTop10Owners() {3560 return await this.collection.getTop10TokenOwners(this.tokenId);3561 }35623563 async getBalance(addressObj: ICrossAccountId) {3564 return await this.collection.getTokenBalance(this.tokenId, addressObj);3565 }35663567 async getTotalPieces() {3568 return await this.collection.getTokenTotalPieces(this.tokenId);3569 }35703571 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3572 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3573 }35743575 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3576 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3577 }35783579 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3580 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3581 }35823583 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3584 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3585 }35863587 async repartition(signer: TSigner, amount: bigint) {3588 return await this.collection.repartitionToken(signer, this.tokenId, amount);3589 }35903591 async burn(signer: TSigner, amount=1n) {3592 return await this.collection.burnToken(signer, this.tokenId, amount);3593 }35943595 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3596 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3597 }35983599 scheduleAt<T extends UniqueHelper>(3600 executionBlockNumber: number,3601 options: ISchedulerOptions = {},3602 ) {3603 const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3604 return new UniqueRFToken(this.tokenId, scheduledCollection);3605 }36063607 scheduleAfter<T extends UniqueHelper>(3608 blocksBeforeExecution: number,3609 options: ISchedulerOptions = {},3610 ) {3611 const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3612 return new UniqueRFToken(this.tokenId, scheduledCollection);3613 }36143615 getSudo<T extends UniqueHelper>() {3616 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3617 }3618}tests/src/vesting.test.tsdiffbeforeafterboth--- a/tests/src/vesting.test.ts
+++ b/tests/src/vesting.test.ts
@@ -28,36 +28,12 @@
});
});
- itSub('cannot send more tokens than have', async ({helper}) => {
- const [sender, receiver] = await helper.arrange.createAccounts([1000n, 1n], donor);
- const manyPeriodsSchedule = {startRelayBlock: 0n, periodBlocks: 1n, periodCount: 100n, perPeriod: 10n * nominal};
- const oneBigSumSchedule = {startRelayBlock: 0n, periodBlocks: 1n, periodCount: 1n, perPeriod: 5000n * nominal};
-
- expect(helper.balance.vestedTransfer(sender, sender.address, manyPeriodsSchedule)).to.be.rejected.with('InsufficientBalanceToLock');
- expect(helper.balance.vestedTransfer(sender, receiver.address, manyPeriodsSchedule)).to.be.rejected.with('InsufficientBalanceToLock');
- expect(helper.balance.vestedTransfer(sender, sender.address, oneBigSumSchedule)).to.be.rejected.with('InsufficientBalanceToLock');
- expect(helper.balance.vestedTransfer(sender, receiver.address, oneBigSumSchedule)).to.be.rejected.with('InsufficientBalanceToLock');
-
- const balanceSender = await helper.balance.getSubstrateFull(sender.address);
- const balanceReceiver = await helper.balance.getSubstrateFull(receiver.address);
-
- expect(balanceSender.free / nominal).to.eq(999n);
- expect(balanceSender.feeFrozen / nominal).to.eq(0n);
- expect(balanceSender.miscFrozen / nominal).to.eq(0n);
- expect(balanceSender.reserved / nominal).to.eq(0n);
-
- expect(balanceReceiver.free).to.be.eq(1n * nominal);
- expect(balanceReceiver.feeFrozen).to.be.eq(0n);
- expect(balanceReceiver.miscFrozen).to.be.eq(0n);
- expect(balanceReceiver.reserved).to.be.eq(0n);
- });
-
itSub('can perform vestedTransfer and claim tokens', async ({helper}) => {
// arrange
const [sender, recepient] = await helper.arrange.createAccounts([1000n, 1n], donor);
const currentRelayBlock = await helper.chain.getRelayBlockNumber();
- const schedule1 = {startRelayBlock: currentRelayBlock + 4n, periodBlocks: 4n, periodCount: 2n, perPeriod: 50n * nominal};
- const schedule2 = {startRelayBlock: currentRelayBlock + 8n, periodBlocks: 8n, periodCount: 2n, perPeriod: 100n * nominal};
+ const schedule1 = {start: currentRelayBlock + 4n, period: 4n, periodCount: 2n, perPeriod: 50n * nominal};
+ const schedule2 = {start: currentRelayBlock + 8n, period: 8n, periodCount: 2n, perPeriod: 100n * nominal};
// act
await helper.balance.vestedTransfer(sender, recepient.address, schedule1);
@@ -125,4 +101,53 @@
expect(balanceSender.miscFrozen).to.eq(0n);
expect(balanceSender.reserved).to.eq(0n);
});
+
+ itSub('cannot send more tokens than have', async ({helper}) => {
+ const [sender, receiver] = await helper.arrange.createAccounts([1000n, 1n], donor);
+ const schedule = {start: 0n, period: 1n, periodCount: 1n, perPeriod: 100n * nominal};
+ const manyPeriodsSchedule = {start: 0n, period: 1n, periodCount: 100n, perPeriod: 10n * nominal};
+ const oneBigSumSchedule = {start: 0n, period: 1n, periodCount: 1n, perPeriod: 5000n * nominal};
+
+ // Sender cannot send vestedTransfer to self or other
+ await expect(helper.balance.vestedTransfer(sender, sender.address, manyPeriodsSchedule)).to.be.rejectedWith(/InsufficientBalance/);
+ await expect(helper.balance.vestedTransfer(sender, receiver.address, manyPeriodsSchedule)).to.be.rejectedWith(/InsufficientBalance/);
+ await expect(helper.balance.vestedTransfer(sender, sender.address, oneBigSumSchedule)).to.be.rejectedWith(/InsufficientBalance/);
+ await expect(helper.balance.vestedTransfer(sender, receiver.address, oneBigSumSchedule)).to.be.rejectedWith(/InsufficientBalance/);
+
+ const balanceSender = await helper.balance.getSubstrateFull(sender.address);
+ const balanceReceiver = await helper.balance.getSubstrateFull(receiver.address);
+
+ // Sender's balance has not changed
+ expect(balanceSender.free / nominal).to.eq(999n);
+ expect(balanceSender.feeFrozen).to.eq(0n);
+ expect(balanceSender.miscFrozen).to.eq(0n);
+ expect(balanceSender.reserved).to.eq(0n);
+
+ // Receiver's balance has not changed
+ expect(balanceReceiver.free).to.be.eq(1n * nominal);
+ expect(balanceReceiver.feeFrozen).to.be.eq(0n);
+ expect(balanceReceiver.miscFrozen).to.be.eq(0n);
+ expect(balanceReceiver.reserved).to.be.eq(0n);
+
+ // Receiver cannot send vestedTransfer back because of freeze
+ await expect(helper.balance.vestedTransfer(receiver, sender.address, schedule)).to.be.rejectedWith(/InsufficientBalance/);
+ });
+
+ itSub('cannot send vestedTransfer with incorrect parameters', async ({helper}) => {
+ const [sender, receiver] = await helper.arrange.createAccounts([1000n, 1n], donor);
+ const incorrectperiodSchedule = {start: 0n, period: 0n, periodCount: 10n, perPeriod: 10n * nominal};
+ const incorrectPeriodCountSchedule = {start: 0n, period: 1n, periodCount: 0n, perPeriod: 10n * nominal};
+ const incorrectPerPeriodSchedule = {start: 0n, period: 1n, periodCount: 1n, perPeriod: 0n * nominal};
+
+ await expect(helper.balance.vestedTransfer(sender, sender.address, incorrectperiodSchedule)).to.be.rejectedWith(/vesting.ZeroVestingPeriod/);
+ await expect(helper.balance.vestedTransfer(sender, receiver.address, incorrectPeriodCountSchedule)).to.be.rejectedWith(/vesting.ZeroVestingPeriod/);
+ await expect(helper.balance.vestedTransfer(sender, receiver.address, incorrectPerPeriodSchedule)).to.be.rejectedWith(/vesting.AmountLow/);
+
+ const balanceSender = await helper.balance.getSubstrateFull(sender.address);
+ // Sender's balance has not changed
+ expect(balanceSender.free / nominal).to.eq(999n);
+ expect(balanceSender.feeFrozen).to.eq(0n);
+ expect(balanceSender.miscFrozen).to.eq(0n);
+ expect(balanceSender.reserved).to.eq(0n);
+ });
});