diff --git a/jest-integration.config.js b/jest-integration.config.js index ea96d3f30..1531be19d 100644 --- a/jest-integration.config.js +++ b/jest-integration.config.js @@ -23,7 +23,7 @@ module.exports = { lines: 42, }, // We need a high coverage for the HathorWallet class - './src/new/wallet.js': { + './src/new/wallet.ts': { statements: 92, branches: 85, functions: 90, diff --git a/src/nano_contracts/builder.ts b/src/nano_contracts/builder.ts index 7a2a5fa4c..a24ff5c72 100644 --- a/src/nano_contracts/builder.ts +++ b/src/nano_contracts/builder.ts @@ -187,6 +187,16 @@ class NanoContractTransactionBuilder { return this; } + /** + * Guard that asserts `this.wallet` is not null and narrows its type for the caller. + * Throws a TypeError if wallet is not set. + */ + private assertWallet(): asserts this is { wallet: HathorWallet } { + if (!this.wallet) { + throw new TypeError('Wallet is required to build nano contract transactions.'); + } + } + /** * Set vertex type * @@ -217,6 +227,7 @@ class NanoContractTransactionBuilder { async executeDeposit( action: NanoContractAction ): Promise<{ inputs: IDataInput[]; outputs: IDataOutput[] }> { + this.assertWallet(); if (action.type !== NanoContractActionType.DEPOSIT) { throw new NanoContractTransactionError( "Can't execute a deposit with an action which type is different than deposit." @@ -313,6 +324,7 @@ class NanoContractTransactionBuilder { * @inner */ executeWithdrawal(action: NanoContractAction): IDataOutput | null { + this.assertWallet(); if (action.type !== NanoContractActionType.WITHDRAWAL) { throw new NanoContractTransactionError( "Can't execute a withdrawal with an action which type is different than withdrawal." @@ -381,6 +393,7 @@ class NanoContractTransactionBuilder { async executeGrantAuthority( action: NanoContractAction ): Promise<{ inputs: IDataInput[]; outputs: IDataOutput[] }> { + this.assertWallet(); if (action.type !== NanoContractActionType.GRANT_AUTHORITY) { throw new NanoContractTransactionError( "Can't execute a grant authority with an action which type is different than grant authority." @@ -449,6 +462,7 @@ class NanoContractTransactionBuilder { * @inner */ executeAcquireAuthority(action: NanoContractAction): IDataOutput | null { + this.assertWallet(); if (action.type !== NanoContractActionType.ACQUIRE_AUTHORITY) { throw new NanoContractTransactionError( "Can't execute an acquire authority with an action which type is different than acquire authority." @@ -481,6 +495,7 @@ class NanoContractTransactionBuilder { * @inner */ async verify() { + this.assertWallet(); if (this.method === NANO_CONTRACTS_INITIALIZE_METHOD && !this.blueprintId) { // Initialize needs the blueprint ID throw new NanoContractTransactionError('Missing blueprint id. Parameter blueprintId in data'); @@ -622,6 +637,7 @@ class NanoContractTransactionBuilder { outputs: IDataOutput[], tokens: string[] ): Promise { + this.assertWallet(); if (this.vertexType === NanoContractVertexType.TRANSACTION) { return transactionUtils.createTransactionFromData( { @@ -682,6 +698,7 @@ class NanoContractTransactionBuilder { * @inner */ async build(): Promise { + this.assertWallet(); let inputs; let outputs; let tokens; diff --git a/src/new/sendTransaction.ts b/src/new/sendTransaction.ts index 589bb8e0b..bf9330fc0 100644 --- a/src/new/sendTransaction.ts +++ b/src/new/sendTransaction.ts @@ -75,7 +75,7 @@ export type ISendOutput = ISendDataOutput | ISendTokenOutput; * 'unexpected-error': if an unexpected error happens; * */ export default class SendTransaction extends EventEmitter { - wallet: HathorWallet; + wallet: HathorWallet | null; storage: IStorage | null; diff --git a/src/new/wallet.js b/src/new/wallet.ts similarity index 81% rename from src/new/wallet.js rename to src/new/wallet.ts index 0a3795ba9..5ca8ae6f5 100644 --- a/src/new/wallet.js +++ b/src/new/wallet.ts @@ -5,6 +5,25 @@ * LICENSE file in the root directory of this source tree. */ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// @ts-nocheck +/* eslint-enable @typescript-eslint/ban-ts-comment */ + +/** + * TypeScript Migration In Progress + * + * Status: Constructor and key public methods have been typed with 'any' + * + * Next Steps: + * - Replace 'any' with proper interfaces and types + * - Enable strict type checking incrementally + * - Integrate with external definitions in other files + * + * Note: @ts-nocheck is enabled to allow gradual migration without breaking the build + * + */ + import { cloneDeep, get } from 'lodash'; import bitcore, { HDPrivateKey } from 'bitcore-lib'; import EventEmitter from 'events'; @@ -100,6 +119,13 @@ const ConnectionState = { * one for each request sent to the server. */ class HathorWallet extends EventEmitter { + /* + * List of mandatory proprieties that are not properly declared + */ + storage: any; + + logger: any; + /** * @param {Object} param * @param {FullnodeConnection} param.connection A connection to the server @@ -142,6 +168,22 @@ class HathorWallet extends EventEmitter { preCalculatedAddresses = null, scanPolicy = null, logger = null, + }: { + connection?: any; + storage?: any; + seed?: any; + passphrase?: any; + xpriv?: any; + xpub?: any; + tokenUid?: any; + password?: any; + pinCode?: any; + debug?: any; + beforeReloadCallback?: any; + multisig?: any; + preCalculatedAddresses?: any; + scanPolicy?: any; + logger?: any; } = {}) { super(); @@ -252,7 +294,7 @@ class HathorWallet extends EventEmitter { * Gets the current server url from connection * @return {string} The server url. Ex.: 'http://server.com:8083' */ - getServerUrl() { + getServerUrl(): any { return this.conn.getCurrentServer(); } @@ -260,14 +302,14 @@ class HathorWallet extends EventEmitter { * Gets the current network from connection * @return {string} The network name. Ex.: 'mainnet', 'testnet' */ - getNetwork() { + getNetwork(): any { return this.conn.getCurrentNetwork(); } /** * Gets the network model object */ - getNetworkObject() { + getNetworkObject(): any { return new Network(this.getNetwork()); } @@ -280,9 +322,9 @@ class HathorWallet extends EventEmitter { * @inner * */ // eslint-disable-next-line class-methods-use-this -- The server address is fetched directly from the configs - async getVersionData() { - const versionData = await new Promise((resolve, reject) => { - versionApi.getVersion(resolve).catch(error => reject(error)); + async getVersionData(): Promise { + const versionData: any = await new Promise((resolve: any, reject: any) => { + versionApi.getVersion(resolve).catch((error: any) => reject(error)); }); return { @@ -310,7 +352,7 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - changeServer(newServer) { + changeServer(newServer: any): any { this.storage.config.setServerUrl(newServer); } @@ -319,7 +361,7 @@ class HathorWallet extends EventEmitter { * @param {number} value The new gap limit value * @returns {Promise} */ - async setGapLimit(value) { + async setGapLimit(value: any): Promise { return this.storage.setGapLimit(value); } @@ -328,17 +370,17 @@ class HathorWallet extends EventEmitter { * @param {number} count Number of addresses to load * @returns {Promise} The index of the last address loaded */ - async indexLimitLoadMore(count) { - const scanPolicy = await this.storage.getScanningPolicy(); + async indexLimitLoadMore(count: any): Promise { + const scanPolicy: any = await this.storage.getScanningPolicy(); if (scanPolicy !== SCANNING_POLICY.INDEX_LIMIT) { throw new Error('Wallet is not configured for index-limit scanning policy'); } - const limits = await this.storage.getIndexLimit(); + const limits: any = await this.storage.getIndexLimit(); if (!limits) { throw new Error('Index limit scanning policy config error'); } - const newEndIndex = limits.endIndex + count; + const newEndIndex: any = limits.endIndex + count; await this.indexLimitSetEndIndex(newEndIndex); return newEndIndex; } @@ -348,13 +390,13 @@ class HathorWallet extends EventEmitter { * @param {number} endIndex The new index limit value * @returns {Promise} */ - async indexLimitSetEndIndex(endIndex) { - const scanPolicy = await this.storage.getScanningPolicy(); + async indexLimitSetEndIndex(endIndex: any): Promise { + const scanPolicy: any = await this.storage.getScanningPolicy(); if (scanPolicy !== SCANNING_POLICY.INDEX_LIMIT) { throw new Error('Wallet is not configured for index-limit scanning policy'); } - const limits = await this.storage.getIndexLimit(); + const limits: any = await this.storage.getIndexLimit(); if (!limits) { throw new Error('Index limit scanning policy config error'); } @@ -364,7 +406,7 @@ class HathorWallet extends EventEmitter { return; } - const newPolicyData = { + const newPolicyData: any = { ...limits, endIndex, policy: SCANNING_POLICY.INDEX_LIMIT, @@ -378,7 +420,7 @@ class HathorWallet extends EventEmitter { * Get the value of the gap limit for this wallet instance. * @returns {Promise} */ - async getGapLimit() { + async getGapLimit(): Promise { return this.storage.getGapLimit(); } @@ -386,8 +428,8 @@ class HathorWallet extends EventEmitter { * Get the access data object from storage. * @returns {Promise} */ - async getAccessData() { - const accessData = await this.storage.getAccessData(); + async getAccessData(): Promise { + const accessData: any = await this.storage.getAccessData(); if (!accessData) { throw new WalletError('Wallet was not initialized.'); } @@ -398,8 +440,8 @@ class HathorWallet extends EventEmitter { * Get the configured wallet type. * @returns {Promise} The wallet type */ - async getWalletType() { - const accessData = await this.getAccessData(); + async getWalletType(): Promise { + const accessData: any = await this.getAccessData(); return accessData.walletType; } @@ -409,8 +451,8 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async getMultisigData() { - const accessData = await this.getAccessData(); + async getMultisigData(): Promise { + const accessData: any = await this.getAccessData(); if (accessData.walletType !== WalletType.MULTISIG) { throw new WalletError('Wallet is not a multisig wallet.'); } @@ -424,14 +466,14 @@ class HathorWallet extends EventEmitter { /** * Enable debug mode. * */ - enableDebugMode() { + enableDebugMode(): any { this.debug = true; } /** * Disable debug mode. */ - disableDebugMode() { + disableDebugMode(): any { this.debug = false; } @@ -440,7 +482,7 @@ class HathorWallet extends EventEmitter { * This can be shortcircuted if the wallet is meant to be signed externally. * @returns {Promise} */ - async isReadonly() { + async isReadonly(): Promise { if (this.isSignedExternally) { return false; } @@ -453,7 +495,7 @@ class HathorWallet extends EventEmitter { * * @param {Number} newState Enum of new state after change */ - async onConnectionChangedState(newState) { + async onConnectionChangedState(newState: any): Promise { if (newState === ConnectionState.CONNECTED) { this.setState(HathorWallet.SYNCING); @@ -463,7 +505,7 @@ class HathorWallet extends EventEmitter { // before loading the full data again if (this.firstConnection) { this.firstConnection = false; - const addressesToLoad = await scanPolicyStartAddresses(this.storage); + const addressesToLoad: any = await scanPolicyStartAddresses(this.storage); await this.syncHistory(addressesToLoad.nextIndex, addressesToLoad.count); } else { if (this.beforeReloadCallback) { @@ -472,7 +514,7 @@ class HathorWallet extends EventEmitter { await this.reloadStorage(); } this.setState(HathorWallet.PROCESSING); - } catch (error) { + } catch (error: any) { this.setState(HathorWallet.ERROR); this.logger.error('Error loading wallet', { error }); } @@ -496,24 +538,24 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getAllSignatures(txHex, pin) { + async getAllSignatures(txHex: any, pin: any): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('getAllSignatures'); } - const tx = helpers.createTxFromHex(txHex, this.getNetworkObject()); - const accessData = await this.storage.getAccessData(); + const tx: any = helpers.createTxFromHex(txHex, this.getNetworkObject()); + const accessData: any = await this.storage.getAccessData(); if (accessData === null) { throw new Error('Wallet is not initialized'); } - const signatures = {}; + const signatures: any = {}; for (const signatureInfo of await this.getSignatures(tx, { pinCode: pin })) { - const { inputIndex, signature } = signatureInfo; + const { inputIndex, signature }: any = signatureInfo; signatures[inputIndex] = signature; } - const p2shSig = new P2SHSignature(accessData.multisigData.pubkey, signatures); + const p2shSig: any = new P2SHSignature(accessData.multisigData.pubkey, signatures); return p2shSig.serialize(); } @@ -530,13 +572,13 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async assemblePartialTransaction(txHex, signatures) { - const tx = helpers.createTxFromHex(txHex, this.getNetworkObject()); - const accessData = await this.storage.getAccessData(); + async assemblePartialTransaction(txHex: any, signatures: any): Promise { + const tx: any = helpers.createTxFromHex(txHex, this.getNetworkObject()); + const accessData: any = await this.storage.getAccessData(); if (accessData === null) { throw new Error('Wallet was not started'); } - const { multisigData } = accessData; + const { multisigData }: any = accessData; if (!multisigData) { throw new Error('Cannot call this method from a p2pkh wallet'); } @@ -585,7 +627,7 @@ class HathorWallet extends EventEmitter { * @returns {AsyncGenerator<{address: string, index: number, transactions: number}>} transactions is the count of txs for this address * @memberof HathorWallet * */ - async *getAllAddresses() { + async *getAllAddresses(): AsyncGenerator { // We add the count of transactions // in order to replicate the same return as the new // wallet service facade @@ -606,8 +648,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getAddressAtIndex(index) { - let address = await this.storage.getAddressAtIndex(index); + async getAddressAtIndex(index: any): Promise { + let address: any = await this.storage.getAddressAtIndex(index); if (address === null) { if ((await this.storage.getWalletType()) === 'p2pkh') { @@ -630,8 +672,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getAddressPathForIndex(index) { - const walletType = await this.storage.getWalletType(); + async getAddressPathForIndex(index: any): Promise { + const walletType: any = await this.storage.getWalletType(); if (walletType === WalletType.MULTISIG) { // P2SH return `${P2SH_ACCT_PATH}/0/${index}`; @@ -653,10 +695,10 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getCurrentAddress({ markAsUsed = false } = {}) { - const address = await this.storage.getCurrentAddress(markAsUsed); - const index = await this.getAddressIndex(address); - const addressPath = await this.getAddressPathForIndex(index); + async getCurrentAddress({ markAsUsed = false }: any = {}): Promise { + const address: any = await this.storage.getCurrentAddress(markAsUsed); + const index: any = await this.getAddressIndex(address); + const addressPath: any = await this.getAddressPathForIndex(index); return { address, index, addressPath }; } @@ -666,7 +708,7 @@ class HathorWallet extends EventEmitter { * * @return {Promise<{ address:string, index:number, addressPath:string }>} */ - async getNextAddress() { + async getNextAddress(): Promise { // First we mark the current address as used, then return the next await this.getCurrentAddress({ markAsUsed: true }); return this.getCurrentAddress(); @@ -675,7 +717,7 @@ class HathorWallet extends EventEmitter { /** * Called when a new message arrives from websocket. */ - handleWebsocketMsg(wsData) { + handleWebsocketMsg(wsData: any): any { if (wsData.type === 'wallet:address_history') { if (this.state !== HathorWallet.READY) { // Cannot process new transactions from ws when the wallet is not ready. @@ -703,7 +745,7 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async getBalance(token = null) { + async getBalance(token: any = null): Promise { // TODO if token is null we should get the balance for each token I have // but we don't use it in the wallets, so I won't implement it if (token === null) { @@ -779,19 +821,19 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getTxHistory(options = {}) { - const newOptions = { + async getTxHistory(options: any = {}): Promise { + const newOptions: any = { token_id: NATIVE_TOKEN_UID, count: 15, skip: 0, ...options, }; - const { skip } = newOptions; - let { count } = newOptions; - const uid = newOptions.token_id || this.token.uid; + const { skip }: any = newOptions; + let { count }: any = newOptions; + const uid: any = newOptions.token_id || this.token.uid; - const txs = []; - let it = 0; + const txs: any = []; + let it: any = 0; for await (const tx of this.storage.tokenHistory(uid)) { if (it < skip) { it++; @@ -800,8 +842,8 @@ class HathorWallet extends EventEmitter { if (count <= 0) { break; } - const txbalance = await this.getTxBalance(tx); - const txHistory = { + const txbalance: any = await this.getTxBalance(tx); + const txHistory: any = { txId: tx.tx_id, timestamp: tx.timestamp, voided: tx.is_voided, @@ -830,8 +872,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async getTokens() { - const tokens = []; + async getTokens(): Promise { + const tokens: any = []; for await (const token of this.storage.getAllTokens()) { tokens.push(token.uid); } @@ -846,7 +888,7 @@ class HathorWallet extends EventEmitter { * @return {Promise} Data from the transaction to get. * Can be null if the wallet does not contain the tx. */ - async getTx(id) { + async getTx(id: any): Promise { return this.storage.getTx(id); } @@ -874,8 +916,8 @@ class HathorWallet extends EventEmitter { * @returns {Promise} Aggregated information about the given address * */ - async getAddressInfo(address, options = {}) { - const { token = NATIVE_TOKEN_UID } = options; + async getAddressInfo(address: any, options: any = {}): Promise { + const { token = NATIVE_TOKEN_UID }: any = options; // Throws an error if the address does not belong to this wallet if (!(await this.storage.isAddressMine(address))) { @@ -883,11 +925,11 @@ class HathorWallet extends EventEmitter { } // Derivation path index - const addressData = await this.storage.getAddressInfo(address); - const index = addressData.bip32AddressIndex; + const addressData: any = await this.storage.getAddressInfo(address); + const index: any = addressData.bip32AddressIndex; // Address information that will be calculated below - const addressInfo = { + const addressInfo: any = { total_amount_received: 0n, total_amount_sent: 0n, total_amount_available: 0n, @@ -905,20 +947,24 @@ class HathorWallet extends EventEmitter { // Iterate through outputs for (const output of tx.outputs) { - const is_address_valid = output.decoded && output.decoded.address === address; - const is_token_valid = token === output.token; - const is_authority = transactionUtils.isAuthorityOutput(output); + const is_address_valid: any = output.decoded && output.decoded.address === address; + const is_token_valid: any = token === output.token; + const is_authority: any = transactionUtils.isAuthorityOutput(output); if (!is_address_valid || !is_token_valid || is_authority) { continue; } - const is_spent = output.spent_by !== null; - const is_time_locked = transactionUtils.isOutputLocked(output); + const is_spent: any = output.spent_by !== null; + const is_time_locked: any = transactionUtils.isOutputLocked(output); // XXX: we currently do not check heightlock on the helper, checking here for compatibility - const nowHeight = await this.storage.getCurrentHeight(); - const rewardLock = this.storage.version?.reward_spend_min_blocks; - const is_height_locked = transactionUtils.isHeightLocked(tx.height, nowHeight, rewardLock); - const is_locked = is_time_locked || is_height_locked; + const nowHeight: any = await this.storage.getCurrentHeight(); + const rewardLock: any = this.storage.version?.reward_spend_min_blocks; + const is_height_locked: any = transactionUtils.isHeightLocked( + tx.height, + nowHeight, + rewardLock + ); + const is_locked: any = is_time_locked || is_height_locked; addressInfo.total_amount_received += output.value; @@ -977,8 +1023,8 @@ class HathorWallet extends EventEmitter { * @return {Promise} Utxos and meta information about it * */ - async getUtxos(options = {}) { - const newOptions = { + async getUtxos(options: any = {}): Promise { + const newOptions: any = { token: options.token, authorities: 0, max_utxos: options.max_utxos, @@ -989,24 +1035,24 @@ class HathorWallet extends EventEmitter { only_available_utxos: options.only_available_utxos, }; /** @type {UtxoDetails} */ - const utxoDetails = { + const utxoDetails: any = { total_amount_available: 0n, total_utxos_available: 0n, total_amount_locked: 0n, total_utxos_locked: 0n, utxos: [], }; - const nowTs = Math.floor(Date.now() / 1000); - const isTimeLocked = timestamp => timestamp && nowTs && nowTs < timestamp; - const nowHeight = await this.storage.getCurrentHeight(); - const rewardLock = this.storage.version?.reward_spend_min_blocks; + const nowTs: any = Math.floor(Date.now() / 1000); + const isTimeLocked: any = (timestamp: any) => timestamp && nowTs && nowTs < timestamp; + const nowHeight: any = await this.storage.getCurrentHeight(); + const rewardLock: any = this.storage.version?.reward_spend_min_blocks; for await (const utxo of this.storage.selectUtxos(newOptions)) { - const isLocked = + const isLocked: any = isTimeLocked(utxo.timelock) || transactionUtils.isHeightLocked(utxo.height, nowHeight, rewardLock); - const utxoInfo = { + const utxoInfo: any = { address: utxo.address, amount: utxo.value, tx_id: utxo.txId, @@ -1051,11 +1097,11 @@ class HathorWallet extends EventEmitter { * @generator * @yields {Utxo} all available utxos */ - async *getAvailableUtxos(options = {}) { + async *getAvailableUtxos(options: any = {}): AsyncGenerator { // This method only returns available utxos for await (const utxo of this.storage.selectUtxos({ ...options, only_available_utxos: true })) { - const addressIndex = await this.getAddressIndex(utxo.address); - const addressPath = await this.getAddressPathForIndex(addressIndex); + const addressIndex: any = await this.getAddressIndex(utxo.address); + const addressPath: any = await this.getAddressPathForIndex(addressIndex); yield { txId: utxo.txId, index: utxo.index, @@ -1080,15 +1126,15 @@ class HathorWallet extends EventEmitter { * * @return {Promise<{utxos: Utxo[], changeAmount: OutputValueType}>} Utxos and change information. */ - async getUtxosForAmount(amount, options = {}) { - const newOptions = { + async getUtxosForAmount(amount: any, options: any = {}): Promise { + const newOptions: any = { token: NATIVE_TOKEN_UID, filter_address: null, ...options, order_by_value: 'desc', }; - const utxos = []; + const utxos: any = []; for await (const utxo of this.getAvailableUtxos(newOptions)) { utxos.push(utxo); } @@ -1107,7 +1153,7 @@ class HathorWallet extends EventEmitter { * @param {boolean} [value=true] The value to set the utxos. * @param {number?} [ttl=null] */ - async markUtxoSelected(txId, index, value = true, ttl = null) { + async markUtxoSelected(txId: any, index: any, value: any = true, ttl: any = null): Promise { await this.storage.utxoSelectAsInput({ txId, index }, value, ttl); } @@ -1127,17 +1173,17 @@ class HathorWallet extends EventEmitter { * @return {Promise} Required data to consolidate utxos * */ - async prepareConsolidateUtxosData(destinationAddress, options = {}) { - const utxoDetails = await this.getUtxos({ ...options, only_available_utxos: true }); - const inputs = []; - const utxos = []; - let total_amount = 0n; + async prepareConsolidateUtxosData(destinationAddress: any, options: any = {}): Promise { + const utxoDetails: any = await this.getUtxos({ ...options, only_available_utxos: true }); + const inputs: any = []; + const utxos: any = []; + let total_amount: any = 0n; for (let i = 0; i < utxoDetails.utxos.length; i++) { if (inputs.length === this.storage.version.max_number_inputs) { // Max number of inputs reached break; } - const utxo = utxoDetails.utxos[i]; + const utxo: any = utxoDetails.utxos[i]; inputs.push({ txId: utxo.tx_id, index: utxo.index, @@ -1145,7 +1191,7 @@ class HathorWallet extends EventEmitter { utxos.push(utxo); total_amount += utxo.amount; } - const outputs = [ + const outputs: any = [ { address: destinationAddress, value: total_amount, @@ -1173,11 +1219,11 @@ class HathorWallet extends EventEmitter { * @return {Promise} * */ - async consolidateUtxosSendTransaction(destinationAddress, options = {}) { + async consolidateUtxosSendTransaction(destinationAddress: any, options: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('consolidateUtxos'); } - const { outputs, inputs, utxos, total_amount } = await this.prepareConsolidateUtxosData( + const { outputs, inputs, utxos, total_amount }: any = await this.prepareConsolidateUtxosData( destinationAddress, options ); @@ -1217,11 +1263,11 @@ class HathorWallet extends EventEmitter { * @return {Promise} Indicates that the transaction is sent or not * */ - async consolidateUtxos(destinationAddress, options = {}) { - const { total_utxos_consolidated, total_amount, sendTx, utxos } = + async consolidateUtxos(destinationAddress: any, options: any = {}): Promise { + const { total_utxos_consolidated, total_amount, sendTx, utxos }: any = await this.consolidateUtxosSendTransaction(destinationAddress, options); - const tx = await sendTx.run(); + const tx: any = await sendTx.run(); return { total_utxos_consolidated, @@ -1267,8 +1313,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async getFullHistory() { - const history = {}; + async getFullHistory(): Promise { + const history: any = {}; for await (const tx of this.storage.txHistory()) { history[tx.tx_id] = tx; } @@ -1281,8 +1327,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async processTxQueue() { - let wsData = this.wsTxQueue.dequeue(); + async processTxQueue(): Promise { + let wsData: any = this.wsTxQueue.dequeue(); while (wsData !== undefined) { // save new txdata @@ -1410,17 +1456,17 @@ class HathorWallet extends EventEmitter { * * @return {Promise} Promise that resolves when transaction is sent */ - async sendTransactionInstance(address, value, options = {}) { + async sendTransactionInstance(address: any, value: any, options: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('sendTransaction'); } - const newOptions = { + const newOptions: any = { token: '00', changeAddress: null, ...options, }; - const { token, changeAddress, pinCode } = newOptions; - const outputs = [{ address, value, token }]; + const { token, changeAddress, pinCode }: any = newOptions; + const outputs: any = [{ address, value, token }]; return this.sendManyOutputsSendTransaction(outputs, { inputs: [], changeAddress, pinCode }); } @@ -1436,8 +1482,8 @@ class HathorWallet extends EventEmitter { * * @return {Promise} Promise that resolves when transaction is sent */ - async sendTransaction(address, value, options = {}) { - const sendTx = await this.sendTransactionInstance(address, value, options); + async sendTransaction(address: any, value: any, options: any = {}): Promise { + const sendTx: any = await this.sendTransactionInstance(address, value, options); return sendTx.run(); } @@ -1472,11 +1518,11 @@ class HathorWallet extends EventEmitter { * * @return {Promise} */ - async sendManyOutputsSendTransaction(outputs, options = {}) { + async sendManyOutputsSendTransaction(outputs: any, options: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('sendManyOutputsTransaction'); } - const newOptions = { + const newOptions: any = { inputs: [], changeAddress: null, startMiningTx: true, @@ -1484,11 +1530,11 @@ class HathorWallet extends EventEmitter { ...options, }; - const pin = newOptions.pinCode || this.pinCode; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } - const { inputs, changeAddress } = newOptions; + const { inputs, changeAddress }: any = newOptions; return new SendTransaction({ wallet: this, outputs, @@ -1506,8 +1552,8 @@ class HathorWallet extends EventEmitter { * * @return {Promise} Promise that resolves when transaction is sent */ - async sendManyOutputsTransaction(outputs, options = {}) { - const sendTransaction = await this.sendManyOutputsSendTransaction(outputs, options); + async sendManyOutputsTransaction(outputs: any, options: any = {}): Promise { + const sendTransaction: any = await this.sendManyOutputsSendTransaction(outputs, options); return sendTransaction.run(); } @@ -1520,10 +1566,10 @@ class HathorWallet extends EventEmitter { * 'password': password to decrypt xpriv information. Required if not set in object. * } */ - async start(optionsParams = {}) { - const options = { pinCode: null, password: null, ...optionsParams }; - const pinCode = options.pinCode || this.pinCode; - const password = options.password || this.password; + async start(optionsParams: any = {}): Promise { + const options: any = { pinCode: null, password: null, ...optionsParams }; + const pinCode: any = options.pinCode || this.pinCode; + const password: any = options.password || this.password; if (!this.xpub && !pinCode) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } @@ -1624,9 +1670,9 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async getAddressPrivKey(pinCode, addressIndex) { - const mainXPrivKey = await this.storage.getMainXPrivKey(pinCode); - const addressHDPrivKey = new bitcore.HDPrivateKey(mainXPrivKey).derive(addressIndex); + async getAddressPrivKey(pinCode: any, addressIndex: any): Promise { + const mainXPrivKey: any = await this.storage.getMainXPrivKey(pinCode); + const addressHDPrivKey: any = new bitcore.HDPrivateKey(mainXPrivKey).derive(addressIndex); return addressHDPrivKey; } @@ -1644,9 +1690,9 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async signMessageWithAddress(message, index, pinCode) { - const addressHDPrivKey = await this.getAddressPrivKey(pinCode, index); - const signedMessage = signMessage(message, addressHDPrivKey.privateKey); + async signMessageWithAddress(message: any, index: any, pinCode: any): Promise { + const addressHDPrivKey: any = await this.getAddressPrivKey(pinCode, index); + const signedMessage: any = signMessage(message, addressHDPrivKey.privateKey); return signedMessage; } @@ -1664,8 +1710,8 @@ class HathorWallet extends EventEmitter { * @inner * @deprecated */ - async handleSendPreparedTransaction(transaction) { - const sendTransaction = new SendTransaction({ wallet: this, transaction }); + async handleSendPreparedTransaction(transaction: any): Promise { + const sendTransaction: any = new SendTransaction({ wallet: this, transaction }); return sendTransaction.runFromMining(); } @@ -1702,11 +1748,16 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner */ - async prepareCreateNewToken(name, symbol, amount, options = {}) { + async prepareCreateNewToken( + name: any, + symbol: any, + amount: any, + options: any = {} + ): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('createNewToken'); } - const newOptions = { + const newOptions: any = { address: null, changeAddress: null, startMiningTx: true, @@ -1723,14 +1774,14 @@ class HathorWallet extends EventEmitter { ...options, }; - const pin = newOptions.pinCode || this.pinCode; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } if (newOptions.mintAuthorityAddress && !newOptions.allowExternalMintAuthorityAddress) { // Validate that the mint authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newOptions.mintAuthorityAddress); + const isAddressMine: any = await this.isAddressMine(newOptions.mintAuthorityAddress); if (!isAddressMine) { throw new Error('The mint authority address must belong to your wallet.'); } @@ -1738,15 +1789,15 @@ class HathorWallet extends EventEmitter { if (newOptions.meltAuthorityAddress && !newOptions.allowExternalMeltAuthorityAddress) { // Validate that the melt authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newOptions.meltAuthorityAddress); + const isAddressMine: any = await this.isAddressMine(newOptions.meltAuthorityAddress); if (!isAddressMine) { throw new Error('The melt authority address must belong to your wallet.'); } } - const mintAddress = newOptions.address || (await this.getCurrentAddress()).address; + const mintAddress: any = newOptions.address || (await this.getCurrentAddress()).address; - const txData = await tokenUtils.prepareCreateTokenData( + const txData: any = await tokenUtils.prepareCreateTokenData( mintAddress, name, symbol, @@ -1779,8 +1830,13 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async createNewTokenSendTransaction(name, symbol, amount, options = {}) { - const transaction = await this.prepareCreateNewToken(name, symbol, amount, options); + async createNewTokenSendTransaction( + name: any, + symbol: any, + amount: any, + options: any = {} + ): Promise { + const transaction: any = await this.prepareCreateNewToken(name, symbol, amount, options); return new SendTransaction({ wallet: this, transaction }); } @@ -1796,8 +1852,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async createNewToken(name, symbol, amount, options = {}) { - const sendTx = await this.createNewTokenSendTransaction(name, symbol, amount, options); + async createNewToken(name: any, symbol: any, amount: any, options: any = {}): Promise { + const sendTx: any = await this.createNewTokenSendTransaction(name, symbol, amount, options); return sendTx.runFromMining(); } @@ -1819,7 +1875,7 @@ class HathorWallet extends EventEmitter { * The "authorities" field actually contains the output value with the authority masks. * Returns an empty array in case there are no tx_outupts for this type. * */ - async getMintAuthority(tokenUid, options = {}) { + async getMintAuthority(tokenUid: any, options: any = {}): Promise { return this.getAuthorityUtxo(tokenUid, 'mint', options); } @@ -1841,7 +1897,7 @@ class HathorWallet extends EventEmitter { * The "authorities" field actually contains the output value with the authority masks. * Returns an empty array in case there are no tx_outupts for this type. * */ - async getMeltAuthority(tokenUid, options = {}) { + async getMeltAuthority(tokenUid: any, options: any = {}): Promise { return this.getAuthorityUtxo(tokenUid, 'melt', options); } @@ -1864,8 +1920,8 @@ class HathorWallet extends EventEmitter { * The "authorities" field actually contains the output value with the authority masks. * Returns an empty array in case there are no tx_outupts for this type. * */ - async getAuthorityUtxo(tokenUid, authority, options = {}) { - let authorityValue; + async getAuthorityUtxo(tokenUid: any, authority: any, options: any = {}): Promise { + let authorityValue: any; if (authority === 'mint') { authorityValue = 1n; } else if (authority === 'melt') { @@ -1874,7 +1930,7 @@ class HathorWallet extends EventEmitter { throw new Error('Invalid authority value.'); } - const newOptions = { + const newOptions: any = { token: tokenUid, authorities: authorityValue, only_available_utxos: options.only_available_utxos ?? false, @@ -1884,7 +1940,7 @@ class HathorWallet extends EventEmitter { // limit number of utxos to select if many is false newOptions.max_utxos = 1; } - const utxos = []; + const utxos: any = []; for await (const utxo of this.storage.selectUtxos(newOptions)) { utxos.push(utxo); } @@ -1919,11 +1975,11 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async prepareMintTokensData(tokenUid, amount, options = {}) { + async prepareMintTokensData(tokenUid: any, amount: any, options: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('mintTokens'); } - const newOptions = { + const newOptions: any = { address: null, changeAddress: null, createAnotherMint: true, @@ -1936,22 +1992,22 @@ class HathorWallet extends EventEmitter { ...options, }; - const pin = newOptions.pinCode || this.pinCode; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } if (newOptions.mintAuthorityAddress && !newOptions.allowExternalMintAuthorityAddress) { // Validate that the mint authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newOptions.mintAuthorityAddress); + const isAddressMine: any = await this.isAddressMine(newOptions.mintAuthorityAddress); if (!isAddressMine) { throw new Error('The mint authority address must belong to your wallet.'); } } - const mintAddress = newOptions.address || (await this.getCurrentAddress()).address; + const mintAddress: any = newOptions.address || (await this.getCurrentAddress()).address; - const mintInput = await this.getMintAuthority(tokenUid, { + const mintInput: any = await this.getMintAuthority(tokenUid, { many: false, only_available_utxos: true, }); @@ -1960,7 +2016,7 @@ class HathorWallet extends EventEmitter { throw new Error("Don't have mint authority output available."); } - const mintOptions = { + const mintOptions: any = { token: tokenUid, mintInput: mintInput[0], createAnotherMint: newOptions.createAnotherMint, @@ -1969,7 +2025,7 @@ class HathorWallet extends EventEmitter { unshiftData: newOptions.unshiftData, data: newOptions.data, }; - const txData = await tokenUtils.prepareMintTxData( + const txData: any = await tokenUtils.prepareMintTxData( mintAddress, amount, this.storage, @@ -1993,8 +2049,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async mintTokensSendTransaction(tokenUid, amount, options = {}) { - const transaction = await this.prepareMintTokensData(tokenUid, amount, options); + async mintTokensSendTransaction(tokenUid: any, amount: any, options: any = {}): Promise { + const transaction: any = await this.prepareMintTokensData(tokenUid, amount, options); return new SendTransaction({ wallet: this, transaction }); } @@ -2010,8 +2066,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async mintTokens(tokenUid, amount, options = {}) { - const sendTx = await this.mintTokensSendTransaction(tokenUid, amount, options); + async mintTokens(tokenUid: any, amount: any, options: any = {}): Promise { + const sendTx: any = await this.mintTokensSendTransaction(tokenUid, amount, options); return sendTx.runFromMining(); } @@ -2041,11 +2097,11 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async prepareMeltTokensData(tokenUid, amount, options = {}) { + async prepareMeltTokensData(tokenUid: any, amount: any, options: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('meltTokens'); } - const newOptions = { + const newOptions: any = { address: null, changeAddress: null, createAnotherMelt: true, @@ -2058,20 +2114,20 @@ class HathorWallet extends EventEmitter { ...options, }; - const pin = newOptions.pinCode || this.pinCode; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } if (newOptions.meltAuthorityAddress && !newOptions.allowExternalMeltAuthorityAddress) { // Validate that the melt authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newOptions.meltAuthorityAddress); + const isAddressMine: any = await this.isAddressMine(newOptions.meltAuthorityAddress); if (!isAddressMine) { throw new Error('The melt authority address must belong to your wallet.'); } } - const meltInput = await this.getMeltAuthority(tokenUid, { + const meltInput: any = await this.getMeltAuthority(tokenUid, { many: false, only_available_utxos: true, }); @@ -2080,14 +2136,14 @@ class HathorWallet extends EventEmitter { throw new Error("Don't have melt authority output available."); } - const meltOptions = { + const meltOptions: any = { createAnotherMelt: newOptions.createAnotherMelt, meltAuthorityAddress: newOptions.meltAuthorityAddress, changeAddress: newOptions.changeAddress, unshiftData: newOptions.unshiftData, data: newOptions.data, }; - const txData = await tokenUtils.prepareMeltTxData( + const txData: any = await tokenUtils.prepareMeltTxData( tokenUid, meltInput[0], newOptions.address || (await this.getCurrentAddress()).address, @@ -2113,8 +2169,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async meltTokensSendTransaction(tokenUid, amount, options = {}) { - const transaction = await this.prepareMeltTokensData(tokenUid, amount, options); + async meltTokensSendTransaction(tokenUid: any, amount: any, options: any = {}): Promise { + const transaction: any = await this.prepareMeltTokensData(tokenUid, amount, options); return new SendTransaction({ wallet: this, transaction }); } @@ -2130,8 +2186,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async meltTokens(tokenUid, amount, options = {}) { - const sendTx = await this.meltTokensSendTransaction(tokenUid, amount, options); + async meltTokens(tokenUid: any, amount: any, options: any = {}): Promise { + const sendTx: any = await this.meltTokensSendTransaction(tokenUid, amount, options); return sendTx.runFromMining(); } @@ -2155,17 +2211,22 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async prepareDelegateAuthorityData(tokenUid, type, destinationAddress, options = {}) { + async prepareDelegateAuthorityData( + tokenUid: any, + type: any, + destinationAddress: any, + options: any = {} + ): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('delegateAuthority'); } - const newOptions = { createAnother: true, pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { createAnother: true, pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } - const { createAnother } = newOptions; - let delegateInput; + const { createAnother }: any = newOptions; + let delegateInput: any; if (type === 'mint') { delegateInput = await this.getMintAuthority(tokenUid, { many: false, @@ -2184,7 +2245,7 @@ class HathorWallet extends EventEmitter { throw new Error({ success: false, message: ErrorMessages.NO_UTXOS_AVAILABLE }); } - const txData = await tokenUtils.prepareDelegateAuthorityTxData( + const txData: any = await tokenUtils.prepareDelegateAuthorityTxData( tokenUid, delegateInput[0], destinationAddress, @@ -2209,8 +2270,13 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async delegateAuthoritySendTransaction(tokenUid, type, destinationAddress, options = {}) { - const transaction = await this.prepareDelegateAuthorityData( + async delegateAuthoritySendTransaction( + tokenUid: any, + type: any, + destinationAddress: any, + options: any = {} + ): Promise { + const transaction: any = await this.prepareDelegateAuthorityData( tokenUid, type, destinationAddress, @@ -2232,8 +2298,13 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async delegateAuthority(tokenUid, type, destinationAddress, options = {}) { - const sendTx = await this.delegateAuthoritySendTransaction( + async delegateAuthority( + tokenUid: any, + type: any, + destinationAddress: any, + options: any = {} + ): Promise { + const sendTx: any = await this.delegateAuthoritySendTransaction( tokenUid, type, destinationAddress, @@ -2261,16 +2332,21 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async prepareDestroyAuthorityData(tokenUid, type, count, options = {}) { + async prepareDestroyAuthorityData( + tokenUid: any, + type: any, + count: any, + options: any = {} + ): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('destroyAuthority'); } - const newOptions = { pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } - let destroyInputs; + let destroyInputs: any; if (type === 'mint') { destroyInputs = await this.getMintAuthority(tokenUid, { many: true, @@ -2289,7 +2365,7 @@ class HathorWallet extends EventEmitter { throw new Error(ErrorMessages.NO_UTXOS_AVAILABLE); } - const data = []; + const data: any = []; for (const utxo of destroyInputs) { // FIXME: select utxos passing count to the method data.push(utxo); @@ -2300,7 +2376,7 @@ class HathorWallet extends EventEmitter { } } - const txData = tokenUtils.prepareDestroyAuthorityTxData(data); + const txData: any = tokenUtils.prepareDestroyAuthorityTxData(data); return transactionUtils.prepareTransaction(txData, pin, this.storage); } @@ -2318,8 +2394,13 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async destroyAuthoritySendTransaction(tokenUid, type, count, options = {}) { - const transaction = await this.prepareDestroyAuthorityData(tokenUid, type, count, options); + async destroyAuthoritySendTransaction( + tokenUid: any, + type: any, + count: any, + options: any = {} + ): Promise { + const transaction: any = await this.prepareDestroyAuthorityData(tokenUid, type, count, options); return new SendTransaction({ wallet: this, transaction }); } @@ -2336,8 +2417,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async destroyAuthority(tokenUid, type, count, options = {}) { - const sendTx = await this.destroyAuthoritySendTransaction(tokenUid, type, count, options); + async destroyAuthority(tokenUid: any, type: any, count: any, options: any = {}): Promise { + const sendTx: any = await this.destroyAuthoritySendTransaction(tokenUid, type, count, options); return sendTx.runFromMining(); } @@ -2348,7 +2429,7 @@ class HathorWallet extends EventEmitter { * garbage collect it. JavaScript currently does not provide a standard way to trigger * garbage collection * */ - clearSensitiveData() { + clearSensitiveData(): any { this.xpriv = undefined; this.seed = undefined; } @@ -2362,7 +2443,7 @@ class HathorWallet extends EventEmitter { * @return {{tx_id: string, index: number, address: string, authorities: OutputValueType}[]} * Array of the authority outputs. * */ - async getAuthorityUtxos(tokenUid, type) { + async getAuthorityUtxos(tokenUid: any, type: any): Promise { if (type === 'mint') { return this.getMintAuthority(tokenUid, { many: true }); } @@ -2372,7 +2453,7 @@ class HathorWallet extends EventEmitter { throw new Error('This should never happen.'); } - getTokenData() { + getTokenData(): any { if (this.tokenUid === NATIVE_TOKEN_UID) { // Hathor token we don't get from the full node this.token = this.storage.getNativeTokenData(); @@ -2384,7 +2465,7 @@ class HathorWallet extends EventEmitter { // READY state with token still null. // I will keep it like that for now but to protect from this // we should change to READY only after both things finish - walletApi.getGeneralTokenInfo(this.tokenUid, response => { + walletApi.getGeneralTokenInfo(this.tokenUid, (response: any) => { if (response.success) { this.token = { uid: this.tokenUid, @@ -2417,16 +2498,16 @@ class HathorWallet extends EventEmitter { * }>} token details */ // eslint-disable-next-line class-methods-use-this -- The server address is fetched directly from the configs - async getTokenDetails(tokenId) { - const result = await new Promise((resolve, reject) => { - walletApi.getGeneralTokenInfo(tokenId, resolve).catch(error => reject(error)); + async getTokenDetails(tokenId: any): Promise { + const result: any = await new Promise((resolve, reject) => { + walletApi.getGeneralTokenInfo(tokenId, resolve).catch((error: any) => reject(error)); }); if (!result.success) { throw new Error(result.message); } - const { name, symbol, mint, melt, total, transactions_count } = result; + const { name, symbol, mint, melt, total, transactions_count }: any = result; // Transform to the same format the wallet service facade responds return { @@ -2444,7 +2525,7 @@ class HathorWallet extends EventEmitter { }; } - isReady() { + isReady(): any { return this.state === HathorWallet.READY; } @@ -2455,7 +2536,7 @@ class HathorWallet extends EventEmitter { * * @return {Promise} * */ - async isAddressMine(address) { + async isAddressMine(address: any): Promise { return this.storage.isAddressMine(address); } @@ -2466,14 +2547,14 @@ class HathorWallet extends EventEmitter { * * @return {Object} Object with the addresses and whether it belongs or not { address: boolean } * */ - async checkAddressesMine(addresses) { - const promises = []; + async checkAddressesMine(addresses: any): Promise { + const promises: any = []; for (const address of addresses) { - promises.push(this.storage.isAddressMine(address).then(mine => ({ address, mine }))); + promises.push(this.storage.isAddressMine(address).then((mine: any) => ({ address, mine }))); } - const results = await Promise.all(promises); - return results.reduce((acc, result) => { + const results: any = await Promise.all(promises); + return results.reduce((acc: any, result: any) => { acc[result.address] = result.mine; return acc; }, {}); @@ -2487,8 +2568,8 @@ class HathorWallet extends EventEmitter { * * @return {Promise} * */ - async getAddressIndex(address) { - const addressInfo = await this.storage.getAddressInfo(address); + async getAddressIndex(address: any): Promise { + const addressInfo: any = await this.storage.getAddressInfo(address); return get(addressInfo, 'bip32AddressIndex', null); } @@ -2507,13 +2588,13 @@ class HathorWallet extends EventEmitter { * const decodedTx = hathorWalletInstance.getTx(txHash); * const txBalance = await hathorWalletInstance.getTxBalance(decodedTx); * */ - async getTxBalance(tx, optionsParam = {}) { - const balance = {}; - const fullBalance = await transactionUtils.getTxBalance(tx, this.storage); + async getTxBalance(tx: any, optionsParam: any = {}): Promise { + const balance: any = {}; + const fullBalance: any = await transactionUtils.getTxBalance(tx, this.storage); // We need to map balance for backwards compatibility for (const [token, tokenBalance] of Object.entries(fullBalance)) { - balance[token] = tokenBalance.tokens.locked + tokenBalance.tokens.unlocked; + balance[token] = (tokenBalance as any).tokens.locked + (tokenBalance as any).tokens.unlocked; } return balance; @@ -2528,8 +2609,8 @@ class HathorWallet extends EventEmitter { * * @return {Set} Set of strings with addresses * */ - async getTxAddresses(tx) { - const addresses = new Set(); + async getTxAddresses(tx: any): Promise { + const addresses: any = new Set(); for (const io of [...tx.outputs, ...tx.inputs]) { if (io.decoded && io.decoded.address && (await this.isAddressMine(io.decoded.address))) { addresses.add(io.decoded.address); @@ -2557,9 +2638,15 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async createNFTSendTransaction(name, symbol, amount, data, options = {}) { + async createNFTSendTransaction( + name: any, + symbol: any, + amount: any, + data: any, + options: any = {} + ): Promise { /** @type {CreateTokenOptions} */ - const newOptions = { + const newOptions: any = { address: null, changeAddress: null, startMiningTx: true, @@ -2574,7 +2661,7 @@ class HathorWallet extends EventEmitter { }; newOptions.data = [data]; newOptions.isCreateNFT = true; - const transaction = await this.prepareCreateNewToken(name, symbol, amount, newOptions); + const transaction: any = await this.prepareCreateNewToken(name, symbol, amount, newOptions); return new SendTransaction({ wallet: this, transaction }); } @@ -2592,8 +2679,8 @@ class HathorWallet extends EventEmitter { * @memberof HathorWallet * @inner * */ - async createNFT(name, symbol, amount, data, options = {}) { - const sendTx = await this.createNFTSendTransaction(name, symbol, amount, data, options); + async createNFT(name: any, symbol: any, amount: any, data: any, options: any = {}): Promise { + const sendTx: any = await this.createNFTSendTransaction(name, symbol, amount, data, options); return sendTx.runFromMining(); } @@ -2608,17 +2695,17 @@ class HathorWallet extends EventEmitter { * addressPath: string, * }[]>} List of indexes and their associated address index */ - async getWalletInputInfo(tx) { - const walletInputs = []; + async getWalletInputInfo(tx: any): Promise { + const walletInputs: any = []; for await (const { tx: spentTx, input, index } of this.storage.getSpentTxs(tx.inputs)) { - const addressInfo = await this.storage.getAddressInfo( + const addressInfo: any = await this.storage.getAddressInfo( spentTx.outputs[input.index].decoded.address ); if (addressInfo === null) { continue; } - const addressPath = await this.getAddressPathForIndex(addressInfo.bip32AddressIndex); + const addressPath: any = await this.getAddressPathForIndex(addressInfo.bip32AddressIndex); walletInputs.push({ inputIndex: index, addressIndex: addressInfo.bip32AddressIndex, @@ -2646,16 +2733,16 @@ class HathorWallet extends EventEmitter { * pubkey: string, * }>} Input and signature information */ - async getSignatures(tx, { pinCode = null } = {}) { + async getSignatures(tx: any, { pinCode = null }: any = {}): Promise { if (await this.isReadonly()) { throw new WalletFromXPubGuard('getSignatures'); } - const pin = pinCode || this.pinCode; + const pin: any = pinCode || this.pinCode; if (!pin) { throw new Error(ERROR_MESSAGE_PIN_REQUIRED); } - const signatures = await this.storage.getTxSignatures(tx, pin); - const sigInfoArray = []; + const signatures: any = await this.storage.getTxSignatures(tx, pin); + const sigInfoArray: any = []; for (const sigData of signatures.inputSignatures) { sigInfoArray.push({ ...sigData, @@ -2678,10 +2765,10 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} The signed transaction */ - async signTx(tx, options = {}) { + async signTx(tx: any, options: any = {}): Promise { for (const sigInfo of await this.getSignatures(tx, options)) { - const { signature, pubkey, inputIndex } = sigInfo; - const inputData = transactionUtils.createInputData( + const { signature, pubkey, inputIndex }: any = sigInfo; + const inputData: any = transactionUtils.createInputData( Buffer.from(signature, 'hex'), Buffer.from(pubkey, 'hex') ); @@ -2698,7 +2785,7 @@ class HathorWallet extends EventEmitter { * * @throws {TxNotFoundError} If the returned error was a transaction not found */ - static _txNotFoundGuard(data) { + static _txNotFoundGuard(data: any): any { if (get(data, 'message', '') === 'Transaction not found') { throw new TxNotFoundError(); } @@ -2712,14 +2799,14 @@ class HathorWallet extends EventEmitter { * @returns {FullNodeTxResponse} Transaction data in the fullnode */ // eslint-disable-next-line class-methods-use-this -- The server address is fetched directly from the configs - async getFullTxById(txId) { - const tx = await new Promise((resolve, reject) => { + async getFullTxById(txId: any): Promise { + const tx: any = await new Promise((resolve, reject) => { txApi .getTransaction(txId, resolve) // txApi will call the `resolve` callback and end the promise chain, // so if it falls here, we should throw .then(() => reject(new Error('API client did not use the callback'))) - .catch(err => reject(err)); + .catch((err: any) => reject(err)); }); if (!tx.success) { HathorWallet._txNotFoundGuard(tx); @@ -2738,12 +2825,12 @@ class HathorWallet extends EventEmitter { * @returns {FullNodeTxConfirmationDataResponse} Transaction confirmation data */ // eslint-disable-next-line class-methods-use-this -- The server address is fetched directly from the configs - async getTxConfirmationData(txId) { - const confirmationData = await new Promise((resolve, reject) => { + async getTxConfirmationData(txId: any): Promise { + const confirmationData: any = await new Promise((resolve, reject) => { txApi .getConfirmationData(txId, resolve) .then(() => reject(new Error('API client did not use the callback'))) - .catch(err => reject(err)); + .catch((err: any) => reject(err)); }); if (!confirmationData.success) { @@ -2765,12 +2852,12 @@ class HathorWallet extends EventEmitter { * @returns {Promise} The graphviz digraph */ // eslint-disable-next-line class-methods-use-this -- The server address is fetched directly from the configs - async graphvizNeighborsQuery(txId, graphType, maxLevel) { - const graphvizData = await new Promise((resolve, reject) => { + async graphvizNeighborsQuery(txId: any, graphType: any, maxLevel: any): Promise { + const graphvizData: any = await new Promise((resolve, reject) => { txApi .getGraphvizNeighbors(txId, graphType, maxLevel, resolve) .then(() => reject(new Error('API client did not use the callback'))) - .catch(err => reject(err)); + .catch((err: any) => reject(err)); }); // The response will either be a string with the graphviz data or an object @@ -2825,7 +2912,7 @@ class HathorWallet extends EventEmitter { * @throws {Error} Token uid not found in tokens list * @throws {Error} Token uid not found in tx */ - async getTxById(txId) { + async getTxById(txId: any): Promise { /** * Hydrate input and output with token uid * @param {Transaction.input|Transaction.output} io - Input or output @@ -2837,8 +2924,8 @@ class HathorWallet extends EventEmitter { * } * @throws {Error} Token uid not found in tokens list */ - const hydrateWithTokenUid = (io, tokens) => { - const { token_data } = io; + const hydrateWithTokenUid = (io: any, tokens: any): any => { + const { token_data }: any = io; if (token_data === 0) { return { @@ -2847,8 +2934,8 @@ class HathorWallet extends EventEmitter { }; } - const tokenIdx = tokenUtils.getTokenIndexFromData(token_data); - const tokenUid = tokens[tokenIdx - 1]?.uid; + const tokenIdx: any = tokenUtils.getTokenIndexFromData(token_data); + const tokenUid: any = tokens[tokenIdx - 1]?.uid; if (!tokenUid) { throw new Error(`Invalid token_data ${token_data}, token not found in tokens list`); } @@ -2864,33 +2951,35 @@ class HathorWallet extends EventEmitter { * @throws {Error} Client did not use the callback * @throws {Error} Transaction not found */ - const fullTx = await this.getFullTxById(txId); - fullTx.tx.outputs = fullTx.tx.outputs.map(output => + const fullTx: any = await this.getFullTxById(txId); + fullTx.tx.outputs = fullTx.tx.outputs.map((output: any) => hydrateWithTokenUid(output, fullTx.tx.tokens) ); - fullTx.tx.inputs = fullTx.tx.inputs.map(input => hydrateWithTokenUid(input, fullTx.tx.tokens)); + fullTx.tx.inputs = fullTx.tx.inputs.map((input: any) => + hydrateWithTokenUid(input, fullTx.tx.tokens) + ); // Get the balance of each token in the transaction that belongs to this wallet // sample output: { 'A': 100, 'B': 10 }, where 'A' and 'B' are token UIDs - const tokenBalances = await this.getTxBalance(fullTx.tx); - const { length: hasBalance } = Object.keys(tokenBalances); + const tokenBalances: any = await this.getTxBalance(fullTx.tx); + const { length: hasBalance }: any = Object.keys(tokenBalances); if (!hasBalance) { throw new Error(`Transaction ${txId} does not have any balance for this wallet`); } - const listTokenUid = Object.keys(tokenBalances); - const txTokens = listTokenUid.map(uid => { + const listTokenUid: any = Object.keys(tokenBalances); + const txTokens: any = listTokenUid.map((uid: any) => { /** * Retrieves the token config from the transaction. * @param {string} tokenUid * @returns {TokenInfo} Token config */ - const getToken = tokenUid => { + const getToken = (tokenUid: any): any => { if (tokenUid === NATIVE_TOKEN_UID) { return this.storage.getNativeTokenData(); } - const token = fullTx.tx.tokens.find(tokenElem => tokenElem.uid === tokenUid); + const token: any = fullTx.tx.tokens.find((tokenElem: any) => tokenElem.uid === tokenUid); if (!token) { throw new Error(`Token ${tokenUid} not found in tx`); } @@ -2898,11 +2987,11 @@ class HathorWallet extends EventEmitter { return token; }; - const isVoided = fullTx.meta.voided_by.length > 0; - const token = getToken(uid); - const tokenBalance = tokenBalances[uid]; + const isVoided: any = fullTx.meta.voided_by.length > 0; + const token: any = getToken(uid); + const tokenBalance: any = tokenBalances[uid]; - const tokenDetails = { + const tokenDetails: any = { txId, timestamp: fullTx.tx.timestamp, version: fullTx.tx.version, @@ -2924,7 +3013,7 @@ class HathorWallet extends EventEmitter { * @param {string} pin * @returns {Promise} */ - async checkPin(pin) { + async checkPin(pin: any): Promise { return this.storage.checkPin(pin); } @@ -2933,7 +3022,7 @@ class HathorWallet extends EventEmitter { * @param {string} password * @returns {Promise} */ - async checkPassword(password) { + async checkPassword(password: any): Promise { return this.storage.checkPassword(password); } @@ -2942,7 +3031,7 @@ class HathorWallet extends EventEmitter { * @param {string} password * @returns {Promise} */ - async checkPinAndPassword(pin, password) { + async checkPinAndPassword(pin: any, password: any): Promise { return (await this.checkPin(pin)) && this.checkPassword(password); // The promise from checkPassword will be returned here } @@ -2950,7 +3039,7 @@ class HathorWallet extends EventEmitter { * Check if the wallet is a hardware wallet. * @returns {Promise} */ - async isHardwareWallet() { + async isHardwareWallet(): Promise { return this.storage.isHardwareWallet(); } @@ -2978,8 +3067,13 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async createAndSendNanoContractTransaction(method, address, data, options = {}) { - const sendTransaction = await this.createNanoContractTransaction( + async createAndSendNanoContractTransaction( + method: any, + address: any, + data: any, + options: any = {} + ): Promise { + const sendTransaction: any = await this.createNanoContractTransaction( method, address, data, @@ -2998,18 +3092,23 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async createNanoContractTransaction(method, address, data, options = {}) { + async createNanoContractTransaction( + method: any, + address: any, + data: any, + options: any = {} + ): Promise { if (await this.storage.isReadonly()) { throw new WalletFromXPubGuard('createNanoContractTransaction'); } - const newOptions = { pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new PinRequiredError(ERROR_MESSAGE_PIN_REQUIRED); } // Get caller pubkey - const addressInfo = await this.storage.getAddressInfo(address); + const addressInfo: any = await this.storage.getAddressInfo(address); if (!addressInfo) { throw new NanoContractTransactionError( `Address used to sign the transaction (${address}) does not belong to the wallet.` @@ -3017,7 +3116,7 @@ class HathorWallet extends EventEmitter { } // Build and send transaction - const builder = new NanoContractTransactionBuilder() + const builder: any = new NanoContractTransactionBuilder() .setMethod(method) .setWallet(this) .setBlueprintId(data.blueprintId) @@ -3027,7 +3126,7 @@ class HathorWallet extends EventEmitter { .setArgs(data.args) .setVertexType(NanoContractVertexType.TRANSACTION); - const nc = await builder.build(); + const nc: any = await builder.build(); return prepareNanoSendTransaction(nc, pin, this.storage); } @@ -3062,13 +3161,13 @@ class HathorWallet extends EventEmitter { * @returns {Promise} */ async createAndSendNanoContractCreateTokenTransaction( - method, - address, - data, - createTokenOptions, - options = {} - ) { - const sendTransaction = await this.createNanoContractCreateTokenTransaction( + method: any, + address: any, + data: any, + createTokenOptions: any, + options: any = {} + ): Promise { + const sendTransaction: any = await this.createNanoContractCreateTokenTransaction( method, address, data, @@ -3090,22 +3189,22 @@ class HathorWallet extends EventEmitter { * @returns {Promise} */ async createNanoContractCreateTokenTransaction( - method, - address, - data, - createTokenOptions, - options = {} - ) { + method: any, + address: any, + data: any, + createTokenOptions: any, + options: any = {} + ): Promise { if (await this.storage.isReadonly()) { throw new WalletFromXPubGuard('createNanoContractCreateTokenTransaction'); } - const newOptions = { pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new PinRequiredError(ERROR_MESSAGE_PIN_REQUIRED); } - const newCreateTokenOptions = { + const newCreateTokenOptions: any = { mintAddress: null, changeAddress: null, createMint: true, @@ -3124,7 +3223,9 @@ class HathorWallet extends EventEmitter { !newCreateTokenOptions.allowExternalMintAuthorityAddress ) { // Validate that the mint authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newCreateTokenOptions.mintAuthorityAddress); + const isAddressMine: any = await this.isAddressMine( + newCreateTokenOptions.mintAuthorityAddress + ); if (!isAddressMine) { throw new NanoContractTransactionError( 'The mint authority address must belong to your wallet.' @@ -3137,7 +3238,9 @@ class HathorWallet extends EventEmitter { !newCreateTokenOptions.allowExternalMeltAuthorityAddress ) { // Validate that the melt authority address belongs to the wallet - const isAddressMine = await this.isAddressMine(newCreateTokenOptions.meltAuthorityAddress); + const isAddressMine: any = await this.isAddressMine( + newCreateTokenOptions.meltAuthorityAddress + ); if (!isAddressMine) { throw new NanoContractTransactionError( 'The melt authority address must belong to your wallet.' @@ -3149,14 +3252,14 @@ class HathorWallet extends EventEmitter { newCreateTokenOptions.mintAddress || (await this.getCurrentAddress()).address; // Get caller pubkey - const addressInfo = await this.storage.getAddressInfo(address); + const addressInfo: any = await this.storage.getAddressInfo(address); if (!addressInfo) { throw new NanoContractTransactionError( `Address used to sign the transaction (${address}) does not belong to the wallet.` ); } // Build and send transaction - const builder = new NanoContractTransactionBuilder() + const builder: any = new NanoContractTransactionBuilder() .setMethod(method) .setWallet(this) .setBlueprintId(data.blueprintId) @@ -3166,7 +3269,7 @@ class HathorWallet extends EventEmitter { .setArgs(data.args) .setVertexType(NanoContractVertexType.CREATE_TOKEN_TRANSACTION, newCreateTokenOptions); - const nc = await builder.build(); + const nc: any = await builder.build(); return prepareNanoSendTransaction(nc, pin, this.storage); } @@ -3180,25 +3283,25 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async getPrivateKeyFromAddress(address, options = {}) { + async getPrivateKeyFromAddress(address: any, options: any = {}): Promise { if (await this.storage.isReadonly()) { throw new WalletFromXPubGuard('getPrivateKeyFromAddress'); } - const newOptions = { pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new PinRequiredError(ERROR_MESSAGE_PIN_REQUIRED); } - const addressIndex = await this.getAddressIndex(address); + const addressIndex: any = await this.getAddressIndex(address); if (addressIndex === null) { throw new AddressError('Address does not belong to the wallet.'); } - const xprivkey = await this.storage.getMainXPrivKey(pin); - const key = HDPrivateKey(xprivkey); + const xprivkey: any = await this.storage.getMainXPrivKey(pin); + const key: any = HDPrivateKey(xprivkey); // Derive key to addressIndex - const derivedKey = key.deriveNonCompliantChild(addressIndex); + const derivedKey: any = key.deriveNonCompliantChild(addressIndex); return derivedKey.privateKey; } @@ -3206,7 +3309,7 @@ class HathorWallet extends EventEmitter { * Set the external tx signing method. * @param {EcdsaTxSign|null} method */ - setExternalTxSigningMethod(method) { + setExternalTxSigningMethod(method: any): any { this.isSignedExternally = !!method; this.storage.setTxSignatureMethod(method); } @@ -3215,7 +3318,7 @@ class HathorWallet extends EventEmitter { * Set the history sync mode. * @param {HistorySyncMode} mode */ - setHistorySyncMode(mode) { + setHistorySyncMode(mode: any): any { this.historySyncMode = mode; } @@ -3225,11 +3328,11 @@ class HathorWallet extends EventEmitter { * @param {boolean} [shouldProcessHistory=false] * @returns {Promise} */ - async syncHistory(startIndex, count, shouldProcessHistory = false) { + async syncHistory(startIndex: any, count: any, shouldProcessHistory: any = false): Promise { if (!(await getSupportedSyncMode(this.storage)).includes(this.historySyncMode)) { throw new Error('Trying to use an unsupported sync method for this wallet.'); } - let syncMode = this.historySyncMode; + let syncMode: any = this.historySyncMode; if ( [HistorySyncMode.MANUAL_STREAM_WS, HistorySyncMode.XPUB_STREAM_WS].includes( this.historySyncMode @@ -3244,7 +3347,7 @@ class HathorWallet extends EventEmitter { this.logger.debug('Falling back to http polling API'); syncMode = HistorySyncMode.POLLING_HTTP_API; } - const syncMethod = getHistorySyncMethod(syncMode); + const syncMethod: any = getHistorySyncMethod(syncMode); // This will add the task to the GLL queue and return a promise that // resolves when the task finishes executing await GLL.add(async () => { @@ -3255,21 +3358,21 @@ class HathorWallet extends EventEmitter { /** * Reload all addresses and transactions from the full node */ - async reloadStorage() { + async reloadStorage(): Promise { await this.conn.onReload(); // unsub all addresses for await (const address of this.storage.getAllAddresses()) { this.conn.unsubscribeAddress(address.base58); } - const accessData = await this.storage.getAccessData(); + const accessData: any = await this.storage.getAccessData(); if (accessData != null) { // Clean entire storage await this.storage.cleanStorage(true, true); // Reset access data await this.storage.saveAccessData(accessData); } - const addressesToLoad = await scanPolicyStartAddresses(this.storage); + const addressesToLoad: any = await scanPolicyStartAddresses(this.storage); await this.syncHistory(addressesToLoad.nextIndex, addressesToLoad.count); } @@ -3282,14 +3385,14 @@ class HathorWallet extends EventEmitter { * @param {string} [options.pinCode] PIN to decrypt the private key. * @returns {Promise} */ - async buildTxTemplate(template, options) { - const newOptions = { + async buildTxTemplate(template: any, options: any): Promise { + const newOptions: any = { signTx: false, pinCode: null, ...options, }; - const instructions = TransactionTemplate.parse(template); - const tx = await this.txTemplateInterpreter.build(instructions, this.debug); + const instructions: any = TransactionTemplate.parse(template); + const tx: any = await this.txTemplateInterpreter.build(instructions, this.debug); if (newOptions.signTx) { await transactionUtils.signTransaction(tx, this.storage, newOptions.pinCode || this.pinCode); tx.prepareToSend(); @@ -3304,8 +3407,8 @@ class HathorWallet extends EventEmitter { * @param {string|undefined} pinCode * @returns {Promise} */ - async runTxTemplate(template, pinCode) { - const transaction = await this.buildTxTemplate(template, { + async runTxTemplate(template: any, pinCode: any): Promise { + const transaction: any = await this.buildTxTemplate(template, { signTx: true, pinCode, }); @@ -3326,8 +3429,16 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async createAndSendOnChainBlueprintTransaction(code, address, options = {}) { - const sendTransaction = await this.createOnChainBlueprintTransaction(code, address, options); + async createAndSendOnChainBlueprintTransaction( + code: any, + address: any, + options: any = {} + ): Promise { + const sendTransaction: any = await this.createOnChainBlueprintTransaction( + code, + address, + options + ); return sendTransaction.runFromMining(); } @@ -3340,31 +3451,31 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async createOnChainBlueprintTransaction(code, address, options) { + async createOnChainBlueprintTransaction(code: any, address: any, options: any): Promise { if (await this.storage.isReadonly()) { throw new WalletFromXPubGuard('createOnChainBlueprintTransaction'); } - const newOptions = { pinCode: null, ...options }; - const pin = newOptions.pinCode || this.pinCode; + const newOptions: any = { pinCode: null, ...options }; + const pin: any = newOptions.pinCode || this.pinCode; if (!pin) { throw new PinRequiredError(ERROR_MESSAGE_PIN_REQUIRED); } // Get caller pubkey - const addressInfo = await this.storage.getAddressInfo(address); + const addressInfo: any = await this.storage.getAddressInfo(address); if (!addressInfo) { throw new NanoContractTransactionError( `Address used to sign the transaction (${address}) does not belong to the wallet.` ); } - const pubkeyStr = await this.storage.getAddressPubkey(addressInfo.bip32AddressIndex); - const pubkey = Buffer.from(pubkeyStr, 'hex'); + const pubkeyStr: any = await this.storage.getAddressPubkey(addressInfo.bip32AddressIndex); + const pubkey: any = Buffer.from(pubkeyStr, 'hex'); // Create code object from code data - const codeContent = Buffer.from(code, 'utf8'); - const codeObj = new Code(CodeKind.PYTHON_ZLIB, codeContent); + const codeContent: any = Buffer.from(code, 'utf8'); + const codeObj: any = new Code(CodeKind.PYTHON_ZLIB, codeContent); - const tx = new OnChainBlueprint(codeObj, pubkey); + const tx: any = new OnChainBlueprint(codeObj, pubkey); return prepareNanoSendTransaction(tx, pin, this.storage); } @@ -3376,10 +3487,22 @@ class HathorWallet extends EventEmitter { * * @returns {Promise} */ - async getNanoHeaderSeqnum(address) { - const addressInfo = await this.storage.getAddressInfo(address); + async getNanoHeaderSeqnum(address: any): Promise { + const addressInfo: any = await this.storage.getAddressInfo(address); return addressInfo.seqnum + 1; } + + // eslint-disable-next-line class-methods-use-this + async startReadOnly( + options?: { skipAddressFetch?: boolean | undefined } | undefined + ): Promise { + throw new Error('Not Implemented'); + } + + // eslint-disable-next-line class-methods-use-this + async getReadOnlyAuthToken(): Promise { + throw new Error('Not implemented.'); + } } // State constants. diff --git a/src/wallet/types.ts b/src/wallet/types.ts index 627120fe0..ea10d3935 100644 --- a/src/wallet/types.ts +++ b/src/wallet/types.ts @@ -347,8 +347,8 @@ export interface IHathorWallet { stop(params?: IStopWalletParams): void; getAddressAtIndex(index: number): Promise; getAddressIndex(address: string): Promise; - getCurrentAddress(options?: { markAsUsed: boolean }): AddressInfoObject; - getNextAddress(): AddressInfoObject; + getCurrentAddress(options?: { markAsUsed: boolean }): AddressInfoObject | Promise; // FIXME: Should have a single return type + getNextAddress(): AddressInfoObject | Promise; // FIXME: Should have a single return type; getAddressPrivKey(pinCode: string, addressIndex: number): Promise; signMessageWithAddress(message: string, index: number, pinCode: string): Promise; prepareCreateNewToken( @@ -398,7 +398,7 @@ export interface IHathorWallet { count: number, options: DestroyAuthorityOptions ): Promise; - getFullHistory(): TransactionFullObject[]; + getFullHistory(): TransactionFullObject[] | Promise; // FIXME: Should have a single return type; getTxBalance(tx: IHistoryTx, optionsParams): Promise<{ [tokenId: string]: OutputValueType }>; onConnectionChangedState(newState: ConnectionState): void; getTokenDetails(tokenId: string): Promise; diff --git a/src/wallet/wallet.ts b/src/wallet/wallet.ts index e73c88d92..f57c8e166 100644 --- a/src/wallet/wallet.ts +++ b/src/wallet/wallet.ts @@ -85,6 +85,7 @@ import { CreateNanoTxData, } from '../nano_contracts/types'; import { WalletServiceStorageProxy } from './walletServiceStorageProxy'; +import HathorWallet from '../new/wallet'; // Time in milliseconds berween each polling to check wallet status // if it ended loading and became ready @@ -2710,7 +2711,7 @@ class HathorWalletServiceWallet extends EventEmitter implements IHathorWallet { const builder = new NanoContractTransactionBuilder() .setMethod(method) - .setWallet(this) + .setWallet(this as unknown as HathorWallet) // FIXME: Should accept IHathorWallet instead .setBlueprintId(data.blueprintId as string) .setNcId(data.ncId as string) .setCaller(callerAddress) @@ -2875,7 +2876,7 @@ class HathorWalletServiceWallet extends EventEmitter implements IHathorWallet { const builder = new NanoContractTransactionBuilder() .setMethod(method) - .setWallet(this) + .setWallet(this as unknown as HathorWallet) // FIXME: Should accept IHathorWallet instead .setBlueprintId(data.blueprintId as string) .setNcId(data.ncId as string) .setCaller(callerAddress)