A Metamask fork with Infura removed and default networks editable
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ciphermask/app/scripts/controllers/computed-balances.js

78 lines
2.0 KiB

7 years ago
const ObservableStore = require('obs-store')
const extend = require('xtend')
const BalanceController = require('./balance')
class ComputedbalancesController {
7 years ago
constructor (opts = {}) {
const { accountTracker, txController, blockTracker } = opts
this.accountTracker = accountTracker
7 years ago
this.txController = txController
this.blockTracker = blockTracker
7 years ago
const initState = extend({
computedBalances: {},
7 years ago
}, opts.initState)
this.store = new ObservableStore(initState)
this.balances = {}
7 years ago
this._initBalanceUpdating()
}
updateAllBalances () {
Object.keys(this.balances).forEach((balance) => {
const address = balance.address
this.balances[address].updateBalance()
})
}
_initBalanceUpdating () {
const store = this.accountTracker.store.getState()
this.syncAllAccountsFromStore(store)
this.accountTracker.store.subscribe(this.syncAllAccountsFromStore.bind(this))
7 years ago
}
syncAllAccountsFromStore(store) {
const upstream = Object.keys(store.accounts)
const balances = Object.keys(this.balances)
.map(address => this.balances[address])
7 years ago
// Follow new addresses
for (let address in balances) {
this.trackAddressIfNotAlready(address)
7 years ago
}
// Unfollow old ones
balances.forEach(({ address }) => {
if (!upstream.includes(address)) {
delete this.balances[address]
}
})
7 years ago
}
trackAddressIfNotAlready (address) {
const state = this.store.getState()
if (!(address in state.computedBalances)) {
this.trackAddress(address)
7 years ago
}
}
trackAddress (address) {
let updater = new BalanceController({
address,
accountTracker: this.accountTracker,
txController: this.txController,
blockTracker: this.blockTracker,
})
updater.store.subscribe((accountBalance) => {
let newState = this.store.getState()
newState.computedBalances[address] = accountBalance
this.store.updateState(newState)
})
this.balances[address] = updater
updater.updateBalance()
7 years ago
}
}
module.exports = ComputedbalancesController