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

273 lines
7.8 KiB
JavaScript
Raw Normal View History

import copyToClipboard from 'copy-to-clipboard';
import log from 'loglevel';
import { clone } from 'lodash';
import React from 'react';
import { render } from 'react-dom';
import browser from 'webextension-polyfill';
import { getEnvironmentType } from '../app/scripts/lib/util';
import { AlertTypes } from '../shared/constants/alerts';
import { maskObject } from '../shared/modules/object.utils';
import { SENTRY_STATE } from '../app/scripts/lib/setupSentry';
import { ENVIRONMENT_TYPE_POPUP } from '../shared/constants/app';
import switchDirection from '../shared/lib/switch-direction';
import { setupLocale } from '../shared/lib/error-utils';
import * as actions from './store/actions';
import configureStore from './store/store';
2020-11-03 00:41:28 +01:00
import {
getPermittedAccountsForCurrentTab,
getSelectedAddress,
} from './selectors';
import { ALERT_STATE } from './ducks/alerts';
import {
getUnconnectedAccountAlertEnabledness,
getUnconnectedAccountAlertShown,
} from './ducks/metamask/metamask';
import Root from './pages';
import txHelper from './helpers/utils/tx-helper';
import { _setBackgroundConnection } from './store/action-queue';
2017-02-20 21:59:44 +01:00
log.setLevel(global.METAMASK_DEBUG ? 'debug' : 'warn');
let reduxStore;
/**
* Method to update backgroundConnection object use by UI
*
* @param backgroundConnection - connection object to background
*/
export const updateBackgroundConnection = (backgroundConnection) => {
_setBackgroundConnection(backgroundConnection);
backgroundConnection.onNotification((data) => {
if (data.method === 'sendUpdate') {
reduxStore.dispatch(actions.updateMetamaskState(data.params[0]));
} else {
throw new Error(
`Internal JSON-RPC Notification Not Handled:\n\n ${JSON.stringify(
data,
)}`,
);
}
});
};
2020-11-03 00:41:28 +01:00
export default function launchMetamaskUi(opts, cb) {
const { backgroundConnection } = opts;
///: BEGIN:ONLY_INCLUDE_IN(desktop)
let desktopEnabled = false;
backgroundConnection.getDesktopEnabled(function (err, result) {
if (err) {
return;
}
desktopEnabled = result;
});
///: END:ONLY_INCLUDE_IN
// check if we are unlocked first
backgroundConnection.getState(function (err, metamaskState) {
if (err) {
cb(
err,
{
...metamaskState,
///: BEGIN:ONLY_INCLUDE_IN(desktop)
desktopEnabled,
///: END:ONLY_INCLUDE_IN
},
backgroundConnection,
);
return;
}
2020-11-03 00:41:28 +01:00
startApp(metamaskState, backgroundConnection, opts).then((store) => {
Add additional Sentry E2E tests (#20425) * Reorganize Sentry error e2e tests The tests have been reorganized into different describe blocks. Each describe block is for either before or after initialization, and either with or without opting into metrics. This was done to simplify later test additions. The conditions for each test are now in the describe block, letting us test additional things in each of these conditions. The conditions were flattened to a single level to avoid excessive indentation. * Add error e2e test for background and UI errors The Sentry e2e tests before initialization only tested background errors, and the after initialization tests only tested UI errors. Now both types of errors are tested in both scenarios. * Add error e2e tests for Sentry error state E2E tests have been added to test the state object sent along with each Sentry error. At the moment this object is empty in some circumstances, but this will change in later PRs. * Rename throw test error function * Only setup debug/test state hooks in dev/test builds The state hooks used for debugging and testing are now only included in dev or test builds. The function name was updated and given a JSDoc description to explain this more clearly as well. * Add state snapshot assertions State snapshot assertions have been added to the e2e error tests. These snapshots will be very useful in reviewing a few PRs that will follow this one. We might decide to remove these snapshots after this set of Sentry refactors, as they might be more work to maintain than they're worth. But they will be useful at least in the short-term. The login step has been removed from a few tests because it introduced indeterminacy (the login process continued asynchronously after the login, and sometimes was not finished when the error was triggered). * Ensure login page has rendered during setup This fixes an intermittent failure on Firefox * Format snapshots with prettier before writing them * Use defined set of date fields rather than infering from name * Remove waits for error screen The error screen only appears after a long timeout, and it doesn't affect the next test steps at all.
2023-08-16 16:22:25 +02:00
setupStateHooks(store);
cb(
null,
store,
///: BEGIN:ONLY_INCLUDE_IN(desktop)
backgroundConnection,
///: END:ONLY_INCLUDE_IN
);
});
});
}
2020-11-03 00:41:28 +01:00
async function startApp(metamaskState, backgroundConnection, opts) {
// parse opts
if (!metamaskState.featureFlags) {
metamaskState.featureFlags = {};
}
2018-03-16 01:29:45 +01:00
Add friendly error handling when background throws an error before listening for connection (#14461) * When background port closes, UI should display a user friendly error. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Remove console.log Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> A couple of fixes 1. Use timeout in metaRPCClientFactory to check if UI can't communicate with bg 2. Refactor locale setup 3. Fixed wording/capitalization 4. Fix locales usage so that linting works 5. Refactor CSS Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> do not simulate errorwq Refactor loading css Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Remove the onDisconnect event handler in ui as this is handled in metarpcclientfactory Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Do not throw in bg Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Fix PR comments Remove unused message 'failedToLoadMessage' Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Move usage of locales to shared/** so that linter can see it. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Do not simulate error. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> metarpc can handle multiple requests, responseHandled should be a map. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> reload metamask button on critical error Use metamask state (if available) to the locale, else read locale files manually. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> use constant and numeric separator Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> refactor error utils remove error simulation Memoize setupLocale function Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> test cases Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Do not simulate error Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> 1. store should be metamask state 2. code refactorings. Tests: mock setupLocale Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Mock fetchLocale instead Test setup locale Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> UI/CSS changes. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Do not simulate failure Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * spell MetaMask correctly Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Rename state to mockStore Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * we should clean up this.responseHandled[id] in the error case. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Fixed PR comments. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * clean up response handled. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com>
2022-06-07 22:37:15 +02:00
const { currentLocaleMessages, enLocaleMessages } = await setupLocale(
metamaskState.currentLocale,
);
if (metamaskState.textDirection === 'rtl') {
await switchDirection('rtl');
}
const draftInitialState = {
activeTab: opts.activeTab,
// metamaskState represents the cross-tab state
metamask: metamaskState,
// appState represents the current tab's popup state
2016-09-13 06:30:04 +02:00
appState: {},
localeMessages: {
currentLocale: metamaskState.currentLocale,
current: currentLocaleMessages,
en: enLocaleMessages,
},
};
updateBackgroundConnection(backgroundConnection);
if (getEnvironmentType() === ENVIRONMENT_TYPE_POPUP) {
const { origin } = draftInitialState.activeTab;
2022-07-31 20:26:40 +02:00
const permittedAccountsForCurrentTab =
getPermittedAccountsForCurrentTab(draftInitialState);
const selectedAddress = getSelectedAddress(draftInitialState);
2022-07-31 20:26:40 +02:00
const unconnectedAccountAlertShownOrigins =
getUnconnectedAccountAlertShown(draftInitialState);
const unconnectedAccountAlertIsEnabled =
getUnconnectedAccountAlertEnabledness(draftInitialState);
if (
origin &&
unconnectedAccountAlertIsEnabled &&
!unconnectedAccountAlertShownOrigins[origin] &&
permittedAccountsForCurrentTab.length > 0 &&
!permittedAccountsForCurrentTab.includes(selectedAddress)
) {
draftInitialState[AlertTypes.unconnectedAccount] = {
state: ALERT_STATE.OPEN,
};
actions.setUnconnectedAccountAlertShown(origin);
}
}
const store = configureStore(draftInitialState);
reduxStore = store;
// if unconfirmed txs, start on txConf page
const unapprovedTxsAll = txHelper(
metamaskState.unapprovedTxs,
metamaskState.unapprovedMsgs,
metamaskState.unapprovedPersonalMsgs,
metamaskState.unapprovedDecryptMsgs,
metamaskState.unapprovedEncryptionPublicKeyMsgs,
metamaskState.unapprovedTypedMessages,
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
metamaskState.networkId,
metamaskState.providerConfig.chainId,
);
const numberOfUnapprovedTx = unapprovedTxsAll.length;
if (numberOfUnapprovedTx > 0) {
2020-11-03 00:41:28 +01:00
store.dispatch(
actions.showConfTxPage({
id: unapprovedTxsAll[0].id,
}),
);
}
// global metamask api - used by tooling
global.metamask = {
updateCurrentLocale: (code) => {
store.dispatch(actions.updateCurrentLocale(code));
},
setProviderType: (type) => {
store.dispatch(actions.setProviderType(type));
},
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
setFeatureFlag: (key, value) => {
store.dispatch(actions.setFeatureFlag(key, value));
3box integration 2.0 (#6972) * Adds threebox controller * Adds threebox approval modal * Fix unit tests and lint after addition of threebox * Correct threebox behaviour after rejecting request for backup; fixes e2e tests. * Update threebox controller for automatic syncing * Ensure frontend locale updates when preferences are changed via direct update within controller * Add toggle in settings for 3box syncing * Update threebox controller for latest 3box version * Delete unnecessary frontend changes for threebox integration * Backing up address book contacts with threebox * Update unit tests for 3box-integration additions * Only enable threebox by default for new wallets * Mock globals for correct unit tests * 3box '1.10.2' -> '^1.10.2' * Correct capilalization on 3Box * Use log.debug instead of console.log in threebox controller * Update yarn.lock * Remove edge build * Split 3box module into background deps js file * extra bundle opts for bg-libs * sync yarn.lock * new3Box logic * Show confirm threebox restore after import * Remove bg-libs.js from manifest file for dev builds * Switch 3Box controller to using the spaces api (instead of the profile api) * Finalize switching to spaces api and only restoring from 3box after import * Update metamask-controller-test.js for threebox controller changes * Make threebox modal style consistent with others and update success button wording * Use mock 3box when in test * Correct 3box modal header * Remove unnecessary property of threebox controller provider * Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal. * Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn * Replace erroneous use of with * Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory * Lint fixes for 3box changes * Log errors encountered when updating 3Box * Remove unnecessary parameter from state update * Add timeout to initial 3Box sync The initial 3Box sync will now timeout after 1 minute. If the timeout is triggered, 3Box is disabled and cannot be re-enabled unless the initial sync does finally finish. If it never finishes, 3Box cannot be enabled unless the extension is reinstalled. The Advanced Settings page was updated to show this option as disabled in that circumstance, with a new discription explaining why it's disabled. The UI here could certainly be improved. Additionally, "on" and "off" labels were added to the toggle to match the other toggles on the Advanced Settings page. * Use non-minified 3Box module We had previously used the minified 3Box module to avoid a build error encountered when `envify` was processing the `libp2p` module (which is used by 3Box). The build would fail because `esprima` (used by `envify`) is incompatible with the object spread/rest operator (which is used in `libp2p`). That issue has been solved by adding a global Babelify transformation specifically for transpiling out the object rest/spread operator from dependencies. It has been targetted to only affect `libp2p` to avoid extending the build time too much. This workaround can be used until a new version of `esprima` is released that includes this bug fix. * Use app key addresses for threebox * Replace use of modal for confirming 3box restoration with a home notification * Adds e2e tests for restoring from threebox * Update eth-keyring-controller to 5.1.0 * Correct parameters passed to getAppKeyAddress in threebox.js * Add prefix to origin passed to getAppKeyAddress in threebox.js * Remove unused locale message. * Prevent CORS errors in firefox e2e tests * Ensure extraneous scripts are excluded from the local test dev build * Move threeBoxLastUpdate state from home.component to redux * Threebox PR code cleanup * Always use first address when initializing threebox * Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue * Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list * Update test/e2e/threebox.spec.js to use new helpers added with pull #7144 * Make setFeatureFlag available on the ui window during testing * Hide threebox feature behind a feature flag that can only be activated via dev console * Remove unnecessary migration of threebox feature flag * Prevent this.init() call in threebox constructor if feature flag is not turned on * Prevent threebox notification from showing if feature flag is falsy * http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
2019-09-16 19:11:01 +02:00
},
};
// start app
render(<Root store={store} />, opts.container);
return store;
}
Add additional Sentry E2E tests (#20425) * Reorganize Sentry error e2e tests The tests have been reorganized into different describe blocks. Each describe block is for either before or after initialization, and either with or without opting into metrics. This was done to simplify later test additions. The conditions for each test are now in the describe block, letting us test additional things in each of these conditions. The conditions were flattened to a single level to avoid excessive indentation. * Add error e2e test for background and UI errors The Sentry e2e tests before initialization only tested background errors, and the after initialization tests only tested UI errors. Now both types of errors are tested in both scenarios. * Add error e2e tests for Sentry error state E2E tests have been added to test the state object sent along with each Sentry error. At the moment this object is empty in some circumstances, but this will change in later PRs. * Rename throw test error function * Only setup debug/test state hooks in dev/test builds The state hooks used for debugging and testing are now only included in dev or test builds. The function name was updated and given a JSDoc description to explain this more clearly as well. * Add state snapshot assertions State snapshot assertions have been added to the e2e error tests. These snapshots will be very useful in reviewing a few PRs that will follow this one. We might decide to remove these snapshots after this set of Sentry refactors, as they might be more work to maintain than they're worth. But they will be useful at least in the short-term. The login step has been removed from a few tests because it introduced indeterminacy (the login process continued asynchronously after the login, and sometimes was not finished when the error was triggered). * Ensure login page has rendered during setup This fixes an intermittent failure on Firefox * Format snapshots with prettier before writing them * Use defined set of date fields rather than infering from name * Remove waits for error screen The error screen only appears after a long timeout, and it doesn't affect the next test steps at all.
2023-08-16 16:22:25 +02:00
/**
* Setup functions on `window.stateHooks`. Some of these support
* application features, and some are just for debugging or testing.
*
* @param {object} store - The Redux store.
*/
function setupStateHooks(store) {
if (process.env.METAMASK_DEBUG || process.env.IN_TEST) {
/**
* The following stateHook is a method intended to throw an error, used in
* our E2E test to ensure that errors are attempted to be sent to sentry.
*
* @param {string} [msg] - The error message to throw, defaults to 'Test Error'
*/
window.stateHooks.throwTestError = async function (msg = 'Test Error') {
const error = new Error(msg);
error.name = 'TestError';
throw error;
};
/**
* The following stateHook is a method intended to throw an error in the
* background, used in our E2E test to ensure that errors are attempted to be
* sent to sentry.
*
* @param {string} [msg] - The error message to throw, defaults to 'Test Error'
*/
window.stateHooks.throwTestBackgroundError = async function (
msg = 'Test Error',
) {
store.dispatch(actions.throwTestBackgroundError(msg));
};
}
2022-11-09 20:28:32 +01:00
window.stateHooks.getCleanAppState = async function () {
const state = clone(store.getState());
state.version = global.platform.getVersion();
state.browser = window.navigator.userAgent;
state.completeTxList = await actions.getTransactions({
filterToCurrentNetwork: false,
});
return state;
};
2022-11-09 20:28:32 +01:00
window.stateHooks.getSentryState = function () {
const fullState = store.getState();
const debugState = maskObject(fullState, SENTRY_STATE);
return {
browser: window.navigator.userAgent,
store: debugState,
version: global.platform.getVersion(),
};
};
}
window.logStateString = async function (cb) {
2022-11-09 20:28:32 +01:00
const state = await window.stateHooks.getCleanAppState();
browser.runtime
.getPlatformInfo()
.then((platform) => {
state.platform = platform;
const stateString = JSON.stringify(state, null, 2);
cb(null, stateString);
})
.catch((err) => {
cb(err);
});
};
window.logState = function (toClipboard) {
return window.logStateString((err, result) => {
if (err) {
console.error(err.message);
} else if (toClipboard) {
copyToClipboard(result);
console.log('State log copied');
} else {
console.log(result);
}
});
};