From 2017eee6c9586edc0420a98f104d07818a2860fb Mon Sep 17 00:00:00 2001 From: nagdahimanshu Date: Wed, 3 Jan 2024 15:16:48 +0100 Subject: [PATCH] :hammer: Code refactoring --- .../blockchain-connector/shared/sdk/auth.js | 32 +- .../blockchain-connector/shared/sdk/client.js | 39 ++- .../shared/sdk/dynamicReward.js | 69 +--- .../shared/sdk/endpoints.js | 317 +++++------------- .../shared/sdk/endpoints_1.js | 92 ++--- .../blockchain-connector/shared/sdk/events.js | 26 +- .../blockchain-connector/shared/sdk/fee.js | 43 +-- .../shared/sdk/interoperability.js | 77 +---- .../blockchain-connector/shared/sdk/legacy.js | 17 +- .../blockchain-connector/shared/sdk/pos.js | 176 +++------- .../blockchain-connector/shared/sdk/token.js | 116 ++----- .../shared/sdk/validators.js | 40 +-- 12 files changed, 278 insertions(+), 766 deletions(-) diff --git a/services/blockchain-connector/shared/sdk/auth.js b/services/blockchain-connector/shared/sdk/auth.js index 60e9b658ad..a9c0e7c7c4 100644 --- a/services/blockchain-connector/shared/sdk/auth.js +++ b/services/blockchain-connector/shared/sdk/auth.js @@ -13,38 +13,16 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Exceptions: { TimeoutException }, - Logger, -} = require('lisk-service-framework'); - -const { timeoutMessage, invokeEndpoint } = require('./client'); - -const logger = Logger(); +const { invokeEndpoint } = require('./client'); const getAuthAccount = async address => { - try { - const authAccountInfo = await invokeEndpoint('auth_getAuthAccount', { address }); - return authAccountInfo; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getAuthAccount'."); - } - throw err; - } + const authAccountInfo = await invokeEndpoint('auth_getAuthAccount', { address }); + return authAccountInfo; }; const getAuthMultiSigRegMsgSchema = async () => { - try { - const multiSigRegMsgSchema = await invokeEndpoint('auth_getMultiSigRegMsgSchema'); - return multiSigRegMsgSchema; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getMultiSigRegMsgSchema'."); - } - logger.warn(`Error returned when invoking 'auth_getMultiSigRegMsgSchema'.\n${err.stack}`); - throw err; - } + const multiSigRegMsgSchema = await invokeEndpoint('auth_getMultiSigRegMsgSchema'); + return multiSigRegMsgSchema; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/client.js b/services/blockchain-connector/shared/sdk/client.js index 9d6bbf7d1f..2b5b0ce7a6 100644 --- a/services/blockchain-connector/shared/sdk/client.js +++ b/services/blockchain-connector/shared/sdk/client.js @@ -13,7 +13,12 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { Logger, Signals, HTTP } = require('lisk-service-framework'); +const { + Logger, + Signals, + HTTP, + Exceptions: { TimeoutException }, +} = require('lisk-service-framework'); const { createWSClient, createIPCClient } = require('@liskhq/lisk-api-client'); const config = require('../../config'); @@ -113,13 +118,14 @@ const getApiClient = async () => { return cachedApiClients[0]; }; -const isResponse2XX = input => !!(input.status === 200); +const isResponse2XX = response => !!String(response.status).startsWith('2'); -let id = 0; +let id = -1; // eslint-disable-next-line consistent-return const invokeEndpoint = async (endpoint, params = {}, numRetries = NUM_REQUEST_RETRIES) => { let retries = numRetries; do { + id++; try { if (config.useHttpApi) { const rpcRequest = { @@ -131,10 +137,7 @@ const invokeEndpoint = async (endpoint, params = {}, numRetries = NUM_REQUEST_RE const response = await HTTP.post(`${liskAddressHttp}/rpc`, rpcRequest); return isResponse2XX(response) - ? (() => { - id++; - return response.data.result; - })() + ? response.data.result : (() => { logger.trace( `Error when invoking endpoint ${endpoint} with params ${JSON.stringify(params)}: ${ @@ -148,9 +151,29 @@ const invokeEndpoint = async (endpoint, params = {}, numRetries = NUM_REQUEST_RE const response = await apiClient._channel.invoke(endpoint, params); return response; } catch (err) { - if (retries && err.message.includes(timeoutMessage)) { + if (err.message.includes(timeoutMessage)) { + if (!retries) { + const exceptionMsg = Object.getOwnPropertyNames(params).length + ? `Request timed out when calling '${endpoint}' with params:\n${JSON.stringify( + params, + null, + '\t', + )}.` + : `Request timed out when calling '${endpoint}'.`; + + throw new TimeoutException(exceptionMsg); + } await delay(ENDPOINT_INVOKE_RETRY_DELAY); } else { + if (Object.getOwnPropertyNames(params).length) { + logger.warn( + `Error invoking '${endpoint}' with params:\n${JSON.stringify(params, null, ' ')}.\n${ + err.stack + }`, + ); + } + + logger.warn(`Error occurred when calling '${endpoint}' :\n${err.stack}`); throw err; } } diff --git a/services/blockchain-connector/shared/sdk/dynamicReward.js b/services/blockchain-connector/shared/sdk/dynamicReward.js index e94c9f249a..d2eef2266c 100644 --- a/services/blockchain-connector/shared/sdk/dynamicReward.js +++ b/services/blockchain-connector/shared/sdk/dynamicReward.js @@ -13,16 +13,9 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Logger, - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); - -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const { getRegisteredModules } = require('./endpoints_1'); -const logger = Logger(); - let registeredRewardModule; let rewardTokenID; @@ -38,60 +31,26 @@ const cacheRegisteredRewardModule = async () => { }; const getRewardTokenID = async () => { - try { - if (!rewardTokenID) { - const response = await invokeEndpoint(`${registeredRewardModule}_getRewardTokenID`); - rewardTokenID = response.tokenID; - } - return rewardTokenID; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getRewardTokenID'."); - } - logger.warn( - `Error returned when invoking '${registeredRewardModule}_getRewardTokenID'.\n${err.stack}`, - ); - throw err; + if (!rewardTokenID) { + const response = await invokeEndpoint(`${registeredRewardModule}_getRewardTokenID`); + rewardTokenID = response.tokenID; } + return rewardTokenID; }; const getAnnualInflation = async height => { - try { - const annualInflation = await invokeEndpoint(`${registeredRewardModule}_getAnnualInflation`, { - height, - }); - return annualInflation; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getAnnualInflation' with block height:${height}.`, - ); - } - logger.warn( - `Error returned when invoking '${registeredRewardModule}_getAnnualInflation' with block height:${height}.\n${err.stack}`, - ); - throw err; - } + const annualInflation = await invokeEndpoint(`${registeredRewardModule}_getAnnualInflation`, { + height, + }); + return annualInflation; }; const getDefaultRewardAtHeight = async height => { - try { - const defaultRewardResponse = await invokeEndpoint( - `${registeredRewardModule}_getDefaultRewardAtHeight`, - { height }, - ); - return defaultRewardResponse; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getDefaultRewardAtHeight' for block height:${height}`, - ); - } - logger.warn( - `Error returned when invoking '${registeredRewardModule}_getDefaultRewardAtHeight' with height: ${height}.\n${err.stack}`, - ); - throw err; - } + const defaultRewardResponse = await invokeEndpoint( + `${registeredRewardModule}_getDefaultRewardAtHeight`, + { height }, + ); + return defaultRewardResponse; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/endpoints.js b/services/blockchain-connector/shared/sdk/endpoints.js index dd7e81dc51..4c26330254 100644 --- a/services/blockchain-connector/shared/sdk/endpoints.js +++ b/services/blockchain-connector/shared/sdk/endpoints.js @@ -15,10 +15,6 @@ */ const BluebirdPromise = require('bluebird'); -const { - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); - const { getSchemas, getRegisteredEndpoints, @@ -33,286 +29,153 @@ const { getBlockByIDFromCache, getTransactionByIDFromCache, } = require('./cache'); -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const { getGenesisHeight, getGenesisBlockID, getGenesisBlock } = require('./genesisBlock'); const config = require('../../config'); const getNetworkConnectedPeers = async () => { - try { - const connectedPeers = await invokeEndpoint('network_getConnectedPeers'); - return connectedPeers; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getNetworkConnectedPeers'."); - } - throw err; - } + const connectedPeers = await invokeEndpoint('network_getConnectedPeers'); + return connectedPeers; }; const getNetworkDisconnectedPeers = async () => { - try { - const disconnectedPeers = await invokeEndpoint('network_getDisconnectedPeers'); - return disconnectedPeers; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getNetworkDisconnectedPeers'."); - } - throw err; - } + const disconnectedPeers = await invokeEndpoint('network_getDisconnectedPeers'); + return disconnectedPeers; }; const getGeneratorStatus = async () => { - try { - const forgingStatus = await invokeEndpoint('generator_getStatus'); - return forgingStatus; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getGeneratorStatus'."); - } - throw err; - } + const forgingStatus = await invokeEndpoint('generator_getStatus'); + return forgingStatus; }; const updateGeneratorStatus = async generatorConfig => { - try { - const response = await invokeEndpoint('generator_updateStatus', { ...generatorConfig }); - return response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'updateGeneratorStatus'."); - } - throw err; - } + const response = await invokeEndpoint('generator_updateStatus', { ...generatorConfig }); + return response; }; const getLastBlock = async () => { - try { - const block = await invokeEndpoint('chain_getLastBlock'); - return block; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getLastBlock'."); - } - throw err; - } + const block = await invokeEndpoint('chain_getLastBlock'); + return block; }; const getBlockByHeight = async (height, includeGenesisAssets = false) => { - try { - if (Number(height) === (await getGenesisHeight())) { - return getGenesisBlock(includeGenesisAssets); - } - - const block = await invokeEndpoint('chain_getBlockByHeight', { height }); - cacheBlocksIfEnabled(block); - - return block; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getBlockByHeight' for height: ${height}.`, - ); - } - throw err; + if (Number(height) === (await getGenesisHeight())) { + return getGenesisBlock(includeGenesisAssets); } + + const block = await invokeEndpoint('chain_getBlockByHeight', { height }); + cacheBlocksIfEnabled(block); + + return block; }; const getBlocksByHeightBetween = async ({ from, to }) => { - try { - const gHeight = await getGenesisHeight(); - const blocksNestedList = [[], []]; - - if (from < gHeight) { - throw new Error(`'from' cannot be lower than the genesis height (${gHeight}).`); - } - - // File based Genesis block handling - if (Number(from) === gHeight) { - blocksNestedList[0] = await getBlockByHeight(gHeight); - from++; - } - - if (from <= to) { - blocksNestedList[1] = await invokeEndpoint('chain_getBlocksByHeightBetween', { from, to }); - } - - const blocks = blocksNestedList.flat(); - cacheBlocksIfEnabled(blocks); - return blocks; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getBlocksByHeightBetween' for heights: ${from} - ${to}.`, - ); - } - throw err; + const gHeight = await getGenesisHeight(); + const blocksNestedList = [[], []]; + + if (from < gHeight) { + throw new Error(`'from' cannot be lower than the genesis height (${gHeight}).`); + } + + // File based Genesis block handling + if (Number(from) === gHeight) { + blocksNestedList[0] = await getBlockByHeight(gHeight); + from++; } + + if (from <= to) { + blocksNestedList[1] = await invokeEndpoint('chain_getBlocksByHeightBetween', { from, to }); + } + + const blocks = blocksNestedList.flat(); + cacheBlocksIfEnabled(blocks); + return blocks; }; const getBlockByID = async (id, includeGenesisAssets = false) => { - try { - // File based Genesis block handling - if (id === (await getGenesisBlockID())) { - return getGenesisBlock(includeGenesisAssets); - } - - const blockFromCache = await getBlockByIDFromCache(id).catch(() => null); - if (blockFromCache) return blockFromCache; - - const block = await invokeEndpoint('chain_getBlockByID', { id }); - cacheBlocksIfEnabled(block); - return block; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException(`Request timed out when calling 'getBlockByID' for ID: ${id}.`); - } - throw err; + // File based Genesis block handling + if (id === (await getGenesisBlockID())) { + return getGenesisBlock(includeGenesisAssets); } + + const blockFromCache = await getBlockByIDFromCache(id).catch(() => null); + if (blockFromCache) return blockFromCache; + + const block = await invokeEndpoint('chain_getBlockByID', { id }); + cacheBlocksIfEnabled(block); + return block; }; const getBlocksByIDs = async ids => { - try { - // File based Genesis block handling - const genesisBlockId = await getGenesisBlockID(); - const genesisBlockIndex = ids.indexOf(genesisBlockId); - if (genesisBlockIndex !== -1) { - const remainingIDs = ids.filter(id => id !== genesisBlockId); - const genesisBlock = await getBlockByID(genesisBlockId); - if (remainingIDs.length === 0) return [genesisBlock]; - - const remainingBlocks = await getBlocksByIDs(remainingIDs); - remainingBlocks.splice(genesisBlockIndex, 0, genesisBlock); - return remainingBlocks; - } - - const blocks = config.cache.isBlockCachingEnabled - ? await BluebirdPromise.map(ids, async id => getBlockByID(id), { concurrency: 1 }) - : await invokeEndpoint('chain_getBlocksByIDs', { ids }); - - return blocks; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getBlocksByIDs' for IDs: ${ids}.`, - ); - } - throw err; + // File based Genesis block handling + const genesisBlockId = await getGenesisBlockID(); + const genesisBlockIndex = ids.indexOf(genesisBlockId); + if (genesisBlockIndex !== -1) { + const remainingIDs = ids.filter(id => id !== genesisBlockId); + const genesisBlock = await getBlockByID(genesisBlockId); + if (remainingIDs.length === 0) return [genesisBlock]; + + const remainingBlocks = await getBlocksByIDs(remainingIDs); + remainingBlocks.splice(genesisBlockIndex, 0, genesisBlock); + return remainingBlocks; } + + const blocks = config.cache.isBlockCachingEnabled + ? await BluebirdPromise.map(ids, async id => getBlockByID(id), { concurrency: 1 }) + : await invokeEndpoint('chain_getBlocksByIDs', { ids }); + + return blocks; }; const getEventsByHeight = async height => { - try { - const events = await invokeEndpoint('chain_getEvents', { height }); - return events; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getEvents'."); - } - throw err; - } + const events = await invokeEndpoint('chain_getEvents', { height }); + return events; }; const getTransactionByID = async id => { - try { - const transactionFromCache = await getTransactionByIDFromCache(id).catch(() => null); - if (transactionFromCache) return transactionFromCache; - - const transaction = await invokeEndpoint('chain_getTransactionByID', { id }); - return transaction; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getTransactionByID' for ID: ${id}.`, - ); - } - throw err; - } + const transactionFromCache = await getTransactionByIDFromCache(id).catch(() => null); + if (transactionFromCache) return transactionFromCache; + + const transaction = await invokeEndpoint('chain_getTransactionByID', { id }); + return transaction; }; const getTransactionsByIDs = async ids => { - try { - const transactions = config.cache.isBlockCachingEnabled - ? await BluebirdPromise.map(ids, async id => getTransactionByID(id), { concurrency: 1 }) - : await invokeEndpoint('chain_getTransactionsByIDs', { ids }); - - return transactions; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'getTransactionsByIDs' for IDs: ${ids}.`, - ); - } - throw err; - } + const transactions = config.cache.isBlockCachingEnabled + ? await BluebirdPromise.map(ids, async id => getTransactionByID(id), { concurrency: 1 }) + : await invokeEndpoint('chain_getTransactionsByIDs', { ids }); + + return transactions; }; const getTransactionsFromPool = async () => { - try { - const transactions = await invokeEndpoint('txpool_getTransactionsFromPool'); - return transactions; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getTransactionsFromPool'."); - } - throw err; - } + const transactions = await invokeEndpoint('txpool_getTransactionsFromPool'); + return transactions; }; const postTransaction = async transaction => { - try { - const response = await invokeEndpoint('txpool_postTransaction', { transaction }); - return response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'postTransaction' with transaction: ${transaction}.`, - ); - } - throw err; - } + const response = await invokeEndpoint('txpool_postTransaction', { transaction }); + return response; }; const dryRunTransaction = async ({ transaction, skipVerify, strict }) => { - try { - const response = await invokeEndpoint('txpool_dryRunTransaction', { - transaction, - skipVerify, - strict, - }); - return response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException( - `Request timed out when calling 'dryRunTransaction' with transaction: ${transaction}.`, - ); - } - throw err; - } + const response = await invokeEndpoint('txpool_dryRunTransaction', { + transaction, + skipVerify, + strict, + }); + return response; }; const getGenerators = async () => { - try { - const generators = await invokeEndpoint('chain_getGeneratorList'); - return generators; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getGenerators'."); - } - throw err; - } + const generators = await invokeEndpoint('chain_getGeneratorList'); + return generators; }; const getBFTParameters = async height => { - try { - const bftParameters = await invokeEndpoint('consensus_getBFTParameters', { height }); - return bftParameters; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getBFTParameters'."); - } - throw err; - } + const bftParameters = await invokeEndpoint('consensus_getBFTParameters', { height }); + return bftParameters; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/endpoints_1.js b/services/blockchain-connector/shared/sdk/endpoints_1.js index 8af83cff67..97f2b0d69c 100644 --- a/services/blockchain-connector/shared/sdk/endpoints_1.js +++ b/services/blockchain-connector/shared/sdk/endpoints_1.js @@ -13,17 +13,11 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Exceptions: { TimeoutException }, - Signals, -} = require('lisk-service-framework'); +const { Signals } = require('lisk-service-framework'); const { invokeEndpoint } = require('./client'); const { engineEndpoints } = require('./constants/endpoints'); -// Constants -const timeoutMessage = 'Response not received in'; - // Caching for constants from SDK application let metadata; let nodeInfo; @@ -33,90 +27,48 @@ let registeredEvents; let registeredModules; const getSchemas = async () => { - try { - if (!schema) { - schema = await invokeEndpoint('system_getSchema'); - schema.ccm = (await invokeEndpoint('interoperability_getCCMSchema')).schema; - } - return schema; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getSchema'."); - } - throw err; + if (!schema) { + schema = await invokeEndpoint('system_getSchema'); + schema.ccm = (await invokeEndpoint('interoperability_getCCMSchema')).schema; } + return schema; }; const getRegisteredEndpoints = async () => { - try { - if (!registeredEndpoints) { - registeredEndpoints = await invokeEndpoint('app_getRegisteredEndpoints'); - } - return registeredEndpoints; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getRegisteredEndpoints'."); - } - throw err; + if (!registeredEndpoints) { + registeredEndpoints = await invokeEndpoint('app_getRegisteredEndpoints'); } + return registeredEndpoints; }; const getRegisteredEvents = async () => { - try { - if (!registeredEvents) { - registeredEvents = await invokeEndpoint('app_getRegisteredEvents'); - } - return registeredEvents; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getRegisteredEvents'."); - } - throw err; + if (!registeredEvents) { + registeredEvents = await invokeEndpoint('app_getRegisteredEvents'); } + return registeredEvents; }; const getNodeInfo = async (isForceUpdate = false) => { - try { - if (isForceUpdate || !nodeInfo) { - nodeInfo = await invokeEndpoint('system_getNodeInfo'); - Signals.get('systemNodeInfo').dispatch(nodeInfo); - } - return nodeInfo; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getNodeInfo'."); - } - throw err; + if (isForceUpdate || !nodeInfo) { + nodeInfo = await invokeEndpoint('system_getNodeInfo'); + Signals.get('systemNodeInfo').dispatch(nodeInfo); } + return nodeInfo; }; const getSystemMetadata = async () => { - try { - if (!metadata) { - metadata = await invokeEndpoint('system_getMetadata'); - } - return metadata; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getSystemMetadata'."); - } - throw err; + if (!metadata) { + metadata = await invokeEndpoint('system_getMetadata'); } + return metadata; }; const getRegisteredModules = async () => { - try { - if (!registeredModules) { - const systemMetadata = await getSystemMetadata(); - registeredModules = systemMetadata.modules.map(module => module.name); - } - return registeredModules; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getRegisteredModules'."); - } - throw err; + if (!registeredModules) { + const systemMetadata = await getSystemMetadata(); + registeredModules = systemMetadata.modules.map(module => module.name); } + return registeredModules; }; const getEngineEndpoints = () => engineEndpoints; diff --git a/services/blockchain-connector/shared/sdk/events.js b/services/blockchain-connector/shared/sdk/events.js index a99305fbde..69b20071bf 100644 --- a/services/blockchain-connector/shared/sdk/events.js +++ b/services/blockchain-connector/shared/sdk/events.js @@ -55,25 +55,23 @@ const logError = (method, err) => { logger.debug(err.stack); }; -const emitNodeEvents = async () => { - getNodeInfo().then(nodeInfo => { +const emitEngineEvents = async () => { + getNodeInfo().then(async nodeInfo => { + const { roundLength } = await getPosConstants(); + setInterval(async () => { const latestNodeInfo = await getNodeInfo(true); - const { syncing } = latestNodeInfo; + const { syncing, height, genesisHeight } = latestNodeInfo; const isNodeSyncComplete = !syncing; if (isNodeSyncComplete) { - if (!lastBlockHeightEvent || latestNodeInfo.height > lastBlockHeightEvent) { - lastBlockHeightEvent = latestNodeInfo.height; - const newBlock = await getBlockByHeight(latestNodeInfo.height); + if (!lastBlockHeightEvent || height > lastBlockHeightEvent) { + lastBlockHeightEvent = height; + const newBlock = await getBlockByHeight(height); Signals.get(EVENT_CHAIN_BLOCK_NEW).dispatch({ blockHeader: newBlock.header }); - const posConstants = await getPosConstants(); - if ( - (latestNodeInfo.height - latestNodeInfo.genesisHeight) % posConstants.roundLength === - 1 - ) { - const bftParameters = await getBFTParameters(latestNodeInfo.height); + if ((height - genesisHeight) % roundLength === 1) { + const bftParameters = await getBFTParameters(height); Signals.get(EVENT_CHAIN_VALIDATORS_CHANGE).dispatch({ nextValidators: bftParameters.validators, certificateThreshold: bftParameters.certificateThreshold, @@ -82,13 +80,13 @@ const emitNodeEvents = async () => { } } } - }, (nodeInfo.genesis.blockTime * 1000) / 2); + }, Math.min(2, nodeInfo.genesis.blockTime) * 1000); }); }; // eslint-disable-next-line consistent-return const subscribeToAllRegisteredEvents = async () => { - if (config.useHttpApi) return emitNodeEvents(); + if (config.useHttpApi) return emitEngineEvents(); // Reset eventsCounter first eventsCounter = 0; diff --git a/services/blockchain-connector/shared/sdk/fee.js b/services/blockchain-connector/shared/sdk/fee.js index 3799aaf10d..e80834a411 100644 --- a/services/blockchain-connector/shared/sdk/fee.js +++ b/services/blockchain-connector/shared/sdk/fee.js @@ -13,12 +13,9 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Logger, - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); +const { Logger } = require('lisk-service-framework'); -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const logger = Logger(); @@ -26,37 +23,21 @@ let feeTokenID; let minFeePerByte; const cacheFeeTokenID = async () => { - try { - logger.trace('Attempting to update feeTokenID.'); - const response = await invokeEndpoint('fee_getFeeTokenID'); - if (response.error) throw response.error; + logger.trace('Attempting to update feeTokenID.'); + const response = await invokeEndpoint('fee_getFeeTokenID'); + if (response.error) throw response.error; - feeTokenID = response.tokenID; - logger.info(`Updated feeTokenID to ${feeTokenID}.`); - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'cacheFeeTokenID'."); - } - logger.warn(`Error occurred when calling 'cacheFeeTokenID':\n${err.stack}`); - throw err; - } + feeTokenID = response.tokenID; + logger.info(`Updated feeTokenID to ${feeTokenID}.`); }; const cacheMinFeePerByte = async () => { - try { - logger.trace('Attempting to update minFeePerByte.'); - const response = await invokeEndpoint('fee_getMinFeePerByte'); - if (response.error) throw response.error; + logger.trace('Attempting to update minFeePerByte.'); + const response = await invokeEndpoint('fee_getMinFeePerByte'); + if (response.error) throw response.error; - minFeePerByte = response.minFeePerByte; - logger.info(`Updated minFeePerByte to ${minFeePerByte}.`); - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'cacheMinFeePerByte'."); - } - logger.warn(`Error occurred when calling 'cacheMinFeePerByte':\n${err.stack}`); - throw err; - } + minFeePerByte = response.minFeePerByte; + logger.info(`Updated minFeePerByte to ${minFeePerByte}.`); }; const cacheFeeConstants = async () => { diff --git a/services/blockchain-connector/shared/sdk/interoperability.js b/services/blockchain-connector/shared/sdk/interoperability.js index cbc80834bb..0170d9bee1 100644 --- a/services/blockchain-connector/shared/sdk/interoperability.js +++ b/services/blockchain-connector/shared/sdk/interoperability.js @@ -13,84 +13,39 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Logger, - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); - -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const { getNodeInfo } = require('./endpoints_1'); -const logger = Logger(); - let mainchainID; let registrationFee; const getChainAccount = async chainID => { - try { - const chainAccount = await invokeEndpoint('interoperability_getChainAccount', { chainID }); - return chainAccount; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getChainAccount'."); - } - logger.warn( - `Error returned when invoking 'interoperability_getChainAccount' with chainID: ${chainID}.\n${err.stack}`, - ); - throw err; - } + const chainAccount = await invokeEndpoint('interoperability_getChainAccount', { chainID }); + return chainAccount; }; const getMainchainID = async () => { - try { - if (!mainchainID) { - const { chainID } = await getNodeInfo(); - const response = await invokeEndpoint('interoperability_getMainchainID', { chainID }); - mainchainID = - response.error && response.error.message.includes('not registered to bus') - ? chainID - : response.mainchainID; - } - return mainchainID; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getMainchainID'."); - } - logger.warn(`Error returned when invoking 'interoperability_getMainchainID'.\n${err.stack}`); - throw err; + if (!mainchainID) { + const { chainID } = await getNodeInfo(); + const response = await invokeEndpoint('interoperability_getMainchainID', { chainID }); + mainchainID = + response.error && response.error.message.includes('not registered to bus') + ? chainID + : response.mainchainID; } + return mainchainID; }; const getChannel = async chainID => { - try { - const channelInfo = await invokeEndpoint('interoperability_getChannel', { chainID }); - return channelInfo; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getChannel'."); - } - logger.warn( - `Error returned when invoking 'interoperability_getChannel' with chainID: ${chainID}.\n${err.stack}`, - ); - throw err; - } + const channelInfo = await invokeEndpoint('interoperability_getChannel', { chainID }); + return channelInfo; }; const getRegistrationFee = async () => { - try { - if (!registrationFee) { - registrationFee = await invokeEndpoint('interoperability_getRegistrationFee'); - } - return registrationFee; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getRegistrationFee'."); - } - logger.warn( - `Error returned when invoking 'interoperability_getRegistrationFee'.\n${err.stack}`, - ); - throw err; + if (!registrationFee) { + registrationFee = await invokeEndpoint('interoperability_getRegistrationFee'); } + return registrationFee; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/legacy.js b/services/blockchain-connector/shared/sdk/legacy.js index dcde6eeb54..c191cde002 100644 --- a/services/blockchain-connector/shared/sdk/legacy.js +++ b/services/blockchain-connector/shared/sdk/legacy.js @@ -13,22 +13,11 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); - -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const getLegacyAccount = async publicKey => { - try { - const legacyAccount = await invokeEndpoint('legacy_getLegacyAccount', { publicKey }); - return legacyAccount; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getLegacyAccount'."); - } - throw err; - } + const legacyAccount = await invokeEndpoint('legacy_getLegacyAccount', { publicKey }); + return legacyAccount; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/pos.js b/services/blockchain-connector/shared/sdk/pos.js index 37474237b5..d502fc1f78 100644 --- a/services/blockchain-connector/shared/sdk/pos.js +++ b/services/blockchain-connector/shared/sdk/pos.js @@ -13,13 +13,9 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Logger, - Signals, - Exceptions: { TimeoutException }, -} = require('lisk-service-framework'); +const { Logger, Signals } = require('lisk-service-framework'); -const { timeoutMessage, invokeEndpoint } = require('./client'); +const { invokeEndpoint } = require('./client'); const { MODULE_NAME_POS } = require('./constants/names'); const { getBlockByHeight } = require('./blocks'); const regex = require('../utils/regex'); @@ -31,171 +27,83 @@ let posModuleConstants; let allPosValidators; const getPosValidator = async address => { - try { - const validator = await invokeEndpoint('pos_getValidator', { address }); - return validator; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosValidator'."); - } - logger.warn( - `Error returned when invoking 'pos_getValidator' with address: ${address}.\n${err.stack}`, - ); - throw err; - } + const validator = await invokeEndpoint('pos_getValidator', { address }); + return validator; }; const getAllPosValidators = async isForceReload => { - try { - if (!allPosValidators || isForceReload) { - const response = await invokeEndpoint('pos_getAllValidators'); - if (response && Array.isArray(response.validators)) { - allPosValidators = response; - logger.info( - `Reloaded PoS validators list with ${allPosValidators.validators.length} entries.`, - ); - } else { - return response; - } - } - return allPosValidators; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getAllPosValidators'."); + if (!allPosValidators || isForceReload) { + const response = await invokeEndpoint('pos_getAllValidators'); + if (response && Array.isArray(response.validators)) { + allPosValidators = response; + logger.info( + `Reloaded PoS validators list with ${allPosValidators.validators.length} entries.`, + ); + } else { + return response; } - logger.warn(`Error returned when invoking 'pos_getAllValidators'.\n${err.stack}`); - throw err; } + return allPosValidators; }; Signals.get('reloadAllPosValidators').add(() => getAllPosValidators(true)); const getPosValidatorsByStake = async limit => { - try { - const validators = await invokeEndpoint('pos_getValidatorsByStake', { limit }); - return validators; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosValidatorsByStake'."); - } - logger.warn(`Error returned when invoking 'pos_getValidatorsByStake'.\n${err.stack}`); - throw err; - } + const validators = await invokeEndpoint('pos_getValidatorsByStake', { limit }); + return validators; }; const getPosConstants = async () => { if (typeof posModuleConstants === 'undefined') { - try { - const response = await invokeEndpoint('pos_getConstants'); - - if (response.error) throw new Error(response.error); - posModuleConstants = response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosConstants'."); - } - logger.warn(`Error returned when invoking 'pos_getConstants'.\n${err.stack}`); - throw err; - } + const response = await invokeEndpoint('pos_getConstants'); + + if (response.error) throw new Error(response.error); + posModuleConstants = response; } return posModuleConstants; }; const getPosPendingUnlocks = async address => { - try { - const response = await invokeEndpoint('pos_getPendingUnlocks', { address }); - return response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosPendingUnlocks'."); - } - logger.warn( - `Error returned when invoking 'pos_getPendingUnlocks' with address: ${address}.\n${err.stack}`, - ); - throw err; - } + const response = await invokeEndpoint('pos_getPendingUnlocks', { address }); + return response; }; const getStaker = async address => { - try { - const staker = await invokeEndpoint('pos_getStaker', { address }); - - if (staker.error && regex.KEY_NOT_EXIST.test(staker.error.message)) { - return { - stakes: [], - pendingUnlocks: [], - }; - } + const staker = await invokeEndpoint('pos_getStaker', { address }); - return staker; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getStaker'."); - } - logger.warn( - `Error returned when invoking 'pos_getStaker' with address: ${address}.\n${err.stack}`, - ); - throw err; + if (staker.error && regex.KEY_NOT_EXIST.test(staker.error.message)) { + return { + stakes: [], + pendingUnlocks: [], + }; } + + return staker; }; const getPosClaimableRewards = async ({ address }) => { - try { - const claimableRewards = await invokeEndpoint('pos_getClaimableRewards', { address }); - return claimableRewards; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosClaimableRewards'."); - } - logger.warn( - `Error returned when invoking 'pos_getClaimableRewards' with param: ${address}.\n${err.stack}`, - ); - throw err; - } + const claimableRewards = await invokeEndpoint('pos_getClaimableRewards', { address }); + return claimableRewards; }; const getPosLockedReward = async ({ address, tokenID }) => { - try { - const lockedReward = await invokeEndpoint('pos_getLockedReward', { address, tokenID }); - return lockedReward; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPosLockedReward'."); - } - logger.warn( - `Error returned when invoking 'pos_getLockedReward' with address: ${address}, tokenID: ${tokenID}.\n${err.stack}`, - ); - throw err; - } + const lockedReward = await invokeEndpoint('pos_getLockedReward', { address, tokenID }); + return lockedReward; }; const getPoSGenesisStakers = async () => { - try { - const genesisHeight = await getGenesisHeight(); - const block = await getBlockByHeight(genesisHeight, true); - const { stakers = [] } = block.assets.find(asset => asset.module === MODULE_NAME_POS).data; - return stakers; - } catch (error) { - if (error.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPoSGenesisStakers'."); - } - throw error; - } + const genesisHeight = await getGenesisHeight(); + const block = await getBlockByHeight(genesisHeight, true); + const { stakers = [] } = block.assets.find(asset => asset.module === MODULE_NAME_POS).data; + return stakers; }; const getPoSGenesisValidators = async () => { - try { - const genesisHeight = await getGenesisHeight(); - const block = await getBlockByHeight(genesisHeight, true); - const { validators = [] } = block.assets.find(asset => asset.module === MODULE_NAME_POS).data; - return validators; - } catch (error) { - if (error.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getPoSGenesisValidators'."); - } - throw error; - } + const genesisHeight = await getGenesisHeight(); + const block = await getBlockByHeight(genesisHeight, true); + const { validators = [] } = block.assets.find(asset => asset.module === MODULE_NAME_POS).data; + return validators; }; module.exports = { diff --git a/services/blockchain-connector/shared/sdk/token.js b/services/blockchain-connector/shared/sdk/token.js index f662c64330..f4a18e6fc6 100644 --- a/services/blockchain-connector/shared/sdk/token.js +++ b/services/blockchain-connector/shared/sdk/token.js @@ -13,13 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Exceptions: { TimeoutException }, - Logger, -} = require('lisk-service-framework'); -const { timeoutMessage, invokeEndpoint } = require('./client'); - -const logger = Logger(); +const { invokeEndpoint } = require('./client'); let escrowedAmounts; let supportedTokens; @@ -27,114 +21,50 @@ let totalSupply; let initializationFees; const getTokenBalances = async address => { - try { - const balances = await invokeEndpoint('token_getBalances', { address }); - return balances; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getTokenBalances'."); - } - logger.warn(`Error returned when invoking 'token_getBalances'.\n${err.stack}`); - throw err; - } + const balances = await invokeEndpoint('token_getBalances', { address }); + return balances; }; const getTokenBalance = async ({ address, tokenID }) => { - try { - const balance = await invokeEndpoint('token_getBalance', { address, tokenID }); - return balance; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getTokenBalance'."); - } - logger.warn(`Error returned when invoking 'token_getBalance'.\n${err.stack}`); - throw err; - } + const balance = await invokeEndpoint('token_getBalance', { address, tokenID }); + return balance; }; const getEscrowedAmounts = async (isForceUpdate = false) => { - try { - if (isForceUpdate || !escrowedAmounts) { - escrowedAmounts = await invokeEndpoint('token_getEscrowedAmounts'); - } - return escrowedAmounts; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getEscrowedAmounts'."); - } - logger.warn(`Error returned when invoking 'token_getEscrowedAmounts'.\n${err.stack}`); - throw err; + if (isForceUpdate || !escrowedAmounts) { + escrowedAmounts = await invokeEndpoint('token_getEscrowedAmounts'); } + return escrowedAmounts; }; const getSupportedTokens = async (isForceUpdate = false) => { - try { - if (isForceUpdate || !supportedTokens) { - supportedTokens = await invokeEndpoint('token_getSupportedTokens'); - } - return supportedTokens; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getSupportedTokens'."); - } - logger.warn(`Error returned when invoking 'token_getSupportedTokens'.\n${err.stack}`); - throw err; + if (isForceUpdate || !supportedTokens) { + supportedTokens = await invokeEndpoint('token_getSupportedTokens'); } + return supportedTokens; }; const getTotalSupply = async (isForceUpdate = false) => { - try { - if (isForceUpdate || !totalSupply) { - totalSupply = await invokeEndpoint('token_getTotalSupply'); - } - return totalSupply; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getTotalSupply'."); - } - logger.warn(`Error returned when invoking 'token_getTotalSupply'.\n${err.stack}`); - throw err; + if (isForceUpdate || !totalSupply) { + totalSupply = await invokeEndpoint('token_getTotalSupply'); } + return totalSupply; }; const getTokenInitializationFees = async () => { - try { - if (!initializationFees) { - const response = await invokeEndpoint('token_getInitializationFees'); - if (response.error) throw new Error(response.error); - initializationFees = response; - } - return initializationFees; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getTokenInitializationFees'."); - } - logger.warn(`Error returned when invoking 'token_getInitializationFees'.\n${err.stack}`); - throw err; + if (!initializationFees) { + const response = await invokeEndpoint('token_getInitializationFees'); + if (response.error) throw new Error(response.error); + initializationFees = response; } + return initializationFees; }; -const hasUserAccount = async ({ address, tokenID }) => { - try { - return invokeEndpoint('token_hasUserAccount', { address, tokenID }); - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'hasUserAccount'."); - } - throw err; - } -}; +const hasUserAccount = async ({ address, tokenID }) => + invokeEndpoint('token_hasUserAccount', { address, tokenID }); -const hasEscrowAccount = async ({ tokenID, escrowChainID }) => { - try { - return invokeEndpoint('token_hasEscrowAccount', { tokenID, escrowChainID }); - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'hasUserAccount'."); - } - throw err; - } -}; +const hasEscrowAccount = async ({ tokenID, escrowChainID }) => + invokeEndpoint('token_hasEscrowAccount', { tokenID, escrowChainID }); const updateTokenInfo = async () => { escrowedAmounts = await getEscrowedAmounts(true); diff --git a/services/blockchain-connector/shared/sdk/validators.js b/services/blockchain-connector/shared/sdk/validators.js index efee6ab0a1..fe6ac05d9d 100644 --- a/services/blockchain-connector/shared/sdk/validators.js +++ b/services/blockchain-connector/shared/sdk/validators.js @@ -13,43 +13,19 @@ * Removal or modification of this copyright notice is prohibited. * */ -const { - Exceptions: { TimeoutException }, - Logger, -} = require('lisk-service-framework'); - -const { timeoutMessage, invokeEndpoint } = require('./client'); - -const logger = Logger(); +const { invokeEndpoint } = require('./client'); const validateBLSKey = async ({ blsKey, proofOfPossession }) => { - try { - const response = await invokeEndpoint('validators_validateBLSKey', { - blsKey, - proofOfPossession, - }); - return response; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - logger.warn( - `Request timed out when calling 'validateBLSKey' with:\nblsKey: ${blsKey}\nproofOfPossession: ${proofOfPossession}`, - ); - throw new TimeoutException("Request timed out when calling 'validateBLSKey'."); - } - throw err; - } + const response = await invokeEndpoint('validators_validateBLSKey', { + blsKey, + proofOfPossession, + }); + return response; }; const getValidator = async address => { - try { - const validatorInfo = await invokeEndpoint('validators_getValidator', { address }); - return validatorInfo; - } catch (err) { - if (err.message.includes(timeoutMessage)) { - throw new TimeoutException("Request timed out when calling 'getValidator'."); - } - throw err; - } + const validatorInfo = await invokeEndpoint('validators_getValidator', { address }); + return validatorInfo; }; module.exports = {