aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers/balance.js
blob: ddeb06cf91243873316649734a4d48bc8eff75dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const ObservableStore = require('obs-store')
const PendingBalanceCalculator = require('../lib/pending-balance-calculator')
const BN = require('ethereumjs-util').BN

class BalanceController {

  constructor (opts = {}) {
    const { address, accountTracker, txController } = opts
    this.address = address
    this.accountTracker = accountTracker
    this.txController = txController

    const initState = {
      ethBalance: undefined,
    }
    this.store = new ObservableStore(initState)

    this.balanceCalc = new PendingBalanceCalculator({
      getBalance: () => Promise.resolve(this._getBalance()),
      getPendingTransactions: this._getPendingTransactions.bind(this),
    })

    this.registerUpdates()
  }

  async updateBalance () {
    const balance = await this.balanceCalc.getBalance()
    this.store.updateState({
      ethBalance: balance,
    })
  }

  registerUpdates () {
    const update = this.updateBalance.bind(this)
    this.txController.on('submitted', update)
    this.txController.on('confirmed', update)
    this.txController.on('failed', update)
    this.txController.blockTracker.on('block', update)
  }

  _getBalance () {
    const store = this.accountTracker.getState()
    const balances = store.accounts
    const entry = balances[this.address]
    const balance = entry.balance
    return balance ? new BN(balance.substring(2), 16) : undefined
  }

  _getPendingTransactions () {
    const pending = this.txController.getFilteredTxList({
      from: this.address,
      status: 'submitted',
      err: undefined,
    })
    return Promise.resolve(pending)
  }

}

module.exports = BalanceController