1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-04 23:14:56 +01:00
metamask-extension/ui/pages/create-account/connect-hardware/index.js

372 lines
11 KiB
JavaScript
Raw Normal View History

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as actions from '../../../store/actions';
import {
getCurrentChainId,
getMetaMaskAccounts,
getRpcPrefsForCurrentProvider,
getMetaMaskAccountsConnected,
} from '../../../selectors';
import { formatBalance } from '../../../helpers/utils/util';
import { getMostRecentOverviewPage } from '../../../ducks/history/history';
import { SECOND } from '../../../../shared/constants/time';
import SelectHardware from './select-hardware';
import AccountList from './account-list';
2018-07-05 23:45:28 +02:00
const U2F_ERROR = 'U2F';
const LEDGER_LIVE_PATH = `m/44'/60'/0'/0/0`;
const MEW_PATH = `m/44'/60'/0'`;
const BIP44_PATH = `m/44'/60'/0'/0`;
const HD_PATHS = [
{ name: 'Ledger Live', value: LEDGER_LIVE_PATH },
{ name: 'Legacy (MEW / MyCrypto)', value: MEW_PATH },
{ name: `BIP44 Standard (e.g. MetaMask, Trezor)`, value: BIP44_PATH },
];
2018-07-05 23:45:28 +02:00
class ConnectHardwareForm extends Component {
state = {
error: null,
selectedAccounts: [],
accounts: [],
browserSupported: true,
unlocked: false,
device: null,
};
2018-07-05 23:45:28 +02:00
2020-11-03 00:41:28 +01:00
UNSAFE_componentWillReceiveProps(nextProps) {
const { accounts } = nextProps;
2020-02-15 21:34:12 +01:00
const newAccounts = this.state.accounts.map((a) => {
const normalizedAddress = a.address.toLowerCase();
const balanceValue = accounts[normalizedAddress]?.balance || null;
a.balance = balanceValue ? formatBalance(balanceValue, 6) : '...';
return a;
});
this.setState({ accounts: newAccounts });
2018-07-13 06:09:42 +02:00
}
2020-11-03 00:41:28 +01:00
componentDidMount() {
this.checkIfUnlocked();
}
2020-11-03 00:41:28 +01:00
async checkIfUnlocked() {
for (const device of ['trezor', 'ledger']) {
const path = this.props.defaultHdPaths[device];
const unlocked = await this.props.checkHardwareStatus(device, path);
if (unlocked) {
this.setState({ unlocked: true });
this.getPage(device, 0, path);
}
}
}
connectToHardwareWallet = (device) => {
this.setState({ device });
2018-07-05 23:45:28 +02:00
if (this.state.accounts.length) {
return;
2018-07-05 23:45:28 +02:00
}
2018-08-14 01:29:43 +02:00
// Default values
this.getPage(device, 0, this.props.defaultHdPaths[device]);
};
2018-08-14 01:29:43 +02:00
onPathChange = (path) => {
2020-11-03 00:41:28 +01:00
this.props.setHardwareWalletDefaultHdPath({
device: this.state.device,
path,
});
this.setState({
selectedAccounts: [],
});
this.getPage(this.state.device, 0, path);
};
2018-07-05 23:45:28 +02:00
onAccountChange = (account) => {
let { selectedAccounts } = this.state;
if (selectedAccounts.includes(account)) {
selectedAccounts = selectedAccounts.filter((acc) => account !== acc);
} else {
selectedAccounts.push(account);
}
this.setState({ selectedAccounts, error: null });
};
2018-07-05 23:45:28 +02:00
2018-08-14 07:26:18 +02:00
onAccountRestriction = () => {
this.setState({ error: this.context.t('ledgerAccountRestriction') });
};
2018-08-14 07:26:18 +02:00
2020-11-03 00:41:28 +01:00
showTemporaryAlert() {
this.props.showAlert(this.context.t('hardwareWalletConnected'));
2018-07-19 08:31:13 +02:00
// Autohide the alert after 5 seconds
2020-02-15 21:34:12 +01:00
setTimeout((_) => {
this.props.hideAlert();
}, SECOND * 5);
2018-07-19 08:31:13 +02:00
}
2018-08-14 07:26:18 +02:00
getPage = (device, page, hdPath) => {
2018-07-05 23:45:28 +02:00
this.props
2018-08-14 01:29:43 +02:00
.connectHardware(device, page, hdPath)
2020-02-15 21:34:12 +01:00
.then((accounts) => {
2018-07-05 23:45:28 +02:00
if (accounts.length) {
2018-07-19 08:31:13 +02:00
// 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();
2018-07-19 08:31:13 +02:00
}
2018-07-09 23:24:52 +02:00
// Map accounts with balances
const newAccounts = accounts.map((account) => {
const normalizedAddress = account.address.toLowerCase();
2020-11-03 00:41:28 +01:00
const balanceValue =
this.props.accounts[normalizedAddress]?.balance || null;
2020-11-03 00:41:28 +01:00
account.balance = balanceValue
? formatBalance(balanceValue, 6)
: '...';
return account;
});
2018-07-09 23:24:52 +02:00
this.setState({
accounts: newAccounts,
unlocked: true,
device,
error: null,
});
2018-07-05 23:45:28 +02:00
}
})
2020-02-15 21:34:12 +01:00
.catch((e) => {
const errorMessage = typeof e === 'string' ? e : e.message;
if (errorMessage === 'Window blocked') {
this.setState({ browserSupported: false, error: null });
} else if (errorMessage.includes(U2F_ERROR)) {
this.setState({ error: U2F_ERROR });
2021-04-26 20:05:48 +02:00
} else if (
errorMessage === 'LEDGER_LOCKED' ||
errorMessage === 'LEDGER_WRONG_APP'
) {
this.setState({
error: this.context.t('ledgerLocked'),
});
} else if (errorMessage.includes('timeout')) {
this.setState({
error: this.context.t('ledgerTimeout'),
});
2020-11-03 00:41:28 +01:00
} else if (
errorMessage !== 'Window closed' &&
errorMessage !== 'Popup closed'
) {
2021-04-26 20:05:48 +02:00
this.setState({
error: errorMessage,
});
}
});
};
2018-07-05 23:45:28 +02:00
onForgetDevice = (device) => {
2020-11-03 00:41:28 +01:00
this.props
.forgetDevice(device)
2020-02-15 21:34:12 +01:00
.then((_) => {
this.setState({
error: null,
selectedAccounts: [],
accounts: [],
unlocked: false,
});
2020-11-03 00:41:28 +01:00
})
.catch((e) => {
this.setState({ error: e.message });
});
};
onUnlockAccounts = (device, path) => {
2020-11-03 00:41:28 +01:00
const {
history,
mostRecentOverviewPage,
unlockHardwareWalletAccounts,
} = this.props;
const { selectedAccounts } = this.state;
2018-07-06 02:59:31 +02:00
if (selectedAccounts.length === 0) {
this.setState({ error: this.context.t('accountSelectionRequired') });
2018-07-05 23:45:28 +02:00
}
2018-07-06 02:59:31 +02:00
const description =
MEW_PATH === path
? this.context.t('hardwareWalletLegacyDescription')
: '';
return unlockHardwareWalletAccounts(
selectedAccounts,
device,
path || null,
description,
)
2020-02-15 21:34:12 +01:00
.then((_) => {
this.context.metricsEvent({
eventOpts: {
category: 'Accounts',
action: 'Connected Hardware Wallet',
name: `Connected Account with: ${device}`,
},
});
history.push(mostRecentOverviewPage);
2020-11-03 00:41:28 +01:00
})
.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 });
});
};
2018-07-05 23:45:28 +02:00
2018-07-06 02:59:31 +02:00
onCancel = () => {
const { history, mostRecentOverviewPage } = this.props;
history.push(mostRecentOverviewPage);
};
2018-07-05 23:45:28 +02:00
2020-11-03 00:41:28 +01:00
renderError() {
if (this.state.error === U2F_ERROR) {
return (
2020-11-03 00:41:28 +01:00
<p className="hw-connect__error">
{this.context.t('troubleConnectingToWallet', [
this.state.device,
// eslint-disable-next-line react/jsx-key
<a
href="https://metamask.zendesk.com/hc/en-us/articles/360020394612-How-to-connect-a-Trezor-or-Ledger-Hardware-Wallet"
key="hardware-connection-guide"
target="_blank"
rel="noopener noreferrer"
className="hw-connect__link"
style={{ marginLeft: '5px', marginRight: '5px' }}
>
{this.context.t('walletConnectionGuide')}
2020-11-03 00:41:28 +01:00
</a>,
])}
</p>
);
}
2020-11-03 00:41:28 +01:00
return this.state.error ? (
<span className="hw-connect__error">{this.state.error}</span>
) : null;
2018-07-05 23:45:28 +02:00
}
2020-11-03 00:41:28 +01:00
renderContent() {
2018-07-05 23:45:28 +02:00
if (!this.state.accounts.length) {
return (
<SelectHardware
connectToHardwareWallet={this.connectToHardwareWallet}
browserSupported={this.state.browserSupported}
2021-04-26 20:05:48 +02:00
useLedgerLive={this.props.useLedgerLive}
/>
);
2018-07-05 23:45:28 +02:00
}
return (
<AccountList
onPathChange={this.onPathChange}
selectedPath={this.props.defaultHdPaths[this.state.device]}
device={this.state.device}
accounts={this.state.accounts}
connectedAccounts={this.props.connectedAccounts}
selectedAccounts={this.state.selectedAccounts}
onAccountChange={this.onAccountChange}
chainId={this.props.chainId}
rpcPrefs={this.props.rpcPrefs}
getPage={this.getPage}
onUnlockAccounts={this.onUnlockAccounts}
onForgetDevice={this.onForgetDevice}
onCancel={this.onCancel}
onAccountRestriction={this.onAccountRestriction}
hdPaths={HD_PATHS}
/>
);
2018-07-05 23:45:28 +02:00
}
2020-11-03 00:41:28 +01:00
render() {
return (
<>
{this.renderError()}
{this.renderContent()}
</>
);
2018-07-05 23:45:28 +02:00
}
}
ConnectHardwareForm.propTypes = {
connectHardware: PropTypes.func,
checkHardwareStatus: PropTypes.func,
forgetDevice: PropTypes.func,
2018-07-19 08:31:13 +02:00
showAlert: PropTypes.func,
hideAlert: PropTypes.func,
unlockHardwareWalletAccounts: PropTypes.func,
2018-08-14 01:29:43 +02:00
setHardwareWalletDefaultHdPath: PropTypes.func,
2018-07-05 23:45:28 +02:00
history: PropTypes.object,
chainId: PropTypes.string,
rpcPrefs: PropTypes.object,
2018-07-05 23:45:28 +02:00
accounts: PropTypes.object,
connectedAccounts: PropTypes.array.isRequired,
2018-08-14 01:29:43 +02:00
defaultHdPaths: PropTypes.object,
mostRecentOverviewPage: PropTypes.string.isRequired,
2021-04-26 20:05:48 +02:00
useLedgerLive: PropTypes.bool.isRequired,
};
2018-07-05 23:45:28 +02:00
const mapStateToProps = (state) => ({
chainId: getCurrentChainId(state),
rpcPrefs: getRpcPrefsForCurrentProvider(state),
accounts: getMetaMaskAccounts(state),
connectedAccounts: getMetaMaskAccountsConnected(state),
defaultHdPaths: state.appState.defaultHdPaths,
mostRecentOverviewPage: getMostRecentOverviewPage(state),
2021-04-26 20:05:48 +02:00
useLedgerLive: state.metamask.useLedgerLive,
});
2018-07-05 23:45:28 +02:00
2020-02-15 21:34:12 +01:00
const mapDispatchToProps = (dispatch) => {
2018-07-05 23:45:28 +02:00
return {
2019-12-03 21:50:55 +01:00
setHardwareWalletDefaultHdPath: ({ device, path }) => {
return dispatch(actions.setHardwareWalletDefaultHdPath({ device, path }));
2018-08-14 01:29:43 +02:00
},
connectHardware: (deviceName, page, hdPath) => {
return dispatch(actions.connectHardware(deviceName, page, hdPath));
2018-07-05 23:45:28 +02:00
},
2018-08-14 01:29:43 +02:00
checkHardwareStatus: (deviceName, hdPath) => {
return dispatch(actions.checkHardwareStatus(deviceName, hdPath));
},
forgetDevice: (deviceName) => {
return dispatch(actions.forgetDevice(deviceName));
},
unlockHardwareWalletAccounts: (
indexes,
deviceName,
hdPath,
hdPathDescription,
) => {
2020-11-03 00:41:28 +01:00
return dispatch(
actions.unlockHardwareWalletAccounts(
indexes,
deviceName,
hdPath,
hdPathDescription,
),
);
2018-07-05 23:45:28 +02:00
},
2018-07-19 08:31:13 +02:00
showAlert: (msg) => dispatch(actions.showAlert(msg)),
hideAlert: () => dispatch(actions.hideAlert()),
};
};
2018-07-05 23:45:28 +02:00
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
2019-03-05 16:45:01 +01:00
metricsEvent: PropTypes.func,
};
2018-07-05 23:45:28 +02:00
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ConnectHardwareForm);