1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/app/scripts/lib/pending-balance-calculator.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

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