A Metamask fork with Infura removed and default networks editable
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ciphermask/ui/app/pages/create-account/connect-hardware/index.js

287 lines
8.5 KiB

6 years ago
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')
6 years ago
const ConnectScreen = require('./connect-screen')
const AccountList = require('./account-list')
const { DEFAULT_ROUTE } = require('../../../helpers/constants/routes')
const { formatBalance } = require('../../../helpers/utils/util')
6 years ago
class ConnectHardwareForm extends Component {
constructor (props) {
6 years ago
super(props)
this.state = {
error: null,
6 years ago
selectedAccount: null,
6 years ago
accounts: [],
browserSupported: true,
unlocked: false,
device: null,
6 years ago
}
}
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) => {
6 years ago
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)
6 years ago
}
onAccountChange = (account) => {
6 years ago
this.setState({selectedAccount: account.toString(), error: null})
6 years ago
}
onAccountRestriction = () => {
this.setState({error: this.context.t('ledgerAccountRestriction') })
}
6 years ago
showTemporaryAlert () {
this.props.showAlert(this.context.t('hardwareWalletConnected'))
// Autohide the alert after 5 seconds
setTimeout(_ => {
this.props.hideAlert()
}, 5000)
}
getPage = (device, page, hdPath) => {
6 years ago
this.props
.connectHardware(device, page, hdPath)
6 years ago
.then(accounts => {
if (accounts.length) {
6 years ago
// 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) {
6 years ago
this.showTemporaryAlert()
}
6 years ago
const newState = { unlocked: true, device, error: null }
6 years ago
// 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()
}
})
6 years ago
// 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) {
6 years ago
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
})
6 years ago
this.setState(newState)
6 years ago
}
})
.catch(e => {
const errorMessage = e.message
if (errorMessage === 'Window blocked') {
6 years ago
this.setState({ browserSupported: false, error: null})
} else if (errorMessage !== 'Window closed' && errorMessage !== 'Popup closed') {
this.setState({ error: errorMessage })
}
6 years ago
})
}
onForgetDevice = (device) => {
this.props.forgetDevice(device)
.then(_ => {
this.setState({
error: null,
selectedAccount: null,
accounts: [],
unlocked: false,
})
}).catch(e => {
this.setState({ error: e.message })
})
}
onUnlockAccount = (device) => {
6 years ago
if (this.state.selectedAccount === null) {
this.setState({ error: this.context.t('accountSelectionRequired') })
6 years ago
}
6 years ago
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.message,
},
})
this.setState({ error: e.message })
Metametrics (#6171) * Add metametrics provider and util. * Add backend api and state for participating in metametrics. * Add frontend action for participating in metametrics. * Add metametrics opt-in screen. * Add metametrics events to first time flow. * Add metametrics events for route changes * Add metametrics events for send and confirm screens * Add metametrics events to dropdowns, transactions, log in and out, settings, sig requests and main screen * Ensures each log in is measured as a new visit by metametrics. * Ensure metametrics is called with an empty string for dimensions params if specified * Adds opt in metametrics modal after unlock for existing users * Adds settings page toggle for opting in and out of MetaMetrics * Switch metametrics dimensions to page level scope * Lint, test and translation fixes for metametrics. * Update design for metametrics opt-in screen * Complete responsive styling of metametrics-opt-in modal * Use new chart image on metrics opt in screens * Incorporate the metametrics opt-in screen into the new onboarding flow * Update e2e tests to accomodate metametrics changes * Mock out metametrics network requests in integration tests * Fix tx-list integration test to support metametrics provider. * Send number of tokens and accounts data with every metametrics event. * Update metametrics event descriptor schema and add new events. * Fix import tos bug and send gas button bug due to metametrics changes. * Various small fixes on the metametrics branch. * Add origin custom variable type to metametrics.util * Fix names of onboarding complete actions (metametrics). * Fix names of Metrics Options actions (metametrics). * Clean up code related to metametrics. * Fix bad merge conflict resolution and improve promise handling in sendMetaMetrics event and confrim tx base * Don't send a second metrics event if user has gone back during first time flow. * Collect metametrics on going back from onboarding create/import. * Add missing custom variable constants for metametrics * Fix metametrics provider * Make height of opt-in modal responsive. * Adjust text content for opt-in modal. * Update metametrics event names and clean up code in opt-in-modal * Put phishing warning step next to last in onboarding flow * Link terms of service on create and import screens of first time flow * Add subtext to options on the onboarding select action screen. * Fix styling of bullet points on end of onboarding screen. * Combine phishing warning and congratulations screens. * Fix placement of users if unlocking after an incomplete onboarding import flow. * Fix capitalization in opt-in screen * Fix last onboarding screen translations * Add link to 'Learn More' on the last screen of onboarding * Code clean up: metametrics branch * Update e2e tests for phishing warning step removal * e2e tests passing on metametrics branch * Different tracking urls for metametrics on development and prod
6 years ago
})
6 years ago
}
6 years ago
onCancel = () => {
this.props.history.push(DEFAULT_ROUTE)
}
6 years ago
renderError () {
return this.state.error
? h('span.error', { style: { margin: '20px 20px 10px', display: 'block', textAlign: 'center' } }, this.state.error)
6 years ago
: null
}
renderContent () {
if (!this.state.accounts.length) {
return h(ConnectScreen, {
connectToHardwareWallet: this.connectToHardwareWallet,
browserSupported: this.state.browserSupported,
6 years ago
})
}
return h(AccountList, {
onPathChange: this.onPathChange,
selectedPath: this.props.defaultHdPaths[this.state.device],
device: this.state.device,
6 years ago
accounts: this.state.accounts,
6 years ago
selectedAccount: this.state.selectedAccount,
6 years ago
onAccountChange: this.onAccountChange,
network: this.props.network,
getPage: this.getPage,
history: this.props.history,
6 years ago
onUnlockAccount: this.onUnlockAccount,
onForgetDevice: this.onForgetDevice,
6 years ago
onCancel: this.onCancel,
onAccountRestriction: this.onAccountRestriction,
6 years ago
})
}
render () {
return h('div', [
6 years ago
this.renderError(),
this.renderContent(),
])
}
}
ConnectHardwareForm.propTypes = {
hideModal: PropTypes.func,
showImportPage: PropTypes.func,
showConnectPage: PropTypes.func,
connectHardware: PropTypes.func,
checkHardwareStatus: PropTypes.func,
forgetDevice: PropTypes.func,
6 years ago
showAlert: PropTypes.func,
hideAlert: PropTypes.func,
unlockHardwareWalletAccount: PropTypes.func,
setHardwareWalletDefaultHdPath: PropTypes.func,
6 years ago
numberOfExistingAccounts: PropTypes.number,
history: PropTypes.object,
t: PropTypes.func,
network: PropTypes.string,
accounts: PropTypes.object,
address: PropTypes.string,
defaultHdPaths: PropTypes.object,
6 years ago
}
const mapStateToProps = state => {
const {
metamask: { network, selectedAddress, identities = {} },
6 years ago
} = state
const accounts = getMetaMaskAccounts(state)
6 years ago
const numberOfExistingAccounts = Object.keys(identities).length
const {
appState: { defaultHdPaths },
} = state
6 years ago
return {
network,
accounts,
address: selectedAddress,
numberOfExistingAccounts,
defaultHdPaths,
6 years ago
}
}
const mapDispatchToProps = dispatch => {
return {
setHardwareWalletDefaultHdPath: ({device, path}) => {
return dispatch(actions.setHardwareWalletDefaultHdPath({device, path}))
},
connectHardware: (deviceName, page, hdPath) => {
return dispatch(actions.connectHardware(deviceName, page, hdPath))
6 years ago
},
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))
6 years ago
},
showImportPage: () => dispatch(actions.showImportPage()),
showConnectPage: () => dispatch(actions.showConnectPage()),
6 years ago
showAlert: (msg) => dispatch(actions.showAlert(msg)),
hideAlert: () => dispatch(actions.hideAlert()),
6 years ago
}
}
ConnectHardwareForm.contextTypes = {
t: PropTypes.func,
Metametrics (#6171) * Add metametrics provider and util. * Add backend api and state for participating in metametrics. * Add frontend action for participating in metametrics. * Add metametrics opt-in screen. * Add metametrics events to first time flow. * Add metametrics events for route changes * Add metametrics events for send and confirm screens * Add metametrics events to dropdowns, transactions, log in and out, settings, sig requests and main screen * Ensures each log in is measured as a new visit by metametrics. * Ensure metametrics is called with an empty string for dimensions params if specified * Adds opt in metametrics modal after unlock for existing users * Adds settings page toggle for opting in and out of MetaMetrics * Switch metametrics dimensions to page level scope * Lint, test and translation fixes for metametrics. * Update design for metametrics opt-in screen * Complete responsive styling of metametrics-opt-in modal * Use new chart image on metrics opt in screens * Incorporate the metametrics opt-in screen into the new onboarding flow * Update e2e tests to accomodate metametrics changes * Mock out metametrics network requests in integration tests * Fix tx-list integration test to support metametrics provider. * Send number of tokens and accounts data with every metametrics event. * Update metametrics event descriptor schema and add new events. * Fix import tos bug and send gas button bug due to metametrics changes. * Various small fixes on the metametrics branch. * Add origin custom variable type to metametrics.util * Fix names of onboarding complete actions (metametrics). * Fix names of Metrics Options actions (metametrics). * Clean up code related to metametrics. * Fix bad merge conflict resolution and improve promise handling in sendMetaMetrics event and confrim tx base * Don't send a second metrics event if user has gone back during first time flow. * Collect metametrics on going back from onboarding create/import. * Add missing custom variable constants for metametrics * Fix metametrics provider * Make height of opt-in modal responsive. * Adjust text content for opt-in modal. * Update metametrics event names and clean up code in opt-in-modal * Put phishing warning step next to last in onboarding flow * Link terms of service on create and import screens of first time flow * Add subtext to options on the onboarding select action screen. * Fix styling of bullet points on end of onboarding screen. * Combine phishing warning and congratulations screens. * Fix placement of users if unlocking after an incomplete onboarding import flow. * Fix capitalization in opt-in screen * Fix last onboarding screen translations * Add link to 'Learn More' on the last screen of onboarding * Code clean up: metametrics branch * Update e2e tests for phishing warning step removal * e2e tests passing on metametrics branch * Different tracking urls for metametrics on development and prod
6 years ago
metricsEvent: PropTypes.func,
6 years ago
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(
ConnectHardwareForm
)