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

250 lines
7.0 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) => {
setupDebuggingHelpers(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,
metamaskState.network,
metamaskState.provider.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;
}
2020-11-03 00:41:28 +01:00
function setupDebuggingHelpers(store) {
/**
* 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.
*/
window.stateHooks.throwTestError = async function () {
const error = new Error('Test Error');
error.name = 'TestError';
throw error;
};
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);
}
});
};