From 0e39aa78c9155da3a8f391e9cba57b5eb11c1a06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Oliveira?= Date: Tue, 6 Apr 2021 10:40:35 +0100 Subject: [PATCH] refactor: remove nested loop --- lib/plugins/wallet/bitcoind/bitcoind.js | 8 ++++---- lib/plugins/zero-conf/blockcypher/blockcypher.js | 13 +++++-------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/lib/plugins/wallet/bitcoind/bitcoind.js b/lib/plugins/wallet/bitcoind/bitcoind.js index 9ab76622..d68a27c3 100644 --- a/lib/plugins/wallet/bitcoind/bitcoind.js +++ b/lib/plugins/wallet/bitcoind/bitcoind.js @@ -128,12 +128,12 @@ function cryptoNetwork (account, cryptoCode) { function fetchRBF (txId) { return fetch('getmempoolentry', [txId]) - .then((res) => _.assign(_.pick(['bip125-replaceable'], res)), { tx_hash: txId }) + .then((res) => { + return [txId, res['bip125-replaceable']] + }) .catch(err => { if (err.code === -5) console.log(`${err.message}`) - const result = { tx_hash: txId } - result['bip125-replaceable'] = true - return result + return [txId, true] }) } diff --git a/lib/plugins/zero-conf/blockcypher/blockcypher.js b/lib/plugins/zero-conf/blockcypher/blockcypher.js index d6cb7775..6cd3582d 100644 --- a/lib/plugins/zero-conf/blockcypher/blockcypher.js +++ b/lib/plugins/zero-conf/blockcypher/blockcypher.js @@ -5,9 +5,9 @@ const _ = require('lodash/fp') const { fetchRBF } = require('../../wallet/bitcoind/bitcoind') module.exports = { authorize } -function highConfidence (confidence, txref) { +function highConfidence (confidence, txref, txRBF) { if (txref.double_spend) return 0 - if (txref.rbf) return 0 + if (txRBF) return 0 if (txref.confirmations > 0 || txref.confidence * 100 >= confidence) return txref.value return 0 } @@ -30,22 +30,19 @@ function authorize (account, toAddress, cryptoAtoms, cryptoCode, isBitcoindAvail return axios.get(url) .then(r => { const data = r.data - const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) if (isBitcoindAvailable && isRBFEnabled && data.unconfirmed_txrefs) { _.map(unconfirmedTxref => { promise.push(new Promise((resolve, reject) => { resolve(fetchRBF(unconfirmedTxref.tx_hash)) })) }, data.unconfirmed_txrefs) return Promise.all(promise) .then(values => { - _.map(rbfInfo => { - _.map(unconfirmedTxref => { - if (rbfInfo.tx_hash === unconfirmedTxref.tx_hash) unconfirmedTxref.rbf = rbfInfo['bip125-replaceable'] - }, data.unconfirmed_txrefs) - }, values) + const unconfirmedTxsRBF = _.fromPairs(values) + const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref, unconfirmedTxsRBF[txref.tx_hash]), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) }) } else { + const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) }