aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers/token-rates.js
blob: b6f084841e36b613d16192704d181029a014c5b7 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const ObservableStore = require('obs-store')
const log = require('loglevel')

// By default, poll every 3 minutes
const DEFAULT_INTERVAL = 180 * 1000

/**
 * A controller that polls for token exchange
 * rates based on a user's current token list
 */
class TokenRatesController {
  /**
   * Creates a TokenRatesController
   *
   * @param {Object} [config] - Options to configure controller
   */
  constructor ({ interval = DEFAULT_INTERVAL, preferences } = {}) {
    this.store = new ObservableStore()
    this.preferences = preferences
    this.interval = interval
  }

  /**
   * Updates exchange rates for all tokens
   */
  async updateExchangeRates () {
    if (!this.isActive) { return }
    const contractExchangeRates = {}
    // copy array to ensure its not modified during iteration
    const tokens = this._tokens.slice()
    for (const token of tokens) {
      if (!token) return log.error(`TokenRatesController - invalid tokens state:\n${JSON.stringify(tokens, null, 2)}`)
      const address = token.address
      contractExchangeRates[address] = await this.fetchExchangeRate(address)
    }
    this.store.putState({ contractExchangeRates })
  }

  /**
   * Fetches a token exchange rate by address
   *
   * @param {String} address - Token contract address
   */
  async fetchExchangeRate (address) {
    try {
      const response = await fetch(`https://metamask.balanc3.net/prices?from=${address}&to=ETH&autoConversion=false&summaryOnly=true`)
      const json = await response.json()
      return json && json.length ? json[0].averagePrice : 0
    } catch (error) {
      log.warn(`MetaMask - TokenRatesController exchange rate fetch failed for ${address}.`, error)
      return 0
    }
  }

  /**
   * @type {Number}
   */
  set interval (interval) {
    this._handle && clearInterval(this._handle)
    if (!interval) { return }
    this._handle = setInterval(() => { this.updateExchangeRates() }, interval)
  }

  /**
   * @type {Object}
   */
  set preferences (preferences) {
    this._preferences && this._preferences.unsubscribe()
    if (!preferences) { return }
    this._preferences = preferences
    this.tokens = preferences.getState().tokens
    preferences.subscribe(({ tokens = [] }) => { this.tokens = tokens })
  }

  /**
   * @type {Array}
   */
  set tokens (tokens) {
    this._tokens = tokens
    this.updateExchangeRates()
  }
}

module.exports = TokenRatesController