From c355a1ec97b16189947c0b2c9524037d33a68346 Mon Sep 17 00:00:00 2001 From: acerasino Date: Mon, 18 Feb 2019 16:02:43 +0100 Subject: [PATCH] #11 Add isTransactionMined in TransactionLib --- src/lib/TransactionLib/TransactionLib.js | 43 ++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/lib/TransactionLib/TransactionLib.js b/src/lib/TransactionLib/TransactionLib.js index c7da9eb..4b98383 100644 --- a/src/lib/TransactionLib/TransactionLib.js +++ b/src/lib/TransactionLib/TransactionLib.js @@ -19,6 +19,11 @@ const providerUrl = 'urlToProvider' const web3Instance = new Web3(new Web3.providers.HttpProvider(providerUrl)) const ethApiLibClient = new EidooEthApiLib(ethApi) + +function waitForMsAsync (time) { + return new Promise(resolve => setTimeout(resolve, time)) +} + /** * It gets nonce from input address. * @@ -251,6 +256,44 @@ class TransactionLib extends ITransactionLib { throw new TransactionCallError(err) } } + + async getTransactionReceipt(hash, fromAddress) { + try { + const { transactions } = await this.ethApiClient.getAccountTxsDetailsAsync(fromAddress) + + const transactionReceipt = _.find(transactions, item => item.transactionReceipt.transactionHash === hash) + return transactionReceipt || null + } catch (err) { + throw new Error(`Error retriving transaction Receipt: ${hash}`) + } + } + + /** + * It checks if the transaction is mined. + * + * @param {String} hash The transaction hash + */ + async isTransactionMined (hash, fromAddress) { + const maxWaitAllowedInMs = 5 * 1000 + const startedAt = new Date() + let transactionReceipit = this.getTransactionReceipt(hash, fromAddress) + let isEnd = false + while (transactionReceipit !== null && !isEnd) { + const now = new Date() + isEnd = (+now - +startedAt) > maxWaitAllowedInMs + transactionReceipit = this.getTransactionReceipt(hash, fromAddress) + this.log.info({ + fn: 'isTransactionMined', + hash, + transactionReceipit, + }, + 'Checking transaction...') + await waitForMsAsync(1000) + } + + const isMined = !!transactionReceipit + return isMined + } } module.exports = TransactionLib