1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 08:09:15 +01:00
metamask-extension/app/scripts/controllers/balance.js

81 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-09-13 00:06:19 +02:00
const ObservableStore = require('obs-store')
const PendingBalanceCalculator = require('../lib/pending-balance-calculator')
2017-09-13 23:20:19 +02:00
const BN = require('ethereumjs-util').BN
2017-09-13 00:06:19 +02:00
class BalanceController {
constructor (opts = {}) {
2017-10-18 21:21:22 +02:00
this._validateParams(opts)
2017-09-25 23:39:22 +02:00
const { address, accountTracker, txController, blockTracker } = opts
2017-10-18 21:21:22 +02:00
2017-09-13 23:20:19 +02:00
this.address = address
2017-09-22 23:13:56 +02:00
this.accountTracker = accountTracker
2017-09-13 00:06:19 +02:00
this.txController = txController
2017-09-25 23:39:22 +02:00
this.blockTracker = blockTracker
2017-09-13 00:06:19 +02:00
const initState = {
2017-09-13 00:06:19 +02:00
ethBalance: undefined,
}
2017-09-13 00:06:19 +02:00
this.store = new ObservableStore(initState)
this.balanceCalc = new PendingBalanceCalculator({
2017-09-25 20:42:08 +02:00
getBalance: () => this._getBalance(),
2017-09-13 23:20:19 +02:00
getPendingTransactions: this._getPendingTransactions.bind(this),
2017-09-13 00:06:19 +02:00
})
2017-09-13 23:20:19 +02:00
2017-09-25 23:36:49 +02:00
this._registerUpdates()
2017-09-13 23:20:19 +02:00
}
async updateBalance () {
const balance = await this.balanceCalc.getBalance()
this.store.updateState({
ethBalance: balance,
})
}
2017-09-25 23:36:49 +02:00
_registerUpdates () {
2017-09-13 23:20:19 +02:00
const update = this.updateBalance.bind(this)
this.txController.on('tx:status-update', (txId, status) => {
switch (status) {
case 'submitted':
case 'confirmed':
case 'failed':
update()
return
default:
return
}
})
this.accountTracker.store.subscribe(update)
2017-09-25 23:39:22 +02:00
this.blockTracker.on('block', update)
2017-09-13 23:20:19 +02:00
}
2017-09-25 20:42:08 +02:00
async _getBalance () {
const { accounts } = this.accountTracker.store.getState()
2017-09-25 20:42:08 +02:00
const entry = accounts[this.address]
2017-09-13 23:20:19 +02:00
const balance = entry.balance
return balance ? new BN(balance.substring(2), 16) : undefined
2017-09-13 23:20:19 +02:00
}
2017-09-25 20:42:08 +02:00
async _getPendingTransactions () {
2017-09-13 23:20:19 +02:00
const pending = this.txController.getFilteredTxList({
from: this.address,
status: 'submitted',
err: undefined,
})
2017-09-25 20:42:08 +02:00
return pending
2017-09-13 00:06:19 +02:00
}
2017-10-18 21:21:22 +02:00
_validateParams (opts) {
const { address, accountTracker, txController, blockTracker } = opts
if (!address || !accountTracker || !txController || !blockTracker) {
const error = 'Cannot construct a balance checker without address, accountTracker, txController, and blockTracker.'
throw new Error(error)
}
}
2017-09-13 00:06:19 +02:00
}
module.exports = BalanceController