1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-27 21:00:13 +01:00
metamask-extension/app/scripts/controllers/computed-balances.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-09-13 00:06:19 +02:00
const ObservableStore = require('obs-store')
const extend = require('xtend')
const BalanceController = require('./balance')
class ComputedbalancesController {
2017-09-13 00:06:19 +02:00
constructor (opts = {}) {
2017-09-25 23:39:22 +02:00
const { accountTracker, txController, blockTracker } = opts
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 = extend({
2017-09-13 23:20:19 +02:00
computedBalances: {},
2017-09-13 00:06:19 +02:00
}, opts.initState)
this.store = new ObservableStore(initState)
this.balances = {}
2017-09-13 00:06:19 +02:00
this._initBalanceUpdating()
}
updateAllBalances () {
for (let address in this.accountTracker.store.getState().accounts) {
this.balances[address].updateBalance()
}
}
2017-09-13 23:20:19 +02:00
_initBalanceUpdating () {
const store = this.accountTracker.store.getState()
2017-09-13 23:20:19 +02:00
this.addAnyAccountsFromStore(store)
this.accountTracker.store.subscribe(this.addAnyAccountsFromStore.bind(this))
2017-09-13 00:06:19 +02:00
}
2017-09-13 23:20:19 +02:00
addAnyAccountsFromStore(store) {
const balances = store.accounts
2017-09-13 00:06:19 +02:00
2017-09-13 23:20:19 +02:00
for (let address in balances) {
this.trackAddressIfNotAlready(address)
2017-09-13 00:06:19 +02:00
}
}
2017-09-13 23:20:19 +02:00
trackAddressIfNotAlready (address) {
const state = this.store.getState()
if (!(address in state.computedBalances)) {
this.trackAddress(address)
2017-09-13 00:06:19 +02:00
}
}
2017-09-13 23:20:19 +02:00
trackAddress (address) {
let updater = new BalanceController({
address,
2017-09-22 23:13:56 +02:00
accountTracker: this.accountTracker,
2017-09-13 23:20:19 +02:00
txController: this.txController,
2017-09-25 23:39:22 +02:00
blockTracker: this.blockTracker,
2017-09-13 23:20:19 +02:00
})
updater.store.subscribe((accountBalance) => {
let newState = this.store.getState()
newState.computedBalances[address] = accountBalance
this.store.updateState(newState)
})
this.balances[address] = updater
2017-09-13 23:20:19 +02:00
updater.updateBalance()
2017-09-13 00:06:19 +02:00
}
}
module.exports = ComputedbalancesController