aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers/currency.js
blob: 1f20dc00548c19c60e0e7a737f8ad97fd3e2bada (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
const ObservableStore = require('obs-store')
const extend = require('xtend')

// every ten minutes
const POLLING_INTERVAL = 600000

class CurrencyController {

  constructor (opts = {}) {
    const initState = extend({
      currentCurrency: 'USD',
      conversionRate: 0,
      conversionDate: 'N/A',
    }, opts.initState)
    this.store = new ObservableStore(initState)
  }

  //
  // PUBLIC METHODS
  //

  getCurrentCurrency () {
    return this.store.getState().currentCurrency
  }

  setCurrentCurrency (currentCurrency) {
    this.store.updateState({ currentCurrency })
  }

  getConversionRate () {
    return this.store.getState().conversionRate
  }

  setConversionRate (conversionRate) {
    this.store.updateState({ conversionRate })
  }

  getConversionDate () {
    return this.store.getState().conversionDate
  }

  setConversionDate (conversionDate) {
    this.store.updateState({ conversionDate })
  }

  updateConversionRate () {
    const currentCurrency = this.getCurrentCurrency()
    return fetch(`https://api.cryptonator.com/api/ticker/eth-${currentCurrency}`)
    .then(response => response.json())
    .then((parsedResponse) => {
      this.setConversionRate(Number(parsedResponse.ticker.price))
      this.setConversionDate(Number(parsedResponse.timestamp))
    }).catch((err) => {
      if (err) {
        console.warn('MetaMask - Failed to query currency conversion.')
        this.setConversionRate(0)
        this.setConversionDate('N/A')
      }
    })
  }

  scheduleConversionInterval () {
    if (this.conversionInterval) {
      clearInterval(this.conversionInterval)
    }
    this.conversionInterval = setInterval(() => {
      this.updateConversionRate()
    }, POLLING_INTERVAL)
  }
}

module.exports = CurrencyController