diff options
author | Dan Finlay <542863+danfinlay@users.noreply.github.com> | 2017-09-28 01:57:02 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-09-28 01:57:02 +0800 |
commit | e72083f6e81f888f714125f7c050e777ea5c9bdd (patch) | |
tree | 8177fb150ae254b838cabec028b3c5e08fbc951e /app/scripts/lib/pending-balance-calculator.js | |
parent | ff5e8746bee0d7461df02e7f2186ff7c90bfcb50 (diff) | |
parent | ca0dff06f5d9283e57b452dcc7e85c31b248b8aa (diff) | |
download | tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar.gz tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar.bz2 tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar.lz tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar.xz tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.tar.zst tangerine-wallet-browser-e72083f6e81f888f714125f7c050e777ea5c9bdd.zip |
Merge branch 'master' into filter-fixes-moar
Diffstat (limited to 'app/scripts/lib/pending-balance-calculator.js')
-rw-r--r-- | app/scripts/lib/pending-balance-calculator.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/app/scripts/lib/pending-balance-calculator.js b/app/scripts/lib/pending-balance-calculator.js new file mode 100644 index 000000000..cea642f1a --- /dev/null +++ b/app/scripts/lib/pending-balance-calculator.js @@ -0,0 +1,51 @@ +const BN = require('ethereumjs-util').BN +const normalize = require('eth-sig-util').normalize + +class PendingBalanceCalculator { + + // Must be initialized with two functions: + // getBalance => Returns a promise of a BN of the current balance in Wei + // getPendingTransactions => Returns an array of TxMeta Objects, + // which have txParams properties, which include value, gasPrice, and gas, + // all in a base=16 hex format. + constructor ({ getBalance, getPendingTransactions }) { + this.getPendingTransactions = getPendingTransactions + this.getNetworkBalance = getBalance + } + + async getBalance() { + const results = await Promise.all([ + this.getNetworkBalance(), + this.getPendingTransactions(), + ]) + + const [ balance, pending ] = results + if (!balance) return undefined + + const pendingValue = pending.reduce((total, tx) => { + return total.add(this.calculateMaxCost(tx)) + }, new BN(0)) + + return `0x${balance.sub(pendingValue).toString(16)}` + } + + calculateMaxCost (tx) { + const txValue = tx.txParams.value + const value = this.hexToBn(txValue) + const gasPrice = this.hexToBn(tx.txParams.gasPrice) + + const gas = tx.txParams.gas + const gasLimit = tx.txParams.gasLimit + const gasLimitBn = this.hexToBn(gas || gasLimit) + + const gasCost = gasPrice.mul(gasLimitBn) + return value.add(gasCost) + } + + hexToBn (hex) { + return new BN(normalize(hex).substring(2), 16) + } + +} + +module.exports = PendingBalanceCalculator |