nifty-wallet/app/scripts/lib/pending-balance-calculator.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-09-06 14:36:15 -07:00
const BN = require('ethereumjs-util').BN
2017-09-07 11:59:15 -07:00
const normalize = require('eth-sig-util').normalize
2017-09-06 14:36:15 -07:00
class PendingBalanceCalculator {
2017-09-07 12:45:00 -07:00
// 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.
2017-09-06 14:36:15 -07:00
constructor ({ getBalance, getPendingTransactions }) {
this.getPendingTransactions = getPendingTransactions
2017-09-07 12:30:25 -07:00
this.getNetworkBalance = getBalance
2017-09-06 14:36:15 -07:00
}
async getBalance() {
2017-09-06 14:37:46 -07:00
const results = await Promise.all([
2017-09-07 12:30:25 -07:00
this.getNetworkBalance(),
2017-09-06 14:37:46 -07:00
this.getPendingTransactions(),
])
const balance = results[0]
const pending = results[1]
if (!balance) return undefined
2017-09-07 12:43:10 -07:00
const pendingValue = pending.reduce((total, tx) => {
2017-09-07 12:30:25 -07:00
return total.add(this.valueFor(tx))
2017-09-07 11:59:15 -07:00
}, new BN(0))
2017-09-07 12:54:28 -07:00
return `0x${balance.sub(pendingValue).toString(16)}`
2017-09-07 11:59:15 -07:00
}
valueFor (tx) {
2017-09-07 12:30:25 -07:00
const txValue = tx.txParams.value
2017-09-07 12:43:10 -07:00
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)
2017-09-06 14:36:15 -07:00
}
2017-09-07 12:43:10 -07:00
hexToBn (hex) {
return new BN(normalize(hex).substring(2), 16)
}
2017-09-06 14:36:15 -07:00
}
module.exports = PendingBalanceCalculator