aboutsummaryrefslogtreecommitdiffstats
path: root/ui/app/pages/create-account/connect-hardware/index.js
blob: 5a91a27250404ef9b856a4f5ab2874de258f6848 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
const { Component } = require('react')
const PropTypes = require('prop-types')
const h = require('react-hyperscript')
const connect = require('react-redux').connect
const actions = require('../../../store/actions')
const { getMetaMaskAccounts } = require('../../../selectors/selectors')
const ConnectScreen = require('./connect-screen')
const AccountList = require('./account-list')
const { DEFAULT_ROUTE } = require('../../../helpers/constants/routes')
const { formatBalance } = require('../../../helpers/utils/util')
const { getPlatform } = require('../../../../../app/scripts/lib/util')
const { PLATFORM_FIREFOX } = require('../../../../../app/scripts/lib/enums')

class ConnectHardwareForm extends Component {
  constructor (props) {
    super(props)
    this.state = {
      error: null,
      selectedAccount: null,
      accounts: [],
      browserSupported: true,
      unlocked: false,
      device: null,
    }
  }

  componentWillReceiveProps (nextProps) {
    const { accounts } = nextProps
    const newAccounts = this.state.accounts.map(a => {
      const normalizedAddress = a.address.toLowerCase()
      const balanceValue = accounts[normalizedAddress] && accounts[normalizedAddress].balance || null
      a.balance = balanceValue ? formatBalance(balanceValue, 6) : '...'
      return a
    })
    this.setState({accounts: newAccounts})
  }


  componentDidMount () {
    this.checkIfUnlocked()
  }

  async checkIfUnlocked () {
    ['trezor', 'ledger'].forEach(async device => {
      const unlocked = await this.props.checkHardwareStatus(device, this.props.defaultHdPaths[device])
      if (unlocked) {
        this.setState({unlocked: true})
        this.getPage(device, 0, this.props.defaultHdPaths[device])
      }
    })
  }

  connectToHardwareWallet = (device) => {
    // Ledger hardware wallets are not supported on firefox
    if (getPlatform() === PLATFORM_FIREFOX && device === 'ledger') {
      this.setState({ browserSupported: false, error: null})
      return null
    }

    if (this.state.accounts.length) {
      return null
    }

    // Default values
    this.getPage(device, 0, this.props.defaultHdPaths[device])
  }

  onPathChange = (path) => {
    this.props.setHardwareWalletDefaultHdPath({device: this.state.device, path})
    this.getPage(this.state.device, 0, path)
  }

  onAccountChange = (account) => {
    this.setState({selectedAccount: account.toString(), error: null})
  }

  onAccountRestriction = () => {
    this.setState({error: this.context.t('ledgerAccountRestriction') })
  }

  showTemporaryAlert () {
    this.props.showAlert(this.context.t('hardwareWalletConnected'))
    // Autohide the alert after 5 seconds
    setTimeout(_ => {
      this.props.hideAlert()
    }, 5000)
  }

  getPage = (device, page, hdPath) => {
    this.props
      .connectHardware(device, page, hdPath)
      .then(accounts => {
        if (accounts.length) {

          // If we just loaded the accounts for the first time
          // (device previously locked) show the global alert
          if (this.state.accounts.length === 0 && !this.state.unlocked) {
            this.showTemporaryAlert()
          }

          const newState = { unlocked: true, device, error: null }
          // Default to the first account
          if (this.state.selectedAccount === null) {
            accounts.forEach((a) => {
              if (a.address.toLowerCase() === this.props.address) {
                newState.selectedAccount = a.index.toString()
              }
            })
          // If the page doesn't contain the selected account, let's deselect it
          } else if (!accounts.filter(a => a.index.toString() === this.state.selectedAccount).length) {
            newState.selectedAccount = null
          }


          // Map accounts with balances
          newState.accounts = accounts.map(account => {
            const normalizedAddress = account.address.toLowerCase()
            const balanceValue = this.props.accounts[normalizedAddress] && this.props.accounts[normalizedAddress].balance || null
            account.balance = balanceValue ? formatBalance(balanceValue, 6) : '...'
            return account
          })

          this.setState(newState)
        }
      })
      .catch(e => {
        if (e === 'Window blocked') {
          this.setState({ browserSupported: false, error: null})
        } else if (e !== 'Window closed' && e !== 'Popup closed') {
          this.setState({ error: e.toString() })
        }
      })
  }

  onForgetDevice = (device) => {
    this.props.forgetDevice(device)
    .then(_ => {
      this.setState({
        error: null,
        selectedAccount: null,
        accounts: [],
        unlocked: false,
      })
    }).catch(e => {
      this.setState({ error: e.toString() })
    })
  }

  onUnlockAccount = (device) => {

    if (this.state.selectedAccount === null) {
      this.setState({ error: this.context.t('accountSelectionRequired') })
    }

    this.props.unlockHardwareWalletAccount(this.state.selectedAccount, device)
    .then(_ => {
      this.context.metricsEvent({
        eventOpts: {
          category: 'Accounts',
          action: 'Connected Hardware Wallet',
          name: 'Connected Account with: ' + device,
        },
      })
      this.props.history.push(DEFAULT_ROUTE)
    }).catch(e => {
      this.context.metricsEvent({
        eventOpts: {
          category: 'Accounts',
          action: 'Connected Hardware Wallet',
          name: 'Error connecting hardware wallet',
        },
        customVariables: {
          error: e.toString(),
        },
      })
      this.setState({ error: e.toString() })
    })
  }

  onCancel = () => {
    this.props.history.push(DEFAULT_ROUTE)
  }

  renderError () {
    return this.state.error
      ? h('span.error', { style: { margin: '20px 20px 10px', display: 'block', textAlign: 'center' } }, this.state.error)
      : null
  }

  renderContent () {
    if (!this.state.accounts.length) {
      return h(ConnectScreen, {
        connectToHardwareWallet: this.connectToHardwareWallet,
        browserSupported: this.state.browserSupported,
      })
    }

    return h(AccountList, {
      onPathChange: this.onPathChange,
      selectedPath: this.props.defaultHdPaths[this.state.device],
      device: this.state.device,
      accounts: this.state.accounts,
      selectedAccount: this.state.selectedAccount,
      onAccountChange: this.onAccountChange,
      network: this.props.network,
      getPage: this.getPage,
      history: this.props.history,
      onUnlockAccount: this.onUnlockAccount,
      onForgetDevice: this.onForgetDevice,
      onCancel: this.onCancel,
      onAccountRestriction: this.onAccountRestriction,
    })
  }

  render () {
    return h('div', [
      this.renderError(),
      this.renderContent(),
    ])
  }
}

ConnectHardwareForm.propTypes = {
  hideModal: PropTypes.func,
  showImportPage: PropTypes.func,
  showConnectPage: PropTypes.func,
  connectHardware: PropTypes.func,
  checkHardwareStatus: PropTypes.func,
  forgetDevice: PropTypes.func,
  showAlert: PropTypes.func,
  hideAlert: PropTypes.func,
  unlockHardwareWalletAccount: PropTypes.func,
  setHardwareWalletDefaultHdPath: PropTypes.func,
  numberOfExistingAccounts: PropTypes.number,
  history: PropTypes.object,
  t: PropTypes.func,
  network: PropTypes.string,
  accounts: PropTypes.object,
  address: PropTypes.string,
  defaultHdPaths: PropTypes.object,
}

const mapStateToProps = state => {
  const {
    metamask: { network, selectedAddress, identities = {} },
  } = state
  const accounts = getMetaMaskAccounts(state)
  const numberOfExistingAccounts = Object.keys(identities).length
  const {
    appState: { defaultHdPaths },
  } = state

  return {
    network,
    accounts,
    address: selectedAddress,
    numberOfExistingAccounts,
    defaultHdPaths,
  }
}

const mapDispatchToProps = dispatch => {
  return {
    setHardwareWalletDefaultHdPath: ({device, path}) => {
      return dispatch(actions.setHardwareWalletDefaultHdPath({device, path}))
    },
    connectHardware: (deviceName, page, hdPath) => {
      return dispatch(actions.connectHardware(deviceName, page, hdPath))
    },
    checkHardwareStatus: (deviceName, hdPath) => {
      return dispatch(actions.checkHardwareStatus(deviceName, hdPath))
    },
    forgetDevice: (deviceName) => {
      return dispatch(actions.forgetDevice(deviceName))
    },
    unlockHardwareWalletAccount: (index, deviceName, hdPath) => {
      return dispatch(actions.unlockHardwareWalletAccount(index, deviceName, hdPath))
    },
    showImportPage: () => dispatch(actions.showImportPage()),
    showConnectPage: () => dispatch(actions.showConnectPage()),
    showAlert: (msg) => dispatch(actions.showAlert(msg)),
    hideAlert: () => dispatch(actions.hideAlert()),
  }
}

ConnectHardwareForm.contextTypes = {
  t: PropTypes.func,
  metricsEvent: PropTypes.func,
}

module.exports = connect(mapStateToProps, mapDispatchToProps)(
  ConnectHardwareForm
)