aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers/balance.js
blob: 4fa4c78fe3e0ad69322563b04f5b4b4e896e5630 (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
61
62
63
64
65
66
67
68
69
70
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, blockTracker } = opts
    this.address = address
    this.accountTracker = accountTracker
    this.txController = txController
    this.blockTracker = blockTracker

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

    this.balanceCalc = new PendingBalanceCalculator({
      getBalance: () => 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('tx:status-update', (txId, status) => {
      switch (status) {
        case 'submitted':
        case 'confirmed':
        case 'failed':
          update()
          return
        default:
          return
      }
    })
    this.accountTracker.store.subscribe(update)
    this.blockTracker.on('block', update)
  }

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

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

}

module.exports = BalanceController