1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-22 19:26:13 +02:00
metamask-extension/app/scripts/controllers/preferences.js

816 lines
26 KiB
JavaScript
Raw Normal View History

Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
import { strict as assert } from 'assert'
2020-12-16 22:14:49 +01:00
import { ObservableStore } from '@metamask/obs-store'
2021-01-21 07:06:41 +01:00
import { ethErrors } from 'eth-rpc-errors'
import { normalize as normalizeAddress } from 'eth-sig-util'
2020-12-02 22:41:30 +01:00
import { isValidAddress } from 'ethereumjs-util'
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
import ethers from 'ethers'
import log from 'loglevel'
import { LISTED_CONTRACT_ADDRESSES } from '../../../shared/constants/tokens'
import { NETWORK_TYPE_TO_ID_MAP } from '../../../shared/constants/network'
import { isPrefixedFormattedHexString } from '../../../shared/modules/utils'
export default class PreferencesController {
2018-04-18 20:41:39 +02:00
/**
*
* @typedef {Object} PreferencesController
* @param {Object} opts - Overrides the defaults for the initial state of this.store
* @property {Object} store The stored object containing a users preferences, stored in local storage
* @property {Array} store.frequentRpcList A list of custom rpcs to provide the user
* @property {Array} store.tokens The tokens the user wants display in their token lists
* @property {Object} store.accountTokens The tokens stored per account and then per network type
* @property {Object} store.assetImages Contains assets objects related to assets added
* @property {boolean} store.useBlockie The users preference for blockie identicons within the UI
Add advanced setting to enable editing nonce on confirmation screens (#7089) * Add UseNonce toggle * Get the toggle actually working and dispatching * Display nonce field on confirmation page * Remove console.log * Add placeholder * Set customNonceValue * Add nonce key/value to txParams * remove customNonceValue from component state * Use translation file and existing CSS class * Use existing TextField component * Remove console.log * Fix lint nits * Okay this sorta works? * Move nonce toggle to advanced tab * Set min to 0 * Wrap value in Number() * Add customNonceMap * Update custom nonce translation * Update styles * Reset CustomNonce * Fix lint * Get tests passing * Add customNonceValue to defaults * Fix test * Fix comments * Update tests * Use camel case * Ensure custom nonce can only be whole number * Correct font size for custom nonce input * UX improvements for custom nonce feature * Fix advanced-tab-component tests for custom nonce changes * Update title of nonce toggle in settings * Remove unused locale message * Cast custom nonce to string in confirm-transaction-base.component * Handle string conversion and invalid values for custom nonces in handler * Don't call getNonceLock in tx controller if there is a custom nonce * Set nonce details for cases where nonce is customized * Fix incorrectly use value for deciding whether to getnoncelock in approveTransaction * Default nonceLock to empty object in approveTransaction * Reapply use on nonceLock in cases where customNonceValue in approveTransaction. * Show warning message if custom nonce is higher than MetaMask's next nonce * Fix e2e test failure caused by custom nonce and 3box toggle conflict * Update nonce warning message to include the suggested nonce * Handle nextNonce comparison and update logic in lifecycle * Default nonce field to suggested nonce * Clear custom nonce on reject or confirm * Fix bug where nonces are not shown in tx list on self sent transactions * Ensure custom nonce is reset after tx is created in background * Convert customNonceValue to number in approve tranasction controller * Lint fix * Call getNextNonce after updating custom nonce
2019-09-27 06:30:36 +02:00
* @property {boolean} store.useNonceField The users preference for nonce field within the UI
* @property {Object} store.featureFlags A key-boolean map, where keys refer to features and booleans to whether the
2019-02-25 20:10:13 +01:00
* user wishes to see that feature.
*
* Feature flags can be set by the global function `setPreference(feature, enabled)`, and so should not expose any sensitive behavior.
* @property {Object} store.knownMethodData Contains all data methods known by the user
* @property {string} store.currentLocale The preferred language locale key
* @property {string} store.selectedAddress A hex string that matches the currently selected address in the app
*
2018-04-18 20:41:39 +02:00
*/
2020-11-03 00:41:28 +01:00
constructor(opts = {}) {
const initState = {
frequentRpcListDetail: [],
2018-07-27 22:05:12 +02:00
accountTokens: {},
accountHiddenTokens: {},
2018-08-21 17:59:42 +02:00
assetImages: {},
tokens: [],
hiddenTokens: [],
2018-06-19 00:33:50 +02:00
suggestedTokens: {},
useBlockie: false,
Add advanced setting to enable editing nonce on confirmation screens (#7089) * Add UseNonce toggle * Get the toggle actually working and dispatching * Display nonce field on confirmation page * Remove console.log * Add placeholder * Set customNonceValue * Add nonce key/value to txParams * remove customNonceValue from component state * Use translation file and existing CSS class * Use existing TextField component * Remove console.log * Fix lint nits * Okay this sorta works? * Move nonce toggle to advanced tab * Set min to 0 * Wrap value in Number() * Add customNonceMap * Update custom nonce translation * Update styles * Reset CustomNonce * Fix lint * Get tests passing * Add customNonceValue to defaults * Fix test * Fix comments * Update tests * Use camel case * Ensure custom nonce can only be whole number * Correct font size for custom nonce input * UX improvements for custom nonce feature * Fix advanced-tab-component tests for custom nonce changes * Update title of nonce toggle in settings * Remove unused locale message * Cast custom nonce to string in confirm-transaction-base.component * Handle string conversion and invalid values for custom nonces in handler * Don't call getNonceLock in tx controller if there is a custom nonce * Set nonce details for cases where nonce is customized * Fix incorrectly use value for deciding whether to getnoncelock in approveTransaction * Default nonceLock to empty object in approveTransaction * Reapply use on nonceLock in cases where customNonceValue in approveTransaction. * Show warning message if custom nonce is higher than MetaMask's next nonce * Fix e2e test failure caused by custom nonce and 3box toggle conflict * Update nonce warning message to include the suggested nonce * Handle nextNonce comparison and update logic in lifecycle * Default nonce field to suggested nonce * Clear custom nonce on reject or confirm * Fix bug where nonces are not shown in tx list on self sent transactions * Ensure custom nonce is reset after tx is created in background * Convert customNonceValue to number in approve tranasction controller * Lint fix * Call getNextNonce after updating custom nonce
2019-09-27 06:30:36 +02:00
useNonceField: false,
usePhishDetect: true,
2019-02-25 20:10:13 +01:00
// WARNING: Do not use feature flags for security-sensitive things.
// Feature flag toggling is available in the global namespace
// for convenient testing of pre-release features, and should never
// perform sensitive operations.
featureFlags: {
showIncomingTransactions: true,
},
knownMethodData: {},
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
firstTimeFlowType: null,
currentLocale: opts.initLangCode,
identities: {},
lostIdentities: {},
forgottenPassword: false,
preferences: {
autoLockTimeLimit: undefined,
showFiatInTestnets: false,
useNativeCurrencyAsPrimaryCurrency: true,
},
completedOnboarding: false,
// ENS decentralized website resolution
2020-11-03 00:41:28 +01:00
ipfsGateway: 'dweb.link',
...opts.initState,
}
2018-06-04 23:21:46 +02:00
this.network = opts.network
this.store = new ObservableStore(initState)
this.store.setMaxListeners(12)
2018-09-27 20:19:09 +02:00
this.openPopup = opts.openPopup
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
this.migrateAddressBookState = opts.migrateAddressBookState
2018-07-27 22:05:12 +02:00
this._subscribeProviderType()
2019-02-25 20:10:13 +01:00
global.setPreference = (key, value) => {
return this.setFeatureFlag(key, value)
}
}
// PUBLIC METHODS
/**
* Sets the {@code forgottenPassword} state property
* @param {boolean} forgottenPassword - whether or not the user has forgotten their password
*/
2020-11-03 00:41:28 +01:00
setPasswordForgotten(forgottenPassword) {
this.store.updateState({ forgottenPassword })
}
2018-04-18 20:41:39 +02:00
/**
* Setter for the `useBlockie` property
*
* @param {boolean} val - Whether or not the user prefers blockie indicators
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
setUseBlockie(val) {
this.store.updateState({ useBlockie: val })
2017-11-24 02:33:44 +01:00
}
Add advanced setting to enable editing nonce on confirmation screens (#7089) * Add UseNonce toggle * Get the toggle actually working and dispatching * Display nonce field on confirmation page * Remove console.log * Add placeholder * Set customNonceValue * Add nonce key/value to txParams * remove customNonceValue from component state * Use translation file and existing CSS class * Use existing TextField component * Remove console.log * Fix lint nits * Okay this sorta works? * Move nonce toggle to advanced tab * Set min to 0 * Wrap value in Number() * Add customNonceMap * Update custom nonce translation * Update styles * Reset CustomNonce * Fix lint * Get tests passing * Add customNonceValue to defaults * Fix test * Fix comments * Update tests * Use camel case * Ensure custom nonce can only be whole number * Correct font size for custom nonce input * UX improvements for custom nonce feature * Fix advanced-tab-component tests for custom nonce changes * Update title of nonce toggle in settings * Remove unused locale message * Cast custom nonce to string in confirm-transaction-base.component * Handle string conversion and invalid values for custom nonces in handler * Don't call getNonceLock in tx controller if there is a custom nonce * Set nonce details for cases where nonce is customized * Fix incorrectly use value for deciding whether to getnoncelock in approveTransaction * Default nonceLock to empty object in approveTransaction * Reapply use on nonceLock in cases where customNonceValue in approveTransaction. * Show warning message if custom nonce is higher than MetaMask's next nonce * Fix e2e test failure caused by custom nonce and 3box toggle conflict * Update nonce warning message to include the suggested nonce * Handle nextNonce comparison and update logic in lifecycle * Default nonce field to suggested nonce * Clear custom nonce on reject or confirm * Fix bug where nonces are not shown in tx list on self sent transactions * Ensure custom nonce is reset after tx is created in background * Convert customNonceValue to number in approve tranasction controller * Lint fix * Call getNextNonce after updating custom nonce
2019-09-27 06:30:36 +02:00
/**
* Setter for the `useNonceField` property
*
* @param {boolean} val - Whether or not the user prefers to set nonce
Add advanced setting to enable editing nonce on confirmation screens (#7089) * Add UseNonce toggle * Get the toggle actually working and dispatching * Display nonce field on confirmation page * Remove console.log * Add placeholder * Set customNonceValue * Add nonce key/value to txParams * remove customNonceValue from component state * Use translation file and existing CSS class * Use existing TextField component * Remove console.log * Fix lint nits * Okay this sorta works? * Move nonce toggle to advanced tab * Set min to 0 * Wrap value in Number() * Add customNonceMap * Update custom nonce translation * Update styles * Reset CustomNonce * Fix lint * Get tests passing * Add customNonceValue to defaults * Fix test * Fix comments * Update tests * Use camel case * Ensure custom nonce can only be whole number * Correct font size for custom nonce input * UX improvements for custom nonce feature * Fix advanced-tab-component tests for custom nonce changes * Update title of nonce toggle in settings * Remove unused locale message * Cast custom nonce to string in confirm-transaction-base.component * Handle string conversion and invalid values for custom nonces in handler * Don't call getNonceLock in tx controller if there is a custom nonce * Set nonce details for cases where nonce is customized * Fix incorrectly use value for deciding whether to getnoncelock in approveTransaction * Default nonceLock to empty object in approveTransaction * Reapply use on nonceLock in cases where customNonceValue in approveTransaction. * Show warning message if custom nonce is higher than MetaMask's next nonce * Fix e2e test failure caused by custom nonce and 3box toggle conflict * Update nonce warning message to include the suggested nonce * Handle nextNonce comparison and update logic in lifecycle * Default nonce field to suggested nonce * Clear custom nonce on reject or confirm * Fix bug where nonces are not shown in tx list on self sent transactions * Ensure custom nonce is reset after tx is created in background * Convert customNonceValue to number in approve tranasction controller * Lint fix * Call getNextNonce after updating custom nonce
2019-09-27 06:30:36 +02:00
*
*/
2020-11-03 00:41:28 +01:00
setUseNonceField(val) {
Add advanced setting to enable editing nonce on confirmation screens (#7089) * Add UseNonce toggle * Get the toggle actually working and dispatching * Display nonce field on confirmation page * Remove console.log * Add placeholder * Set customNonceValue * Add nonce key/value to txParams * remove customNonceValue from component state * Use translation file and existing CSS class * Use existing TextField component * Remove console.log * Fix lint nits * Okay this sorta works? * Move nonce toggle to advanced tab * Set min to 0 * Wrap value in Number() * Add customNonceMap * Update custom nonce translation * Update styles * Reset CustomNonce * Fix lint * Get tests passing * Add customNonceValue to defaults * Fix test * Fix comments * Update tests * Use camel case * Ensure custom nonce can only be whole number * Correct font size for custom nonce input * UX improvements for custom nonce feature * Fix advanced-tab-component tests for custom nonce changes * Update title of nonce toggle in settings * Remove unused locale message * Cast custom nonce to string in confirm-transaction-base.component * Handle string conversion and invalid values for custom nonces in handler * Don't call getNonceLock in tx controller if there is a custom nonce * Set nonce details for cases where nonce is customized * Fix incorrectly use value for deciding whether to getnoncelock in approveTransaction * Default nonceLock to empty object in approveTransaction * Reapply use on nonceLock in cases where customNonceValue in approveTransaction. * Show warning message if custom nonce is higher than MetaMask's next nonce * Fix e2e test failure caused by custom nonce and 3box toggle conflict * Update nonce warning message to include the suggested nonce * Handle nextNonce comparison and update logic in lifecycle * Default nonce field to suggested nonce * Clear custom nonce on reject or confirm * Fix bug where nonces are not shown in tx list on self sent transactions * Ensure custom nonce is reset after tx is created in background * Convert customNonceValue to number in approve tranasction controller * Lint fix * Call getNextNonce after updating custom nonce
2019-09-27 06:30:36 +02:00
this.store.updateState({ useNonceField: val })
}
/**
* Setter for the `usePhishDetect` property
*
* @param {boolean} val - Whether or not the user prefers phishing domain protection
*
*/
2020-11-03 00:41:28 +01:00
setUsePhishDetect(val) {
this.store.updateState({ usePhishDetect: val })
}
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
/**
* Setter for the `firstTimeFlowType` property
*
* @param {string} type - Indicates the type of first time flow - create or import - the user wishes to follow
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
*
*/
2020-11-03 00:41:28 +01:00
setFirstTimeFlowType(type) {
this.store.updateState({ firstTimeFlowType: type })
}
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
2020-11-03 00:41:28 +01:00
getSuggestedTokens() {
2018-06-19 00:05:41 +02:00
return this.store.getState().suggestedTokens
}
2020-11-03 00:41:28 +01:00
getAssetImages() {
2018-08-21 17:59:42 +02:00
return this.store.getState().assetImages
}
/**
* Add new methodData to state, to avoid requesting this information again through Infura
*
* @param {string} fourBytePrefix - Four-byte method signature
* @param {string} methodData - Corresponding data method
*/
2020-11-03 00:41:28 +01:00
addKnownMethodData(fourBytePrefix, methodData) {
const { knownMethodData } = this.store.getState()
knownMethodData[fourBytePrefix] = methodData
this.store.updateState({ knownMethodData })
}
2018-06-19 00:05:41 +02:00
/**
* wallet_watchAsset request handler.
*
* @param {Object} req - The watchAsset JSON-RPC request object.
*/
async requestWatchAsset(req) {
const { type, options } = req.params
switch (type) {
case 'ERC20':
return await this._handleWatchAssetERC20(options)
default:
throw ethErrors.rpc.invalidParams(
`Asset of type "${type}" not supported.`,
)
}
2018-06-19 00:05:41 +02:00
}
2018-04-18 20:41:39 +02:00
/**
* Setter for the `currentLocale` property
*
* @param {string} key - he preferred language locale key
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
setCurrentLocale(key) {
const textDirection = ['ar', 'dv', 'fa', 'he', 'ku'].includes(key)
? 'rtl'
: 'auto'
this.store.updateState({
currentLocale: key,
textDirection,
})
return textDirection
2018-03-16 01:29:45 +01:00
}
/**
* Updates identities to only include specified addresses. Removes identities
* not included in addresses array
*
* @param {string[]} addresses - An array of hex addresses
*
*/
2020-11-03 00:41:28 +01:00
setAddresses(addresses) {
const oldIdentities = this.store.getState().identities
const oldAccountTokens = this.store.getState().accountTokens
const oldAccountHiddenTokens = this.store.getState().accountHiddenTokens
2018-07-27 22:05:12 +02:00
const identities = addresses.reduce((ids, address, index) => {
const oldId = oldIdentities[address] || {}
2019-12-03 21:50:55 +01:00
ids[address] = { name: `Account ${index + 1}`, address, ...oldId }
return ids
}, {})
2018-07-31 01:09:17 +02:00
const accountTokens = addresses.reduce((tokens, address) => {
const oldTokens = oldAccountTokens[address] || {}
tokens[address] = oldTokens
return tokens
}, {})
const accountHiddenTokens = addresses.reduce((hiddenTokens, address) => {
const oldHiddenTokens = oldAccountHiddenTokens[address] || {}
hiddenTokens[address] = oldHiddenTokens
return hiddenTokens
}, {})
this.store.updateState({ identities, accountTokens, accountHiddenTokens })
}
2018-07-11 06:20:40 +02:00
/**
* Removes an address from state
*
* @param {string} address - A hex address
* @returns {string} the address that was removed
2018-07-11 06:20:40 +02:00
*/
2020-11-03 00:41:28 +01:00
removeAddress(address) {
const {
identities,
accountTokens,
accountHiddenTokens,
} = this.store.getState()
2018-07-11 06:20:40 +02:00
if (!identities[address]) {
throw new Error(`${address} can't be deleted cause it was not found`)
}
delete identities[address]
2018-07-27 22:05:12 +02:00
delete accountTokens[address]
delete accountHiddenTokens[address]
this.store.updateState({ identities, accountTokens, accountHiddenTokens })
2018-07-11 06:20:40 +02:00
// If the selected account is no longer valid,
// select an arbitrary other account:
if (address === this.getSelectedAddress()) {
const selected = Object.keys(identities)[0]
this.setSelectedAddress(selected)
}
return address
}
/**
* Adds addresses to the identities object without removing identities
*
* @param {string[]} addresses - An array of hex addresses
*
*/
2020-11-03 00:41:28 +01:00
addAddresses(addresses) {
const {
identities,
accountTokens,
accountHiddenTokens,
} = this.store.getState()
addresses.forEach((address) => {
// skip if already exists
if (identities[address]) {
return
}
// add missing identity
const identityCount = Object.keys(identities).length
accountTokens[address] = {}
accountHiddenTokens[address] = {}
identities[address] = { name: `Account ${identityCount + 1}`, address }
})
this.store.updateState({ identities, accountTokens, accountHiddenTokens })
}
/**
* Synchronizes identity entries with known accounts.
* Removes any unknown identities, and returns the resulting selected address.
*
* @param {Array<string>} addresses - known to the vault.
* @returns {Promise<string>} selectedAddress the selected address.
*/
2020-11-03 00:41:28 +01:00
syncAddresses(addresses) {
if (!Array.isArray(addresses) || addresses.length === 0) {
throw new Error('Expected non-empty array of addresses.')
}
2018-07-03 00:49:33 +02:00
const { identities, lostIdentities } = this.store.getState()
2018-07-03 00:49:33 +02:00
const newlyLost = {}
Object.keys(identities).forEach((identity) => {
if (!addresses.includes(identity)) {
newlyLost[identity] = identities[identity]
2018-06-05 00:34:38 +02:00
delete identities[identity]
}
})
2018-06-04 23:21:46 +02:00
// Identities are no longer present.
if (Object.keys(newlyLost).length > 0) {
// store lost accounts
2020-07-21 23:10:45 +02:00
Object.keys(newlyLost).forEach((key) => {
lostIdentities[key] = newlyLost[key]
2020-07-21 23:10:45 +02:00
})
2018-06-04 23:21:46 +02:00
}
this.store.updateState({ identities, lostIdentities })
this.addAddresses(addresses)
2018-06-05 00:18:12 +02:00
// If the selected account is no longer valid,
// select an arbitrary other account:
let selected = this.getSelectedAddress()
if (!addresses.includes(selected)) {
selected = addresses[0]
this.setSelectedAddress(selected)
}
return selected
}
2020-11-03 00:41:28 +01:00
removeSuggestedTokens() {
return new Promise((resolve) => {
2018-08-04 01:24:12 +02:00
this.store.updateState({ suggestedTokens: {} })
resolve({})
2018-08-04 01:24:12 +02:00
})
}
2018-04-18 20:41:39 +02:00
/**
* Setter for the `selectedAddress` property
*
* @param {string} _address - A new hex address for an account
* @returns {Promise<void>} Promise resolves with tokens
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
setSelectedAddress(_address) {
2018-07-27 01:28:12 +02:00
const address = normalizeAddress(_address)
2018-07-31 21:59:19 +02:00
this._updateTokens(address)
Fix order of accounts in `eth_accounts` response (#8342) * Fix order of accounts in `eth_accounts` response The accounts returned by `eth_accounts` were in a fixed order - the order in which the keyring returned them - rather than ordered with the selected account first. The accounts returned by the `accountsChanged` event were ordered with the selected account first, but the same order wasn't used for `eth_accounts`. We needed to store additional state in order to determine the correct account order correctly on all dapps. We had only been storing the current selected account, but since we also need to determine the primary account per dapp (i.e. the last "selected" account among the accounts exposed to that dapp), that wasn't enough. A `lastSelected` property has been added to each identity in the preferences controller to keep track of the last selected time. This property is set to the current time (in milliseconds) whenever a new selection is made. The accounts returned with `accountsChanged` and by `eth_accounts` are both ordered by this property. The `updatePermittedAccounts` function was merged with the internal methods for responding to account selection, to keep things simpler. It wasn't called externally anyway, so it wasn't needed in the public API. * Remove caveat update upon change in selected account The order of accounts in the caveat isn't meaningful, so the caveat doesn't need to be updated when the accounts get re-ordered. * Emit event regardless of account order Now that we're no longer relying upon the caveat for the account order, we also have no way of knowing if a particular account selection resulted in a change in order or not. The notification is now emitted whenever an exposed account is selected - even if the order stayed the same. The inpage provider currently caches the account order, so it can be relied upon to ignore these redundant events. We were already emiting redundant `accountsChanged` events in some cases anyway.
2020-04-16 20:20:01 +02:00
const { identities, tokens } = this.store.getState()
const selectedIdentity = identities[address]
if (!selectedIdentity) {
throw new Error(`Identity for '${address} not found`)
}
selectedIdentity.lastSelected = Date.now()
this.store.updateState({ identities, selectedAddress: address })
2018-07-27 01:28:12 +02:00
return Promise.resolve(tokens)
}
/**
* Getter for the `selectedAddress` property
*
* @returns {string} The hex address for the currently selected account
*
*/
2020-11-03 00:41:28 +01:00
getSelectedAddress() {
return this.store.getState().selectedAddress
}
/**
* Contains data about tokens users add to their account.
* @typedef {Object} AddedToken
* @property {string} address - The hex address for the token contract. Will be all lower cased and hex-prefixed.
* @property {string} symbol - The symbol of the token, usually 3 or 4 capitalized letters
* {@link https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol}
* @property {boolean} decimals - The number of decimals the token uses.
* {@link https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals}
*/
/**
* Adds a new token to the token array and removes it from the hiddenToken array, or updates the token if passed an address that already exists.
* Modifies the existing tokens array from the store. All objects in the tokens array array AddedToken objects.
* @see AddedToken {@link AddedToken}
*
* @param {string} rawAddress - Hex address of the token contract. May or may not be a checksum address.
* @param {string} symbol - The symbol of the token
* @param {number} decimals - The number of decimals the token uses.
* @returns {Promise<array>} Promises the new array of AddedToken objects.
*
*/
2020-11-03 00:41:28 +01:00
async addToken(rawAddress, symbol, decimals, image) {
const address = normalizeAddress(rawAddress)
const newEntry = { address, symbol, decimals }
const { tokens, hiddenTokens } = this.store.getState()
2018-08-21 17:59:42 +02:00
const assetImages = this.getAssetImages()
const updatedHiddenTokens = hiddenTokens.filter(
(tokenAddress) => tokenAddress !== rawAddress.toLowerCase(),
)
const previousEntry = tokens.find((token) => {
return token.address === address
})
const previousIndex = tokens.indexOf(previousEntry)
if (previousEntry) {
tokens[previousIndex] = newEntry
} else {
tokens.push(newEntry)
}
2018-08-23 20:54:40 +02:00
assetImages[address] = image
this._updateAccountTokens(tokens, assetImages, updatedHiddenTokens)
return Promise.resolve(tokens)
}
2018-04-18 20:41:39 +02:00
/**
* Removes a specified token from the tokens array and adds it to hiddenTokens array
2018-04-18 20:41:39 +02:00
*
* @param {string} rawAddress - Hex address of the token contract to remove.
* @returns {Promise<array>} The new array of AddedToken objects
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
removeToken(rawAddress) {
const { tokens, hiddenTokens } = this.store.getState()
2018-08-21 17:59:42 +02:00
const assetImages = this.getAssetImages()
2020-02-15 21:34:12 +01:00
const updatedTokens = tokens.filter((token) => token.address !== rawAddress)
const updatedHiddenTokens = [...hiddenTokens, rawAddress.toLowerCase()]
2018-08-21 17:59:42 +02:00
delete assetImages[rawAddress]
this._updateAccountTokens(updatedTokens, assetImages, updatedHiddenTokens)
return Promise.resolve(updatedTokens)
}
2018-04-18 20:41:39 +02:00
/**
* A getter for the `tokens` property
*
* @returns {Array} The current array of AddedToken objects
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
getTokens() {
return this.store.getState().tokens
}
/**
* Sets a custom label for an account
* @param {string} account - the account to set a label for
* @param {string} label - the custom label for the account
* @returns {Promise<string>}
*/
2020-11-03 00:41:28 +01:00
setAccountLabel(account, label) {
if (!account) {
2020-11-03 00:41:28 +01:00
throw new Error(
`setAccountLabel requires a valid address, got ${String(account)}`,
)
}
const address = normalizeAddress(account)
2019-12-03 21:50:55 +01:00
const { identities } = this.store.getState()
identities[address] = identities[address] || {}
identities[address].name = label
this.store.updateState({ identities })
return Promise.resolve(label)
}
/**
* updates custom RPC details
*
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
* @param {Object} newRpcDetails - Options bag.
* @param {string} newRpcDetails.rpcUrl - The RPC url to add to frequentRpcList.
* @param {string} newRpcDetails.chainId - The chainId of the selected network.
* @param {string} [newRpcDetails.ticker] - Optional ticker symbol of the selected network.
* @param {string} [newRpcDetails.nickname] - Optional nickname of the selected network.
* @param {Object} [newRpcDetails.rpcPrefs] - Optional RPC preferences, such as the block explorer URL
*
*/
2020-11-03 00:41:28 +01:00
async updateRpc(newRpcDetails) {
const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => {
return element.rpcUrl === newRpcDetails.rpcUrl
})
if (index > -1) {
const rpcDetail = rpcList[index]
const updatedRpc = { ...rpcDetail, ...newRpcDetails }
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
if (rpcDetail.chainId !== updatedRpc.chainId) {
// When the chainId is changed, associated address book entries should
// also be migrated. The address book entries are keyed by the `network` state,
// which for custom networks is the chainId with a fallback to the networkId
// if the chainId is not set.
let addressBookKey = rpcDetail.chainId
if (!addressBookKey) {
// We need to find the networkId to determine what these addresses were keyed by
2020-11-03 00:41:28 +01:00
const provider = new ethers.providers.JsonRpcProvider(
rpcDetail.rpcUrl,
)
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
try {
addressBookKey = await provider.send('net_version')
assert(typeof addressBookKey === 'string')
} catch (error) {
log.debug(error)
2020-11-03 00:41:28 +01:00
log.warn(
`Failed to get networkId from ${rpcDetail.rpcUrl}; skipping address book migration`,
)
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
}
}
// There is an edge case where two separate RPC endpoints are keyed by the same
// value. In this case, the contact book entries are duplicated so that they remain
// on both networks, since we don't know which network each contact is intended for.
let duplicate = false
2020-11-03 00:41:28 +01:00
const builtInProviderNetworkIds = Object.values(
NETWORK_TYPE_TO_ID_MAP,
).map((ids) => ids.networkId)
const otherRpcEntries = rpcList.filter(
(entry) => entry.rpcUrl !== newRpcDetails.rpcUrl,
)
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
if (
builtInProviderNetworkIds.includes(addressBookKey) ||
otherRpcEntries.some((entry) => entry.chainId === addressBookKey)
) {
duplicate = true
}
2020-11-03 00:41:28 +01:00
this.migrateAddressBookState(
addressBookKey,
updatedRpc.chainId,
duplicate,
)
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
}
rpcList[index] = updatedRpc
this.store.updateState({ frequentRpcListDetail: rpcList })
} else {
New settings custom rpc form (#6490) * Add networks tab to settings, with header. * Adds network list to settings network tab. * Adds form to settings networks tab and connects it to network list. * Network tab: form adding and editing working * Settings network form properly handles input errors * Add translations for settings network form * Clean up styles of settings network tab. * Add popup-view styles and behaviour to settings network tab. * Fix save button on settings network form * Adds 'Add Network' button and addMode to settings networks tab * Lint fix for settings networks tab addition * Fix navigation in settings networks tab. * Editing an rpcurl in networks tab does not create new network, just changes rpc of old * Fix layout of settings tabs other than network * Networks dropdown 'Custom Rpc' item links to networks tab in settings. * Update settings sidebar networks subheader. * Make networks tab buttons width consistent with input widths in extension view. * Fix settings screen subheader height in popup view * Fix height of add networks button in popup view * Add optional label to chainId and symbol form labels in networks setting tab * Style fixes for networks tab headers * Add ability to customize block explorer used by custom rpc * Stylistic improvements+fixes to custom rpc form. * Hide cancel button. * Highlight and show network form of provider by default. * Standardize network subheader name to 'Networks' * Update e2e tests for new settings network form * Update unit tests for new rpcPrefs prop * Extract blockexplorer url construction into method. * Fix broken styles on non-network tabs in popup mode * Fix block explorer url links for cases when provider in state has not been updated. * Fix vertical spacing of network form * Don't allow click of save button on network form if nothing has changed * Ensure add network button is shown in popup view * Lint fix for networks tab * Fix block explorer url preference setting. * Fix e2e tests for custom blockexplorer in account details modal changes. * Update integration test states to include frequentRpcList property * Fix some capitalizations in en/messages.json * Remove some console.logs added during custom rpc form work * Fix external account link text and url for modal and dropdown. * Documentation, url validation, proptype required additions and lint fixes on network tab and form.
2019-05-09 19:27:14 +02:00
const { rpcUrl, chainId, ticker, nickname, rpcPrefs = {} } = newRpcDetails
this.addToFrequentRpcList(rpcUrl, chainId, ticker, nickname, rpcPrefs)
}
}
2018-04-18 20:41:39 +02:00
/**
* Adds custom RPC url to state.
2018-04-18 20:41:39 +02:00
*
* @param {string} rpcUrl - The RPC url to add to frequentRpcList.
* @param {string} chainId - The chainId of the selected network.
* @param {string} [ticker] - Ticker symbol of the selected network.
* @param {string} [nickname] - Nickname of the selected network.
Update address book state upon custom RPC chainId edit (#9493) When the `chainId` for a custom RPC endpoint is edited, we now migrate the corresponding address book entries to ensure they are not orphaned. The address book entries are grouped by the `metamask.network` state, which unfortunately was sometimes the `chainId`, and sometimes the `networkId`. It was always the `networkId` for built-in Infura networks, but for custom RPC endpoints it would be set to the user-set `chainId` field, with a fallback to the `networkId` of the network. A recent change will force users to enter valid `chainId`s on all custom networks, which will be normalized to be hex-prefixed. As a result, address book contacts will now be keyed by a different string. The contact entries are now migrated when this edit takes place. There are some edge cases where two separate entries share the same set of contacts. For example, if two entries have the same `chainId`, or if they had the same `networkId` and had no `chainId` set. When the `chainId` is edited in such cases, the contacts are duplicated on both networks. This is the best we can do, as we don't have any way to know which network the contacts _should_ be on. The `typed-message-manager` unit tests have also been updated as part of this commit because the addition of `sinon.restore()` to the preferences controller tests ended up clearing a test object in-between individual tests in that file. The test object is now re-constructed before each individual test.
2020-10-07 19:32:17 +02:00
* @param {Object} [rpcPrefs] - Optional RPC preferences, such as the block explorer URL
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
addToFrequentRpcList(
rpcUrl,
chainId,
ticker = 'ETH',
nickname = '',
rpcPrefs = {},
) {
const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => {
return element.rpcUrl === rpcUrl
})
if (index !== -1) {
rpcList.splice(index, 1)
}
if (!isPrefixedFormattedHexString(chainId)) {
throw new Error(`Invalid chainId: "${chainId}"`)
}
rpcList.push({ rpcUrl, chainId, ticker, nickname, rpcPrefs })
this.store.updateState({ frequentRpcListDetail: rpcList })
}
/**
* Removes custom RPC url from state.
*
* @param {string} url - The RPC url to remove from frequentRpcList.
* @returns {Promise<array>} Promise resolving to updated frequentRpcList.
*
*/
2020-11-03 00:41:28 +01:00
removeFromFrequentRpcList(url) {
const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => {
return element.rpcUrl === url
})
if (index !== -1) {
rpcList.splice(index, 1)
}
this.store.updateState({ frequentRpcListDetail: rpcList })
return Promise.resolve(rpcList)
2017-02-21 21:32:13 +01:00
}
2018-04-18 20:41:39 +02:00
/**
* Getter for the `frequentRpcListDetail` property.
2018-04-18 20:41:39 +02:00
*
* @returns {array<array>} An array of rpc urls.
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
getFrequentRpcListDetail() {
return this.store.getState().frequentRpcListDetail
2017-02-21 21:32:13 +01:00
}
2017-11-14 17:04:55 +01:00
2018-04-18 20:41:39 +02:00
/**
* Updates the `featureFlags` property, which is an object. One property within that object will be set to a boolean.
*
* @param {string} feature - A key that corresponds to a UI feature.
* @param {boolean} activated - Indicates whether or not the UI feature should be displayed
* @returns {Promise<object>} Promises a new object; the updated featureFlags object.
2018-04-18 20:41:39 +02:00
*
*/
2020-11-03 00:41:28 +01:00
setFeatureFlag(feature, activated) {
2017-11-14 17:04:55 +01:00
const currentFeatureFlags = this.store.getState().featureFlags
const updatedFeatureFlags = {
...currentFeatureFlags,
[feature]: activated,
}
this.store.updateState({ featureFlags: updatedFeatureFlags })
2017-11-16 20:28:59 +01:00
2017-11-14 17:04:55 +01:00
return Promise.resolve(updatedFeatureFlags)
}
/**
* Updates the `preferences` property, which is an object. These are user-controlled features
* found in the settings page.
* @param {string} preference - The preference to enable or disable.
* @param {boolean} value - Indicates whether or not the preference should be enabled or disabled.
* @returns {Promise<object>} Promises a new object; the updated preferences object.
*/
2020-11-03 00:41:28 +01:00
setPreference(preference, value) {
const currentPreferences = this.getPreferences()
const updatedPreferences = {
...currentPreferences,
[preference]: value,
}
this.store.updateState({ preferences: updatedPreferences })
return Promise.resolve(updatedPreferences)
}
/**
* A getter for the `preferences` property
* @returns {Object} A key-boolean map of user-selected preferences.
*/
2020-11-03 00:41:28 +01:00
getPreferences() {
return this.store.getState().preferences
}
/**
* Sets the completedOnboarding state to true, indicating that the user has completed the
* onboarding process.
*/
2020-11-03 00:41:28 +01:00
completeOnboarding() {
this.store.updateState({ completedOnboarding: true })
return Promise.resolve(true)
}
/**
* A getter for the `ipfsGateway` property
* @returns {string} The current IPFS gateway domain
*/
2020-11-03 00:41:28 +01:00
getIpfsGateway() {
return this.store.getState().ipfsGateway
}
/**
* A setter for the `ipfsGateway` property
* @param {string} domain - The new IPFS gateway domain
* @returns {Promise<string>} A promise of the update IPFS gateway domain
*/
2020-11-03 00:41:28 +01:00
setIpfsGateway(domain) {
this.store.updateState({ ipfsGateway: domain })
return Promise.resolve(domain)
}
//
// PRIVATE METHODS
//
2018-08-07 00:28:47 +02:00
/**
* Subscription to network provider type.
*
*
*/
2020-11-03 00:41:28 +01:00
_subscribeProviderType() {
2018-07-31 21:59:19 +02:00
this.network.providerStore.subscribe(() => {
const { tokens, hiddenTokens } = this._getTokenRelatedStates()
this._updateAccountTokens(tokens, this.getAssetImages(), hiddenTokens)
})
}
/**
* Updates `accountTokens`, `tokens`, `accountHiddenTokens` and `hiddenTokens` of current account and network according to it.
*
* @param {array} tokens - Array of tokens to be updated.
* @param {array} assetImages - Array of assets objects related to assets added
* @param {array} hiddenTokens - Array of tokens hidden by user
*
*/
_updateAccountTokens(tokens, assetImages, hiddenTokens) {
2020-11-03 00:41:28 +01:00
const {
accountTokens,
providerType,
selectedAddress,
accountHiddenTokens,
2020-11-03 00:41:28 +01:00
} = this._getTokenRelatedStates()
accountTokens[selectedAddress][providerType] = tokens
accountHiddenTokens[selectedAddress][providerType] = hiddenTokens
this.store.updateState({
accountTokens,
tokens,
assetImages,
accountHiddenTokens,
hiddenTokens,
})
2018-07-27 22:05:12 +02:00
}
2018-07-27 22:05:12 +02:00
/**
* Updates `tokens` and `hiddenTokens` of current account and network.
2018-07-27 22:05:12 +02:00
*
* @param {string} selectedAddress - Account address to be updated with.
2018-07-27 22:05:12 +02:00
*
*/
2020-11-03 00:41:28 +01:00
_updateTokens(selectedAddress) {
const { tokens, hiddenTokens } = this._getTokenRelatedStates(
selectedAddress,
)
this.store.updateState({ tokens, hiddenTokens })
2018-07-31 21:59:19 +02:00
}
/**
* A getter for `tokens`, `accountTokens`, `hiddenTokens` and `accountHiddenTokens` related states.
2018-07-31 21:59:19 +02:00
*
* @param {string} [selectedAddress] - A new hex address for an account
* @returns {Object.<array, object, string, string>} States to interact with tokens in `accountTokens`
2018-07-31 21:59:19 +02:00
*
*/
2020-11-03 00:41:28 +01:00
_getTokenRelatedStates(selectedAddress) {
const { accountTokens, accountHiddenTokens } = this.store.getState()
if (!selectedAddress) {
// eslint-disable-next-line no-param-reassign
selectedAddress = this.store.getState().selectedAddress
}
const providerType = this.network.providerStore.getState().type
if (!(selectedAddress in accountTokens)) {
accountTokens[selectedAddress] = {}
}
if (!(selectedAddress in accountHiddenTokens)) {
accountHiddenTokens[selectedAddress] = {}
}
if (!(providerType in accountTokens[selectedAddress])) {
accountTokens[selectedAddress][providerType] = []
}
if (!(providerType in accountHiddenTokens[selectedAddress])) {
accountHiddenTokens[selectedAddress][providerType] = []
}
const tokens = accountTokens[selectedAddress][providerType]
const hiddenTokens = accountHiddenTokens[selectedAddress][providerType]
return {
tokens,
accountTokens,
hiddenTokens,
accountHiddenTokens,
providerType,
selectedAddress,
}
2018-08-07 00:28:47 +02:00
}
/**
* Handle the suggestion of an ERC20 asset through `watchAsset`
* *
* @param {Object} tokenMetadata - Token metadata
*
*/
async _handleWatchAssetERC20(tokenMetadata) {
this._validateERC20AssetParams(tokenMetadata)
const address = normalizeAddress(tokenMetadata.address)
const { symbol, decimals, image } = tokenMetadata
this._addSuggestedERC20Asset(address, symbol, decimals, image)
await this.openPopup()
const tokenAddresses = this.getTokens().filter(
(token) => token.address === address,
)
return tokenAddresses.length > 0
}
2018-08-21 17:59:42 +02:00
/**
* Validates that the passed options for suggested token have all required properties.
*
* @param {Object} opts - The options object to validate
2018-08-21 17:59:42 +02:00
* @throws {string} Throw a custom error indicating that address, symbol and/or decimals
* doesn't fulfill requirements
*
*/
_validateERC20AssetParams({ address, symbol, decimals }) {
if (!address || !symbol || typeof decimals === 'undefined') {
throw ethErrors.rpc.invalidParams(
`Must specify address, symbol, and decimals.`,
2020-11-03 00:41:28 +01:00
)
}
if (typeof symbol !== 'string') {
throw ethErrors.rpc.invalidParams(`Invalid symbol: not a string.`)
}
if (!(symbol.length < 7)) {
throw ethErrors.rpc.invalidParams(
`Invalid symbol "${symbol}": longer than 6 characters.`,
)
}
2018-08-21 17:59:42 +02:00
const numDecimals = parseInt(decimals, 10)
if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) {
throw ethErrors.rpc.invalidParams(
`Invalid decimals "${decimals}": must be 0 <= 36.`,
2020-11-03 00:41:28 +01:00
)
2018-08-21 17:59:42 +02:00
}
if (!isValidAddress(address)) {
throw ethErrors.rpc.invalidParams(`Invalid address "${address}".`)
}
2018-08-21 17:59:42 +02:00
}
_addSuggestedERC20Asset(address, symbol, decimals, image) {
const newEntry = {
address,
symbol,
decimals,
image,
unlisted: !LISTED_CONTRACT_ADDRESSES.includes(address),
}
const suggested = this.getSuggestedTokens()
suggested[address] = newEntry
this.store.updateState({ suggestedTokens: suggested })
}
}