aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/lib/controllers/shapeshift.js
blob: 6c02dc3ebf5ef1f2d9e17a8138014c018143d92f (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const ObservableStore = require('obs-store')
const extend = require('xtend')

// every three seconds when an incomplete tx is waiting
const POLLING_INTERVAL = 3000

class ShapeshiftController {

  constructor (opts = {}) {
    const initState = extend({
      shapeShiftTxList: [],
    }, opts)
    this.store = new ObservableStore(initState)
  }

  //
  // PUBLIC METHODS
  //

  getShapeShiftTxList () {
    const shapeShiftTxList = this.store.getState().shapeShiftTxList

    shapeShiftTxList.forEach((tx) => {
      if (tx.response.status === 'no_deposits') {
        this.updateTx(tx)
      }
    })
    console.dir({shapeShiftTxList})
    return shapeShiftTxList
  }

  getPendingTxs () {
    const txs = this.getShapeShiftTxList()
    const pending = txs.filter(tx => tx.response.status !== 'complete')
    return pending
  }

  pollForUpdates () {
    const pendingTxs = this.getPendingTxs()

    if (pendingTxs.length === 0) {
      return
    }

    Promise.all(pendingTxs.map((tx) => {
      return this.updateTx(tx)
    }))
    .then((results) => {
      results.forEach(tx => this.saveTx(tx))
      setTimeout(this.pollForUpdates.bind(this), POLLING_INTERVAL)
    })
  }

  updateTx (tx) {
    const url = `https://shapeshift.io/txStat/${tx.depositAddress}`
    return fetch(url)
    .then((response) => {
      tx.response = response.json()
      if (tx.response.status === 'complete') {
        tx.time = new Date().getTime()
      }
      return tx
    })
  }

  saveTx (tx) {
    const { shapeShiftTxList } = this.store.getState()
    const index = shapeShiftTxList.indexOf(tx)
    if (index !== -1) {
      shapeShiftTxList[index] = tx
      this.store.updateState({ shapeShiftTxList })
    }
  }

  createShapeShiftTx (depositAddress, depositType) {
    const state = this.store.getState()
    let { shapeShiftTxList } = state

    var shapeShiftTx = {
      depositAddress,
      depositType,
      key: 'shapeshift',
      time: new Date().getTime(),
      response: {},
    }

    if (!shapeShiftTxList) {
      shapeShiftTxList = [shapeShiftTx]
    } else {
      shapeShiftTxList.push(shapeShiftTx)
    }
    console.dir({ shapeShiftTxList })

    this.store.updateState({ shapeShiftTxList })
    this.pollForUpdates()
  }

}

module.exports = ShapeshiftController