aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/pending-balance-calculator.js
diff options
context:
space:
mode:
authorDan Finlay <dan@danfinlay.com>2017-09-23 05:30:31 +0800
committerDan Finlay <dan@danfinlay.com>2017-09-23 05:30:31 +0800
commitaa2abc00eb86c1cb746a59a6e307a6bc255e6466 (patch)
treec6056fb31ac0c79bfebc5e36d7dd56e8cabfd543 /app/scripts/lib/pending-balance-calculator.js
parent08b36b9b582853b411a19e48b407c70596381f61 (diff)
parentf128240e7f877280fa59bf22f2ea8285bb467022 (diff)
downloadtangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.gz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.bz2
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.lz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.xz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.zst
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.zip
Merge branch 'AddBalanceController' into BreakOutKeyringController
Diffstat (limited to 'app/scripts/lib/pending-balance-calculator.js')
-rw-r--r--app/scripts/lib/pending-balance-calculator.js53
1 files changed, 53 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..c66bffbbb
--- /dev/null
+++ b/app/scripts/lib/pending-balance-calculator.js
@@ -0,0 +1,53 @@
+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 = results[0]
+ const pending = results[1]
+
+ if (!balance) return undefined
+
+ const pendingValue = pending.reduce((total, tx) => {
+ return total.add(this.valueFor(tx))
+ }, new BN(0))
+
+ return `0x${balance.sub(pendingValue).toString(16)}`
+ }
+
+ valueFor (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