1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-22 01:47:00 +01:00

Convert shared/constants/hardware-wallets.js -> Typescript (#17310)

This commit is contained in:
ryanml 2023-01-20 08:14:40 -07:00 committed by GitHub
parent c744f2d0cf
commit a19a5d60d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 339 additions and 314 deletions

View File

@ -1,5 +1,5 @@
import { draftTransactionInitialState } from '../ui/ducks/send'; import { draftTransactionInitialState } from '../ui/ducks/send';
import { KEYRING_TYPES } from '../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../shared/constants/hardware-wallets';
const state = { const state = {
invalidCustomNetwork: { invalidCustomNetwork: {
@ -1163,14 +1163,14 @@ const state = {
unapprovedTypedMessages: {}, unapprovedTypedMessages: {},
unapprovedTypedMessagesCount: 0, unapprovedTypedMessagesCount: 0,
keyringTypes: [ keyringTypes: [
KEYRING_TYPES.IMPORTED, HardwareKeyringTypes.imported,
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
KEYRING_TYPES.LEDGER, HardwareKeyringTypes.ledger,
], ],
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: [ accounts: [
'0x64a845a5b02460acf8a3d84503b0d68d028b4bb4', '0x64a845a5b02460acf8a3d84503b0d68d028b4bb4',
'0xb19ac54efa18cc3a14a5b821bfec73d284bf0c5e', '0xb19ac54efa18cc3a14a5b821bfec73d284bf0c5e',

View File

@ -3,7 +3,7 @@ import { normalize as normalizeAddress } from 'eth-sig-util';
import { ethers } from 'ethers'; import { ethers } from 'ethers';
import { IPFS_DEFAULT_GATEWAY_URL } from '../../../shared/constants/network'; import { IPFS_DEFAULT_GATEWAY_URL } from '../../../shared/constants/network';
import { isPrefixedFormattedHexString } from '../../../shared/modules/network.utils'; import { isPrefixedFormattedHexString } from '../../../shared/modules/network.utils';
import { LEDGER_TRANSPORT_TYPES } from '../../../shared/constants/hardware-wallets'; import { LedgerTransportTypes } from '../../../shared/constants/hardware-wallets';
import { THEME_TYPE } from '../../../ui/pages/settings/settings-tab/settings-tab.constant'; import { THEME_TYPE } from '../../../ui/pages/settings/settings-tab/settings-tab.constant';
import { NETWORK_EVENTS } from './network'; import { NETWORK_EVENTS } from './network';
@ -64,8 +64,8 @@ export default class PreferencesController {
ipfsGateway: IPFS_DEFAULT_GATEWAY_URL, ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,
infuraBlocked: null, infuraBlocked: null,
ledgerTransportType: window.navigator.hid ledgerTransportType: window.navigator.hid
? LEDGER_TRANSPORT_TYPES.WEBHID ? LedgerTransportTypes.webhid
: LEDGER_TRANSPORT_TYPES.U2F, : LedgerTransportTypes.u2f,
improvedTokenAllowanceEnabled: false, improvedTokenAllowanceEnabled: false,
transactionSecurityCheckEnabled: false, transactionSecurityCheckEnabled: false,
theme: THEME_TYPE.OS, theme: THEME_TYPE.OS,

View File

@ -1,7 +1,7 @@
import KeyringController from 'eth-keyring-controller'; import KeyringController from 'eth-keyring-controller';
import log from 'loglevel'; import log from 'loglevel';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
const seedPhraseVerifier = { const seedPhraseVerifier = {
/** /**
@ -23,7 +23,7 @@ const seedPhraseVerifier = {
const keyringController = new KeyringController({}); const keyringController = new KeyringController({});
const Keyring = keyringController.getKeyringClassForType( const Keyring = keyringController.getKeyringClassForType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
const opts = { const opts = {
mnemonic: seedPhrase, mnemonic: seedPhrase,

View File

@ -6,13 +6,13 @@ import { cloneDeep } from 'lodash';
import KeyringController from 'eth-keyring-controller'; import KeyringController from 'eth-keyring-controller';
import firstTimeState from '../first-time-state'; import firstTimeState from '../first-time-state';
import mockEncryptor from '../../../test/lib/mock-encryptor'; import mockEncryptor from '../../../test/lib/mock-encryptor';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
import seedPhraseVerifier from './seed-phrase-verifier'; import seedPhraseVerifier from './seed-phrase-verifier';
describe('SeedPhraseVerifier', () => { describe('SeedPhraseVerifier', () => {
describe('verifyAccounts', () => { describe('verifyAccounts', () => {
const password = 'passw0rd1'; const password = 'passw0rd1';
const hdKeyTree = KEYRING_TYPES.HD_KEY_TREE; const { hdKeyTree } = HardwareKeyringTypes;
let keyringController; let keyringController;
let primaryKeyring; let primaryKeyring;

View File

@ -69,9 +69,11 @@ import {
GAS_DEV_API_BASE_URL, GAS_DEV_API_BASE_URL,
SWAPS_CLIENT_ID, SWAPS_CLIENT_ID,
} from '../../shared/constants/swaps'; } from '../../shared/constants/swaps';
import { KEYRING_TYPES } from '../../shared/constants/keyrings';
import { CHAIN_IDS } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { DEVICE_NAMES } from '../../shared/constants/hardware-wallets'; import {
HardwareDeviceNames,
HardwareKeyringTypes,
} from '../../shared/constants/hardware-wallets';
import { import {
CaveatTypes, CaveatTypes,
RestrictedMethods, RestrictedMethods,
@ -2272,7 +2274,7 @@ export default class MetamaskController extends EventEmitter {
); );
const [primaryKeyring] = keyringController.getKeyringsByType( const [primaryKeyring] = keyringController.getKeyringsByType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
if (!primaryKeyring) { if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found'); throw new Error('MetamaskController - No HD Key Tree found');
@ -2399,10 +2401,10 @@ export default class MetamaskController extends EventEmitter {
// Accounts // Accounts
const [hdKeyring] = this.keyringController.getKeyringsByType( const [hdKeyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
const simpleKeyPairKeyrings = this.keyringController.getKeyringsByType( const simpleKeyPairKeyrings = this.keyringController.getKeyringsByType(
KEYRING_TYPES.IMPORTED, HardwareKeyringTypes.hdKeyTree,
); );
const hdAccounts = await hdKeyring.getAccounts(); const hdAccounts = await hdKeyring.getAccounts();
const simpleKeyPairKeyringAccounts = await Promise.all( const simpleKeyPairKeyringAccounts = await Promise.all(
@ -2563,7 +2565,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
getPrimaryKeyringMnemonic() { getPrimaryKeyringMnemonic() {
const [keyring] = this.keyringController.getKeyringsByType( const [keyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
if (!keyring.mnemonic) { if (!keyring.mnemonic) {
throw new Error('Primary keyring mnemonic unavailable.'); throw new Error('Primary keyring mnemonic unavailable.');
@ -2578,16 +2580,16 @@ export default class MetamaskController extends EventEmitter {
async getKeyringForDevice(deviceName, hdPath = null) { async getKeyringForDevice(deviceName, hdPath = null) {
let keyringName = null; let keyringName = null;
switch (deviceName) { switch (deviceName) {
case DEVICE_NAMES.TREZOR: case HardwareDeviceNames.trezor:
keyringName = TrezorKeyring.type; keyringName = TrezorKeyring.type;
break; break;
case DEVICE_NAMES.LEDGER: case HardwareDeviceNames.ledger:
keyringName = LedgerBridgeKeyring.type; keyringName = LedgerBridgeKeyring.type;
break; break;
case DEVICE_NAMES.QR: case HardwareDeviceNames.qr:
keyringName = QRHardwareKeyring.type; keyringName = QRHardwareKeyring.type;
break; break;
case DEVICE_NAMES.LATTICE: case HardwareDeviceNames.lattice:
keyringName = LatticeKeyring.type; keyringName = LatticeKeyring.type;
break; break;
default: default:
@ -2602,10 +2604,10 @@ export default class MetamaskController extends EventEmitter {
if (hdPath && keyring.setHdPath) { if (hdPath && keyring.setHdPath) {
keyring.setHdPath(hdPath); keyring.setHdPath(hdPath);
} }
if (deviceName === DEVICE_NAMES.LATTICE) { if (deviceName === HardwareDeviceNames.lattice) {
keyring.appName = 'MetaMask'; keyring.appName = 'MetaMask';
} }
if (deviceName === DEVICE_NAMES.TREZOR) { if (deviceName === HardwareDeviceNames.trezor) {
const model = keyring.getModel(); const model = keyring.getModel();
this.appStateController.setTrezorModel(model); this.appStateController.setTrezorModel(model);
} }
@ -2616,7 +2618,7 @@ export default class MetamaskController extends EventEmitter {
} }
async attemptLedgerTransportCreation() { async attemptLedgerTransportCreation() {
const keyring = await this.getKeyringForDevice(DEVICE_NAMES.LEDGER); const keyring = await this.getKeyringForDevice(HardwareDeviceNames.ledger);
return await keyring.attemptMakeApp(); return await keyring.attemptMakeApp();
} }
@ -2694,12 +2696,12 @@ export default class MetamaskController extends EventEmitter {
async getAccountType(address) { async getAccountType(address) {
const keyring = await this.keyringController.getKeyringForAccount(address); const keyring = await this.keyringController.getKeyringForAccount(address);
switch (keyring.type) { switch (keyring.type) {
case KEYRING_TYPES.TREZOR: case HardwareKeyringTypes.trezor:
case KEYRING_TYPES.LATTICE: case HardwareKeyringTypes.lattice:
case KEYRING_TYPES.QR: case HardwareKeyringTypes.qr:
case KEYRING_TYPES.LEDGER: case HardwareKeyringTypes.ledger:
return 'hardware'; return 'hardware';
case KEYRING_TYPES.IMPORTED: case HardwareKeyringTypes.imported:
return 'imported'; return 'imported';
default: default:
return 'MetaMask'; return 'MetaMask';
@ -2717,16 +2719,16 @@ export default class MetamaskController extends EventEmitter {
async getDeviceModel(address) { async getDeviceModel(address) {
const keyring = await this.keyringController.getKeyringForAccount(address); const keyring = await this.keyringController.getKeyringForAccount(address);
switch (keyring.type) { switch (keyring.type) {
case KEYRING_TYPES.TREZOR: case HardwareKeyringTypes.trezor:
return keyring.getModel(); return keyring.getModel();
case KEYRING_TYPES.QR: case HardwareKeyringTypes.qr:
return keyring.getName(); return keyring.getName();
case KEYRING_TYPES.LEDGER: case HardwareKeyringTypes.ledger:
// TODO: get model after ledger keyring exposes method // TODO: get model after ledger keyring exposes method
return DEVICE_NAMES.LEDGER; return HardwareDeviceNames.ledger;
case KEYRING_TYPES.LATTICE: case HardwareKeyringTypes.lattice:
// TODO: get model after lattice keyring exposes method // TODO: get model after lattice keyring exposes method
return DEVICE_NAMES.LATTICE; return HardwareDeviceNames.lattice;
default: default:
return 'N/A'; return 'N/A';
} }
@ -2769,7 +2771,9 @@ export default class MetamaskController extends EventEmitter {
newAccounts.forEach((address) => { newAccounts.forEach((address) => {
if (!oldAccounts.includes(address)) { if (!oldAccounts.includes(address)) {
const label = this.getAccountLabel( const label = this.getAccountLabel(
deviceName === DEVICE_NAMES.QR ? keyring.getName() : deviceName, deviceName === HardwareDeviceNames.qr
? keyring.getName()
: deviceName,
index, index,
hdPathDescription, hdPathDescription,
); );
@ -2796,7 +2800,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
async addNewAccount(accountCount) { async addNewAccount(accountCount) {
const [primaryKeyring] = this.keyringController.getKeyringsByType( const [primaryKeyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
if (!primaryKeyring) { if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found'); throw new Error('MetamaskController - No HD Key Tree found');
@ -2841,7 +2845,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
async verifySeedPhrase() { async verifySeedPhrase() {
const [primaryKeyring] = this.keyringController.getKeyringsByType( const [primaryKeyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.HD_KEY_TREE, HardwareKeyringTypes.hdKeyTree,
); );
if (!primaryKeyring) { if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found'); throw new Error('MetamaskController - No HD Key Tree found');
@ -2963,7 +2967,7 @@ export default class MetamaskController extends EventEmitter {
async importAccountWithStrategy(strategy, args) { async importAccountWithStrategy(strategy, args) {
const privateKey = await accountImporter.importAccount(strategy, args); const privateKey = await accountImporter.importAccount(strategy, args);
const keyring = await this.keyringController.addNewKeyring( const keyring = await this.keyringController.addNewKeyring(
KEYRING_TYPES.IMPORTED, HardwareKeyringTypes.imported,
[privateKey], [privateKey],
); );
const [firstAccount] = await keyring.getAccounts(); const [firstAccount] = await keyring.getAccounts();
@ -3246,7 +3250,7 @@ export default class MetamaskController extends EventEmitter {
const keyring = await this.keyringController.getKeyringForAccount(address); const keyring = await this.keyringController.getKeyringForAccount(address);
switch (keyring.type) { switch (keyring.type) {
case KEYRING_TYPES.LEDGER: { case HardwareKeyringTypes.ledger: {
return new Promise((_, reject) => { return new Promise((_, reject) => {
reject( reject(
new Error('Ledger does not support eth_getEncryptionPublicKey.'), new Error('Ledger does not support eth_getEncryptionPublicKey.'),
@ -3254,7 +3258,7 @@ export default class MetamaskController extends EventEmitter {
}); });
} }
case KEYRING_TYPES.TREZOR: { case HardwareKeyringTypes.trezor: {
return new Promise((_, reject) => { return new Promise((_, reject) => {
reject( reject(
new Error('Trezor does not support eth_getEncryptionPublicKey.'), new Error('Trezor does not support eth_getEncryptionPublicKey.'),
@ -3262,7 +3266,7 @@ export default class MetamaskController extends EventEmitter {
}); });
} }
case KEYRING_TYPES.LATTICE: { case HardwareKeyringTypes.lattice: {
return new Promise((_, reject) => { return new Promise((_, reject) => {
reject( reject(
new Error('Lattice does not support eth_getEncryptionPublicKey.'), new Error('Lattice does not support eth_getEncryptionPublicKey.'),
@ -3270,7 +3274,7 @@ export default class MetamaskController extends EventEmitter {
}); });
} }
case KEYRING_TYPES.QR: { case HardwareKeyringTypes.qr: {
return Promise.reject( return Promise.reject(
new Error('QR hardware does not support eth_getEncryptionPublicKey.'), new Error('QR hardware does not support eth_getEncryptionPublicKey.'),
); );
@ -4397,7 +4401,7 @@ export default class MetamaskController extends EventEmitter {
const newValue = const newValue =
this.preferencesController.setLedgerTransportPreference(transportType); this.preferencesController.setLedgerTransportPreference(transportType);
const keyring = await this.getKeyringForDevice(DEVICE_NAMES.LEDGER); const keyring = await this.getKeyringForDevice(HardwareDeviceNames.ledger);
if (keyring?.updateTransportMethod) { if (keyring?.updateTransportMethod) {
return keyring.updateTransportMethod(newValue).catch((e) => { return keyring.updateTransportMethod(newValue).catch((e) => {
// If there was an error updating the transport, we should // If there was an error updating the transport, we should
@ -4486,14 +4490,14 @@ export default class MetamaskController extends EventEmitter {
*/ */
setLocked() { setLocked() {
const [trezorKeyring] = this.keyringController.getKeyringsByType( const [trezorKeyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
); );
if (trezorKeyring) { if (trezorKeyring) {
trezorKeyring.dispose(); trezorKeyring.dispose();
} }
const [ledgerKeyring] = this.keyringController.getKeyringsByType( const [ledgerKeyring] = this.keyringController.getKeyringsByType(
KEYRING_TYPES.LEDGER, HardwareKeyringTypes.ledger,
); );
ledgerKeyring?.destroy?.(); ledgerKeyring?.destroy?.();

View File

@ -10,8 +10,10 @@ import browser from 'webextension-polyfill';
import { TransactionStatus } from '../../shared/constants/transaction'; import { TransactionStatus } from '../../shared/constants/transaction';
import createTxMeta from '../../test/lib/createTxMeta'; import createTxMeta from '../../test/lib/createTxMeta';
import { NETWORK_TYPES } from '../../shared/constants/network'; import { NETWORK_TYPES } from '../../shared/constants/network';
import { KEYRING_TYPES } from '../../shared/constants/keyrings'; import {
import { DEVICE_NAMES } from '../../shared/constants/hardware-wallets'; HardwareDeviceNames,
HardwareKeyringTypes,
} from '../../shared/constants/hardware-wallets';
import { addHexPrefix, deferredPromise } from './lib/util'; import { addHexPrefix, deferredPromise } from './lib/util';
const Ganache = require('../../test/e2e/ganache'); const Ganache = require('../../test/e2e/ganache');
@ -205,7 +207,7 @@ describe('MetaMaskController', function () {
it('adds private key to keyrings in KeyringController', async function () { it('adds private key to keyrings in KeyringController', async function () {
const simpleKeyrings = const simpleKeyrings =
metamaskController.keyringController.getKeyringsByType( metamaskController.keyringController.getKeyringsByType(
KEYRING_TYPES.IMPORTED, HardwareKeyringTypes.imported,
); );
const privKeyBuffer = simpleKeyrings[0].wallets[0].privateKey; const privKeyBuffer = simpleKeyrings[0].wallets[0].privateKey;
const pubKeyBuffer = simpleKeyrings[0].wallets[0].publicKey; const pubKeyBuffer = simpleKeyrings[0].wallets[0].publicKey;
@ -479,15 +481,15 @@ describe('MetaMaskController', function () {
it('should add the Trezor Hardware keyring', async function () { it('should add the Trezor Hardware keyring', async function () {
sinon.spy(metamaskController.keyringController, 'addNewKeyring'); sinon.spy(metamaskController.keyringController, 'addNewKeyring');
await metamaskController await metamaskController
.connectHardware(DEVICE_NAMES.TREZOR, 0) .connectHardware(HardwareDeviceNames.trezor, 0)
.catch(() => null); .catch(() => null);
const keyrings = const keyrings =
await metamaskController.keyringController.getKeyringsByType( await metamaskController.keyringController.getKeyringsByType(
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
); );
assert.deepEqual( assert.deepEqual(
metamaskController.keyringController.addNewKeyring.getCall(0).args, metamaskController.keyringController.addNewKeyring.getCall(0).args,
[KEYRING_TYPES.TREZOR], [HardwareKeyringTypes.trezor],
); );
assert.equal(keyrings.length, 1); assert.equal(keyrings.length, 1);
}); });
@ -495,15 +497,15 @@ describe('MetaMaskController', function () {
it('should add the Ledger Hardware keyring', async function () { it('should add the Ledger Hardware keyring', async function () {
sinon.spy(metamaskController.keyringController, 'addNewKeyring'); sinon.spy(metamaskController.keyringController, 'addNewKeyring');
await metamaskController await metamaskController
.connectHardware(DEVICE_NAMES.LEDGER, 0) .connectHardware(HardwareDeviceNames.ledger, 0)
.catch(() => null); .catch(() => null);
const keyrings = const keyrings =
await metamaskController.keyringController.getKeyringsByType( await metamaskController.keyringController.getKeyringsByType(
KEYRING_TYPES.LEDGER, HardwareKeyringTypes.ledger,
); );
assert.deepEqual( assert.deepEqual(
metamaskController.keyringController.addNewKeyring.getCall(0).args, metamaskController.keyringController.addNewKeyring.getCall(0).args,
[KEYRING_TYPES.LEDGER], [HardwareKeyringTypes.ledger],
); );
assert.equal(keyrings.length, 1); assert.equal(keyrings.length, 1);
}); });
@ -526,10 +528,10 @@ describe('MetaMaskController', function () {
it('should be locked by default', async function () { it('should be locked by default', async function () {
await metamaskController await metamaskController
.connectHardware(DEVICE_NAMES.TREZOR, 0) .connectHardware(HardwareDeviceNames.trezor, 0)
.catch(() => null); .catch(() => null);
const status = await metamaskController.checkHardwareStatus( const status = await metamaskController.checkHardwareStatus(
DEVICE_NAMES.TREZOR, HardwareDeviceNames.trezor,
); );
assert.equal(status, false); assert.equal(status, false);
}); });
@ -549,12 +551,12 @@ describe('MetaMaskController', function () {
it('should wipe all the keyring info', async function () { it('should wipe all the keyring info', async function () {
await metamaskController await metamaskController
.connectHardware(DEVICE_NAMES.TREZOR, 0) .connectHardware(HardwareDeviceNames.trezor, 0)
.catch(() => null); .catch(() => null);
await metamaskController.forgetDevice(DEVICE_NAMES.TREZOR); await metamaskController.forgetDevice(HardwareDeviceNames.trezor);
const keyrings = const keyrings =
await metamaskController.keyringController.getKeyringsByType( await metamaskController.keyringController.getKeyringsByType(
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
); );
assert.deepEqual(keyrings[0].accounts, []); assert.deepEqual(keyrings[0].accounts, []);
@ -593,11 +595,11 @@ describe('MetaMaskController', function () {
sinon.spy(metamaskController.preferencesController, 'setSelectedAddress'); sinon.spy(metamaskController.preferencesController, 'setSelectedAddress');
sinon.spy(metamaskController.preferencesController, 'setAccountLabel'); sinon.spy(metamaskController.preferencesController, 'setAccountLabel');
await metamaskController await metamaskController
.connectHardware(DEVICE_NAMES.TREZOR, 0, `m/44'/1'/0'/0`) .connectHardware(HardwareDeviceNames.trezor, 0, `m/44'/1'/0'/0`)
.catch(() => null); .catch(() => null);
await metamaskController.unlockHardwareWalletAccount( await metamaskController.unlockHardwareWalletAccount(
accountToUnlock, accountToUnlock,
DEVICE_NAMES.TREZOR, HardwareDeviceNames.trezor,
`m/44'/1'/0'/0`, `m/44'/1'/0'/0`,
); );
}); });
@ -614,7 +616,7 @@ describe('MetaMaskController', function () {
it('should set unlockedAccount in the keyring', async function () { it('should set unlockedAccount in the keyring', async function () {
const keyrings = const keyrings =
await metamaskController.keyringController.getKeyringsByType( await metamaskController.keyringController.getKeyringsByType(
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
); );
assert.equal(keyrings[0].unlockedAccount, accountToUnlock); assert.equal(keyrings[0].unlockedAccount, accountToUnlock);
}); });

View File

@ -1,5 +1,5 @@
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { LEDGER_TRANSPORT_TYPES } from '../../../shared/constants/hardware-wallets'; import { LedgerTransportTypes } from '../../../shared/constants/hardware-wallets';
const version = 66; const version = 66;
@ -20,15 +20,15 @@ export default {
function transformState(state) { function transformState(state) {
const defaultTransportType = window.navigator.hid const defaultTransportType = window.navigator.hid
? LEDGER_TRANSPORT_TYPES.WEBHID ? LedgerTransportTypes.webhid
: LEDGER_TRANSPORT_TYPES.U2F; : LedgerTransportTypes.u2f;
const useLedgerLive = Boolean(state.PreferencesController?.useLedgerLive); const useLedgerLive = Boolean(state.PreferencesController?.useLedgerLive);
const newState = { const newState = {
...state, ...state,
PreferencesController: { PreferencesController: {
...state?.PreferencesController, ...state?.PreferencesController,
ledgerTransportType: useLedgerLive ledgerTransportType: useLedgerLive
? LEDGER_TRANSPORT_TYPES.LIVE ? LedgerTransportTypes.live
: defaultTransportType, : defaultTransportType,
}, },
}; };

View File

@ -1,4 +1,4 @@
import { LEDGER_TRANSPORT_TYPES } from '../../../shared/constants/hardware-wallets'; import { LedgerTransportTypes } from '../../../shared/constants/hardware-wallets';
import migration66 from './066'; import migration66 from './066';
describe('migration #66', () => { describe('migration #66', () => {
@ -29,7 +29,7 @@ describe('migration #66', () => {
const newStorage = await migration66.migrate(oldStorage); const newStorage = await migration66.migrate(oldStorage);
expect( expect(
newStorage.data.PreferencesController.ledgerTransportType, newStorage.data.PreferencesController.ledgerTransportType,
).toStrictEqual(LEDGER_TRANSPORT_TYPES.U2F); ).toStrictEqual(LedgerTransportTypes.u2f);
}); });
it('should set ledgerTransportType to `u2f` if no useLedgerLive property exists and webhid is not available', async () => { it('should set ledgerTransportType to `u2f` if no useLedgerLive property exists and webhid is not available', async () => {
@ -43,7 +43,7 @@ describe('migration #66', () => {
const newStorage = await migration66.migrate(oldStorage); const newStorage = await migration66.migrate(oldStorage);
expect( expect(
newStorage.data.PreferencesController.ledgerTransportType, newStorage.data.PreferencesController.ledgerTransportType,
).toStrictEqual(LEDGER_TRANSPORT_TYPES.U2F); ).toStrictEqual(LedgerTransportTypes.u2f);
}); });
it('should set ledgerTransportType to `u2f` if useLedgerLive is false and webhid is not available', async () => { it('should set ledgerTransportType to `u2f` if useLedgerLive is false and webhid is not available', async () => {
@ -59,7 +59,7 @@ describe('migration #66', () => {
const newStorage = await migration66.migrate(oldStorage); const newStorage = await migration66.migrate(oldStorage);
expect( expect(
newStorage.data.PreferencesController.ledgerTransportType, newStorage.data.PreferencesController.ledgerTransportType,
).toStrictEqual(LEDGER_TRANSPORT_TYPES.U2F); ).toStrictEqual(LedgerTransportTypes.u2f);
}); });
it('should set ledgerTransportType to `webhid` if useLedgerLive is false and webhid is available', async () => { it('should set ledgerTransportType to `webhid` if useLedgerLive is false and webhid is available', async () => {
@ -77,7 +77,7 @@ describe('migration #66', () => {
const newStorage = await migration66.migrate(oldStorage); const newStorage = await migration66.migrate(oldStorage);
expect( expect(
newStorage.data.PreferencesController.ledgerTransportType, newStorage.data.PreferencesController.ledgerTransportType,
).toStrictEqual(LEDGER_TRANSPORT_TYPES.WEBHID); ).toStrictEqual(LedgerTransportTypes.webhid);
}); });
it('should set ledgerTransportType to `ledgerLive` if useLedgerLive is true', async () => { it('should set ledgerTransportType to `ledgerLive` if useLedgerLive is true', async () => {
@ -111,6 +111,6 @@ describe('migration #66', () => {
const newStorage = await migration66.migrate(oldStorage); const newStorage = await migration66.migrate(oldStorage);
expect( expect(
newStorage.data.PreferencesController.ledgerTransportType, newStorage.data.PreferencesController.ledgerTransportType,
).toStrictEqual(LEDGER_TRANSPORT_TYPES.LIVE); ).toStrictEqual(LedgerTransportTypes.live);
}); });
}); });

View File

@ -1,74 +0,0 @@
/**
* Accounts can be instantiated from simple, HD or the multiple hardware wallet
* keyring types. Both simple and HD are treated as default but we do special
* case accounts managed by a hardware wallet.
*/
export const HARDWARE_KEYRING_TYPES = {
LEDGER: 'Ledger Hardware',
TREZOR: 'Trezor Hardware',
LATTICE: 'Lattice Hardware',
QR: 'QR Hardware Wallet Device',
};
export const DEVICE_NAMES = {
LEDGER: 'ledger',
TREZOR: 'trezor',
QR: 'QR Hardware',
LATTICE: 'lattice',
};
export const KEYRING_NAMES = {
LEDGER: 'Ledger',
TREZOR: 'Trezor',
QR: 'QR',
LATTICE: 'Lattice1',
};
/**
* Used for setting the users preference for ledger transport type
*/
export const LEDGER_TRANSPORT_TYPES = {
LIVE: 'ledgerLive',
WEBHID: 'webhid',
U2F: 'u2f',
};
export const LEDGER_USB_VENDOR_ID = '0x2c97';
export const WEBHID_CONNECTED_STATUSES = {
CONNECTED: 'connected',
NOT_CONNECTED: 'notConnected',
UNKNOWN: 'unknown',
};
export const TRANSPORT_STATES = {
NONE: 'NONE',
VERIFIED: 'VERIFIED',
DEVICE_OPEN_FAILURE: 'DEVICE_OPEN_FAILURE',
UNKNOWN_FAILURE: 'UNKNOWN_FAILURE',
};
export const AFFILIATE_LINKS = {
LEDGER: 'https://shop.ledger.com/?r=17c4991a03fa',
GRIDPLUS: 'https://gridplus.io/?afmc=7p',
TREZOR:
'https://shop.trezor.io/product/trezor-one-black?offer_id=35&aff_id=11009',
KEYSTONE:
'https://shop.keyst.one/?rfsn=6088257.656b3e9&utm_source=refersion&utm_medium=affiliate&utm_campaign=6088257.656b3e9',
AIRGAP: 'https://airgap.it/',
COOLWALLET: 'https://www.coolwallet.io/',
DCENT: 'https://dcentwallet.com/',
};
export const AFFILIATE_TUTORIAL_LINKS = {
LEDGER:
'https://support.ledger.com/hc/en-us/articles/4404366864657-Set-up-and-use-MetaMask-to-access-your-Ledger-Ethereum-ETH-account?docs=true',
GRIDPLUS: 'https://docs.gridplus.io/setup/metamask',
TREZOR: 'https://wiki.trezor.io/Apps:MetaMask',
KEYSTONE:
'https://support.keyst.one/3rd-party-wallets/eth-and-web3-wallets-keystone/bind-metamask-with-keystone',
AIRGAP: 'https://support.airgap.it/guides/metamask/',
COOLWALLET: 'https://www.coolwallet.io/metamask-step-by-step-guides/',
DCENT:
'https://medium.com/dcentwallet/dcent-wallet-now-supports-qr-based-protocol-to-link-with-metamask-57555f02603f',
};

View File

@ -0,0 +1,71 @@
/**
* Accounts can be instantiated from simple, HD or the multiple hardware wallet
* keyring types. Both simple and HD are treated as default but we do special
* case accounts managed by a hardware wallet.
*/
export enum HardwareKeyringTypes {
ledger = 'Ledger Hardware',
trezor = 'Trezor Hardware',
lattice = 'Lattice Hardware',
qr = 'QR Hardware Wallet Device',
hdKeyTree = 'HD Key Tree',
imported = 'Simple Key Pair',
}
export enum HardwareKeyringNames {
ledger = 'Ledger',
trezor = 'Trezor',
lattice = 'Lattice1',
qr = 'QR',
}
export enum HardwareDeviceNames {
ledger = 'ledger',
trezor = 'trezor',
lattice = 'lattice',
qr = 'QR Hardware',
}
export enum HardwareTransportStates {
none = 'NONE',
verified = 'VERIFIED',
deviceOpenFailure = 'DEVICE_OPEN_FAILURE',
unknownFailure = 'UNKNOWN_FAILURE',
}
export enum HardwareAffiliateLinks {
ledger = 'https://shop.ledger.com/?r=17c4991a03fa',
gridplus = 'https://gridplus.io/?afmc=7p',
trezor = 'https://shop.trezor.io/product/trezor-one-black?offer_id=35&aff_id=11009',
keystone = 'https://shop.keyst.one/?rfsn=6088257.656b3e9&utm_source=refersion&utm_medium=affiliate&utm_campaign=6088257.656b3e9',
airgap = 'https://airgap.it/',
coolwallet = 'https://www.coolwallet.io/',
dcent = 'https://dcentwallet.com/',
}
export enum HardwareAffiliateTutorialLinks {
ledger = 'https://support.ledger.com/hc/en-us/articles/4404366864657-Set-up-and-use-MetaMask-to-access-your-Ledger-Ethereum-ETH-account?docs=true',
gridplus = 'https://docs.gridplus.io/setup/metamask',
trezor = 'https://wiki.trezor.io/Apps:MetaMask',
keystone = 'https://support.keyst.one/3rd-party-wallets/eth-and-web3-wallets-keystone/bind-metamask-with-keystone',
airgap = 'https://support.airgap.it/guides/metamask/',
coolwallet = 'https://www.coolwallet.io/metamask-step-by-step-guides/',
dcent = 'https://medium.com/dcentwallet/dcent-wallet-now-supports-qr-based-protocol-to-link-with-metamask-57555f02603f',
}
/**
* Used for setting the users preference for ledger transport type
*/
export enum LedgerTransportTypes {
live = 'ledgerLive',
webhid = 'webhid',
u2f = 'u2f',
}
export enum WebHIDConnectedStatuses {
connected = 'connected',
notConnected = 'notConnected',
unknown = 'unknown',
}
export const LEDGER_USB_VENDOR_ID = '0x2c97';

View File

@ -1,7 +0,0 @@
import { HARDWARE_KEYRING_TYPES } from './hardware-wallets';
export const KEYRING_TYPES = {
HD_KEY_TREE: 'HD Key Tree',
IMPORTED: 'Simple Key Pair',
...HARDWARE_KEYRING_TYPES,
};

View File

@ -1,5 +1,5 @@
import { CHAIN_IDS } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { KEYRING_TYPES } from '../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../shared/constants/hardware-wallets';
const createGetSmartTransactionFeesApiResponse = () => { const createGetSmartTransactionFeesApiResponse = () => {
return { return {
@ -253,10 +253,13 @@ export const createSwapsMockStore = () => {
}, },
}, },
selectedAddress: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', selectedAddress: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
keyringTypes: [KEYRING_TYPES.IMPORTED, KEYRING_TYPES.HD_KEY_TREE], keyringTypes: [
HardwareKeyringTypes.imported,
HardwareKeyringTypes.hdKeyTree,
],
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: [ accounts: [
'0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
'c5b8dbac4c1d3f152cdeb400e2313f309c410acb', 'c5b8dbac4c1d3f152cdeb400e2313f309c410acb',
@ -264,7 +267,7 @@ export const createSwapsMockStore = () => {
], ],
}, },
{ {
type: KEYRING_TYPES.IMPORTED, type: HardwareKeyringTypes.imported,
accounts: ['0xd85a4b6a394794842887b8284293d69163007bbb'], accounts: ['0xd85a4b6a394794842887b8284293d69163007bbb'],
}, },
], ],

View File

@ -3,7 +3,7 @@ import sinon from 'sinon';
import configureMockStore from 'redux-mock-store'; import configureMockStore from 'redux-mock-store';
import { fireEvent, screen } from '@testing-library/react'; import { fireEvent, screen } from '@testing-library/react';
import { renderWithProvider } from '../../../../test/lib/render-helpers'; import { renderWithProvider } from '../../../../test/lib/render-helpers';
import { KEYRING_TYPES } from '../../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../../shared/constants/hardware-wallets';
import AccountMenu from '.'; import AccountMenu from '.';
describe('Account Menu', () => { describe('Account Menu', () => {
@ -37,11 +37,11 @@ describe('Account Menu', () => {
], ],
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: ['0xAdress'], accounts: ['0xAdress'],
}, },
{ {
type: KEYRING_TYPES.IMPORTED, type: HardwareKeyringTypes.imported,
accounts: ['0x1'], accounts: ['0x1'],
}, },
], ],

View File

@ -2,8 +2,10 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useI18nContext } from '../../../hooks/useI18nContext'; import { useI18nContext } from '../../../hooks/useI18nContext';
import { KEYRING_TYPES } from '../../../../shared/constants/keyrings'; import {
import { KEYRING_NAMES } from '../../../../shared/constants/hardware-wallets'; HardwareKeyringNames,
HardwareKeyringTypes,
} from '../../../../shared/constants/hardware-wallets';
export default function KeyRingLabel({ keyring }) { export default function KeyRingLabel({ keyring }) {
const t = useI18nContext(); const t = useI18nContext();
@ -17,20 +19,20 @@ export default function KeyRingLabel({ keyring }) {
const { type } = keyring; const { type } = keyring;
switch (type) { switch (type) {
case KEYRING_TYPES.QR: case HardwareKeyringTypes.qr:
label = KEYRING_NAMES.QR; label = HardwareKeyringNames.qr;
break; break;
case KEYRING_TYPES.IMPORTED: case HardwareKeyringTypes.imported:
label = t('imported'); label = t('imported');
break; break;
case KEYRING_TYPES.TREZOR: case HardwareKeyringTypes.trezor:
label = KEYRING_NAMES.TREZOR; label = HardwareKeyringNames.trezor;
break; break;
case KEYRING_TYPES.LEDGER: case HardwareKeyringTypes.ledger:
label = KEYRING_NAMES.LEDGER; label = HardwareKeyringNames.ledger;
break; break;
case KEYRING_TYPES.LATTICE: case HardwareKeyringTypes.lattice:
label = KEYRING_NAMES.LATTICE; label = HardwareKeyringNames.lattice;
break; break;
default: default:
return null; return null;

View File

@ -11,7 +11,7 @@ import { renderWithProvider } from '../../../../../test/lib/render-helpers';
import * as actions from '../../../../store/actions'; import * as actions from '../../../../store/actions';
import { CHAIN_IDS } from '../../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../../shared/constants/network';
import { KEYRING_TYPES } from '../../../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../../../shared/constants/hardware-wallets';
import UnconnectedAccountAlert from '.'; import UnconnectedAccountAlert from '.';
@ -49,7 +49,7 @@ describe('Unconnected Account Alert', () => {
const keyrings = [ const keyrings = [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: [ accounts: [
'0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
'0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b', '0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b',

View File

@ -2,10 +2,10 @@ import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { import {
LEDGER_TRANSPORT_TYPES, LedgerTransportTypes,
WebHIDConnectedStatuses,
HardwareTransportStates,
LEDGER_USB_VENDOR_ID, LEDGER_USB_VENDOR_ID,
WEBHID_CONNECTED_STATUSES,
TRANSPORT_STATES,
} from '../../../../shared/constants/hardware-wallets'; } from '../../../../shared/constants/hardware-wallets';
import { import {
PLATFORM_FIREFOX, PLATFORM_FIREFOX,
@ -68,8 +68,8 @@ export default function LedgerInstructionField({ showDataInstruction }) {
useEffect(() => { useEffect(() => {
const initialConnectedDeviceCheck = async () => { const initialConnectedDeviceCheck = async () => {
if ( if (
ledgerTransportType === LEDGER_TRANSPORT_TYPES.WEBHID && ledgerTransportType === LedgerTransportTypes.webhid &&
webHidConnectedStatus !== WEBHID_CONNECTED_STATUSES.CONNECTED webHidConnectedStatus !== WebHIDConnectedStatuses.connected
) { ) {
const devices = await window.navigator.hid.getDevices(); const devices = await window.navigator.hid.getDevices();
const webHidIsConnected = devices.some( const webHidIsConnected = devices.some(
@ -78,37 +78,41 @@ export default function LedgerInstructionField({ showDataInstruction }) {
dispatch( dispatch(
setLedgerWebHidConnectedStatus( setLedgerWebHidConnectedStatus(
webHidIsConnected webHidIsConnected
? WEBHID_CONNECTED_STATUSES.CONNECTED ? WebHIDConnectedStatuses.connected
: WEBHID_CONNECTED_STATUSES.NOT_CONNECTED, : WebHIDConnectedStatuses.notConnected,
), ),
); );
} }
}; };
const determineTransportStatus = async () => { const determineTransportStatus = async () => {
if ( if (
ledgerTransportType === LEDGER_TRANSPORT_TYPES.WEBHID && ledgerTransportType === LedgerTransportTypes.webhid &&
webHidConnectedStatus === WEBHID_CONNECTED_STATUSES.CONNECTED && webHidConnectedStatus === WebHIDConnectedStatuses.connected &&
transportStatus === TRANSPORT_STATES.NONE transportStatus === HardwareTransportStates.none
) { ) {
try { try {
const transportedCreated = await attemptLedgerTransportCreation(); const transportedCreated = await attemptLedgerTransportCreation();
dispatch( dispatch(
setLedgerTransportStatus( setLedgerTransportStatus(
transportedCreated transportedCreated
? TRANSPORT_STATES.VERIFIED ? HardwareTransportStates.verified
: TRANSPORT_STATES.UNKNOWN_FAILURE, : HardwareTransportStates.unknownFailure,
), ),
); );
} catch (e) { } catch (e) {
if (e.message.match('Failed to open the device')) { if (e.message.match('Failed to open the device')) {
dispatch( dispatch(
setLedgerTransportStatus(TRANSPORT_STATES.DEVICE_OPEN_FAILURE), setLedgerTransportStatus(
HardwareTransportStates.deviceOpenFailure,
),
); );
} else if (e.message.match('the device is already open')) { } else if (e.message.match('the device is already open')) {
dispatch(setLedgerTransportStatus(TRANSPORT_STATES.VERIFIED)); dispatch(
setLedgerTransportStatus(HardwareTransportStates.verified),
);
} else { } else {
dispatch( dispatch(
setLedgerTransportStatus(TRANSPORT_STATES.UNKNOWN_FAILURE), setLedgerTransportStatus(HardwareTransportStates.unknownFailure),
); );
} }
} }
@ -120,12 +124,12 @@ export default function LedgerInstructionField({ showDataInstruction }) {
useEffect(() => { useEffect(() => {
return () => { return () => {
dispatch(setLedgerTransportStatus(TRANSPORT_STATES.NONE)); dispatch(setLedgerTransportStatus(HardwareTransportStates.none));
}; };
}, [dispatch]); }, [dispatch]);
const usingLedgerLive = ledgerTransportType === LEDGER_TRANSPORT_TYPES.LIVE; const usingLedgerLive = ledgerTransportType === LedgerTransportTypes.live;
const usingWebHID = ledgerTransportType === LEDGER_TRANSPORT_TYPES.WEBHID; const usingWebHID = ledgerTransportType === LedgerTransportTypes.webhid;
const isFirefox = getPlatform() === PLATFORM_FIREFOX; const isFirefox = getPlatform() === PLATFORM_FIREFOX;
@ -165,7 +169,7 @@ export default function LedgerInstructionField({ showDataInstruction }) {
{t('ledgerConnectionInstructionCloseOtherApps')} {t('ledgerConnectionInstructionCloseOtherApps')}
</Button> </Button>
</span>, </span>,
transportStatus === TRANSPORT_STATES.DEVICE_OPEN_FAILURE, transportStatus === HardwareTransportStates.deviceOpenFailure,
)} )}
{renderInstructionStep( {renderInstructionStep(
<span> <span>
@ -184,8 +188,8 @@ export default function LedgerInstructionField({ showDataInstruction }) {
dispatch( dispatch(
setLedgerWebHidConnectedStatus({ setLedgerWebHidConnectedStatus({
webHidConnectedStatus: webHidIsConnected webHidConnectedStatus: webHidIsConnected
? WEBHID_CONNECTED_STATUSES.CONNECTED ? WebHIDConnectedStatuses.connected
: WEBHID_CONNECTED_STATUSES.NOT_CONNECTED, : WebHIDConnectedStatuses.notConnected,
}), }),
); );
} else { } else {
@ -199,8 +203,7 @@ export default function LedgerInstructionField({ showDataInstruction }) {
</Button> </Button>
</span>, </span>,
usingWebHID && usingWebHID &&
webHidConnectedStatus === webHidConnectedStatus === WebHIDConnectedStatuses.notConnected,
WEBHID_CONNECTED_STATUSES.NOT_CONNECTED,
COLORS.WARNING_DEFAULT, COLORS.WARNING_DEFAULT,
)} )}
</div> </div>

View File

@ -21,7 +21,7 @@ import {
import { useI18nContext } from '../../../hooks/useI18nContext'; import { useI18nContext } from '../../../hooks/useI18nContext';
import { getEnvironmentType } from '../../../../app/scripts/lib/util'; import { getEnvironmentType } from '../../../../app/scripts/lib/util';
import { ENVIRONMENT_TYPE_FULLSCREEN } from '../../../../shared/constants/app'; import { ENVIRONMENT_TYPE_FULLSCREEN } from '../../../../shared/constants/app';
import { KEYRING_TYPES } from '../../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../../shared/constants/hardware-wallets';
import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics'; import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics';
import { MetaMetricsContext } from '../../../contexts/metametrics'; import { MetaMetricsContext } from '../../../contexts/metametrics';
@ -41,7 +41,7 @@ export default function AccountOptionsMenu({ anchorElement, onClose }) {
const trackEvent = useContext(MetaMetricsContext); const trackEvent = useContext(MetaMetricsContext);
const blockExplorerLinkText = useSelector(getBlockExplorerLinkText); const blockExplorerLinkText = useSelector(getBlockExplorerLinkText);
const isRemovable = keyring.type !== KEYRING_TYPES.HD_KEY_TREE; const isRemovable = keyring.type !== HardwareKeyringTypes.hdKeyTree;
const routeToAddBlockExplorerUrl = () => { const routeToAddBlockExplorerUrl = () => {
history.push(`${NETWORKS_ROUTE}#blockExplorerUrl`); history.push(`${NETWORKS_ROUTE}#blockExplorerUrl`);

View File

@ -3,7 +3,7 @@ import configureStore from 'redux-mock-store';
import { fireEvent, screen, waitFor } from '@testing-library/react'; import { fireEvent, screen, waitFor } from '@testing-library/react';
import { renderWithProvider } from '../../../../test/lib/render-helpers'; import { renderWithProvider } from '../../../../test/lib/render-helpers';
import { CHAIN_IDS } from '../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../shared/constants/network';
import { KEYRING_TYPES } from '../../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../../shared/constants/hardware-wallets';
import MenuBar from './menu-bar'; import MenuBar from './menu-bar';
const initState = { const initState = {
@ -21,7 +21,7 @@ const initState = {
}, },
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: ['0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'], accounts: ['0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'],
}, },
], ],

View File

@ -2,7 +2,7 @@ import React from 'react';
import configureMockStore from 'redux-mock-store'; import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk'; import thunk from 'redux-thunk';
import { renderWithProvider } from '../../../../test/jest/rendering'; import { renderWithProvider } from '../../../../test/jest/rendering';
import { KEYRING_TYPES } from '../../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../../shared/constants/hardware-wallets';
import TokenOverview from './token-overview'; import TokenOverview from './token-overview';
describe('TokenOverview', () => { describe('TokenOverview', () => {
@ -22,11 +22,11 @@ describe('TokenOverview', () => {
selectedAddress: '0x1', selectedAddress: '0x1',
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: ['0x1', '0x2'], accounts: ['0x1', '0x2'],
}, },
{ {
type: KEYRING_TYPES.LEDGER, type: HardwareKeyringTypes.ledger,
accounts: [], accounts: [],
}, },
], ],

View File

@ -1,6 +1,6 @@
import { import {
WEBHID_CONNECTED_STATUSES, WebHIDConnectedStatuses,
TRANSPORT_STATES, HardwareTransportStates,
} from '../../../shared/constants/hardware-wallets'; } from '../../../shared/constants/hardware-wallets';
import * as actionConstants from '../../store/actionConstants'; import * as actionConstants from '../../store/actionConstants';
@ -49,8 +49,8 @@ export default function reduceApp(state = {}, action) {
gasLoadingAnimationIsShowing: false, gasLoadingAnimationIsShowing: false,
smartTransactionsError: null, smartTransactionsError: null,
smartTransactionsErrorMessageDismissed: false, smartTransactionsErrorMessageDismissed: false,
ledgerWebHidConnectedStatus: WEBHID_CONNECTED_STATUSES.UNKNOWN, ledgerWebHidConnectedStatus: WebHIDConnectedStatuses.unknown,
ledgerTransportStatus: TRANSPORT_STATES.NONE, ledgerTransportStatus: HardwareTransportStates.none,
newNetworkAdded: '', newNetworkAdded: '',
newCollectibleAddedMessage: '', newCollectibleAddedMessage: '',
portfolioTooltipWasShownInThisSession: false, portfolioTooltipWasShownInThisSession: false,

View File

@ -1,5 +1,5 @@
import * as actionConstants from '../../store/actionConstants'; import * as actionConstants from '../../store/actionConstants';
import { DEVICE_NAMES } from '../../../shared/constants/hardware-wallets'; import { HardwareDeviceNames } from '../../../shared/constants/hardware-wallets';
import reduceApp from './app'; import reduceApp from './app';
const actions = actionConstants; const actions = actionConstants;
@ -261,7 +261,7 @@ describe('App State', () => {
const state = reduceApp(metamaskState, { const state = reduceApp(metamaskState, {
type: actions.SET_HARDWARE_WALLET_DEFAULT_HD_PATH, type: actions.SET_HARDWARE_WALLET_DEFAULT_HD_PATH,
value: { value: {
device: DEVICE_NAMES.LEDGER, device: HardwareDeviceNames.ledger,
path: "m/44'/60'/0'", path: "m/44'/60'/0'",
}, },
}); });

View File

@ -15,7 +15,7 @@ import { updateTransactionGasFees } from '../../store/actions';
import { setCustomGasLimit, setCustomGasPrice } from '../gas/gas.duck'; import { setCustomGasLimit, setCustomGasPrice } from '../gas/gas.duck';
import { decGWEIToHexWEI } from '../../helpers/utils/conversions.util'; import { decGWEIToHexWEI } from '../../helpers/utils/conversions.util';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils';
import { stripHexPrefix } from '../../../shared/modules/hexstring-utils'; import { stripHexPrefix } from '../../../shared/modules/hexstring-utils';
@ -433,7 +433,7 @@ export function getLedgerTransportType(state) {
export function isAddressLedger(state, address) { export function isAddressLedger(state, address) {
const keyring = findKeyringForAddress(state, address); const keyring = findKeyringForAddress(state, address);
return keyring?.type === KEYRING_TYPES.LEDGER; return keyring?.type === HardwareKeyringTypes.ledger;
} }
/** /**
@ -445,6 +445,6 @@ export function isAddressLedger(state, address) {
*/ */
export function doesUserHaveALedgerAccount(state) { export function doesUserHaveALedgerAccount(state) {
return state.metamask.keyrings.some((kr) => { return state.metamask.keyrings.some((kr) => {
return kr.type === KEYRING_TYPES.LEDGER; return kr.type === HardwareKeyringTypes.ledger;
}); });
} }

View File

@ -13,7 +13,7 @@ import {
} from '../../pages/send/send.constants'; } from '../../pages/send/send.constants';
import { CHAIN_IDS } from '../../../shared/constants/network'; import { CHAIN_IDS } from '../../../shared/constants/network';
import { GAS_ESTIMATE_TYPES, GAS_LIMITS } from '../../../shared/constants/gas'; import { GAS_ESTIMATE_TYPES, GAS_LIMITS } from '../../../shared/constants/gas';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
import { import {
AssetType, AssetType,
TokenStandard, TokenStandard,
@ -1278,7 +1278,7 @@ describe('Send Slice', () => {
identities: { '0xAddress': { address: '0xAddress' } }, identities: { '0xAddress': { address: '0xAddress' } },
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: ['0xAddress'], accounts: ['0xAddress'],
}, },
], ],

View File

@ -8,7 +8,7 @@ import Dropdown from '../../../components/ui/dropdown';
import { getURLHostName } from '../../../helpers/utils/util'; import { getURLHostName } from '../../../helpers/utils/util';
import { DEVICE_NAMES } from '../../../../shared/constants/hardware-wallets'; import { HardwareDeviceNames } from '../../../../shared/constants/hardware-wallets';
import { EVENT } from '../../../../shared/constants/metametrics'; import { EVENT } from '../../../../shared/constants/metametrics';
class AccountList extends Component { class AccountList extends Component {
@ -65,9 +65,9 @@ class AccountList extends Component {
renderHeader() { renderHeader() {
const { device } = this.props; const { device } = this.props;
const shouldShowHDPaths = [ const shouldShowHDPaths = [
DEVICE_NAMES.LEDGER, HardwareDeviceNames.ledger,
DEVICE_NAMES.LATTICE, HardwareDeviceNames.lattice,
DEVICE_NAMES.TREZOR, HardwareDeviceNames.trezor,
].includes(device.toLowerCase()); ].includes(device.toLowerCase());
return ( return (
<div className="hw-connect"> <div className="hw-connect">

View File

@ -13,8 +13,8 @@ import { getMostRecentOverviewPage } from '../../../ducks/history/history';
import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics'; import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics';
import { SECOND } from '../../../../shared/constants/time'; import { SECOND } from '../../../../shared/constants/time';
import { import {
DEVICE_NAMES, HardwareDeviceNames,
LEDGER_TRANSPORT_TYPES, LedgerTransportTypes,
} from '../../../../shared/constants/hardware-wallets'; } from '../../../../shared/constants/hardware-wallets';
import ZENDESK_URLS from '../../../helpers/constants/zendesk-url'; import ZENDESK_URLS from '../../../helpers/constants/zendesk-url';
import SelectHardware from './select-hardware'; import SelectHardware from './select-hardware';
@ -89,9 +89,9 @@ class ConnectHardwareForm extends Component {
async checkIfUnlocked() { async checkIfUnlocked() {
for (const device of [ for (const device of [
DEVICE_NAMES.TREZOR, HardwareDeviceNames.trezor,
DEVICE_NAMES.LEDGER, HardwareDeviceNames.ledger,
DEVICE_NAMES.LATTICE, HardwareDeviceNames.lattice,
]) { ]) {
const path = this.props.defaultHdPaths[device]; const path = this.props.defaultHdPaths[device];
const unlocked = await this.props.checkHardwareStatus(device, path); const unlocked = await this.props.checkHardwareStatus(device, path);
@ -364,7 +364,7 @@ ConnectHardwareForm.propTypes = {
connectedAccounts: PropTypes.array.isRequired, connectedAccounts: PropTypes.array.isRequired,
defaultHdPaths: PropTypes.object, defaultHdPaths: PropTypes.object,
mostRecentOverviewPage: PropTypes.string.isRequired, mostRecentOverviewPage: PropTypes.string.isRequired,
ledgerTransportType: PropTypes.oneOf(Object.values(LEDGER_TRANSPORT_TYPES)), ledgerTransportType: PropTypes.oneOf(Object.values(LedgerTransportTypes)),
}; };
const mapStateToProps = (state) => ({ const mapStateToProps = (state) => ({

View File

@ -8,10 +8,10 @@ import LogoTrezor from '../../../components/ui/logo/logo-trezor';
import LogoLattice from '../../../components/ui/logo/logo-lattice'; import LogoLattice from '../../../components/ui/logo/logo-lattice';
import { import {
DEVICE_NAMES, HardwareDeviceNames,
LEDGER_TRANSPORT_TYPES, LedgerTransportTypes,
AFFILIATE_LINKS, HardwareAffiliateLinks,
AFFILIATE_TUTORIAL_LINKS, HardwareAffiliateTutorialLinks,
} from '../../../../shared/constants/hardware-wallets'; } from '../../../../shared/constants/hardware-wallets';
import ZENDESK_URLS from '../../../helpers/constants/zendesk-url'; import ZENDESK_URLS from '../../../helpers/constants/zendesk-url';
import { EVENT } from '../../../../shared/constants/metametrics'; import { EVENT } from '../../../../shared/constants/metametrics';
@ -25,7 +25,7 @@ export default class SelectHardware extends Component {
static propTypes = { static propTypes = {
connectToHardwareWallet: PropTypes.func.isRequired, connectToHardwareWallet: PropTypes.func.isRequired,
browserSupported: PropTypes.bool.isRequired, browserSupported: PropTypes.bool.isRequired,
ledgerTransportType: PropTypes.oneOf(Object.values(LEDGER_TRANSPORT_TYPES)), ledgerTransportType: PropTypes.oneOf(Object.values(LedgerTransportTypes)),
}; };
state = { state = {
@ -43,9 +43,11 @@ export default class SelectHardware extends Component {
return ( return (
<button <button
className={classnames('hw-connect__btn', { className={classnames('hw-connect__btn', {
selected: this.state.selectedDevice === DEVICE_NAMES.TREZOR, selected: this.state.selectedDevice === HardwareDeviceNames.trezor,
})} })}
onClick={(_) => this.setState({ selectedDevice: DEVICE_NAMES.TREZOR })} onClick={(_) =>
this.setState({ selectedDevice: HardwareDeviceNames.trezor })
}
> >
<LogoTrezor className="hw-connect__btn__img" ariaLabel="Trezor" /> <LogoTrezor className="hw-connect__btn__img" ariaLabel="Trezor" />
</button> </button>
@ -56,9 +58,11 @@ export default class SelectHardware extends Component {
return ( return (
<button <button
className={classnames('hw-connect__btn', { className={classnames('hw-connect__btn', {
selected: this.state.selectedDevice === DEVICE_NAMES.LATTICE, selected: this.state.selectedDevice === HardwareDeviceNames.lattice,
})} })}
onClick={(_) => this.setState({ selectedDevice: DEVICE_NAMES.LATTICE })} onClick={(_) =>
this.setState({ selectedDevice: HardwareDeviceNames.lattice })
}
> >
<LogoLattice className="hw-connect__btn__img" ariaLabel="Lattice" /> <LogoLattice className="hw-connect__btn__img" ariaLabel="Lattice" />
</button> </button>
@ -69,9 +73,11 @@ export default class SelectHardware extends Component {
return ( return (
<button <button
className={classnames('hw-connect__btn', { className={classnames('hw-connect__btn', {
selected: this.state.selectedDevice === DEVICE_NAMES.LEDGER, selected: this.state.selectedDevice === HardwareDeviceNames.ledger,
})} })}
onClick={(_) => this.setState({ selectedDevice: DEVICE_NAMES.LEDGER })} onClick={(_) =>
this.setState({ selectedDevice: HardwareDeviceNames.ledger })
}
> >
<LogoLedger className="hw-connect__btn__img" ariaLabel="Ledger" /> <LogoLedger className="hw-connect__btn__img" ariaLabel="Ledger" />
</button> </button>
@ -82,9 +88,11 @@ export default class SelectHardware extends Component {
return ( return (
<button <button
className={classnames('hw-connect__btn', { className={classnames('hw-connect__btn', {
selected: this.state.selectedDevice === DEVICE_NAMES.QR, selected: this.state.selectedDevice === HardwareDeviceNames.qr,
})} })}
onClick={(_) => this.setState({ selectedDevice: DEVICE_NAMES.QR })} onClick={(_) =>
this.setState({ selectedDevice: HardwareDeviceNames.qr })
}
> >
<LogoQRBased className="hw-connect__btn__img" ariaLabel="QRCode" /> <LogoQRBased className="hw-connect__btn__img" ariaLabel="QRCode" />
</button> </button>
@ -164,13 +172,13 @@ export default class SelectHardware extends Component {
renderTutorialsteps() { renderTutorialsteps() {
switch (this.state.selectedDevice) { switch (this.state.selectedDevice) {
case DEVICE_NAMES.LEDGER: case HardwareDeviceNames.ledger:
return this.renderLedgerTutorialSteps(); return this.renderLedgerTutorialSteps();
case DEVICE_NAMES.TREZOR: case HardwareDeviceNames.trezor:
return this.renderTrezorTutorialSteps(); return this.renderTrezorTutorialSteps();
case DEVICE_NAMES.LATTICE: case HardwareDeviceNames.lattice:
return this.renderLatticeTutorialSteps(); return this.renderLatticeTutorialSteps();
case DEVICE_NAMES.QR: case HardwareDeviceNames.qr:
return this.renderQRHardwareWalletSteps(); return this.renderQRHardwareWalletSteps();
default: default:
return ''; return '';
@ -179,7 +187,7 @@ export default class SelectHardware extends Component {
renderLedgerTutorialSteps() { renderLedgerTutorialSteps() {
const steps = []; const steps = [];
if (this.props.ledgerTransportType === LEDGER_TRANSPORT_TYPES.LIVE) { if (this.props.ledgerTransportType === LedgerTransportTypes.live) {
steps.push({ steps.push({
renderButtons: false, renderButtons: false,
title: this.context.t('step1LedgerWallet'), title: this.context.t('step1LedgerWallet'),
@ -230,7 +238,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Ledger Buy Now', event: 'Clicked Ledger Buy Now',
}); });
window.open(AFFILIATE_LINKS.LEDGER, '_blank'); window.open(HardwareAffiliateLinks.ledger, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -243,7 +251,10 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Ledger Tutorial', event: 'Clicked Ledger Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.LEDGER, '_blank'); window.open(
HardwareAffiliateTutorialLinks.ledger,
'_blank',
);
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -298,7 +309,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked GridPlus Buy Now', event: 'Clicked GridPlus Buy Now',
}); });
window.open(AFFILIATE_LINKS.GRIDPLUS, '_blank'); window.open(HardwareAffiliateLinks.gridplus, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -311,7 +322,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked GidPlus Tutorial', event: 'Clicked GidPlus Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.GRIDPLUS, '_blank'); window.open(HardwareAffiliateTutorialLinks.gridplus, '_blank');
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -364,7 +375,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Trezor Buy Now', event: 'Clicked Trezor Buy Now',
}); });
window.open(AFFILIATE_LINKS.TREZOR, '_blank'); window.open(HardwareAffiliateLinks.trezor, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -377,7 +388,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Trezor Tutorial', event: 'Clicked Trezor Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.TREZOR, '_blank'); window.open(HardwareAffiliateTutorialLinks.trezor, '_blank');
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -418,7 +429,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Keystone Buy Now', event: 'Clicked Keystone Buy Now',
}); });
window.open(AFFILIATE_LINKS.KEYSTONE, '_blank'); window.open(HardwareAffiliateLinks.keystone, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -431,7 +442,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked Keystone Tutorial', event: 'Clicked Keystone Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.KEYSTONE, '_blank'); window.open(HardwareAffiliateTutorialLinks.keystone, '_blank');
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -453,7 +464,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked AirGap Vault Buy Now', event: 'Clicked AirGap Vault Buy Now',
}); });
window.open(AFFILIATE_LINKS.AIRGAP, '_blank'); window.open(HardwareAffiliateLinks.airgap, '_blank');
}} }}
> >
{this.context.t('downloadNow')} {this.context.t('downloadNow')}
@ -466,7 +477,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked AirGap Vault Tutorial', event: 'Clicked AirGap Vault Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.AIRGAP, '_blank'); window.open(HardwareAffiliateTutorialLinks.airgap, '_blank');
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -488,7 +499,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked CoolWallet Buy Now', event: 'Clicked CoolWallet Buy Now',
}); });
window.open(AFFILIATE_LINKS.COOLWALLET, '_blank'); window.open(HardwareAffiliateLinks.coolwallet, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -501,7 +512,10 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked CoolWallet Tutorial', event: 'Clicked CoolWallet Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.COOLWALLET, '_blank'); window.open(
HardwareAffiliateTutorialLinks.coolwallet,
'_blank',
);
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}
@ -521,7 +535,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked DCent Buy Now', event: 'Clicked DCent Buy Now',
}); });
window.open(AFFILIATE_LINKS.DCENT, '_blank'); window.open(HardwareAffiliateLinks.dcent, '_blank');
}} }}
> >
{this.context.t('buyNow')} {this.context.t('buyNow')}
@ -534,7 +548,7 @@ export default class SelectHardware extends Component {
category: EVENT.CATEGORIES.NAVIGATION, category: EVENT.CATEGORIES.NAVIGATION,
event: 'Clicked DCent Tutorial', event: 'Clicked DCent Tutorial',
}); });
window.open(AFFILIATE_TUTORIAL_LINKS.DCENT, '_blank'); window.open(HardwareAffiliateTutorialLinks.dcent, '_blank');
}} }}
> >
{this.context.t('tutorial')} {this.context.t('tutorial')}

View File

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { action } from '@storybook/addon-actions'; import { action } from '@storybook/addon-actions';
import { LEDGER_TRANSPORT_TYPES } from '../../../../shared/constants/hardware-wallets'; import { LedgerTransportTypes } from '../../../../shared/constants/hardware-wallets';
import SelectHardware from './select-hardware'; import SelectHardware from './select-hardware';
export default { export default {
@ -15,7 +15,7 @@ export const DefaultStory = () => {
connectToHardwareWallet={(selectedDevice) => connectToHardwareWallet={(selectedDevice) =>
action(`Continue connect to ${selectedDevice}`)() action(`Continue connect to ${selectedDevice}`)()
} }
ledgerTransportType={LEDGER_TRANSPORT_TYPES.LIVE} ledgerTransportType={LedgerTransportTypes.live}
/> />
); );
}; };
@ -27,7 +27,7 @@ export const BrowserNotSupported = () => {
<SelectHardware <SelectHardware
browserSupported={false} browserSupported={false}
connectToHardwareWallet={() => undefined} connectToHardwareWallet={() => undefined}
ledgerTransportType={LEDGER_TRANSPORT_TYPES.LIVE} ledgerTransportType={LedgerTransportTypes.live}
/> />
); );
}; };

View File

@ -8,7 +8,7 @@ import qrCode from 'qrcode-generator';
import Button from '../../components/ui/button'; import Button from '../../components/ui/button';
import LoadingScreen from '../../components/ui/loading-screen'; import LoadingScreen from '../../components/ui/loading-screen';
import { MINUTE, SECOND } from '../../../shared/constants/time'; import { MINUTE, SECOND } from '../../../shared/constants/time';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
const PASSWORD_PROMPT_SCREEN = 'PASSWORD_PROMPT_SCREEN'; const PASSWORD_PROMPT_SCREEN = 'PASSWORD_PROMPT_SCREEN';
const REVEAL_SEED_SCREEN = 'REVEAL_SEED_SCREEN'; const REVEAL_SEED_SCREEN = 'REVEAL_SEED_SCREEN';
@ -82,7 +82,7 @@ export default class MobileSyncPage extends Component {
async exportAccounts() { async exportAccounts() {
const addresses = []; const addresses = [];
this.props.keyrings.forEach((keyring) => { this.props.keyrings.forEach((keyring) => {
if (keyring.type === KEYRING_TYPES.IMPORTED) { if (keyring.type === HardwareKeyringTypes.imported) {
addresses.push(keyring.accounts[0]); addresses.push(keyring.accounts[0]);
} }
}); });

View File

@ -10,7 +10,7 @@ import {
setBackgroundConnection, setBackgroundConnection,
} from '../../../test/jest'; } from '../../../test/jest';
import { GAS_ESTIMATE_TYPES } from '../../../shared/constants/gas'; import { GAS_ESTIMATE_TYPES } from '../../../shared/constants/gas';
import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../../shared/constants/hardware-wallets';
import { INITIAL_SEND_STATE_FOR_EXISTING_DRAFT } from '../../../test/jest/mocks'; import { INITIAL_SEND_STATE_FOR_EXISTING_DRAFT } from '../../../test/jest/mocks';
import Send from './send'; import Send from './send';
@ -86,7 +86,7 @@ const baseStore = {
selectedAddress: '0x0', selectedAddress: '0x0',
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.HD_KEY_TREE, type: HardwareKeyringTypes.hdKeyTree,
accounts: ['0x0'], accounts: ['0x0'],
}, },
], ],

View File

@ -16,7 +16,7 @@ import {
} from '../../../helpers/utils/settings-search'; } from '../../../helpers/utils/settings-search';
import { import {
LEDGER_TRANSPORT_TYPES, LedgerTransportTypes,
LEDGER_USB_VENDOR_ID, LEDGER_USB_VENDOR_ID,
} from '../../../../shared/constants/hardware-wallets'; } from '../../../../shared/constants/hardware-wallets';
import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics'; import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics';
@ -49,7 +49,7 @@ export default class AdvancedTab extends PureComponent {
setAutoLockTimeLimit: PropTypes.func.isRequired, setAutoLockTimeLimit: PropTypes.func.isRequired,
setShowFiatConversionOnTestnetsPreference: PropTypes.func.isRequired, setShowFiatConversionOnTestnetsPreference: PropTypes.func.isRequired,
setShowTestNetworks: PropTypes.func.isRequired, setShowTestNetworks: PropTypes.func.isRequired,
ledgerTransportType: PropTypes.oneOf(Object.values(LEDGER_TRANSPORT_TYPES)), ledgerTransportType: PropTypes.oneOf(Object.values(LedgerTransportTypes)),
setLedgerTransportPreference: PropTypes.func.isRequired, setLedgerTransportPreference: PropTypes.func.isRequired,
setDismissSeedBackUpReminder: PropTypes.func.isRequired, setDismissSeedBackUpReminder: PropTypes.func.isRequired,
dismissSeedBackUpReminder: PropTypes.bool.isRequired, dismissSeedBackUpReminder: PropTypes.bool.isRequired,
@ -473,18 +473,18 @@ export default class AdvancedTab extends PureComponent {
const transportTypeOptions = [ const transportTypeOptions = [
{ {
name: LEDGER_TRANSPORT_NAMES.LIVE, name: LEDGER_TRANSPORT_NAMES.LIVE,
value: LEDGER_TRANSPORT_TYPES.LIVE, value: LedgerTransportTypes.live,
}, },
{ {
name: LEDGER_TRANSPORT_NAMES.U2F, name: LEDGER_TRANSPORT_NAMES.U2F,
value: LEDGER_TRANSPORT_TYPES.U2F, value: LedgerTransportTypes.u2f,
}, },
]; ];
if (window.navigator.hid) { if (window.navigator.hid) {
transportTypeOptions.push({ transportTypeOptions.push({
name: LEDGER_TRANSPORT_NAMES.WEBHID, name: LEDGER_TRANSPORT_NAMES.WEBHID,
value: LEDGER_TRANSPORT_TYPES.WEBHID, value: LedgerTransportTypes.webhid,
}); });
} }
@ -520,14 +520,14 @@ export default class AdvancedTab extends PureComponent {
selectedOption={ledgerTransportType} selectedOption={ledgerTransportType}
onChange={async (transportType) => { onChange={async (transportType) => {
if ( if (
ledgerTransportType === LEDGER_TRANSPORT_TYPES.LIVE && ledgerTransportType === LedgerTransportTypes.live &&
transportType === LEDGER_TRANSPORT_TYPES.WEBHID transportType === LedgerTransportTypes.webhid
) { ) {
this.setState({ showLedgerTransportWarning: true }); this.setState({ showLedgerTransportWarning: true });
} }
setLedgerTransportPreference(transportType); setLedgerTransportPreference(transportType);
if ( if (
transportType === LEDGER_TRANSPORT_TYPES.WEBHID && transportType === LedgerTransportTypes.webhid &&
userHasALedgerAccount userHasALedgerAccount
) { ) {
await window.navigator.hid.requestDevice({ await window.navigator.hid.requestDevice({

View File

@ -22,11 +22,11 @@ import {
CHAIN_IDS, CHAIN_IDS,
NETWORK_TYPES, NETWORK_TYPES,
} from '../../shared/constants/network'; } from '../../shared/constants/network';
import { KEYRING_TYPES } from '../../shared/constants/keyrings';
import { import {
WEBHID_CONNECTED_STATUSES, HardwareKeyringTypes,
LEDGER_TRANSPORT_TYPES, WebHIDConnectedStatuses,
TRANSPORT_STATES, LedgerTransportTypes,
HardwareTransportStates,
} from '../../shared/constants/hardware-wallets'; } from '../../shared/constants/hardware-wallets';
import { import {
@ -130,7 +130,7 @@ export function hasUnsignedQRHardwareTransaction(state) {
} }
const { from } = txParams; const { from } = txParams;
const { keyrings } = state.metamask; const { keyrings } = state.metamask;
const qrKeyring = keyrings.find((kr) => kr.type === KEYRING_TYPES.QR); const qrKeyring = keyrings.find((kr) => kr.type === HardwareKeyringTypes.qr);
if (!qrKeyring) { if (!qrKeyring) {
return false; return false;
} }
@ -148,7 +148,7 @@ export function hasUnsignedQRHardwareMessage(state) {
} }
const { from } = msgParams; const { from } = msgParams;
const { keyrings } = state.metamask; const { keyrings } = state.metamask;
const qrKeyring = keyrings.find((kr) => kr.type === KEYRING_TYPES.QR); const qrKeyring = keyrings.find((kr) => kr.type === HardwareKeyringTypes.qr);
if (!qrKeyring) { if (!qrKeyring) {
return false; return false;
} }
@ -239,11 +239,11 @@ export function getAccountType(state) {
const type = currentKeyring && currentKeyring.type; const type = currentKeyring && currentKeyring.type;
switch (type) { switch (type) {
case KEYRING_TYPES.TREZOR: case HardwareKeyringTypes.trezor:
case KEYRING_TYPES.LEDGER: case HardwareKeyringTypes.ledger:
case KEYRING_TYPES.LATTICE: case HardwareKeyringTypes.lattice:
return 'hardware'; return 'hardware';
case KEYRING_TYPES.IMPORTED: case HardwareKeyringTypes.imported:
return 'imported'; return 'imported';
default: default:
return 'default'; return 'default';
@ -982,10 +982,11 @@ export const getUnreadNotificationsCount = createSelector(
*/ */
function getAllowedAnnouncementIds(state) { function getAllowedAnnouncementIds(state) {
const currentKeyring = getCurrentKeyring(state); const currentKeyring = getCurrentKeyring(state);
const currentKeyringIsLedger = currentKeyring?.type === KEYRING_TYPES.LEDGER; const currentKeyringIsLedger =
currentKeyring?.type === HardwareKeyringTypes.ledger;
const supportsWebHid = window.navigator.hid !== undefined; const supportsWebHid = window.navigator.hid !== undefined;
const currentlyUsingLedgerLive = const currentlyUsingLedgerLive =
getLedgerTransportType(state) === LEDGER_TRANSPORT_TYPES.LIVE; getLedgerTransportType(state) === LedgerTransportTypes.live;
return { return {
1: false, 1: false,
@ -1118,13 +1119,12 @@ export function getTokenList(state) {
export function doesAddressRequireLedgerHidConnection(state, address) { export function doesAddressRequireLedgerHidConnection(state, address) {
const addressIsLedger = isAddressLedger(state, address); const addressIsLedger = isAddressLedger(state, address);
const transportTypePreferenceIsWebHID = const transportTypePreferenceIsWebHID =
getLedgerTransportType(state) === LEDGER_TRANSPORT_TYPES.WEBHID; getLedgerTransportType(state) === LedgerTransportTypes.webhid;
const webHidIsNotConnected = const webHidIsNotConnected =
getLedgerWebHidConnectedStatus(state) !== getLedgerWebHidConnectedStatus(state) !== WebHIDConnectedStatuses.connected;
WEBHID_CONNECTED_STATUSES.CONNECTED;
const ledgerTransportStatus = getLedgerTransportStatus(state); const ledgerTransportStatus = getLedgerTransportStatus(state);
const transportIsNotSuccessfullyCreated = const transportIsNotSuccessfullyCreated =
ledgerTransportStatus !== TRANSPORT_STATES.VERIFIED; ledgerTransportStatus !== HardwareTransportStates.verified;
return ( return (
addressIsLedger && addressIsLedger &&

View File

@ -1,5 +1,5 @@
import mockState from '../../test/data/mock-state.json'; import mockState from '../../test/data/mock-state.json';
import { KEYRING_TYPES } from '../../shared/constants/keyrings'; import { HardwareKeyringTypes } from '../../shared/constants/hardware-wallets';
import * as selectors from './selectors'; import * as selectors from './selectors';
describe('Selectors', () => { describe('Selectors', () => {
@ -18,38 +18,38 @@ describe('Selectors', () => {
describe('#isHardwareWallet', () => { describe('#isHardwareWallet', () => {
it('returns false if it is not a HW wallet', () => { it('returns false if it is not a HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.IMPORTED; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.imported;
expect(selectors.isHardwareWallet(mockState)).toBe(false); expect(selectors.isHardwareWallet(mockState)).toBe(false);
}); });
it('returns true if it is a Ledger HW wallet', () => { it('returns true if it is a Ledger HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.LEDGER; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.ledger;
expect(selectors.isHardwareWallet(mockState)).toBe(true); expect(selectors.isHardwareWallet(mockState)).toBe(true);
}); });
it('returns true if it is a Trezor HW wallet', () => { it('returns true if it is a Trezor HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.TREZOR; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.trezor;
expect(selectors.isHardwareWallet(mockState)).toBe(true); expect(selectors.isHardwareWallet(mockState)).toBe(true);
}); });
}); });
describe('#getHardwareWalletType', () => { describe('#getHardwareWalletType', () => {
it('returns undefined if it is not a HW wallet', () => { it('returns undefined if it is not a HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.IMPORTED; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.imported;
expect(selectors.getHardwareWalletType(mockState)).toBeUndefined(); expect(selectors.getHardwareWalletType(mockState)).toBeUndefined();
}); });
it('returns "Ledger Hardware" if it is a Ledger HW wallet', () => { it('returns "Ledger Hardware" if it is a Ledger HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.LEDGER; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.ledger;
expect(selectors.getHardwareWalletType(mockState)).toBe( expect(selectors.getHardwareWalletType(mockState)).toBe(
KEYRING_TYPES.LEDGER, HardwareKeyringTypes.ledger,
); );
}); });
it('returns "Trezor Hardware" if it is a Trezor HW wallet', () => { it('returns "Trezor Hardware" if it is a Trezor HW wallet', () => {
mockState.metamask.keyrings[0].type = KEYRING_TYPES.TREZOR; mockState.metamask.keyrings[0].type = HardwareKeyringTypes.trezor;
expect(selectors.getHardwareWalletType(mockState)).toBe( expect(selectors.getHardwareWalletType(mockState)).toBe(
KEYRING_TYPES.TREZOR, HardwareKeyringTypes.trezor,
); );
}); });
}); });
@ -87,7 +87,7 @@ describe('Selectors', () => {
...mockState.metamask, ...mockState.metamask,
keyrings: [ keyrings: [
{ {
type: KEYRING_TYPES.LEDGER, type: HardwareKeyringTypes.ledger,
accounts: ['0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'], accounts: ['0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'],
}, },
], ],

View File

@ -30,8 +30,8 @@ import { switchedToUnconnectedAccount } from '../ducks/alerts/unconnected-accoun
import { getUnconnectedAccountAlertEnabledness } from '../ducks/metamask/metamask'; import { getUnconnectedAccountAlertEnabledness } from '../ducks/metamask/metamask';
import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils';
import { import {
DEVICE_NAMES, HardwareDeviceNames,
LEDGER_TRANSPORT_TYPES, LedgerTransportTypes,
LEDGER_USB_VENDOR_ID, LEDGER_USB_VENDOR_ID,
} from '../../shared/constants/hardware-wallets'; } from '../../shared/constants/hardware-wallets';
import { EVENT } from '../../shared/constants/metametrics'; import { EVENT } from '../../shared/constants/metametrics';
@ -425,12 +425,12 @@ export function connectHardware(deviceName, page, hdPath, t) {
let accounts; let accounts;
try { try {
if (deviceName === DEVICE_NAMES.LEDGER) { if (deviceName === HardwareDeviceNames.ledger) {
await submitRequestToBackground('establishLedgerTransportPreference'); await submitRequestToBackground('establishLedgerTransportPreference');
} }
if ( if (
deviceName === DEVICE_NAMES.LEDGER && deviceName === HardwareDeviceNames.ledger &&
ledgerTransportType === LEDGER_TRANSPORT_TYPES.WEBHID ledgerTransportType === LedgerTransportTypes.webhid
) { ) {
const connectedDevices = await window.navigator.hid.requestDevice({ const connectedDevices = await window.navigator.hid.requestDevice({
filters: [{ vendorId: LEDGER_USB_VENDOR_ID }], filters: [{ vendorId: LEDGER_USB_VENDOR_ID }],
@ -451,14 +451,14 @@ export function connectHardware(deviceName, page, hdPath, t) {
} catch (error) { } catch (error) {
log.error(error); log.error(error);
if ( if (
deviceName === DEVICE_NAMES.LEDGER && deviceName === HardwareDeviceNames.ledger &&
ledgerTransportType === LEDGER_TRANSPORT_TYPES.WEBHID && ledgerTransportType === LedgerTransportTypes.webhid &&
error.message.match('Failed to open the device') error.message.match('Failed to open the device')
) { ) {
dispatch(displayWarning(t('ledgerDeviceOpenFailureMessage'))); dispatch(displayWarning(t('ledgerDeviceOpenFailureMessage')));
throw new Error(t('ledgerDeviceOpenFailureMessage')); throw new Error(t('ledgerDeviceOpenFailureMessage'));
} else { } else {
if (deviceName !== DEVICE_NAMES.QR) { if (deviceName !== HardwareDeviceNames.qr) {
dispatch(displayWarning(error.message)); dispatch(displayWarning(error.message));
} }
throw error; throw error;

View File

@ -4,7 +4,7 @@ import thunk from 'redux-thunk';
import enLocale from '../../app/_locales/en/messages.json'; import enLocale from '../../app/_locales/en/messages.json';
import MetaMaskController from '../../app/scripts/metamask-controller'; import MetaMaskController from '../../app/scripts/metamask-controller';
import { TransactionStatus } from '../../shared/constants/transaction'; import { TransactionStatus } from '../../shared/constants/transaction';
import { DEVICE_NAMES } from '../../shared/constants/hardware-wallets'; import { HardwareDeviceNames } from '../../shared/constants/hardware-wallets';
import { GAS_LIMITS } from '../../shared/constants/gas'; import { GAS_LIMITS } from '../../shared/constants/gas';
import * as actions from './actions'; import * as actions from './actions';
import { _setBackgroundConnection } from './action-queue'; import { _setBackgroundConnection } from './action-queue';
@ -443,7 +443,10 @@ describe('Actions', () => {
_setBackgroundConnection(background); _setBackgroundConnection(background);
await store.dispatch( await store.dispatch(
actions.checkHardwareStatus(DEVICE_NAMES.LEDGER, `m/44'/60'/0'/0`), actions.checkHardwareStatus(
HardwareDeviceNames.ledger,
`m/44'/60'/0'/0`,
),
); );
expect(checkHardwareStatus.callCount).toStrictEqual(1); expect(checkHardwareStatus.callCount).toStrictEqual(1);
}); });
@ -483,7 +486,7 @@ describe('Actions', () => {
_setBackgroundConnection(background); _setBackgroundConnection(background);
await store.dispatch(actions.forgetDevice(DEVICE_NAMES.LEDGER)); await store.dispatch(actions.forgetDevice(HardwareDeviceNames.ledger));
expect(forgetDevice.callCount).toStrictEqual(1); expect(forgetDevice.callCount).toStrictEqual(1);
}); });
@ -525,7 +528,11 @@ describe('Actions', () => {
_setBackgroundConnection(background); _setBackgroundConnection(background);
await store.dispatch( await store.dispatch(
actions.connectHardware(DEVICE_NAMES.LEDGER, 0, `m/44'/60'/0'/0`), actions.connectHardware(
HardwareDeviceNames.ledger,
0,
`m/44'/60'/0'/0`,
),
); );
expect(connectHardware.callCount).toStrictEqual(1); expect(connectHardware.callCount).toStrictEqual(1);
}); });
@ -551,7 +558,7 @@ describe('Actions', () => {
]; ];
await expect( await expect(
store.dispatch(actions.connectHardware(DEVICE_NAMES.LEDGER)), store.dispatch(actions.connectHardware(HardwareDeviceNames.ledger)),
).rejects.toThrow('error'); ).rejects.toThrow('error');
expect(store.getActions()).toStrictEqual(expectedActions); expect(store.getActions()).toStrictEqual(expectedActions);
@ -575,7 +582,7 @@ describe('Actions', () => {
await store.dispatch( await store.dispatch(
actions.unlockHardwareWalletAccounts( actions.unlockHardwareWalletAccounts(
[0], [0],
DEVICE_NAMES.LEDGER, HardwareDeviceNames.ledger,
`m/44'/60'/0'/0`, `m/44'/60'/0'/0`,
'', '',
), ),