diff --git a/.circleci/config.yml b/.circleci/config.yml index 1f6300816..b8666d879 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -53,6 +53,9 @@ workflows: - prep-build-test: requires: - prep-deps + - prep-build-test-flask: + requires: + - prep-deps - prep-build-test-metrics: requires: - prep-deps @@ -78,6 +81,12 @@ workflows: - test-e2e-firefox: requires: - prep-build-test + - test-e2e-chrome-snaps: + requires: + - prep-build-test-flask + - test-e2e-firefox-snaps: + requires: + - prep-build-test-flask - test-e2e-chrome-metrics: requires: - prep-build-test-metrics @@ -130,6 +139,8 @@ workflows: - test-e2e-firefox - test-e2e-chrome-metrics - test-e2e-firefox-metrics + - test-e2e-chrome-snaps + - test-e2e-firefox-snaps - benchmark: requires: - prep-build-test @@ -283,6 +294,28 @@ jobs: - dist-flask - builds-flask + prep-build-test-flask: + executor: node-browsers-medium-plus + steps: + - checkout + - attach_workspace: + at: . + - run: + name: Build extension for testing + command: yarn build:test:flask + - run: + name: Move test build to 'dist-test' to avoid conflict with production build + command: mv ./dist ./dist-test-flask + - run: + name: Move test zips to 'builds-test' to avoid conflict with production build + command: mv ./builds ./builds-test-flask + - persist_to_workspace: + root: . + paths: + - dist-test-flask + - builds-test-flask + + prep-build-test: executor: node-browsers-medium-plus steps: @@ -465,6 +498,60 @@ jobs: path: test-artifacts destination: test-artifacts + test-e2e-firefox-snaps: + executor: node-browsers + steps: + - checkout + - run: + name: Install Firefox + command: ./.circleci/scripts/firefox-install.sh + - attach_workspace: + at: . + - run: + name: Move test build to dist + command: mv ./dist-test-flask ./dist + - run: + name: Move test zips to builds + command: mv ./builds-test-flask ./builds + - run: + name: test:e2e:firefox:snaps + command: | + if .circleci/scripts/test-run-e2e.sh + then + yarn test:e2e:firefox:snaps --retries 2 + fi + no_output_timeout: 20m + - store_artifacts: + path: test-artifacts + destination: test-artifacts + + test-e2e-chrome-snaps: + executor: node-browsers + steps: + - checkout + - run: + name: Re-Install Chrome + command: ./.circleci/scripts/chrome-install.sh + - attach_workspace: + at: . + - run: + name: Move test build to dist + command: mv ./dist-test-flask ./dist + - run: + name: Move test zips to builds + command: mv ./builds-test-flask ./builds + - run: + name: test:e2e:chrome:snaps + command: | + if .circleci/scripts/test-run-e2e.sh + then + yarn test:e2e:chrome:snaps --retries 2 + fi + no_output_timeout: 20m + - store_artifacts: + path: test-artifacts + destination: test-artifacts + test-e2e-chrome-metrics: executor: node-browsers steps: diff --git a/.circleci/scripts/chrome-install.sh b/.circleci/scripts/chrome-install.sh index c4cf6bb70..e2cbd7bdc 100755 --- a/.circleci/scripts/chrome-install.sh +++ b/.circleci/scripts/chrome-install.sh @@ -5,12 +5,12 @@ set -u set -o pipefail # To get the latest version, see -CHROME_VERSION='98.0.4758.80-1' +CHROME_VERSION='99.0.4844.51-1' CHROME_BINARY="google-chrome-stable_${CHROME_VERSION}_amd64.deb" CHROME_BINARY_URL="https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/${CHROME_BINARY}" # To retrieve this checksum, run the `wget` and `shasum` commands below -CHROME_BINARY_SHA512SUM='83d151f05017ee1f255f4134ee84efdb5c7826d6c64d43e6d402bef1569e4800806be0f87af3cacd240917cacaeedb9cae5833ccbc65740482f6aafbef9b38e7' +CHROME_BINARY_SHA512SUM='f0fa5c6c23d9e8373aafa14622ed4362cbf3a101691ce309864e4aa0030dc3bf7b8e7c8ce294c06106b26eb6b8dc0f2b80376bf2a49d703fc9f6597961b9432e' wget -O "${CHROME_BINARY}" -t 5 "${CHROME_BINARY_URL}" diff --git a/.depcheckrc.yml b/.depcheckrc.yml index 15f3c91b9..f7c189f91 100644 --- a/.depcheckrc.yml +++ b/.depcheckrc.yml @@ -18,6 +18,7 @@ ignores: - '@metamask/auto-changelog' # invoked as `auto-changelog` - '@metamask/forwarder' - '@metamask/test-dapp' + - '@metamask/design-tokens' # Only imported in index.css - '@sentry/cli' # invoked as `sentry-cli` - 'chromedriver' - 'depcheck' # ooo meta @@ -34,6 +35,7 @@ ignores: - '@storybook/core' - '@storybook/addon-essentials' - '@storybook/addon-a11y' + - 'storybook-dark-mode' - 'style-loader' - 'css-loader' - 'sass-loader' diff --git a/.eslintrc.babel.js b/.eslintrc.babel.js new file mode 100644 index 000000000..b067db84b --- /dev/null +++ b/.eslintrc.babel.js @@ -0,0 +1,9 @@ +module.exports = { + parser: '@babel/eslint-parser', + plugins: ['@babel'], + rules: { + '@babel/no-invalid-this': 'error', + // Prettier handles this + '@babel/semi': 'off', + }, +}; diff --git a/.eslintrc.base.js b/.eslintrc.base.js new file mode 100644 index 000000000..47c379969 --- /dev/null +++ b/.eslintrc.base.js @@ -0,0 +1,67 @@ +const path = require('path'); + +module.exports = { + extends: [ + '@metamask/eslint-config', + path.resolve(__dirname, '.eslintrc.jsdoc.js'), + ], + + globals: { + document: 'readonly', + window: 'readonly', + }, + + rules: { + 'default-param-last': 'off', + 'prefer-object-spread': 'error', + 'require-atomic-updates': 'off', + + // This is the same as our default config, but for the noted exceptions + 'spaced-comment': [ + 'error', + 'always', + { + markers: [ + 'global', + 'globals', + 'eslint', + 'eslint-disable', + '*package', + '!', + ',', + // Local additions + '/:', // This is for our code fences + ], + exceptions: ['=', '-'], + }, + ], + + 'no-invalid-this': 'off', + + // TODO: remove this override + 'padding-line-between-statements': [ + 'error', + { + blankLine: 'always', + prev: 'directive', + next: '*', + }, + { + blankLine: 'any', + prev: 'directive', + next: 'directive', + }, + // Disabled temporarily to reduce conflicts while PR queue is large + // { + // blankLine: 'always', + // prev: ['multiline-block-like', 'multiline-expression'], + // next: ['multiline-block-like', 'multiline-expression'], + // }, + ], + + // It is common to import modules without assigning them to variables in + // a browser context. For instance, we may import polyfills which change + // global variables, or we may import stylesheets. + 'import/no-unassigned-import': 'off', + }, +}; diff --git a/.eslintrc.js b/.eslintrc.js index 9c0bc07e9..84b68eada 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,132 +1,112 @@ +const path = require('path'); const { version: reactVersion } = require('react/package.json'); module.exports = { root: true, - parser: '@babel/eslint-parser', - parserOptions: { - sourceType: 'module', - ecmaVersion: 2017, - ecmaFeatures: { - experimentalObjectRestSpread: true, - impliedStrict: true, - modules: true, - blockBindings: true, - arrowFunctions: true, - objectLiteralShorthandMethods: true, - objectLiteralShorthandProperties: true, - templateStrings: true, - classes: true, - jsx: true, - }, - }, - + // Ignore files which are also in .prettierignore ignorePatterns: [ - '!.eslintrc.js', - '!.mocharc.js', - 'node_modules/**', - 'dist/**', - 'builds/**', - 'test-*/**', - 'docs/**', - 'coverage/', - 'jest-coverage/', - 'development/chromereload.js', 'app/vendor/**', - 'test/e2e/send-eth-with-private-key-test/**', - 'nyc_output/**', - '.vscode/**', - 'lavamoat/*/policy.json', - 'storybook-build/**', + 'builds/**/*', + 'dist/**/*', + 'development/chromereload.js', ], - - extends: ['@metamask/eslint-config', '@metamask/eslint-config-nodejs'], - - plugins: ['@babel', 'import', 'jsdoc'], - - globals: { - document: 'readonly', - window: 'readonly', - }, - - rules: { - 'default-param-last': 'off', - 'prefer-object-spread': 'error', - 'require-atomic-updates': 'off', - - // This is the same as our default config, but for the noted exceptions - 'spaced-comment': [ - 'error', - 'always', - { - markers: [ - 'global', - 'globals', - 'eslint', - 'eslint-disable', - '*package', - '!', - ',', - // Local additions - '/:', // This is for our code fences - ], - exceptions: ['=', '-'], - }, - ], - - 'import/no-unassigned-import': 'off', - - 'no-invalid-this': 'off', - '@babel/no-invalid-this': 'error', - - // Prettier handles this - '@babel/semi': 'off', - - 'node/no-process-env': 'off', - - // Allow tag `jest-environment` to work around Jest bug - // See: https://github.com/facebook/jest/issues/7780 - 'jsdoc/check-tag-names': ['error', { definedTags: ['jest-environment'] }], - - // TODO: remove this override - 'padding-line-between-statements': [ - 'error', - { - blankLine: 'always', - prev: 'directive', - next: '*', - }, - { - blankLine: 'any', - prev: 'directive', - next: 'directive', - }, - // Disabled temporarily to reduce conflicts while PR queue is large - // { - // blankLine: 'always', - // prev: ['multiline-block-like', 'multiline-expression'], - // next: ['multiline-block-like', 'multiline-expression'], - // }, - ], - - // TODO: re-enable these rules - 'node/no-sync': 'off', - 'node/no-unpublished-import': 'off', - 'node/no-unpublished-require': 'off', - 'jsdoc/match-description': 'off', - 'jsdoc/require-description': 'off', - 'jsdoc/require-jsdoc': 'off', - 'jsdoc/require-param-description': 'off', - 'jsdoc/require-param-type': 'off', - 'jsdoc/require-returns-description': 'off', - 'jsdoc/require-returns-type': 'off', - 'jsdoc/require-returns': 'off', - 'jsdoc/valid-types': 'off', - }, overrides: [ + /** + * == Modules == + * + * The first two sections here, which cover module syntax, are mutually + * exclusive: the set of files covered between them may NOT overlap. This is + * because we do not allow a file to use two different styles for specifying + * imports and exports (however theoretically possible it may be). + */ + { - files: ['ui/**/*.js', 'test/lib/render-helpers.js', 'test/jest/*.js'], - plugins: ['react'], + /** + * Modules (CommonJS module syntax) + * + * This is code that uses `require()` and `module.exports` to import and + * export other modules. + */ + files: [ + '.eslintrc.js', + '.eslintrc.*.js', + '.mocharc.js', + '*.config.js', + 'development/**/*.js', + 'test/e2e/**/*.js', + 'test/helpers/*.js', + 'test/lib/wait-until-called.js', + ], + extends: [ + path.resolve(__dirname, '.eslintrc.base.js'), + path.resolve(__dirname, '.eslintrc.node.js'), + path.resolve(__dirname, '.eslintrc.babel.js'), + ], + parserOptions: { + sourceType: 'module', + }, + rules: { + // This rule does not work with CommonJS modules. We will just have to + // trust that all of the files specified above are indeed modules. + 'import/unambiguous': 'off', + }, + }, + /** + * Modules (ES module syntax) + * + * This is code that explicitly uses `import`/`export` instead of + * `require`/`module.exports`. + */ + { + files: [ + 'app/**/*.js', + 'shared/**/*.js', + 'ui/**/*.js', + '**/*.test.js', + 'test/lib/**/*.js', + 'test/mocks/**/*.js', + 'test/jest/**/*.js', + 'test/stub/**/*.js', + 'test/unit-global/**/*.js', + ], + // TODO: Convert these files to modern JS + excludedFiles: ['test/lib/wait-until-called.js'], + extends: [ + path.resolve(__dirname, '.eslintrc.base.js'), + path.resolve(__dirname, '.eslintrc.node.js'), + path.resolve(__dirname, '.eslintrc.babel.js'), + ], + parserOptions: { + sourceType: 'module', + }, + }, + + /** + * == Everything else == + * + * The sections from here on out may overlap with each other in various + * ways depending on their function. + */ + + /** + * React-specific code + * + * Code in this category contains JSX and hence needs to be run through the + * React plugin. + */ + { + files: [ + 'test/lib/render-helpers.js', + 'test/jest/rendering.js', + 'ui/**/*.js', + ], extends: ['plugin:react/recommended', 'plugin:react-hooks/recommended'], + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + }, + plugins: ['react'], rules: { 'react/no-unused-prop-types': 'error', 'react/no-unused-state': 'error', @@ -139,74 +119,100 @@ module.exports = { 'react/default-props-match-prop-types': 'error', 'react/jsx-no-duplicate-props': 'error', }, - }, - { - files: ['test/e2e/**/*.spec.js'], - extends: ['@metamask/eslint-config-mocha'], - rules: { - 'mocha/no-hooks-for-single-case': 'off', - 'mocha/no-setup-in-describe': 'off', + settings: { + react: { + // If this is set to 'detect', ESLint will import React in order to + // find its version. Because we run ESLint in the build system under + // LavaMoat, this means that detecting the React version requires a + // LavaMoat policy for all of React, in the build system. That's a + // no-go, so we grab it from React's package.json. + version: reactVersion, + }, }, }, + /** + * Mocha tests + * + * These are files that make use of globals and syntax introduced by the + * Mocha library. + */ { - files: ['app/scripts/migrations/*.js', '*.stories.js'], - rules: { - 'import/no-anonymous-default-export': ['error', { allowObject: true }], - }, - }, - { - files: ['app/scripts/migrations/*.js'], - rules: { - 'node/global-require': 'off', - }, - }, - { - files: ['**/*.test.js'], + files: [ + '**/*.test.js', + 'test/lib/wait-until-called.js', + 'test/e2e/**/*.spec.js', + ], excludedFiles: [ - 'ui/**/*.test.js', - 'ui/__mocks__/*.js', - 'shared/**/*.test.js', - 'development/**/*.test.js', + 'app/scripts/controllers/network/**/*.test.js', + 'app/scripts/controllers/permissions/**/*.test.js', 'app/scripts/lib/**/*.test.js', 'app/scripts/migrations/*.test.js', 'app/scripts/platforms/*.test.js', - 'app/scripts/controllers/network/**/*.test.js', - 'app/scripts/controllers/permissions/**/*.test.js', + 'development/**/*.test.js', + 'shared/**/*.test.js', + 'ui/**/*.test.js', + 'ui/__mocks__/*.js', ], extends: ['@metamask/eslint-config-mocha'], rules: { + // In Mocha tests, it is common to use `this` to store values or do + // things like force the test to fail. + '@babel/no-invalid-this': 'off', 'mocha/no-setup-in-describe': 'off', }, }, + /** + * Jest tests + * + * These are files that make use of globals and syntax introduced by the + * Jest library. + */ { - files: ['**/__snapshots__/*.snap'], - plugins: ['jest'], + files: [ + '**/__snapshots__/*.snap', + 'app/scripts/controllers/network/**/*.test.js', + 'app/scripts/controllers/permissions/**/*.test.js', + 'app/scripts/lib/**/*.test.js', + 'app/scripts/migrations/*.test.js', + 'app/scripts/platforms/*.test.js', + 'development/**/*.test.js', + 'shared/**/*.test.js', + 'test/jest/*.js', + 'test/helpers/*.js', + 'ui/**/*.test.js', + 'ui/__mocks__/*.js', + ], + extends: ['@metamask/eslint-config-jest'], + parserOptions: { + sourceType: 'module', + }, rules: { + 'import/unambiguous': 'off', + 'import/named': 'off', 'jest/no-large-snapshots': [ 'error', { maxSize: 50, inlineMaxSize: 50 }, ], - }, - }, - { - files: [ - 'ui/**/*.test.js', - 'ui/__mocks__/*.js', - 'shared/**/*.test.js', - 'development/**/*.test.js', - 'app/scripts/lib/**/*.test.js', - 'app/scripts/migrations/*.test.js', - 'app/scripts/platforms/*.test.js', - 'app/scripts/controllers/network/**/*.test.js', - 'app/scripts/controllers/permissions/**/*.test.js', - ], - extends: ['@metamask/eslint-config-jest'], - rules: { 'jest/no-restricted-matchers': 'off', - 'import/unambiguous': 'off', - 'import/named': 'off', }, }, + /** + * Migrations + */ + { + files: ['app/scripts/migrations/*.js', '**/*.stories.js'], + rules: { + 'import/no-anonymous-default-export': ['error', { allowObject: true }], + }, + }, + /** + * Executables and related files + * + * These are files that run in a Node context. They are either designed to + * run as executables (in which case they will have a shebang at the top) or + * are dependencies of executables (in which case they may use + * `process.exit` to exit). + */ { files: [ 'development/**/*.js', @@ -218,27 +224,9 @@ module.exports = { 'node/shebang': 'off', }, }, - { - files: [ - '.eslintrc.js', - '.mocharc.js', - 'babel.config.js', - 'jest.config.js', - 'nyc.config.js', - 'stylelint.config.js', - 'app/scripts/lockdown-run.js', - 'app/scripts/lockdown-more.js', - 'development/**/*.js', - 'test/e2e/**/*.js', - 'test/env.js', - 'test/setup.js', - 'test/helpers/protect-intrinsics-helpers.js', - 'test/lib/wait-until-called.js', - ], - parserOptions: { - sourceType: 'script', - }, - }, + /** + * Lockdown files + */ { files: [ 'app/scripts/lockdown-run.js', @@ -251,19 +239,11 @@ module.exports = { Compartment: 'readonly', }, }, + { + files: ['app/scripts/lockdown-run.js', 'app/scripts/lockdown-more.js'], + parserOptions: { + sourceType: 'script', + }, + }, ], - - settings: { - jsdoc: { - mode: 'typescript', - }, - react: { - // If this is set to 'detect', ESLint will import React in order to find - // its version. Because we run ESLint in the build system under LavaMoat, - // this means that detecting the React version requires a LavaMoat policy - // for all of React, in the build system. That's a no-go, so we grab it - // from React's package.json. - version: reactVersion, - }, - }, }; diff --git a/.eslintrc.jsdoc.js b/.eslintrc.jsdoc.js new file mode 100644 index 000000000..862145853 --- /dev/null +++ b/.eslintrc.jsdoc.js @@ -0,0 +1,23 @@ +module.exports = { + // Note that jsdoc is already in the `plugins` array thanks to + // @metamask/eslint-config — this just extends the config there + rules: { + // Allow tag `jest-environment` to work around Jest bug + // See: https://github.com/facebook/jest/issues/7780 + 'jsdoc/check-tag-names': ['error', { definedTags: ['jest-environment'] }], + 'jsdoc/match-description': 'off', + 'jsdoc/require-description': 'off', + 'jsdoc/require-jsdoc': 'off', + 'jsdoc/require-param-description': 'off', + 'jsdoc/require-param-type': 'off', + 'jsdoc/require-returns-description': 'off', + 'jsdoc/require-returns-type': 'off', + 'jsdoc/require-returns': 'off', + 'jsdoc/valid-types': 'off', + }, + settings: { + jsdoc: { + mode: 'typescript', + }, + }, +}; diff --git a/.eslintrc.node.js b/.eslintrc.node.js new file mode 100644 index 000000000..78a12a346 --- /dev/null +++ b/.eslintrc.node.js @@ -0,0 +1,10 @@ +module.exports = { + extends: ['@metamask/eslint-config-nodejs'], + rules: { + 'node/no-process-env': 'off', + // TODO: re-enable these rules + 'node/no-sync': 'off', + 'node/no-unpublished-import': 'off', + 'node/no-unpublished-require': 'off', + }, +}; diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index cb38aaf16..889bd9d1b 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -89,6 +89,7 @@ body: - Trezor - Keystone - GridPlus Lattice1 + - AirGap Vault - Other (please elaborate in the "Additional Context" section) - type: textarea id: additional diff --git a/.prettierignore b/.prettierignore index 2e0417ca7..a98c312ad 100644 --- a/.prettierignore +++ b/.prettierignore @@ -10,3 +10,4 @@ app/vendor/** .vscode/** test/e2e/send-eth-with-private-key-test/** *.scss +development/chromereload.js diff --git a/.storybook/3.COLORS.stories.mdx b/.storybook/3.COLORS.stories.mdx new file mode 100644 index 000000000..b694a721a --- /dev/null +++ b/.storybook/3.COLORS.stories.mdx @@ -0,0 +1,201 @@ +import { Meta } from '@storybook/addon-docs'; +import ActionaleMessage from '../ui/components/ui/actionable-message'; +import designTokenDiagramImage from './images/design.token.graphic.svg'; + + + +# Color + +Color is used to express style and communicate meaning. + + + +
+ +## Design tokens + +We are importing design tokens as CSS variables from [@metamask/design-tokens](https://github.com/MetaMask/design-tokens) repo to help consolidate colors and enable theming across all MetaMask products. + +### Token tiers + +We follow a 3 tiered system for color design tokens and css variables. + +
+ +
+ +
+
+ +### **Brand colors** (tier 1) + +These colors **SHOULD NOT** be used in your styles directly. They are used as a reference for the [theme colors](#theme-colors-tier-2). Brand colors should just keep track of every color used in our app. + +#### Example of brand color css variables + +```css +/** !!!DO NOT USE BRAND COLORS DIRECTLY IN YOUR CODE!!! */ +var(--brand-colors-white-white000) +var(--brand-colors-white-white010) +var(--brand-colors-grey-grey030) +``` + +### **Theme colors** (tier 2) + +Theme colors are color agnostic, semantically neutral and theme compatible design tokens that you can use in your code and styles. Please refer to the description of each token for it's intended purpose in [@metamask/design-tokens](https://github.com/MetaMask/design-tokens/blob/main/src/figma/tokens.json#L329-L554). + +#### Example of theme color css variables + +```css +/** Backgrounds */ +var(--color-background-default) +var(--color-background-alternative) + +/** Text */ +var(--color-text-default) +var(--color-text-alternative) +var(--color-text-muted) + +/** Icons */ +var(--color-icon-default) +var(--color-icon-muted) + +/** Borders */ +var(--color-border-default) +var(--color-border-muted) + +/** Overlays */ +var(--color-overlay-default) +var(--color-overlay-inverse) + +/** User Actions */ +var(--color-primary-default) +var(--color-primary-alternative) +var(--color-primary-muted) +var(--color-primary-inverse) +var(--color-primary-disabled) + +var(--color-secondary-default) +var(--color-secondary-alternative) +var(--color-secondary-muted) +var(--color-secondary-inverse) +var(--color-secondary-disabled) + +/** States */ +/** Error */ +var(--color-error-default) +var(--color-error-alternative) +var(--color-error-muted) +var(--color-error-inverse) +var(--color-error-disabled) + +/** Warning */ +var(--color-warning-default) +var(--color-warning-alternative) +var(--color-warning-muted) +var(--color-warning-inverse) +var(--color-warning-disabled) + +/** Success */ +var(--color-success-default) +var(--color-success-alternative) +var(--color-success-muted) +var(--color-success-inverse) +var(--color-success-disabled) + +/** Info */ +var(--color-info-default) +var(--color-info-alternative) +var(--color-info-muted) +var(--color-info-inverse) +var(--color-info-disabled) +``` + +### **Component colors** (tier 3) + +Another level of abstraction is component tier colors that you can define at the top of your styles and use at the component specific level. + +```scss +.button { + --color-background-primary: var(--color-primary-default); + --color-text-primary: var(--color-primary-inverse); + --color-border-primary: var(--color-primary-default); + + --color-background-primary-hover: var(--color-primary-alternative); + --color-border-primary-hover: var(--color-primary-alternative); + + .btn-primary { + background-color: var(--color-background-primary); + color: var(--color-text-primary); + border: 1px solid var(--color-border-primary); + + &:hover { + background-color: var(--color-background-primary-hover); + border: 1px solid var(--color-border-primary-hover); + } + + /** btn-primary css continued... */ + } +} +``` + +## Takeaways + +- Do not use static HEX values in your code. Use the [theme colors](#theme-colors-tier-2). If one does not exist for your use case ask the designer or [create an issue](https://github.com/MetaMask/metamask-extension/issues/new) and tag it with a `design-system` label. +- Make sure the design token you are using is for it's intended purpose. Please refer to the description of each token in [@metamask/design-tokens](https://github.com/MetaMask/design-tokens/blob/main/src/figma/tokens.json#L329-L554). + +### ❌ Don't do this + +Don't use static hex values or brand color tokens in your code. + +```css +/** +* Don't do this +* Static hex values create inconsistency and will break UI when using dark mode +**/ +.card { + background-color: #ffffff; + color: #24272a; +} + +/** +* Don't do this +* Not theme compatible and will break UI when using dark theme +**/ +.card { + background-color: var(--brand-colors-white-white000); + color: var(--brand-colors-grey-grey800); +} +``` + +### ✅ Do this + +Do use component tiered and [theme colors](#theme-colors-tier-2) in your styles and code + +```css +.card { + --color-background: var(--color-background-default); + --color-text: var(--color-text-default); + + background-color: var(--color-background); + color: var(--color-text); +} +``` + +
+ +## References + +- [@metamask/design-tokens](https://github.com/MetaMask/design-tokens) +- [Figma brand colors library](https://www.figma.com/file/cBAUPFMnbv6tHR1J8KvBI2/Brand-Colors?node-id=0%3A1) (internal use only) +- [Figma theme colors library](https://www.figma.com/file/kdFzEC7xzSNw7cXteqgzDW/Light-Theme-Colors?node-id=0%3A1) (internal use only) +- [Figma dark theme colors library](https://www.figma.com/file/rLKsoqpjyoKauYnFDcBIbO/Dark-Theme-Colors?node-id=0%3A1) (internal use only) diff --git a/.storybook/images/design.token.graphic.svg b/.storybook/images/design.token.graphic.svg new file mode 100644 index 000000000..ad64afba9 --- /dev/null +++ b/.storybook/images/design.token.graphic.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.storybook/main.js b/.storybook/main.js index 30c216825..5ce2f32d7 100644 --- a/.storybook/main.js +++ b/.storybook/main.js @@ -14,6 +14,7 @@ module.exports = { '@storybook/addon-a11y', '@storybook/addon-knobs', './i18n-party-addon/register.js', + 'storybook-dark-mode', ], // Uses babel.config.js settings and prevents "Missing class properties transform" error babel: async (options) => ({ overrides: options.overrides }), diff --git a/.storybook/metamask-storybook-theme.js b/.storybook/metamask-storybook-theme.js index 6623f4fe0..49f8c814d 100644 --- a/.storybook/metamask-storybook-theme.js +++ b/.storybook/metamask-storybook-theme.js @@ -1,12 +1,10 @@ // .storybook/YourTheme.js import { create } from '@storybook/theming'; -import logo from '../app/images/logo/metamask-logo-horizontal.svg'; export default create({ base: 'light', brandTitle: 'MetaMask Storybook', - brandImage: logo, // Typography fontBase: 'Euclid, Roboto, Helvetica, Arial, sans-serif', diff --git a/.storybook/preview.js b/.storybook/preview.js index 9e6fe2206..517e7820a 100644 --- a/.storybook/preview.js +++ b/.storybook/preview.js @@ -1,4 +1,4 @@ -import React, { useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; import { addDecorator, addParameters } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { Provider } from 'react-redux'; @@ -13,13 +13,14 @@ import { Router } from 'react-router-dom'; import { createBrowserHistory } from 'history'; import { _setBackgroundConnection } from '../ui/store/actions'; import MetaMaskStorybookTheme from './metamask-storybook-theme'; +import addons from '@storybook/addons'; addParameters({ backgrounds: { - default: 'light', + default: 'default', values: [ - { name: 'light', value: '#FFFFFF' }, - { name: 'dark', value: '#333333' }, + { name: 'default', value: 'var(--color-background-default)' }, + { name: 'alternative', value: 'var(--color-background-alternative)' }, ], }, docs: { @@ -27,7 +28,13 @@ addParameters({ }, options: { storySort: { - order: ['Getting Started', 'Components', ['UI', 'App'], 'Pages'], + order: [ + 'Getting Started', + 'Design Tokens', + 'Components', + ['UI', 'App'], + 'Pages', + ], }, }, }); @@ -66,8 +73,29 @@ const proxiedBackground = new Proxy( _setBackgroundConnection(proxiedBackground); const metamaskDecorator = (story, context) => { + const [isDark, setDark] = useState(false); + const channel = addons.getChannel(); const currentLocale = context.globals.locale; const current = allLocales[currentLocale]; + + useEffect(() => { + channel.on('DARK_MODE', setDark); + return () => channel.off('DARK_MODE', setDark); + }, [channel, setDark]); + + useEffect(() => { + const currentTheme = document.documentElement.getAttribute('data-theme'); + + if (!currentTheme) + document.documentElement.setAttribute('data-theme', 'light'); + + if (currentTheme === 'light' && isDark) { + document.documentElement.setAttribute('data-theme', 'dark'); + } else if (currentTheme === 'dark' && !isDark) { + document.documentElement.setAttribute('data-theme', 'light'); + } + }, [isDark]); + return ( diff --git a/app/_locales/am/messages.json b/app/_locales/am/messages.json index 51ea3e653..8d9e27e13 100644 --- a/app/_locales/am/messages.json +++ b/app/_locales/am/messages.json @@ -750,9 +750,6 @@ "restore": { "message": "እነበረበት መልስ" }, - "restoreAccountWithSeed": { - "message": "መለያዎን በዘር ሐረግ ወደነበረበት ይመልሱ" - }, "revealSeedWords": { "message": "የዘር ቃላትን ይግለጹ" }, diff --git a/app/_locales/ar/messages.json b/app/_locales/ar/messages.json index 0a93bbd3e..d3e78ae7b 100644 --- a/app/_locales/ar/messages.json +++ b/app/_locales/ar/messages.json @@ -766,9 +766,6 @@ "restore": { "message": "استعادة" }, - "restoreAccountWithSeed": { - "message": "قم باستعادة حسابك بواسطة عبارة الأمان" - }, "revealSeedWords": { "message": "كشف كلمات عبارات الأمان" }, diff --git a/app/_locales/bg/messages.json b/app/_locales/bg/messages.json index 35f765175..df8c830ae 100644 --- a/app/_locales/bg/messages.json +++ b/app/_locales/bg/messages.json @@ -761,9 +761,6 @@ "restore": { "message": "Възстановяване" }, - "restoreAccountWithSeed": { - "message": "Възстановете акаунта си с фраза зародиш" - }, "revealSeedWords": { "message": "Разкрий думите зародиш" }, diff --git a/app/_locales/bn/messages.json b/app/_locales/bn/messages.json index 69577c0e7..7290dab16 100644 --- a/app/_locales/bn/messages.json +++ b/app/_locales/bn/messages.json @@ -765,9 +765,6 @@ "restore": { "message": "পুনরুদ্ধার করুন" }, - "restoreAccountWithSeed": { - "message": "সীড ফ্রেজ দিয়ে আপনার অ্যাকাউন্ট রিস্টোর করুন" - }, "revealSeedWords": { "message": "সীড শব্দগুলি প্রকাশ করুন" }, diff --git a/app/_locales/ca/messages.json b/app/_locales/ca/messages.json index 03ff652ce..ce8f14237 100644 --- a/app/_locales/ca/messages.json +++ b/app/_locales/ca/messages.json @@ -743,9 +743,6 @@ "restore": { "message": "Restaura" }, - "restoreAccountWithSeed": { - "message": "Restaura el teu compte amb Frase de Recuperació" - }, "revealSeedWords": { "message": "Revelar Paraules de Recuperació" }, diff --git a/app/_locales/da/messages.json b/app/_locales/da/messages.json index 709e63bcc..f6f1e92d6 100644 --- a/app/_locales/da/messages.json +++ b/app/_locales/da/messages.json @@ -746,9 +746,6 @@ "restore": { "message": "Gendan" }, - "restoreAccountWithSeed": { - "message": "Gendan din konto med Seed-sætning" - }, "revealSeedWords": { "message": "Vis Seedord" }, diff --git a/app/_locales/de/messages.json b/app/_locales/de/messages.json index 5549b95d7..a192caee0 100644 --- a/app/_locales/de/messages.json +++ b/app/_locales/de/messages.json @@ -1279,19 +1279,12 @@ "importAccountError": { "message": "Fehler beim Importieren des Kontos." }, - "importAccountLinkText": { - "message": "mit einer Geheime Wiederherstellungsphrase importieren" - }, "importAccountMsg": { "message": " Importierte Accounts werden nicht mit der Seed-Wörterfolge deines ursprünglichen MetaMask Accounts verknüpft. Erfahre mehr über importierte Accounts." }, "importAccountSeedPhrase": { "message": "Ein Konto mit einem Seed-Schlüssel importieren" }, - "importAccountText": { - "message": "oder $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Geben Sie die Geheime Wiederherstellungsphrase (alias Seed Phrase) ein, die Sie beim Erstellen Ihrer Wallet erhalten haben. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1532,7 +1525,7 @@ "message": "niedrig" }, "mainnet": { - "message": "Athereum Hauptnetz" + "message": "Ethereum Hauptnetz" }, "makeAnotherSwap": { "message": "Eine neue Wallet erstellen" @@ -1745,9 +1738,6 @@ "message": "Konto $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Sammelobjekt wurde nicht hinzugefügt, weil: $1" - }, "newCollectibleAddedMessage": { "message": "Sammelobjekt wurde erfolgreich hinzugefügt!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Wiederherstellen" }, - "restoreAccountWithSeed": { - "message": "Ihr Konto mit mnemonischer Phrase wiederherstellen" - }, "restoreWalletPreferences": { "message": "$1 hat ein Backup Ihrer Daten gefunden. Möchten Sie die Präferenzen Ihrer Wallet wiederherstellen?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Nur das erste Konto auf dieser Wallet wird automatisch geladen. Wenn Sie nach Abschluss dieses Vorgangs weitere Konten hinzufügen möchten, klicken Sie auf das Dropdown-Menü und wählen Sie dann Konto erstellen." }, - "secretPhraseWarning": { - "message": "Wenn Sie eine andere geheime Wiederherstellungsphrase verwenden, werden Ihre aktuelle Wallet, Ihre Konten und Vermögenswerte dauerhaft aus dieser App entfernt. Diese Aktion kann nicht rückgängig gemacht werden." - }, "secretRecoveryPhrase": { "message": "Geheime Wiederherstellungsphrase" }, diff --git a/app/_locales/el/messages.json b/app/_locales/el/messages.json index 387bf6031..b66f85652 100644 --- a/app/_locales/el/messages.json +++ b/app/_locales/el/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Σφάλμα εισαγωγής λογαριασμού." }, - "importAccountLinkText": { - "message": "εισαγωγή χρησιμοποιώντας τη Μυστική Φράση Ανάκτησης" - }, "importAccountMsg": { "message": "Οι λογαριασμοί που εισάγονται δεν θα συσχετιστούν με τη Μυστική Φράση Ανάκτησης του λογαριασμού σας MetaTask που δημιουργήθηκε αρχικά. Μάθετε περισσότερα για τους εισηγμένους λογαριασμούς" }, "importAccountSeedPhrase": { "message": "Εισαγωγή λογαριασμού με Μυστική Φράση Ανάκτησης" }, - "importAccountText": { - "message": "ή $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Εισάγετε τη Μυστική Φράση Ανάκτησης (δλδ Seed Phrase) που σας δόθηκε όταν δημιουργήσατε το πορτοφόλι σας. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Λογαριασμός $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Το Collectible δεν προστέθηκε επειδή: $1" - }, "newCollectibleAddedMessage": { "message": "Το Collectible προστέθηκε με επιτυχία!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Επαναφορά" }, - "restoreAccountWithSeed": { - "message": "Επαναφέρετε τον Λογαριασμό σας με Φράση Επαναφοράς" - }, "restoreWalletPreferences": { "message": "Βρέθηκε ένα αντίγραφο ασφαλείας των δεδομένων σας από το $1. Θα θέλατε να επαναφέρετε τις προτιμήσεις του πορτοφολιού σας;", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Μόνο ο πρώτος λογαριασμός σε αυτό το πορτοφόλι θα φορτώσει αυτόματα. Μετά την ολοκλήρωση αυτής της διαδικασίας, για να προσθέσετε επιπλέον λογαριασμούς, κάντε κλικ στο αναπτυσσόμενο μενού και, στη συνέχεια, επιλέξτε Δημιουργία Λογαριασμού." }, - "secretPhraseWarning": { - "message": "Αν κάνετε επαναφορά χρησιμοποιώντας μια άλλη Μυστική Φράση Ανάκτησης, το τρέχον πορτοφόλι, οι λογαριασμοί και τα περιουσιακά στοιχεία σας θα αφαιρεθούν από αυτή την εφαρμογή μόνιμα. Αυτή η ενέργεια δεν μπορεί να αναιρεθεί." - }, "secretRecoveryPhrase": { "message": "Μυστική Φράση Ανάκτησης" }, diff --git a/app/_locales/en/messages.json b/app/_locales/en/messages.json index ba8a7c370..4f7b20b11 100644 --- a/app/_locales/en/messages.json +++ b/app/_locales/en/messages.json @@ -42,7 +42,7 @@ "message": "QR-based HW Wallet" }, "QRHardwareWalletSteps2Description": { - "message": "AirGap Vault & Ngrave (Coming Soon)" + "message": "Ngrave (Coming Soon)" }, "about": { "message": "About" @@ -58,6 +58,10 @@ "message": "$1 may access and spend up to this max amount", "description": "$1 is the url of the site requesting ability to spend" }, + "accessAndSpendNoticeNFT": { + "message": "$1 may access and spend this asset", + "description": "$1 is the url of the site requesting ability to spend" + }, "accessingYourCamera": { "message": "Accessing your camera..." }, @@ -98,6 +102,9 @@ "addANetwork": { "message": "Add a network" }, + "addANetworkManually": { + "message": "Add a network manually" + }, "addANickname": { "message": "Add a nickname" }, @@ -137,6 +144,9 @@ "addFriendsAndAddresses": { "message": "Add friends and addresses you trust" }, + "addFromAListOfPopularNetworks": { + "message": "Add from a list of popular networks or add a network manually. Only interact with the entities you trust." + }, "addMemo": { "message": "Add memo" }, @@ -191,6 +201,12 @@ "aggregatorFeeCost": { "message": "Aggregator network fee" }, + "airgapVault": { + "message": "AirGap Vault" + }, + "airgapVaultTutorial": { + "message": " (Tutorials)" + }, "alertDisableTooltip": { "message": "This can be changed in \"Settings > Alerts\"" }, @@ -267,6 +283,9 @@ "approvedAmountWithColon": { "message": "Approved amount:" }, + "approvedAsset": { + "message": "Approved asset" + }, "areYouDeveloper": { "message": "Are you a developer?" }, @@ -400,6 +419,13 @@ "message": "Transak supports debit card and bank transfers (depending on location) in 59+ countries. $1 deposits into your MetaMask account.", "description": "$1 represents the cypto symbol to be purchased" }, + "buyEth": { + "message": "Buy ETH" + }, + "buyOther": { + "message": "Buy $1 or deposit from another account.", + "description": "$1 is a token symbol" + }, "buyWithWyre": { "message": "Buy ETH with Wyre" }, @@ -467,6 +493,9 @@ "close": { "message": "Close" }, + "collectibleAddFailedMessage": { + "message": "NFT can’t be added as the ownership details do not match. Make sure you have entered correct information." + }, "collectibleAddressError": { "message": "This token is an NFT. Add on the $1", "description": "$1 is a clickable link with text defined by the 'importNFTPage' key" @@ -612,6 +641,9 @@ "convertTokenToNFTDescription": { "message": "We've detected that this asset is an NFT. Metamask now has full native support for NFTs. Would you like to remove it from your token list and add it as an NFT?" }, + "convertTokenToNFTExistDescription": { + "message": "We’ve detected that this asset has been added as an NFT. Would you like to remove it from your token list?" + }, "copiedExclamation": { "message": "Copied!" }, @@ -691,6 +723,9 @@ "customGasSubTitle": { "message": "Increasing fee may decrease processing times, but it is not guaranteed." }, + "customNetworks": { + "message": "Custom networks" + }, "customSpendLimit": { "message": "Custom Spend Limit" }, @@ -714,6 +749,9 @@ "message": "$1 has recommended this price.", "description": "$1 represents the Dapp's origin" }, + "darkTheme": { + "message": "Dark" + }, "data": { "message": "Data" }, @@ -749,6 +787,9 @@ "decryptRequest": { "message": "Decrypt request" }, + "defaultTheme": { + "message": "Default" + }, "delete": { "message": "Delete" }, @@ -814,6 +855,9 @@ "dontShowThisAgain": { "message": "Don't show this again" }, + "downArrow": { + "message": "down arrow" + }, "downloadGoogleChrome": { "message": "Download Google Chrome" }, @@ -989,7 +1033,7 @@ "message": "Use OpenSea's API to fetch NFT data. NFT auto-detection relies on OpenSea's API, and will not be available when this is turned off." }, "enableSmartTransactions": { - "message": "Enable smart transactions" + "message": "Enable Smart Transactions" }, "enableToken": { "message": "enable $1", @@ -1206,6 +1250,9 @@ "forgetDevice": { "message": "Forget this device" }, + "forgotPassword": { + "message": "Forgot password?" + }, "from": { "message": "From" }, @@ -1334,6 +1381,9 @@ "goerli": { "message": "Goerli Test Network" }, + "gotIt": { + "message": "Got it!" + }, "grantedToWithColon": { "message": "Granted to:" }, @@ -1372,6 +1422,9 @@ "hide": { "message": "Hide" }, + "hideSeedPhrase": { + "message": "Hide seed phrase" + }, "hideToken": { "message": "Hide token" }, @@ -1408,19 +1461,12 @@ "importAccountError": { "message": "Error importing account." }, - "importAccountLinkText": { - "message": "import using Secret Recovery Phrase" - }, "importAccountMsg": { "message": "Imported accounts will not be associated with your originally created MetaMask account Secret Recovery Phrase. Learn more about imported accounts" }, "importAccountSeedPhrase": { "message": "Import a wallet with Secret Recovery Phrase" }, - "importAccountText": { - "message": "or $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Enter your Secret Recovery Phrase (aka Seed Phrase) that you were given when you created your wallet. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1478,6 +1524,10 @@ "insufficientBalance": { "message": "Insufficient balance." }, + "insufficientCurrency": { + "message": "You do not have enough $1 in your account to pay for transaction fees on $2 network.", + "description": "$1 is currency, $2 is network" + }, "insufficientFunds": { "message": "Insufficient funds." }, @@ -1647,6 +1697,9 @@ "letsGoSetUp": { "message": "Yes, let’s get set up!" }, + "levelArrow": { + "message": "level arrow" + }, "likeToImportTokens": { "message": "Would you like to import these tokens?" }, @@ -1677,6 +1730,10 @@ "lockTimeTooGreat": { "message": "Lock time is too great" }, + "logo": { + "message": "$1 logo", + "description": "$1 is the name of the ticker" + }, "low": { "message": "Low" }, @@ -1815,6 +1872,12 @@ "missingNFT": { "message": "Don't see your NFT?" }, + "missingSetting": { + "message": "Can't find a setting?" + }, + "missingSettingRequest": { + "message": "Request here" + }, "missingToken": { "message": "Don't see your token?" }, @@ -1926,9 +1989,6 @@ "message": "Account $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Collectible was not added because: $1" - }, "newCollectibleAddedMessage": { "message": "Collectible was successfully added!" }, @@ -1948,7 +2008,7 @@ "message": "“$1” was successfully added!" }, "newPassword": { - "message": "New password (min 8 chars)" + "message": "New password (8 characters min)" }, "newToMetaMask": { "message": "New to MetaMask?" @@ -2199,6 +2259,9 @@ "onlyConnectTrust": { "message": "Only connect with sites you trust." }, + "onlyInteractWith": { + "message": "Only interact with entities you trust." + }, "openFullScreenForLedgerWebHid": { "message": "Open MetaMask in full screen to connect your ledger via WebHID.", "description": "Shown to the user on the confirm screen when they are viewing MetaMask in a popup window but need to connect their ledger via webhid." @@ -2215,6 +2278,9 @@ "or": { "message": "or" }, + "orDeposit": { + "message": "or deposit from another account." + }, "origin": { "message": "Origin" }, @@ -2236,11 +2302,18 @@ "passwordSetupDetails": { "message": "This password will unlock your MetaMask wallet only on this device. MetaMask can not recover this password." }, + "passwordStrength": { + "message": "Password strength: $1", + "description": "Return password strength to the user when user wants to create password." + }, + "passwordStrengthDescription": { + "message": "A strong password can improve the security of your wallet should your device be stolen or compromised." + }, "passwordTermsWarning": { "message": "I understand that MetaMask cannot recover this password for me. $1" }, "passwordsDontMatch": { - "message": "Passwords Don't Match" + "message": "Passwords don't match" }, "pastePrivateKey": { "message": "Enter your private key string here:", @@ -2299,6 +2372,9 @@ "personalAddressDetected": { "message": "Personal address detected. Input the token contract address." }, + "pleaseConfirm": { + "message": "Please confirm" + }, "plusXMore": { "message": "+ $1 more", "description": "$1 is a number of additional but unshown items in a list- this message will be shown in place of those items" @@ -2356,6 +2432,12 @@ "queued": { "message": "Queued" }, + "reAddAccounts": { + "message": "re-add any other accounts" + }, + "reAdded": { + "message": "re-added" + }, "readdToken": { "message": "You can add this token back in the future by going to “Import token” in your accounts options menu." }, @@ -2434,6 +2516,10 @@ "removeSnap": { "message": "Remove Snap" }, + "removeSnapConfirmation": { + "message": "Are you sure you want to remove $1?", + "description": "$1 represents the name of the snap" + }, "removeSnapDescription": { "message": "This action will delete the snap, its data and revoke your given permissions." }, @@ -2455,12 +2541,21 @@ "resetAccountDescription": { "message": "Resetting your account will clear your transaction history. This will not change the balances in your accounts or require you to re-enter your Secret Recovery Phrase." }, + "resetWallet": { + "message": "Reset Wallet" + }, + "resetWalletSubHeader": { + "message": "MetaMask does not keep a copy of your password. If you’re having trouble unlocking your account, you will need to reset your wallet. You can do this by providing the Secret Recovery Phrase you used when you set up your wallet." + }, + "resetWalletUsingSRP": { + "message": "This action will delete your current wallet and Secret Recovery Phrase from this device, along with the list of accounts you’ve curated. After resetting with a Secret Recovery Phrase, you’ll see a list of accounts based on the Secret Recovery Phrase you use to reset. This new list will automatically include accounts that have a balance. You’ll also be able to $1 created previously. Custom accounts that you’ve imported will need to be $2, and any custom tokens you’ve added to an account will need to be $3 as well." + }, + "resetWalletWarning": { + "message": "Make sure you’re using the correct Secret Recovery Phrase before proceeding. You will not be able to undo this." + }, "restore": { "message": "Restore" }, - "restoreAccountWithSeed": { - "message": "Restore your Account with Secret Recovery Phrase" - }, "restoreWalletPreferences": { "message": "A backup of your data from $1 has been found. Would you like to restore your wallet preferences?", "description": "$1 is the date at which the data was backed up" @@ -2483,6 +2578,9 @@ "revealSeedWordsWarningTitle": { "message": "DO NOT share this phrase with anyone!" }, + "revealTheSeedPhrase": { + "message": "Reveal seed phrase" + }, "rinkeby": { "message": "Rinkeby Test Network" }, @@ -2516,6 +2614,9 @@ "searchResults": { "message": "Search Results" }, + "searchSettings": { + "message": "Search in settings" + }, "searchTokens": { "message": "Search Tokens" }, @@ -2528,9 +2629,6 @@ "secretPhrase": { "message": "Only the first account on this wallet will auto load. After completing this process, to add additional accounts, click the drop down menu, then select Create Account." }, - "secretPhraseWarning": { - "message": "If you restore using another Secret Recovery Phrase, your current wallet, accounts and assets will be removed from this app permanently. This action cannot be undone." - }, "secretRecoveryPhrase": { "message": "Secret Recovery Phrase" }, @@ -2553,22 +2651,22 @@ "message": "Secure my wallet (recommended)" }, "seedPhraseIntroSidebarBulletFour": { - "message": "Write down and store in multiple secret places." + "message": "Write down and store in multiple secret places" }, "seedPhraseIntroSidebarBulletOne": { "message": "Save in a password manager" }, "seedPhraseIntroSidebarBulletThree": { - "message": "Store in a safe-deposit box." + "message": "Store in a safe deposit box" }, "seedPhraseIntroSidebarBulletTwo": { - "message": "Store in a bank vault." + "message": "Store in a bank vault" }, "seedPhraseIntroSidebarCopyOne": { "message": "Your Secret Recovery Phrase is a 12-word phrase that is the “master key” to your wallet and your funds" }, "seedPhraseIntroSidebarCopyThree": { - "message": "If someone asks for your recovery phrase they are likely trying to scam you and steal your wallet funds" + "message": "If someone asks for your recovery phrase they are likely trying to scam you and steal your wallet funds." }, "seedPhraseIntroSidebarCopyTwo": { "message": "Never, ever share your Secret Recovery Phrase, not even with MetaMask!" @@ -2668,6 +2766,9 @@ "settings": { "message": "Settings" }, + "settingsSearchMatchingNotFound": { + "message": "No matching results found" + }, "show": { "message": "Show" }, @@ -2889,20 +2990,23 @@ "storePhrase": { "message": "Store this phrase in a password manager like 1Password." }, + "strong": { + "message": "Strong" + }, "stxAreHere": { - "message": "Smart transactions are here!" + "message": "Smart Transactions are here!" }, "stxBenefit1": { - "message": "Decrease transaction costs" + "message": "Minimize transaction costs" }, "stxBenefit2": { - "message": "Reduce failures & minimize costs" + "message": "Reduce transaction failures" }, "stxBenefit3": { - "message": "Protect from front-running" + "message": "Eliminate stuck transactions" }, "stxBenefit4": { - "message": "Eliminate stuck transactions" + "message": "Prevent front-running" }, "stxCancelled": { "message": "Swap would have failed" @@ -2914,7 +3018,7 @@ "message": "Try your swap again. We’ll be here to protect you against similar risks next time." }, "stxDescription": { - "message": "Smart transactions use MetaMask smart contracts to simulate transactions before submitting in order to..." + "message": "MetaMask Swaps just got a whole lot smarter! Enabling Smart Transactions will allow MetaMask to programmatically optimize your Swap to help:" }, "stxFailure": { "message": "Swap failed" @@ -2936,7 +3040,7 @@ "message": "Privately submitting the Swap..." }, "stxSubDescription": { - "message": "Enabling allows MetaMask to simulate transactions, proactively cancel bad transactions and sign MetaMask Swaps transactions for you." + "message": "* Smart Transactions will attempt to submit your transaction privately, multiple times. If all attempts fail, the transaction will be broadcast publicly to ensure your Swap successfully goes through." }, "stxSuccess": { "message": "Swap complete!" @@ -3367,6 +3471,12 @@ "testFaucet": { "message": "Test Faucet" }, + "theme": { + "message": "Theme" + }, + "themeDescription": { + "message": "Choose your preferred MetaMask theme." + }, "thisWillCreate": { "message": "This will create a new wallet and Secret Recovery Phrase" }, @@ -3606,6 +3716,12 @@ "message": "Sending collectible (ERC-721) tokens is not currently supported", "description": "This is an error message we show the user if they attempt to send a collectible asset type, for which currently don't support sending" }, + "unverifiedContractAddressMessage": { + "message": "We cannot verify this contract. Make sure you trust this address." + }, + "upArrow": { + "message": "up arrow" + }, "updatedWithDate": { "message": "Updated $1" }, @@ -3633,6 +3749,9 @@ "useTokenDetectionDescription": { "message": "We use third-party APIs to detect and display new tokens sent to your wallet. Turn off if you don’t want MetaMask to pull data from those services." }, + "useTokenDetectionPrivacyDesc": { + "message": "Automatically displaying tokens sent to your account involves communication with third party servers to fetch token’s images. Those serves will have access to your IP address." + }, "usedByClients": { "message": "Used by a variety of different clients" }, @@ -3710,6 +3829,9 @@ "walletCreationSuccessTitle": { "message": "Wallet creation successful" }, + "weak": { + "message": "Weak" + }, "web3ShimUsageNotification": { "message": "We noticed that the current website tried to use the removed window.web3 API. If the site appears to be broken, please click $1 for more information.", "description": "$1 is a clickable link." diff --git a/app/_locales/es/messages.json b/app/_locales/es/messages.json index cefb30eaa..a08ff6118 100644 --- a/app/_locales/es/messages.json +++ b/app/_locales/es/messages.json @@ -826,19 +826,12 @@ "importAccount": { "message": "Importar cuenta" }, - "importAccountLinkText": { - "message": "importar con la frase secreta de recuperación" - }, "importAccountMsg": { "message": " Las cuentas importadas no se asociarán con la frase secreta de recuperación de la cuenta original de MetaMask. Más información sobre las cuentas importadas " }, "importAccountSeedPhrase": { "message": "Importar una cuenta con la frase secreta de recuperación" }, - "importAccountText": { - "message": "o $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importTokenQuestion": { "message": "¿Desea importar el token?" }, @@ -1421,9 +1414,6 @@ "restore": { "message": "Restaurar" }, - "restoreAccountWithSeed": { - "message": "Restaurar la cuenta con la frase secreta de recuperación" - }, "restoreWalletPreferences": { "message": "Se encontró una copia de seguridad de los datos de $1. ¿Desea restaurar las preferencias de cartera?", "description": "$1 is the date at which the data was backed up" diff --git a/app/_locales/es_419/messages.json b/app/_locales/es_419/messages.json index b1d29d4a9..a154558d3 100644 --- a/app/_locales/es_419/messages.json +++ b/app/_locales/es_419/messages.json @@ -1322,19 +1322,12 @@ "importAccountError": { "message": "Error al importar la cuenta." }, - "importAccountLinkText": { - "message": "importar con la frase secreta de recuperación" - }, "importAccountMsg": { "message": "Las cuentas importadas no se asociarán con la frase secreta de recuperación de la cuenta original de MetaMask. Aprenda más sobre las cuentas importadas" }, "importAccountSeedPhrase": { "message": "Importar una cartera con la frase secreta de recuperación" }, - "importAccountText": { - "message": "o $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Ingrese su frase secreta de recuperación (también conocida como Frase Semilla) que recibió al crear su cartera. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1794,9 +1787,6 @@ "message": "Cuenta $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "No se añadió el coleccionable porque: $1" - }, "newCollectibleAddedMessage": { "message": "¡El coleccionable fue añadido con éxito!" }, @@ -2278,9 +2268,6 @@ "restore": { "message": "Restaurar" }, - "restoreAccountWithSeed": { - "message": "Restaurar la cuenta con la frase secreta de recuperación" - }, "restoreWalletPreferences": { "message": "Se encontró una copia de seguridad de los datos de $1. ¿Desea restaurar las preferencias de cartera?", "description": "$1 is the date at which the data was backed up" @@ -2346,10 +2333,7 @@ "message": "ADVERTENCIA: No revele su frase de respaldo. Cualquier persona que tenga esta frase puede robarle los ethers." }, "secretPhrase": { - "message": "Solo la primera cuenta de esta cartera se cargará automáticamente. Después de llevar a cabo este proceso, para agregar cuentas adicionales haga clic en el menú desplegable y luego seleccione Crear cuenta." - }, - "secretPhraseWarning": { - "message": "Si restablece utilizando otra frase secreta de recuperación, su cartera actual, sus cuentas y sus activos se eliminarán de esta aplicación de forma permanente. Esta acción es irreversible." + "message": "Ingrese su frase secreta aquí para restaurar su bóveda." }, "secretRecoveryPhrase": { "message": "Frase secreta de recuperación" diff --git a/app/_locales/et/messages.json b/app/_locales/et/messages.json index b349b34b2..8bf5aa8ac 100644 --- a/app/_locales/et/messages.json +++ b/app/_locales/et/messages.json @@ -755,9 +755,6 @@ "restore": { "message": "Taasta" }, - "restoreAccountWithSeed": { - "message": "Taastage konto seemnefraasi abil" - }, "revealSeedWords": { "message": "Kuva seemnesõnu" }, diff --git a/app/_locales/fa/messages.json b/app/_locales/fa/messages.json index eb43442d2..32b7c8e48 100644 --- a/app/_locales/fa/messages.json +++ b/app/_locales/fa/messages.json @@ -765,9 +765,6 @@ "restore": { "message": "بازیابی" }, - "restoreAccountWithSeed": { - "message": "حساب تان را با عبارت بازیاب، بازیابی کنید" - }, "revealSeedWords": { "message": "کلمات بازیاب را آشکار کنید" }, diff --git a/app/_locales/fi/messages.json b/app/_locales/fi/messages.json index d00a8ff3e..108165b57 100644 --- a/app/_locales/fi/messages.json +++ b/app/_locales/fi/messages.json @@ -762,9 +762,6 @@ "restore": { "message": "Palauta" }, - "restoreAccountWithSeed": { - "message": "Palauta tilisi käyttäen salaustekstiä (seed phrase)" - }, "revealSeedWords": { "message": "Paljasta salaussanat" }, diff --git a/app/_locales/fil/messages.json b/app/_locales/fil/messages.json index 06999930d..64695058e 100644 --- a/app/_locales/fil/messages.json +++ b/app/_locales/fil/messages.json @@ -689,9 +689,6 @@ "restore": { "message": "Ipanumbalik" }, - "restoreAccountWithSeed": { - "message": "I-restore ang iyong Account gamit ang Seed Phrase" - }, "revealSeedWords": { "message": "Ipakita ang Seed Words" }, diff --git a/app/_locales/fr/messages.json b/app/_locales/fr/messages.json index b1bc21ee4..a311e6ca5 100644 --- a/app/_locales/fr/messages.json +++ b/app/_locales/fr/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Erreur d’importation de compte." }, - "importAccountLinkText": { - "message": "importer en utilisant la phrase secrète de récupération" - }, "importAccountMsg": { "message": "Les comptes importés ne seront pas associés à la phrase secrète de récupération que vous avez créée au départ dans MetaMask. En savoir plus sur les comptes importés" }, "importAccountSeedPhrase": { "message": "Importez un compte avec une phrase mnémotechnique" }, - "importAccountText": { - "message": "ou $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Saisissez la phrase secrète de récupération (aussi appelée « phrase mnémonique » ou « seed ») qui vous a été attribuée lors de la création de votre portefeuille. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Compte $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Le collectible n’a pas été ajouté, car : $1" - }, "newCollectibleAddedMessage": { "message": "Le collectible a été ajouté avec succès !" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Restaurer" }, - "restoreAccountWithSeed": { - "message": "Restaurer votre compte avec une phrase Seed." - }, "restoreWalletPreferences": { "message": "Une sauvegarde de vos données de $1 a été trouvée. Voulez-vous restaurer vos préférences de portefeuille ?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Seul le premier compte de ce portefeuille sera chargé automatiquement. Après avoir terminé ce processus, pour ajouter des comptes supplémentaires, cliquez sur le menu déroulant, puis sélectionnez Créer un compte." }, - "secretPhraseWarning": { - "message": "Si vous effectuez une restauration à l’aide d’une autre phrase secrète de récupération, votre portefeuille, vos comptes et vos actifs actuels seront définitivement supprimés de cette application. Cette action est irréversible." - }, "secretRecoveryPhrase": { "message": "Phrase secrète de récupération" }, diff --git a/app/_locales/he/messages.json b/app/_locales/he/messages.json index 70a04be83..8cfe2edbd 100644 --- a/app/_locales/he/messages.json +++ b/app/_locales/he/messages.json @@ -762,9 +762,6 @@ "restore": { "message": "שחזר" }, - "restoreAccountWithSeed": { - "message": "שחזר את חשבונך באמצעות צירוף הגרעין" - }, "revealSeedWords": { "message": "גלה מילות Seed" }, diff --git a/app/_locales/hi/messages.json b/app/_locales/hi/messages.json index 0853cd02b..626d1ae25 100644 --- a/app/_locales/hi/messages.json +++ b/app/_locales/hi/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "खाता आयात करने में त्रुटि।" }, - "importAccountLinkText": { - "message": "गुप्त रिकवरी फ्रेज का उपयोग करके आयात करें" - }, "importAccountMsg": { "message": "आयातित खाते आपके मूल रूप से बनाए गए MetaMask खाते के गुप्त रिकवरी फ्रेज से संबद्ध नहीं होंगे। आयातित खातों के बारे में अधिक जानें" }, "importAccountSeedPhrase": { "message": "गुप्त रिकवरी फ्रेज के साथ एक खाता आयात करें" }, - "importAccountText": { - "message": "या $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "अपना सीक्रेट रिकवरी फ्रेज (उर्फ सीड फ्रेज) दर्ज करें जो आपको अपना वॉलेट बनाने पर दिया गया था। $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "खाता $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "संग्रहणीय नहीं जोड़ा गया था क्योंकि: $1" - }, "newCollectibleAddedMessage": { "message": "संग्रहणीय सफलतापूर्वक जोड़ा गया!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "पुनर्स्थापित करें" }, - "restoreAccountWithSeed": { - "message": "गुप्त रिकवरी फ्रेज के साथ अपने खाते को पुनर्स्थापित करें" - }, "restoreWalletPreferences": { "message": "$1 से आपके डेटा का बैकअप मिला है। क्या आप अपनी वॉलेट वरीयताओं को पुनर्स्थापित करना चाहते हैं?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "इस वॉलेट पर केवल पहला खाता स्वतः लोड होगा। इस प्रक्रिया को पूरा करने के बाद, अतिरिक्त खाते जोड़ने के लिए, ड्रॉप डाउन मेन्यू पर क्लिक करें, फिर खाता बनाएं चुनें।" }, - "secretPhraseWarning": { - "message": "यदि आप किसी दूसरे सीक्रेट रिकवरी फ्रेज का उपयोग कर पुनर्स्थापित करते हैं, तो इस ऐप से आपके वर्तमान वॉलेट, अकाउंट, और संपति स्थायी रूप से हटा दिये जाएंगे। यह क्रिया पूर्ववत नहीं की जा सकती।" - }, "secretRecoveryPhrase": { "message": "सीक्रेट रिकवरी फ्रेज" }, diff --git a/app/_locales/hr/messages.json b/app/_locales/hr/messages.json index 1de58c64d..eb3ffefb1 100644 --- a/app/_locales/hr/messages.json +++ b/app/_locales/hr/messages.json @@ -758,9 +758,6 @@ "restore": { "message": "Vrati" }, - "restoreAccountWithSeed": { - "message": "Obnovite svoj račun početnom rečenicom" - }, "revealSeedWords": { "message": "Otkrij početne riječi" }, diff --git a/app/_locales/ht/messages.json b/app/_locales/ht/messages.json index dae10bef3..44409dd45 100644 --- a/app/_locales/ht/messages.json +++ b/app/_locales/ht/messages.json @@ -479,9 +479,6 @@ "restore": { "message": "Retabli" }, - "restoreAccountWithSeed": { - "message": "Retabli kont ou avèk yo Seed Fraz" - }, "revealSeedWords": { "message": "Revele Seed Mo Yo" }, diff --git a/app/_locales/hu/messages.json b/app/_locales/hu/messages.json index 764e55689..ddbde0797 100644 --- a/app/_locales/hu/messages.json +++ b/app/_locales/hu/messages.json @@ -758,9 +758,6 @@ "restore": { "message": "Visszaállítás" }, - "restoreAccountWithSeed": { - "message": "Fiók helyreállítása a seed mondat segítségével" - }, "revealSeedWords": { "message": "Seed szavak megjelenítése" }, diff --git a/app/_locales/id/messages.json b/app/_locales/id/messages.json index 84418a062..bae413007 100644 --- a/app/_locales/id/messages.json +++ b/app/_locales/id/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Galat saat mengimpor akun." }, - "importAccountLinkText": { - "message": "impor menggunakan Frasa Pemulihan Rahasia" - }, "importAccountMsg": { "message": "Akun yang diimpor tidak akan dikaitkan dengan Frasa Pemulihan Rahasia akun MetaMask yang asli dibuat. Pelajari selengkapnya tentang akun yang diimpor" }, "importAccountSeedPhrase": { "message": "Impor dompet dengan Frasa Pemulihan Rahasia" }, - "importAccountText": { - "message": "atau $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Masukkan Frasa Pemulihan Rahasia Anda (alias Frasa Benih) yang diberikan saat Anda membuat dompet. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Akun $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Koleksi tidak ditambahkan karena: $1" - }, "newCollectibleAddedMessage": { "message": "Koleksi berhasil ditambahkan!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Pulihkan" }, - "restoreAccountWithSeed": { - "message": "Pulihkan Akun dengan Frasa Pemulihan Rahasia" - }, "restoreWalletPreferences": { "message": "Cadangan data Anda dari $1 telah ditemukan. Pulihkan preferensi dompet Anda?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Hanya akun pertama di dompet ini yang akan dimuat secara otomatis. Setelah proses ini selesai, untuk menambahkan akun tambahan, klik menu drop down, lalu pilih Buat Akun." }, - "secretPhraseWarning": { - "message": "Jika Anda memulihkan menggunakan Frasa Pemulihan Rahasia lainnya, dompet, akun, dan aset Anda saat ini akan dihapus dari aplikasi ini secara permanen. Tindakan ini tidak dapat dibatalkan." - }, "secretRecoveryPhrase": { "message": "Frasa Pemulihan Rahasia" }, diff --git a/app/_locales/it/messages.json b/app/_locales/it/messages.json index 3ebfc6e95..b686b183b 100644 --- a/app/_locales/it/messages.json +++ b/app/_locales/it/messages.json @@ -1152,9 +1152,6 @@ "restore": { "message": "Ripristina" }, - "restoreAccountWithSeed": { - "message": "Ripristina Account con la Frase Seed" - }, "restoreWalletPreferences": { "message": "È stato trovato un backup dei tuoi dati da $1. Vuoi ripristinare le preferenze del portafoglio?", "description": "$1 is the date at which the data was backed up" diff --git a/app/_locales/ja/messages.json b/app/_locales/ja/messages.json index 88ff32476..e544f3a6b 100644 --- a/app/_locales/ja/messages.json +++ b/app/_locales/ja/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "アカウントのインポート中にエラーが発生しました。" }, - "importAccountLinkText": { - "message": "シークレットリカバリーフレーズを使用してインポート" - }, "importAccountMsg": { "message": " インポートされたアカウントは、最初に作成したMetaMaskアカウントのシークレットリカバリーフレーズと関連付けられません。インポートされたアカウントの詳細を表示" }, "importAccountSeedPhrase": { "message": "シークレットリカバリーフレーズを使用してウォレットをインポート" }, - "importAccountText": { - "message": "または$1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "ウォレットの作成時に提供されたシークレットリカバリーフレーズ (シードフレーズ) を入力してください。$1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "アカウント$1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "次の理由により、コレクティブルは追加されませんでした: $1" - }, "newCollectibleAddedMessage": { "message": "コレクティブルが追加されました!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "復元" }, - "restoreAccountWithSeed": { - "message": "シークレットリカバリーフレーズでアカウントを復元" - }, "restoreWalletPreferences": { "message": "$1のデータのバックアップが見つかりました。ウォレットの基本設定を復元しますか?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "このウォレットの最初のアカウントのみが自動的に読み込まれます。 このプロセスの完了後、他のアカウントを追加するには、ドロップダウンメニューをクリックし、[アカウントを作成] を選択します。" }, - "secretPhraseWarning": { - "message": "別のシークレットリカバリーフレーズを使用して復元すると、現在のウォレット、アカウント、アセットは永久にこのアプリから削除されます。この操作は元に戻せません。" - }, "secretRecoveryPhrase": { "message": "シークレットリカバリーフレーズ" }, diff --git a/app/_locales/kn/messages.json b/app/_locales/kn/messages.json index 5e74dd375..e6c557c5c 100644 --- a/app/_locales/kn/messages.json +++ b/app/_locales/kn/messages.json @@ -765,9 +765,6 @@ "restore": { "message": "ಮರುಸ್ಥಾಪನೆ" }, - "restoreAccountWithSeed": { - "message": "ಸೀಡ್ ಫ್ರೇಸ್‌ನೊಂದಿಗೆ ನಿಮ್ಮ ಖಾತೆಯನ್ನು ಮರುಸ್ಥಾಪಿಸಿ" - }, "revealSeedWords": { "message": "ಸೀಡ್ ವರ್ಡ್ಸ್ ಬಹಿರಂಗಪಡಿಸಿ" }, diff --git a/app/_locales/ko/messages.json b/app/_locales/ko/messages.json index 413bb0212..9814be129 100644 --- a/app/_locales/ko/messages.json +++ b/app/_locales/ko/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "계정 가져오기 오류" }, - "importAccountLinkText": { - "message": "비밀 복구 구문을 사용해 가져오기" - }, "importAccountMsg": { "message": "가져온 계정은 본래 생성한 MetaMask 계정 비밀 복구 구문과 연결하지 못합니다. 가져온 계정에 대해 자세히 알아보기" }, "importAccountSeedPhrase": { "message": "비밀 복구 구문으로 계정 가져오기" }, - "importAccountText": { - "message": "또는 $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "지갑을 만들 때 받은 비밀 복구 구문(시드 구문)을 입력하세요. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "계정 $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "다음 이유 때문에 수집 금액이 추가되지 않았습니다: $1" - }, "newCollectibleAddedMessage": { "message": "수집이 성공적으로 추가되었습니다!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "복구" }, - "restoreAccountWithSeed": { - "message": "비밀 복구 구문으로 계정 복구" - }, "restoreWalletPreferences": { "message": "$1의 데이터 백업이 발견되었습니다. 지갑 환경설정을 복원할까요?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "금고를 복구하려면 비밀 구문을 여기에 입력하세요." }, - "secretPhraseWarning": { - "message": "다른 비밀 복구 구문을 사용하여 복구하면 현재 지갑, 계정 및 자산이 이 앱에서 영구적으로 제거됩니다. 이 작업은 취소할 수 없습니다." - }, "secretRecoveryPhrase": { "message": "비밀 복구 구문" }, diff --git a/app/_locales/lt/messages.json b/app/_locales/lt/messages.json index efb5c8ab8..1a7dd9a51 100644 --- a/app/_locales/lt/messages.json +++ b/app/_locales/lt/messages.json @@ -765,9 +765,6 @@ "restore": { "message": "Atkurti" }, - "restoreAccountWithSeed": { - "message": "Atkurti paskyrą naudojant atkūrimo frazę" - }, "revealSeedWords": { "message": "Atskleisti atkūrimo žodžius" }, diff --git a/app/_locales/lv/messages.json b/app/_locales/lv/messages.json index 273904682..adf1c19d4 100644 --- a/app/_locales/lv/messages.json +++ b/app/_locales/lv/messages.json @@ -761,9 +761,6 @@ "restore": { "message": "Atjaunot" }, - "restoreAccountWithSeed": { - "message": "Atjaunojiet savu kontu ar atkopšanas frāzi" - }, "revealSeedWords": { "message": "Parādīt atkopšanas vārdus" }, diff --git a/app/_locales/ms/messages.json b/app/_locales/ms/messages.json index 60ca3829c..0675bc2a5 100644 --- a/app/_locales/ms/messages.json +++ b/app/_locales/ms/messages.json @@ -745,9 +745,6 @@ "restore": { "message": "Pulihkan" }, - "restoreAccountWithSeed": { - "message": "Pulihkan Akaun anda dengan Ungkapan Benih" - }, "revealSeedWords": { "message": "Dedahkan Ungkapan Benih" }, diff --git a/app/_locales/no/messages.json b/app/_locales/no/messages.json index 444a81229..a8bb4af03 100644 --- a/app/_locales/no/messages.json +++ b/app/_locales/no/messages.json @@ -752,9 +752,6 @@ "restore": { "message": "Gjenopprett" }, - "restoreAccountWithSeed": { - "message": "Gjenopprett konto med frøfrase" - }, "revealSeedWords": { "message": "Vis frøord" }, diff --git a/app/_locales/ph/messages.json b/app/_locales/ph/messages.json index 6d82062e4..c738b5788 100644 --- a/app/_locales/ph/messages.json +++ b/app/_locales/ph/messages.json @@ -842,19 +842,12 @@ "importAccount": { "message": "Mag-import ng Account" }, - "importAccountLinkText": { - "message": "i-import gamit ang Secret Recovery Phrase" - }, "importAccountMsg": { "message": " Ang mga na-import na account ay hindi mauugnay sa orihinal mong nagawang Secret Recovery Phrase ng MetaMask account. Matuto pa tungkol sa mga na-import account " }, "importAccountSeedPhrase": { "message": "Mag-import ng account gamit ang Secret Recovery Phrase" }, - "importAccountText": { - "message": "o $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importTokenQuestion": { "message": "Mag-import ng token?" }, @@ -1446,9 +1439,6 @@ "restore": { "message": "I-restore" }, - "restoreAccountWithSeed": { - "message": "I-restore ang iyong Account gamit ang Secret Recovery Phrase" - }, "restoreWalletPreferences": { "message": "Nakita ang backup ng iyong data mula sa $1. Gusto mo bang i-restore ang mga kagustuhan mo sa wallet?", "description": "$1 is the date at which the data was backed up" diff --git a/app/_locales/pl/messages.json b/app/_locales/pl/messages.json index e37cdeca0..43f9ca385 100644 --- a/app/_locales/pl/messages.json +++ b/app/_locales/pl/messages.json @@ -759,9 +759,6 @@ "restore": { "message": "Przywróć" }, - "restoreAccountWithSeed": { - "message": "Przywróć konto frazą seed" - }, "revealSeedWords": { "message": "Pokaż słowa seed" }, diff --git a/app/_locales/pt_BR/messages.json b/app/_locales/pt_BR/messages.json index d6c8a3923..5d1289040 100644 --- a/app/_locales/pt_BR/messages.json +++ b/app/_locales/pt_BR/messages.json @@ -1306,19 +1306,12 @@ "importAccountError": { "message": "Erro de importação de conta." }, - "importAccountLinkText": { - "message": "importe usando a Frase de Recuperação Secreta" - }, "importAccountMsg": { "message": "As contas importadas não estarão associadas à Frase de Recuperação Secreta da conta da MetaMask criada originalmente. Saiba mais sobre as contas importadas" }, "importAccountSeedPhrase": { "message": "Importe uma carteira com a Frase de Recuperação Secreta" }, - "importAccountText": { - "message": "ou $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Digite sua Frase de Recuperação Secreta (ou seja, a frase seed) que lhe foi dada quando você criou a sua carteira. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1778,9 +1771,6 @@ "message": "Conta $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "O colecionável não foi adicionado pelo seguinte motivo: $1" - }, "newCollectibleAddedMessage": { "message": "O colecionável foi adicionado com sucesso!" }, @@ -2262,9 +2252,6 @@ "restore": { "message": "Restaurar" }, - "restoreAccountWithSeed": { - "message": "Restaure sua conta com a Frase de Recuperação Secreta" - }, "restoreWalletPreferences": { "message": "Encontramos um backup dos seus dados de $1. Gostaria de restaurar as preferências da sua carteira?", "description": "$1 is the date at which the data was backed up" @@ -2332,9 +2319,6 @@ "secretPhrase": { "message": "Somente a primeira conta nessa carteira será carregada automaticamente. Após concluir esse processo, para adicionar mais contas, clique no menu suspenso e selecione Criar Conta." }, - "secretPhraseWarning": { - "message": "Se você restaurar usando outra Frase de Recuperação Secreta, sua carteira, conta e ativos atuais serão removidos permanentemente deste aplicativo. Essa ação será irreversível." - }, "secretRecoveryPhrase": { "message": "Frase de Recuperação Secreta" }, diff --git a/app/_locales/ro/messages.json b/app/_locales/ro/messages.json index 37135974e..387fac7bb 100644 --- a/app/_locales/ro/messages.json +++ b/app/_locales/ro/messages.json @@ -752,9 +752,6 @@ "restore": { "message": "Restabilește" }, - "restoreAccountWithSeed": { - "message": "Restaurați-vă contul folosind fraza inițială" - }, "revealSeedWords": { "message": "Arată cuvintele din seed" }, diff --git a/app/_locales/ru/messages.json b/app/_locales/ru/messages.json index 23c46ab20..b2dd593ba 100644 --- a/app/_locales/ru/messages.json +++ b/app/_locales/ru/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Ошибка импорта счета." }, - "importAccountLinkText": { - "message": "импортировать с использованием секретной фразы для восстановления" - }, "importAccountMsg": { "message": "Импортированные счета не будут связаны с секретной фразой для восстановления вашего изначально созданного счета MetaMask. Узнайте больше об импортированных счетах" }, "importAccountSeedPhrase": { "message": "Импорт кошелька с помощью секретной фразы для восстановления" }, - "importAccountText": { - "message": "или $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Введите секретную фразу для восстановления (также известную как «сид-фраза»), которую вы получили при создании кошелька. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Счет $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Причина, по которой не был добавлен коллекционный актив: $1" - }, "newCollectibleAddedMessage": { "message": "Коллекционный актив успешно добавлен!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Восстановить" }, - "restoreAccountWithSeed": { - "message": "Восстановите свой счет с помощью секретной фразы для восстановления" - }, "restoreWalletPreferences": { "message": "Найдена резервная копия ваших данных из $1. Хотите восстановить настройки кошелька?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Автоматически загружается только первый счет в этом кошельке. Для добавления дополнительных счетов, после завершения этого процесса нажмите на выпадающее меню, а затем выберите «Создать счет»." }, - "secretPhraseWarning": { - "message": "Если вы выполняете восстановление с использованием другой секретной фразы для восстановления, ваш текущий кошелек, счета и активы будут удалены из этого приложения без возможности восстановления. Это действие нельзя отменить." - }, "secretRecoveryPhrase": { "message": "Секретная фраза для восстановления" }, diff --git a/app/_locales/sk/messages.json b/app/_locales/sk/messages.json index 5e818d979..396bdf170 100644 --- a/app/_locales/sk/messages.json +++ b/app/_locales/sk/messages.json @@ -734,9 +734,6 @@ "restore": { "message": "Obnoviť" }, - "restoreAccountWithSeed": { - "message": "Obnoviť účet pomocou seed frázy" - }, "revealSeedWords": { "message": "Zobrazit slova klíčové fráze" }, diff --git a/app/_locales/sl/messages.json b/app/_locales/sl/messages.json index d2cfea50b..490e9ed0c 100644 --- a/app/_locales/sl/messages.json +++ b/app/_locales/sl/messages.json @@ -753,9 +753,6 @@ "restore": { "message": "Obnovi" }, - "restoreAccountWithSeed": { - "message": "Obnovi račun z seed phrase" - }, "revealSeedWords": { "message": "Razkrij seed words" }, diff --git a/app/_locales/sr/messages.json b/app/_locales/sr/messages.json index c6c35376c..63a52f898 100644 --- a/app/_locales/sr/messages.json +++ b/app/_locales/sr/messages.json @@ -756,9 +756,6 @@ "restore": { "message": "Поново отвори" }, - "restoreAccountWithSeed": { - "message": "Povratite svoj nalog uz pomoć seed fraze" - }, "revealSeedWords": { "message": "Otkrivanje početnih reči" }, diff --git a/app/_locales/sv/messages.json b/app/_locales/sv/messages.json index 0000c4949..c3fa28d56 100644 --- a/app/_locales/sv/messages.json +++ b/app/_locales/sv/messages.json @@ -749,9 +749,6 @@ "restore": { "message": "Återställ" }, - "restoreAccountWithSeed": { - "message": "Återställ ditt konto med seedphrase" - }, "revealSeedWords": { "message": "Visa seed-ord" }, diff --git a/app/_locales/sw/messages.json b/app/_locales/sw/messages.json index 247318676..8c4eb4f27 100644 --- a/app/_locales/sw/messages.json +++ b/app/_locales/sw/messages.json @@ -743,9 +743,6 @@ "restore": { "message": "Rejesha" }, - "restoreAccountWithSeed": { - "message": "Rejesha Akaunti yako kwa kutumia Kirai Kianzio." - }, "revealSeedWords": { "message": "Onyesha Maneno ya Kianzio" }, diff --git a/app/_locales/tl/messages.json b/app/_locales/tl/messages.json index 20d2c1182..64bd5b6fc 100644 --- a/app/_locales/tl/messages.json +++ b/app/_locales/tl/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Error sa pag-import ng account." }, - "importAccountLinkText": { - "message": "i-import gamit ang Secret Recovery Phrase" - }, "importAccountMsg": { "message": "Ang mga na-import na account ay hindi mauugnay sa orihinal mong nagawang Secret Recovery Phrase ng MetaMask account. Matuto pa tungkol sa mga na-import account" }, "importAccountSeedPhrase": { "message": "Mag-import ng account gamit ang Secret Recovery Phrase" }, - "importAccountText": { - "message": "o $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Ilagay ang iyong Secret Recovery Phrase (kilala rin bilang Seed Phrase) na ibinigay sa iyo noong gumawa ka ng iyong wallet. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Account $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Ang collectible ay hindi idinagdag dahil: $1" - }, "newCollectibleAddedMessage": { "message": "Ang collectible ay tagumpay na naidagdag!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "I-restore" }, - "restoreAccountWithSeed": { - "message": "I-restore ang iyong Account gamit ang Secret Recovery Phrase" - }, "restoreWalletPreferences": { "message": "Nakita ang backup ng iyong data mula sa $1. Gusto mo bang i-restore ang mga kagustuhan mo sa wallet?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Ang unang account lang sa wallet na ito ang awtomatikong maglo-load. Pagkatapos makumpleto ang prosesong ito, upang magdagdag ng mga karagdagang account, i-click ang drop down na menu, pagkatapos ay piliin ang Gumawa ng Account." }, - "secretPhraseWarning": { - "message": "Kapag nagre-restore ka gamit ang isa pang Secret Recovery Phrase, permanenteng aalisin sa app na ito ang iyong kasalukuyang wallet, mga account, at asset. Ang gawaing ito ay hindi pwedeng baguhin." - }, "secretRecoveryPhrase": { "message": "Secret Recovery Phrase" }, diff --git a/app/_locales/tr/messages.json b/app/_locales/tr/messages.json index a6d03b419..1f19939af 100644 --- a/app/_locales/tr/messages.json +++ b/app/_locales/tr/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Hesap içe aktarılırken hata oluştu." }, - "importAccountLinkText": { - "message": "Gizli Kurtarma İfadesi kullanarak içe aktar" - }, "importAccountMsg": { "message": "İçe aktarılan hesaplar ilk olarak oluşturduğunuz MetaMask hesabı Gizli Kurtarma ifadenizle ilişkilendirilmez. İçe aktarılan hesaplar hakkında daha fazla bilgi edinin" }, "importAccountSeedPhrase": { "message": "Gizli Kurtarma İfadesi ile bir cüzdanı içe aktarın" }, - "importAccountText": { - "message": "veya $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Cüzdanınızı oluşturduğunuzda size verilen Gizli Kurtarma İfadenizi (başka bir deyişle Tohum İfadesi) girin. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Hesap $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Tahsil edilebilir tutar eklenmedi ve sebebi: $1" - }, "newCollectibleAddedMessage": { "message": "Tahsil edilebilir tutar başarılı bir şekilde eklendi!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Geri Yükle" }, - "restoreAccountWithSeed": { - "message": "Gizli Kurtarma İfadesi ile Hesabınızı geri yükleyin" - }, "restoreWalletPreferences": { "message": "Verilerinizin $1 tarihinden bir yedeği bulundu. Cüzdan tercihlerinizi geri yüklemek ister misiniz?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Sadece bu cüzdandaki ilk hesap otomatik olarak yüklenecektir. Bu işlem tamamlandıktan sonra ilave hesaplar eklemek için açılır menüye tıklayın ardından Hesap Oluştur seçeneğini seçin." }, - "secretPhraseWarning": { - "message": "Başka bir Gizli Kurtarma İfadesini kullanarak geri yükleme işlemi yaparsanız mevcut cüzdan, hesap ve varlıklarınız bu uygulamadan kalıcı olarak silinir. Bu işlem geri alınamaz." - }, "secretRecoveryPhrase": { "message": "Gizli Kurtarma İfadesi" }, diff --git a/app/_locales/uk/messages.json b/app/_locales/uk/messages.json index ec6b77371..ed521399c 100644 --- a/app/_locales/uk/messages.json +++ b/app/_locales/uk/messages.json @@ -765,9 +765,6 @@ "restore": { "message": "Відновити" }, - "restoreAccountWithSeed": { - "message": "Відновіть ваш обліковий запис за допомогою seed-фрази" - }, "revealSeedWords": { "message": "Показати мнемонічні слова" }, diff --git a/app/_locales/vi/messages.json b/app/_locales/vi/messages.json index 503ce3495..d3cc6931c 100644 --- a/app/_locales/vi/messages.json +++ b/app/_locales/vi/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "Lỗi khi nhập tài khoản." }, - "importAccountLinkText": { - "message": "nhập bằng Cụm mật khẩu khôi phục bí mật" - }, "importAccountMsg": { "message": "Tài khoản đã nhập sẽ không được liên kết với Cụm mật khẩu khôi phục bí mật cho tài khoản MetaMask đã tạo ban đầu của bạn. Tìm hiểu thêm về các tài khoản đã nhập" }, "importAccountSeedPhrase": { "message": "Nhập một ví bằng Cụm mật khẩu khôi phục bí mật" }, - "importAccountText": { - "message": "hoặc $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "Nhập Cụm Mật Khẩu Khôi Phục Bí Mật (còn được gọi là Cụm Mật Khẩu Gốc) mà bạn được cấp khi tạo ví. $1", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "Tài khoản $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "Bộ sưu tập đã không được thêm vì: $1" - }, "newCollectibleAddedMessage": { "message": "Bộ sưu tập đã được thêm thành công!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "Khôi phục" }, - "restoreAccountWithSeed": { - "message": "Khôi phục tài khoản của bạn bằng cụm mật khẩu khôi phục bí mật" - }, "restoreWalletPreferences": { "message": "Đã tìm thấy bản sao lưu dữ liệu của bạn từ $1. Bạn có muốn khôi phục các tùy chọn ưu tiên trong ví của mình không?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "Chỉ tự động tải tài khoản đầu tên trên ví. Sau khi hoàn tất quá trình này, để thêm tài khoản bổ sung, hãy nhấn vào trình đơn thả xuống và chọn Tạo tài khoản." }, - "secretPhraseWarning": { - "message": "Nếu bạn khôi phục bằng cách sử dụng một Cụm Mật Khẩu Khôi Phục Bí Mật khác, thì ví, tài khoản và tài sản hiện tại của bạn sẽ bị xóa khỏi ứng dụng này vĩnh viễn. Không thể hoàn tác hành động này." - }, "secretRecoveryPhrase": { "message": "Cụm Mật Khẩu Khôi Phục Bí Mật" }, diff --git a/app/_locales/zh_CN/messages.json b/app/_locales/zh_CN/messages.json index 1e662c7b1..d9c4aa6ea 100644 --- a/app/_locales/zh_CN/messages.json +++ b/app/_locales/zh_CN/messages.json @@ -1273,19 +1273,12 @@ "importAccountError": { "message": "导入帐户时出错。" }, - "importAccountLinkText": { - "message": "使用账户助记词导入" - }, "importAccountMsg": { "message": "导入的账户将不会与最初创建的 MetaMask 账户助记词相关联。了解更多有关导入账户的信息 。" }, "importAccountSeedPhrase": { "message": "使用账户助记词导入账户" }, - "importAccountText": { - "message": "或 $1", - "description": "$1 represents the text from `importAccountLinkText` as a link" - }, "importExistingWalletDescription": { "message": "输入您创建$1钱包时提供的保密恢复短语(或Seed Phrase)。", "description": "$1 is the words 'Learn More' from key 'learnMore', separated here so that it can be added as a link" @@ -1745,9 +1738,6 @@ "message": "账户 $1", "description": "Default name of next account to be created on create account screen" }, - "newCollectibleAddFailed": { - "message": "未添加收藏,因为:$1" - }, "newCollectibleAddedMessage": { "message": "收藏已成功添加!" }, @@ -2229,9 +2219,6 @@ "restore": { "message": "恢复" }, - "restoreAccountWithSeed": { - "message": "使用账户助记词恢复您的账户" - }, "restoreWalletPreferences": { "message": "已找到于 $1 的数据备份。您想恢复您的钱包设置吗?", "description": "$1 is the date at which the data was backed up" @@ -2299,9 +2286,6 @@ "secretPhrase": { "message": "只有这个钱包上的第一个帐户将自动加载。 完成此流程后,点击下拉菜单,然后选择创建账户。" }, - "secretPhraseWarning": { - "message": "如果您使用另一个账户助记词来还原,您当前的钱包、帐户和资产将永久从这个应用中移除。 此操作不能撤消。" - }, "secretRecoveryPhrase": { "message": "账户助记词" }, diff --git a/app/_locales/zh_TW/messages.json b/app/_locales/zh_TW/messages.json index 92d7e10b9..ba978532e 100644 --- a/app/_locales/zh_TW/messages.json +++ b/app/_locales/zh_TW/messages.json @@ -747,9 +747,6 @@ "resetAccountDescription": { "message": "重置帳戶將清除您的交易紀錄" }, - "restoreAccountWithSeed": { - "message": "透過助憶詞還原您的帳戶" - }, "revealSeedWords": { "message": "顯示助憶詞" }, diff --git a/app/build-types/beta/images/logo/metamask-logo-horizontal-dark.svg b/app/build-types/beta/images/logo/metamask-logo-horizontal-dark.svg deleted file mode 100644 index 43a44eb0e..000000000 --- a/app/build-types/beta/images/logo/metamask-logo-horizontal-dark.svg +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/build-types/beta/images/logo/metamask-logo-horizontal.svg b/app/build-types/beta/images/logo/metamask-logo-horizontal.svg deleted file mode 100644 index 3155a5149..000000000 --- a/app/build-types/beta/images/logo/metamask-logo-horizontal.svg +++ /dev/null @@ -1,148 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/build-types/flask/images/logo/metamask-logo-horizontal-dark.svg b/app/build-types/flask/images/logo/metamask-logo-horizontal-dark.svg deleted file mode 100644 index 450ac8434..000000000 --- a/app/build-types/flask/images/logo/metamask-logo-horizontal-dark.svg +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/build-types/flask/images/logo/metamask-logo-horizontal.svg b/app/build-types/flask/images/logo/metamask-logo-horizontal.svg deleted file mode 100644 index c38ba8c45..000000000 --- a/app/build-types/flask/images/logo/metamask-logo-horizontal.svg +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/images/arbitrum.svg b/app/images/arbitrum.svg new file mode 100644 index 000000000..5e79c8ccd --- /dev/null +++ b/app/images/arbitrum.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/images/caret-left-black.svg b/app/images/caret-left-black.svg deleted file mode 100644 index f225424f0..000000000 --- a/app/images/caret-left-black.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/app/images/caret-left.svg b/app/images/caret-left.svg deleted file mode 100644 index 775d76e39..000000000 --- a/app/images/caret-left.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/app/images/caret-right.svg b/app/images/caret-right.svg deleted file mode 100644 index 1308f59ce..000000000 --- a/app/images/caret-right.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/app/images/icons/caret-down.svg b/app/images/icons/caret-down.svg deleted file mode 100644 index 8ab7b0319..000000000 --- a/app/images/icons/caret-down.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/app/images/icons/collapse.svg b/app/images/icons/collapse.svg deleted file mode 100644 index 74d6207c9..000000000 --- a/app/images/icons/collapse.svg +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/images/logo/metamask-logo-horizontal.svg b/app/images/logo/metamask-logo-horizontal.svg deleted file mode 100644 index bc60a0782..000000000 --- a/app/images/logo/metamask-logo-horizontal.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/app/images/logo/metamask-smart-transactions@4x.png b/app/images/logo/metamask-smart-transactions@4x.png deleted file mode 100644 index 636576495..000000000 Binary files a/app/images/logo/metamask-smart-transactions@4x.png and /dev/null differ diff --git a/app/images/logo/smart-transactions-header.png b/app/images/logo/smart-transactions-header.png new file mode 100644 index 000000000..d0fa8ea94 Binary files /dev/null and b/app/images/logo/smart-transactions-header.png differ diff --git a/app/images/optimism.svg b/app/images/optimism.svg new file mode 100644 index 000000000..e8c6e64e4 --- /dev/null +++ b/app/images/optimism.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/images/times.svg b/app/images/times.svg new file mode 100644 index 000000000..5aa9be3a5 --- /dev/null +++ b/app/images/times.svg @@ -0,0 +1,3 @@ + + + diff --git a/app/scripts/background.js b/app/scripts/background.js index 0c941c7f9..4e6176436 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -16,6 +16,7 @@ import { ENVIRONMENT_TYPE_POPUP, ENVIRONMENT_TYPE_NOTIFICATION, ENVIRONMENT_TYPE_FULLSCREEN, + PLATFORM_FIREFOX, } from '../../shared/constants/app'; import { SECOND } from '../../shared/constants/time'; import { @@ -38,6 +39,7 @@ import rawFirstTimeState from './first-time-state'; import getFirstPreferredLangCode from './lib/get-first-preferred-lang-code'; import getObjStructure from './lib/getObjStructure'; import setupEnsIpfsResolver from './lib/ens-ipfs/setup'; +import { getPlatform } from './lib/util'; /* eslint-enable import/first */ const { sentry } = global; @@ -345,12 +347,22 @@ function setupController(initState, initLangCode) { */ function connectRemote(remotePort) { const processName = remotePort.name; - const isMetaMaskInternalProcess = metamaskInternalProcessHash[processName]; if (metamaskBlockedPorts.includes(remotePort.name)) { return; } + let isMetaMaskInternalProcess = false; + const sourcePlatform = getPlatform(); + + if (sourcePlatform === PLATFORM_FIREFOX) { + isMetaMaskInternalProcess = metamaskInternalProcessHash[processName]; + } else { + isMetaMaskInternalProcess = + remotePort.sender.origin === + `chrome-extension://${extension.runtime.id}`; + } + if (isMetaMaskInternalProcess) { const portStream = new PortStream(remotePort); // communication with popup diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js index c2f740e7e..c98c1683c 100644 --- a/app/scripts/controllers/detect-tokens.js +++ b/app/scripts/controllers/detect-tokens.js @@ -3,8 +3,8 @@ import { warn } from 'loglevel'; import SINGLE_CALL_BALANCES_ABI from 'single-call-balance-checker-abi'; import { SINGLE_CALL_BALANCES_ADDRESS } from '../constants/contracts'; import { MINUTE } from '../../../shared/constants/time'; -import { isEqualCaseInsensitive } from '../../../ui/helpers/utils/util'; import { MAINNET_CHAIN_ID } from '../../../shared/constants/network'; +import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; // By default, poll every 3 minutes const DEFAULT_INTERVAL = MINUTE * 3; diff --git a/app/scripts/controllers/onboarding.js b/app/scripts/controllers/onboarding.js index 370ca5e8e..812ba7e44 100644 --- a/app/scripts/controllers/onboarding.js +++ b/app/scripts/controllers/onboarding.js @@ -69,7 +69,7 @@ export default class OnboardingController { * @param {string} tabId - The id of the tab registering */ registerOnboarding = async (location, tabId) => { - if (this.completedOnboarding) { + if (this.store.getState().completedOnboarding) { log.debug('Ignoring registerOnboarding; user already onboarded'); return; } diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 4a503e7e6..73e3b7963 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -68,6 +68,7 @@ export default class PreferencesController { ledgerTransportType: window.navigator.hid ? LEDGER_TRANSPORT_TYPES.WEBHID : LEDGER_TRANSPORT_TYPES.U2F, + theme: 'default', ...opts.initState, }; @@ -169,6 +170,15 @@ export default class PreferencesController { this.store.updateState({ eip1559V2Enabled: val }); } + /** + * Setter for the `theme` property + * + * @param {string} val - 'default' or 'dark' value based on the mode selected by user. + */ + setTheme(val) { + this.store.updateState({ theme: val }); + } + /** * Add new methodData to state, to avoid requesting this information again through Infura * diff --git a/app/scripts/controllers/preferences.test.js b/app/scripts/controllers/preferences.test.js index d6c8c59bf..10e7ba215 100644 --- a/app/scripts/controllers/preferences.test.js +++ b/app/scripts/controllers/preferences.test.js @@ -351,4 +351,18 @@ describe('preferences controller', function () { ); }); }); + + describe('setTheme', function () { + it('should default to value "default"', function () { + const state = preferencesController.store.getState(); + assert.equal(state.theme, 'default'); + }); + + it('should set the setTheme property in state', function () { + const state = preferencesController.store.getState(); + assert.equal(state.theme, 'default'); + preferencesController.setTheme('dark'); + assert.equal(preferencesController.store.getState().theme, 'dark'); + }); + }); }); diff --git a/app/scripts/controllers/swaps.js b/app/scripts/controllers/swaps.js index 8b16a86dc..6eb800793 100644 --- a/app/scripts/controllers/swaps.js +++ b/app/scripts/controllers/swaps.js @@ -28,7 +28,7 @@ import { } from '../../../ui/pages/swaps/swaps.util'; import fetchWithCache from '../../../ui/helpers/utils/fetch-with-cache'; import { MINUTE, SECOND } from '../../../shared/constants/time'; -import { isEqualCaseInsensitive } from '../../../ui/helpers/utils/util'; +import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; import { NETWORK_EVENTS } from './network'; // The MAX_GAS_LIMIT is a number that is higher than the maximum gas costs we have observed on any aggregator diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 04eae26f8..24fb0cf78 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -3,13 +3,12 @@ import { ObservableStore } from '@metamask/obs-store'; import { bufferToHex, keccak, toBuffer, isHexString } from 'ethereumjs-util'; import EthQuery from 'ethjs-query'; import { ethErrors } from 'eth-rpc-errors'; -import abi from 'human-standard-token-abi'; import Common from '@ethereumjs/common'; import { TransactionFactory } from '@ethereumjs/tx'; -import { ethers } from 'ethers'; import NonceTracker from 'nonce-tracker'; import log from 'loglevel'; import BigNumber from 'bignumber.js'; +import { merge, pickBy } from 'lodash'; import cleanErrorStack from '../../lib/cleanErrorStack'; import { hexToBn, @@ -46,16 +45,15 @@ import { NETWORK_TYPE_RPC, CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP, } from '../../../../shared/constants/network'; -import { isEIP1559Transaction } from '../../../../shared/modules/transaction.utils'; -import { readAddressAsContract } from '../../../../shared/modules/contract-utils'; -import { isEqualCaseInsensitive } from '../../../../ui/helpers/utils/util'; +import { + determineTransactionType, + isEIP1559Transaction, +} from '../../../../shared/modules/transaction.utils'; import TransactionStateManager from './tx-state-manager'; import TxGasUtil from './tx-gas-utils'; import PendingTransactionTracker from './pending-tx-tracker'; import * as txUtils from './lib/util'; -const hstInterface = new ethers.utils.Interface(abi); - const MAX_MEMSTORE_TX_LIST_SIZE = 100; // Number of transactions (by unique nonces) to keep in memory const SWAP_TRANSACTION_TYPES = [ @@ -130,6 +128,8 @@ export default class TransactionController extends EventEmitter { this.updateEventFragment = opts.updateEventFragment; this.finalizeEventFragment = opts.finalizeEventFragment; this.getEventFragmentById = opts.getEventFragmentById; + this.getDeviceModel = opts.getDeviceModel; + this.getAccountType = opts.getAccountType; this.memStore = new ObservableStore({}); this.query = new EthQuery(this.provider); @@ -347,6 +347,235 @@ export default class TransactionController extends EventEmitter { }); } + // ==================================================================================================================================================== + + /** + * @param {number} txId + * @returns {TransactionMeta} the txMeta who matches the given id if none found + * for the network returns undefined + */ + _getTransaction(txId) { + const { transactions } = this.store.getState(); + return transactions[txId]; + } + + _checkIfTxStatusIsUnapproved(txId) { + return ( + this.txStateManager.getTransaction(txId).status === + TRANSACTION_STATUSES.UNAPPROVED + ); + } + + _updateTransaction(txId, proposedUpdate, note) { + const txMeta = this.txStateManager.getTransaction(txId); + const updated = merge(txMeta, proposedUpdate); + this.txStateManager.updateTransaction(updated, note); + } + + /** + * + * @param {string} txId - transaction id + * @param {object} editableParams - holds the editable parameters + * @param {object} editableParams.data + * @param {string} editableParams.from + * @param {string} editableParams.to + * @param {string} editableParams.value + */ + updateEditableParams(txId, { data, from, to, value }) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + + const editableParams = { + txParams: { + data, + from, + to, + value, + }, + }; + + // only update what is defined + editableParams.txParams = pickBy(editableParams.txParams); + const note = `Update Editable Params for ${txId}`; + this._updateTransaction(txId, editableParams, note); + } + + /** + * updates the gas fees of the transaction with id if the transaction state is unapproved + * + * @param {string} txId - transaction id + * @param {object} txGasFees - holds the gas fees parameters + * @param {string} txGasFees.gasLimit + * @param {string} txGasFees.gasPrice + * @param {string} txGasFees.maxPriorityFeePerGas + * @param {string} txGasFees.maxFeePerGas + * @param {string} txGasFees.estimateUsed + * @param {string} txGasFees.estimateSuggested + * @param {string} txGasFees.defaultGasEstimates + * @param {string} txGasFees.gas + * @param {string} txGasFees.originalGasEstimate + */ + updateTransactionGasFees( + txId, + { + gas, + gasLimit, + gasPrice, + maxPriorityFeePerGas, + maxFeePerGas, + estimateUsed, + estimateSuggested, + defaultGasEstimates, + originalGasEstimate, + }, + ) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + + let txGasFees = { + txParams: { + gas, + gasLimit, + gasPrice, + maxPriorityFeePerGas, + maxFeePerGas, + }, + estimateUsed, + estimateSuggested, + defaultGasEstimates, + originalGasEstimate, + }; + + // only update what is defined + txGasFees.txParams = pickBy(txGasFees.txParams); + txGasFees = pickBy(txGasFees); + const note = `Update Transaction Gas Fees for ${txId}`; + this._updateTransaction(txId, txGasFees, note); + } + + /** + * updates the estimate base fees of the transaction with id if the transaction state is unapproved + * + * @param {string} txId - transaction id + * @param {object} txEstimateBaseFees - holds the estimate base fees parameters + * @param {string} txEstimateBaseFees.estimatedBaseFee + * @param {string} txEstimateBaseFees.decEstimatedBaseFee + */ + updateTransactionEstimatedBaseFee( + txId, + { estimatedBaseFee, decEstimatedBaseFee }, + ) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + + let txEstimateBaseFees = { estimatedBaseFee, decEstimatedBaseFee }; + // only update what is defined + txEstimateBaseFees = pickBy(txEstimateBaseFees); + + const note = `Update Transaction Estimated Base Fees for ${txId}`; + this._updateTransaction(txId, txEstimateBaseFees, note); + } + + /** + * updates a swap approval transaction with provided metadata and source token symbol + * if the transaction state is unapproved. + * + * @param {string} txId + * @param {object} swapApprovalTransaction - holds the metadata and token symbol + * @param {string} swapApprovalTransaction.type + * @param {string} swapApprovalTransaction.sourceTokenSymbol + */ + updateSwapApprovalTransaction(txId, { type, sourceTokenSymbol }) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + + let swapApprovalTransaction = { type, sourceTokenSymbol }; + // only update what is defined + swapApprovalTransaction = pickBy(swapApprovalTransaction); + + const note = `Update Swap Approval Transaction for ${txId}`; + this._updateTransaction(txId, swapApprovalTransaction, note); + } + + /** + * updates a swap transaction with provided metadata and source token symbol + * if the transaction state is unapproved. + * + * @param {string} txId + * @param {object} swapTransaction - holds the metadata + * @param {string} swapTransaction.sourceTokenSymbol + * @param {string} swapTransaction.destinationTokenSymbol + * @param {string} swapTransaction.type + * @param {string} swapTransaction.destinationTokenDecimals + * @param {string} swapTransaction.destinationTokenAddress + * @param {string} swapTransaction.swapMetaData + * @param {string} swapTransaction.swapTokenValue + * @param {string} swapTransaction.estimatedBaseFee + * @param {string} swapTransaction.approvalTxId + */ + updateSwapTransaction( + txId, + { + sourceTokenSymbol, + destinationTokenSymbol, + type, + destinationTokenDecimals, + destinationTokenAddress, + swapMetaData, + swapTokenValue, + estimatedBaseFee, + approvalTxId, + }, + ) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + let swapTransaction = { + sourceTokenSymbol, + destinationTokenSymbol, + type, + destinationTokenDecimals, + destinationTokenAddress, + swapMetaData, + swapTokenValue, + estimatedBaseFee, + approvalTxId, + }; + + // only update what is defined + swapTransaction = pickBy(swapTransaction); + + const note = `Update Swap Transaction for ${txId}`; + this._updateTransaction(txId, swapTransaction, note); + } + + /** + * updates a transaction's user settings only if the transaction state is unapproved + * + * @param {string} txId + * @param {object} userSettings - holds the metadata + * @param {string} userSettings.userEditedGasLimit + * @param {string} userSettings.userFeeLevel + */ + updateTransactionUserSettings(txId, { userEditedGasLimit, userFeeLevel }) { + if (!this._checkIfTxStatusIsUnapproved(txId)) { + return; + } + + let userSettings = { userEditedGasLimit, userFeeLevel }; + // only update what is defined + userSettings = pickBy(userSettings); + + const note = `Update User Settings for ${txId}`; + this._updateTransaction(txId, userSettings, note); + } + + // ==================================================================================================================================================== + /** * Validates and generates a txMeta with defaults and puts it in txStateManager * store. @@ -376,7 +605,7 @@ export default class TransactionController extends EventEmitter { * `generateTxMeta` adds the default txMeta properties to the passed object. * These include the tx's `id`. As we use the id for determining order of * txes in the tx-state-manager, it is necessary to call the asynchronous - * method `this._determineTransactionType` after `generateTxMeta`. + * method `determineTransactionType` after `generateTxMeta`. */ let txMeta = this.txStateManager.generateTxMeta({ txParams: normalizedTxParams, @@ -404,8 +633,9 @@ export default class TransactionController extends EventEmitter { } } - const { type, getCodeResponse } = await this._determineTransactionType( + const { type, getCodeResponse } = await determineTransactionType( txParams, + this.query, ); txMeta.type = transactionType || type; @@ -1461,67 +1691,6 @@ export default class TransactionController extends EventEmitter { }); } - /** - * @typedef { 'transfer' | 'approve' | 'transferfrom' | 'contractInteraction'| 'simpleSend' } InferrableTransactionTypes - */ - - /** - * @typedef {Object} InferTransactionTypeResult - * @property {InferrableTransactionTypes} type - The type of transaction - * @property {string} getCodeResponse - The contract code, in hex format if - * it exists. '0x0' or '0x' are also indicators of non-existent contract - * code - */ - - /** - * Determines the type of the transaction by analyzing the txParams. - * This method will return one of the types defined in shared/constants/transactions - * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these - * represent specific events that we control from the extension and are added manually - * at transaction creation. - * - * @param {Object} txParams - Parameters for the transaction - * @returns {InferTransactionTypeResult} - */ - async _determineTransactionType(txParams) { - const { data, to } = txParams; - let name; - try { - name = data && hstInterface.parseTransaction({ data }).name; - } catch (error) { - log.debug('Failed to parse transaction data.', error, data); - } - - const tokenMethodName = [ - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - ].find((methodName) => isEqualCaseInsensitive(methodName, name)); - - let result; - if (data && tokenMethodName) { - result = tokenMethodName; - } else if (data && !to) { - result = TRANSACTION_TYPES.DEPLOY_CONTRACT; - } - - let contractCode; - - if (!result) { - const { - contractCode: resultCode, - isContractAddress, - } = await readAddressAsContract(this.query, to); - - contractCode = resultCode; - result = isContractAddress - ? TRANSACTION_TYPES.CONTRACT_INTERACTION - : TRANSACTION_TYPES.SIMPLE_SEND; - } - - return { type: result, getCodeResponse: contractCode }; - } - /** * Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions * in the list have the same nonce @@ -1735,6 +1904,8 @@ export default class TransactionController extends EventEmitter { eip_1559_version: eip1559Version, gas_edit_type: 'none', gas_edit_attempted: 'none', + account_type: await this.getAccountType(this.getSelectedAddress()), + device_model: await this.getDeviceModel(this.getSelectedAddress()), }; const sensitiveProperties = { diff --git a/app/scripts/controllers/transactions/index.test.js b/app/scripts/controllers/transactions/index.test.js index c20fd5459..7ebcde2b0 100644 --- a/app/scripts/controllers/transactions/index.test.js +++ b/app/scripts/controllers/transactions/index.test.js @@ -82,6 +82,8 @@ describe('Transaction Controller', function () { getEventFragmentById: () => fragmentExists === false ? undefined : { id: 0 }, getEIP1559GasFeeEstimates: () => undefined, + getAccountType: () => 'MetaMask', + getDeviceModel: () => 'N/A', }); txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop }); @@ -1303,156 +1305,6 @@ describe('Transaction Controller', function () { }); }); - describe('#_determineTransactionType', function () { - it('should return a simple send type when to is truthy but data is falsy', async function () { - const result = await txController._determineTransactionType({ - to: '0xabc', - data: '', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.SIMPLE_SEND, - getCodeResponse: null, - }); - }); - - it('should return a token transfer type when data is for the respective method call', async function () { - const result = await txController._determineTransactionType({ - to: '0xabc', - data: - '0xa9059cbb0000000000000000000000002f318C334780961FB129D2a6c30D0763d9a5C970000000000000000000000000000000000000000000000000000000000000000a', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - getCodeResponse: undefined, - }); - }); - - it('should return a token approve type when data is for the respective method call', async function () { - const result = await txController._determineTransactionType({ - to: '0xabc', - data: - '0x095ea7b30000000000000000000000002f318C334780961FB129D2a6c30D0763d9a5C9700000000000000000000000000000000000000000000000000000000000000005', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - getCodeResponse: undefined, - }); - }); - - it('should return a contract deployment type when to is falsy and there is data', async function () { - const result = await txController._determineTransactionType({ - to: '', - data: '0xabd', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.DEPLOY_CONTRACT, - getCodeResponse: undefined, - }); - }); - - it('should return a simple send type with a 0x getCodeResponse when there is data and but the to address is not a contract address', async function () { - const result = await txController._determineTransactionType({ - to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', - data: '0xabd', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.SIMPLE_SEND, - getCodeResponse: '0x', - }); - }); - - it('should return a simple send type with a null getCodeResponse when to is truthy and there is data and but getCode returns an error', async function () { - const result = await txController._determineTransactionType({ - to: '0xabc', - data: '0xabd', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.SIMPLE_SEND, - getCodeResponse: null, - }); - }); - - it('should return a contract interaction type with the correct getCodeResponse when to is truthy and there is data and it is not a token transaction', async function () { - const _providerResultStub = { - // 1 gwei - eth_gasPrice: '0x0de0b6b3a7640000', - // by default, all accounts are external accounts (not contracts) - eth_getCode: '0xa', - }; - const _provider = createTestProviderTools({ - scaffold: _providerResultStub, - }).provider; - const _fromAccount = getTestAccounts()[0]; - const _blockTrackerStub = new EventEmitter(); - _blockTrackerStub.getCurrentBlock = noop; - _blockTrackerStub.getLatestBlock = noop; - const _txController = new TransactionController({ - provider: _provider, - getGasPrice() { - return '0xee6b2800'; - }, - networkStore: new ObservableStore(currentNetworkId), - getCurrentChainId: () => currentChainId, - txHistoryLimit: 10, - blockTracker: _blockTrackerStub, - signTransaction: (ethTx) => - new Promise((resolve) => { - ethTx.sign(_fromAccount.key); - resolve(); - }), - getParticipateInMetrics: () => false, - }); - const result = await _txController._determineTransactionType({ - to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', - data: 'abd', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.CONTRACT_INTERACTION, - getCodeResponse: '0x0a', - }); - }); - - it('should return a contract interaction type with the correct getCodeResponse when to is a contract address and data is falsy', async function () { - const _providerResultStub = { - // 1 gwei - eth_gasPrice: '0x0de0b6b3a7640000', - // by default, all accounts are external accounts (not contracts) - eth_getCode: '0xa', - }; - const _provider = createTestProviderTools({ - scaffold: _providerResultStub, - }).provider; - const _fromAccount = getTestAccounts()[0]; - const _blockTrackerStub = new EventEmitter(); - _blockTrackerStub.getCurrentBlock = noop; - _blockTrackerStub.getLatestBlock = noop; - const _txController = new TransactionController({ - provider: _provider, - getGasPrice() { - return '0xee6b2800'; - }, - networkStore: new ObservableStore(currentNetworkId), - getCurrentChainId: () => currentChainId, - txHistoryLimit: 10, - blockTracker: _blockTrackerStub, - signTransaction: (ethTx) => - new Promise((resolve) => { - ethTx.sign(_fromAccount.key); - resolve(); - }), - getParticipateInMetrics: () => false, - }); - const result = await _txController._determineTransactionType({ - to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', - data: '', - }); - assert.deepEqual(result, { - type: TRANSACTION_TYPES.CONTRACT_INTERACTION, - getCodeResponse: '0x0a', - }); - }); - }); - describe('#getPendingTransactions', function () { it('should show only submitted and approved transactions as pending transaction', function () { txController.txStateManager._addTransactionsToState([ @@ -1616,6 +1468,8 @@ describe('Transaction Controller', function () { referrer: 'metamask', source: 'user', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { default_gas: '0.000031501', @@ -1691,6 +1545,8 @@ describe('Transaction Controller', function () { referrer: 'metamask', source: 'user', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { default_gas: '0.000031501', @@ -1776,6 +1632,8 @@ describe('Transaction Controller', function () { referrer: 'other', source: 'dapp', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { default_gas: '0.000031501', @@ -1853,6 +1711,8 @@ describe('Transaction Controller', function () { referrer: 'other', source: 'dapp', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { default_gas: '0.000031501', @@ -1930,6 +1790,8 @@ describe('Transaction Controller', function () { referrer: 'other', source: 'dapp', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { gas_price: '2', @@ -1989,6 +1851,8 @@ describe('Transaction Controller', function () { eip_1559_version: '0', gas_edit_attempted: 'none', gas_edit_type: 'none', + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { baz: 3.0, @@ -2058,6 +1922,8 @@ describe('Transaction Controller', function () { referrer: 'other', source: 'dapp', type: TRANSACTION_TYPES.SIMPLE_SEND, + account_type: 'MetaMask', + device_model: 'N/A', }, sensitiveProperties: { baz: 3.0, @@ -2159,4 +2025,202 @@ describe('Transaction Controller', function () { assert.deepEqual(result, expectedParams); }); }); + + describe('update transaction methods', function () { + let txStateManager; + + beforeEach(function () { + txStateManager = txController.txStateManager; + txStateManager.addTransaction({ + id: '1', + status: TRANSACTION_STATUSES.UNAPPROVED, + metamaskNetworkId: currentNetworkId, + txParams: { + gasLimit: '0x001', + gasPrice: '0x002', + // max fees can not be mixed with gasPrice + // maxPriorityFeePerGas: '0x003', + // maxFeePerGas: '0x004', + to: VALID_ADDRESS, + from: VALID_ADDRESS, + }, + estimateUsed: '0x005', + estimatedBaseFee: '0x006', + decEstimatedBaseFee: '6', + type: 'swap', + sourceTokenSymbol: 'ETH', + destinationTokenSymbol: 'UNI', + destinationTokenDecimals: 16, + destinationTokenAddress: VALID_ADDRESS, + swapMetaData: {}, + swapTokenValue: '0x007', + userEditedGasLimit: '0x008', + userFeeLevel: 'medium', + }); + }); + + it('updates transaction gas fees', function () { + // test update gasFees + txController.updateTransactionGasFees('1', { + gasPrice: '0x0022', + gasLimit: '0x0011', + }); + let result = txStateManager.getTransaction('1'); + assert.equal(result.txParams.gasPrice, '0x0022'); + // TODO: weird behavior here...only gasPrice gets returned. + // assert.equal(result.txParams.gasLimit, '0x0011'); + + // test update maxPriorityFeePerGas + txStateManager.addTransaction({ + id: '2', + status: TRANSACTION_STATUSES.UNAPPROVED, + metamaskNetworkId: currentNetworkId, + txParams: { + maxPriorityFeePerGas: '0x003', + to: VALID_ADDRESS, + from: VALID_ADDRESS, + }, + estimateUsed: '0x005', + }); + txController.updateTransactionGasFees('2', { + maxPriorityFeePerGas: '0x0033', + }); + result = txStateManager.getTransaction('2'); + assert.equal(result.txParams.maxPriorityFeePerGas, '0x0033'); + + // test update maxFeePerGas + txStateManager.addTransaction({ + id: '3', + status: TRANSACTION_STATUSES.UNAPPROVED, + metamaskNetworkId: currentNetworkId, + txParams: { + maxPriorityFeePerGas: '0x003', + maxFeePerGas: '0x004', + to: VALID_ADDRESS, + from: VALID_ADDRESS, + }, + estimateUsed: '0x005', + }); + txController.updateTransactionGasFees('3', { maxFeePerGas: '0x0044' }); + result = txStateManager.getTransaction('3'); + assert.equal(result.txParams.maxFeePerGas, '0x0044'); + + // test update estimate used + txController.updateTransactionGasFees('3', { estimateUsed: '0x0055' }); + result = txStateManager.getTransaction('3'); + assert.equal(result.estimateUsed, '0x0055'); + }); + + it('updates estimated base fee', function () { + txController.updateTransactionEstimatedBaseFee('1', { + estimatedBaseFee: '0x0066', + decEstimatedBaseFee: '66', + }); + const result = txStateManager.getTransaction('1'); + assert.equal(result.estimatedBaseFee, '0x0066'); + assert.equal(result.decEstimatedBaseFee, '66'); + }); + + it('updates swap approval transaction', function () { + txController.updateSwapApprovalTransaction('1', { + type: 'swapApproval', + sourceTokenSymbol: 'XBN', + }); + + const result = txStateManager.getTransaction('1'); + assert.equal(result.type, 'swapApproval'); + assert.equal(result.sourceTokenSymbol, 'XBN'); + }); + + it('updates swap transaction', function () { + txController.updateSwapTransaction('1', { + sourceTokenSymbol: 'BTCX', + destinationTokenSymbol: 'ETH', + }); + + const result = txStateManager.getTransaction('1'); + assert.equal(result.sourceTokenSymbol, 'BTCX'); + assert.equal(result.destinationTokenSymbol, 'ETH'); + assert.equal(result.destinationTokenDecimals, 16); + assert.equal(result.destinationTokenAddress, VALID_ADDRESS); + assert.equal(result.swapTokenValue, '0x007'); + + txController.updateSwapTransaction('1', { + type: 'swapped', + destinationTokenDecimals: 8, + destinationTokenAddress: VALID_ADDRESS_TWO, + swapTokenValue: '0x0077', + }); + assert.equal(result.sourceTokenSymbol, 'BTCX'); + assert.equal(result.destinationTokenSymbol, 'ETH'); + assert.equal(result.type, 'swapped'); + assert.equal(result.destinationTokenDecimals, 8); + assert.equal(result.destinationTokenAddress, VALID_ADDRESS_TWO); + assert.equal(result.swapTokenValue, '0x0077'); + }); + + it('updates transaction user settings', function () { + txController.updateTransactionUserSettings('1', { + userEditedGasLimit: '0x0088', + userFeeLevel: 'high', + }); + + const result = txStateManager.getTransaction('1'); + assert.equal(result.userEditedGasLimit, '0x0088'); + assert.equal(result.userFeeLevel, 'high'); + }); + + it('does not update if status is not unapproved', function () { + txStateManager.addTransaction({ + id: '4', + status: TRANSACTION_STATUSES.APPROVED, + metamaskNetworkId: currentNetworkId, + txParams: { + maxPriorityFeePerGas: '0x007', + maxFeePerGas: '0x008', + to: VALID_ADDRESS, + from: VALID_ADDRESS, + }, + estimateUsed: '0x009', + }); + + txController.updateTransactionGasFees('4', { maxFeePerGas: '0x0088' }); + let result = txStateManager.getTransaction('4'); + assert.equal(result.txParams.maxFeePerGas, '0x008'); + + // test update estimate used + txController.updateTransactionGasFees('4', { estimateUsed: '0x0099' }); + result = txStateManager.getTransaction('4'); + assert.equal(result.estimateUsed, '0x009'); + }); + + it('does not update unknown parameters in update method', function () { + txController.updateSwapTransaction('1', { + type: 'swapped', + destinationTokenDecimals: 8, + destinationTokenAddress: VALID_ADDRESS_TWO, + swapTokenValue: '0x011', + gasPrice: '0x12', + }); + + let result = txStateManager.getTransaction('1'); + + assert.equal(result.type, 'swapped'); + assert.equal(result.destinationTokenDecimals, 8); + assert.equal(result.destinationTokenAddress, VALID_ADDRESS_TWO); + assert.equal(result.swapTokenValue, '0x011'); + assert.equal(result.txParams.gasPrice, '0x002'); // not updated even though it's passed in to update + + txController.updateTransactionGasFees('1', { + estimateUsed: '0x13', + gasPrice: '0x14', + destinationTokenAddress: VALID_ADDRESS, + }); + + result = txStateManager.getTransaction('1'); + assert.equal(result.estimateUsed, '0x13'); + assert.equal(result.txParams.gasPrice, '0x14'); + assert.equal(result.destinationTokenAddress, VALID_ADDRESS_TWO); // not updated even though it's passed in to update + }); + }); }); diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index a9f549bed..ef6b9b86e 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -9,7 +9,11 @@ import createFilterMiddleware from 'eth-json-rpc-filters'; import createSubscriptionManager from 'eth-json-rpc-filters/subscriptionManager'; import { providerAsMiddleware } from 'eth-json-rpc-middleware'; import KeyringController from 'eth-keyring-controller'; -import { errorCodes as rpcErrorCodes, ethErrors } from 'eth-rpc-errors'; +import { + errorCodes as rpcErrorCodes, + EthereumRpcError, + ethErrors, +} from 'eth-rpc-errors'; import { Mutex } from 'await-semaphore'; import { stripHexPrefix } from 'ethereumjs-util'; import log from 'loglevel'; @@ -34,16 +38,12 @@ import { CollectiblesController, AssetsContractController, CollectibleDetectionController, -} from '@metamask/controllers'; -import SmartTransactionsController from '@metamask/smart-transactions-controller'; -import { PermissionController, SubjectMetadataController, - ///: BEGIN:ONLY_INCLUDE_IN(flask) - SnapController, - ///: END:ONLY_INCLUDE_IN -} from '@metamask/snap-controllers'; +} from '@metamask/controllers'; +import SmartTransactionsController from '@metamask/smart-transactions-controller'; ///: BEGIN:ONLY_INCLUDE_IN(flask) +import { SnapController } from '@metamask/snap-controllers'; import { IframeExecutionService } from '@metamask/iframe-execution-environment-service'; ///: END:ONLY_INCLUDE_IN @@ -74,6 +74,7 @@ import { MILLISECOND } from '../../shared/constants/time'; import { ///: BEGIN:ONLY_INCLUDE_IN(flask) MESSAGE_TYPE, + PLATFORM_FIREFOX, ///: END:ONLY_INCLUDE_IN POLLING_TOKEN_ENVIRONMENT_TYPES, SUBJECT_TYPES, @@ -82,7 +83,7 @@ import { import { hexToDecimal } from '../../ui/helpers/utils/conversions.util'; import { getTokenValueParam } from '../../ui/helpers/utils/token-util'; import { getTransactionData } from '../../ui/helpers/utils/transactions.util'; -import { isEqualCaseInsensitive } from '../../ui/helpers/utils/util'; +import { isEqualCaseInsensitive } from '../../shared/modules/string-utils'; import ComposableObservableStore from './lib/ComposableObservableStore'; import AccountTracker from './lib/account-tracker'; import createLoggerMiddleware from './lib/createLoggerMiddleware'; @@ -134,6 +135,10 @@ import { ///: END:ONLY_INCLUDE_IN } from './controllers/permissions'; +///: BEGIN:ONLY_INCLUDE_IN(flask) +import { getPlatform } from './lib/util'; +///: END:ONLY_INCLUDE_IN + export const METAMASK_CONTROLLER_EVENTS = { // Fired after state changes that impact the extension badge (unapproved msg count) // The process of updating the badge happens in app/scripts/background.js. @@ -230,9 +235,15 @@ export default class MetamaskController extends EventEmitter { state: initState.TokensController, }); - this.assetsContractController = new AssetsContractController({ - provider: this.provider, - }); + this.assetsContractController = new AssetsContractController( + { + onPreferencesStateChange: (listener) => + this.preferencesController.store.subscribe(listener), + }, + { + provider: this.provider, + }, + ); this.collectiblesController = new CollectiblesController( { @@ -601,7 +612,10 @@ export default class MetamaskController extends EventEmitter { ], }); + const usingFirefox = getPlatform() === PLATFORM_FIREFOX; + this.snapController = new SnapController({ + npmRegistryUrl: usingFirefox ? 'https://registry.npmjs.cf/' : undefined, endowmentPermissionNames: Object.values(EndowmentPermissions), terminateAllSnaps: this.workerController.terminateAllSnaps.bind( this.workerController, @@ -700,6 +714,8 @@ export default class MetamaskController extends EventEmitter { getExternalPendingTransactions: this.getExternalPendingTransactions.bind( this, ), + getAccountType: this.getAccountType.bind(this), + getDeviceModel: this.getDeviceModel.bind(this), }); this.txController.on('newUnapprovedTx', () => opts.showUserConfirmation()); @@ -1269,7 +1285,6 @@ export default class MetamaskController extends EventEmitter { appStateController, collectiblesController, collectibleDetectionController, - assetsContractController, currencyRateController, detectTokensController, ensController, @@ -1422,11 +1437,10 @@ export default class MetamaskController extends EventEmitter { setEIP1559V2Enabled: preferencesController.setEIP1559V2Enabled.bind( preferencesController, ), + setTheme: preferencesController.setTheme.bind(preferencesController), // AssetsContractController - getTokenStandardAndDetails: assetsContractController.getTokenStandardAndDetails.bind( - assetsContractController, - ), + getTokenStandardAndDetails: this.getTokenStandardAndDetails.bind(this), // CollectiblesController addCollectible: collectiblesController.addCollectible.bind( @@ -1523,6 +1537,20 @@ export default class MetamaskController extends EventEmitter { ), getTransactions: txController.getTransactions.bind(txController), + updateEditableParams: txController.updateEditableParams.bind( + txController, + ), + updateTransactionGasFees: txController.updateTransactionGasFees.bind( + txController, + ), + + updateSwapApprovalTransaction: txController.updateSwapApprovalTransaction.bind( + txController, + ), + updateSwapTransaction: txController.updateSwapTransaction.bind( + txController, + ), + // messageManager signMessage: this.signMessage.bind(this), cancelMessage: this.cancelMessage.bind(this), @@ -1707,7 +1735,12 @@ export default class MetamaskController extends EventEmitter { resolvePendingApproval: approvalController.accept.bind( approvalController, ), - rejectPendingApproval: approvalController.reject.bind(approvalController), + rejectPendingApproval: async (id, error) => { + approvalController.reject( + id, + new EthereumRpcError(error.code, error.message, error.data), + ); + }, // Notifications updateViewedNotifications: notificationController.updateViewed.bind( @@ -1749,6 +1782,19 @@ export default class MetamaskController extends EventEmitter { }; } + async getTokenStandardAndDetails(address, userAddress, tokenId) { + const details = await this.assetsContractController.getTokenStandardAndDetails( + address, + userAddress, + tokenId, + ); + return { + ...details, + decimals: details?.decimals?.toString(10), + balance: details?.balance?.toString(10), + }; + } + //============================================================================= // VAULT / KEYRING RELATED METHODS //============================================================================= @@ -2189,6 +2235,54 @@ export default class MetamaskController extends EventEmitter { return true; } + /** + * Retrieves the keyring for the selected address and using the .type returns + * a subtype for the account. Either 'hardware', 'imported' or 'MetaMask'. + * + * @param {string} address - Address to retrieve keyring for + * @returns {'hardware' | 'imported' | 'MetaMask'} + */ + async getAccountType(address) { + const keyring = await this.keyringController.getKeyringForAccount(address); + switch (keyring.type) { + case KEYRING_TYPES.TREZOR: + case KEYRING_TYPES.LATTICE: + case KEYRING_TYPES.QR: + case KEYRING_TYPES.LEDGER: + return 'hardware'; + case KEYRING_TYPES.IMPORTED: + return 'imported'; + default: + return 'MetaMask'; + } + } + + /** + * Retrieves the keyring for the selected address and using the .type + * determines if a more specific name for the device is available. Returns + * 'N/A' for non hardware wallets. + * + * @param {string} address - Address to retrieve keyring for + * @returns {'ledger' | 'lattice' | 'N/A' | string} + */ + async getDeviceModel(address) { + const keyring = await this.keyringController.getKeyringForAccount(address); + switch (keyring.type) { + case KEYRING_TYPES.TREZOR: + return keyring.getModel(); + case KEYRING_TYPES.QR: + return keyring.getName(); + case KEYRING_TYPES.LEDGER: + // TODO: get model after ledger keyring exposes method + return DEVICE_NAMES.LEDGER; + case KEYRING_TYPES.LATTICE: + // TODO: get model after lattice keyring exposes method + return DEVICE_NAMES.LATTICE; + default: + return 'N/A'; + } + } + /** * get hardware account label * diff --git a/development/build/README.md b/development/build/README.md index 7d6cd8d9c..85823992b 100644 --- a/development/build/README.md +++ b/development/build/README.md @@ -1,6 +1,7 @@ # The MetaMask Build System -> _tl;dr_ `yarn dist` for prod, `yarn start` for local development +> _tl;dr_ `yarn dist` for prod, `yarn start` for local development. +> Add `--build-type flask` to build Flask, our canary distribution with more experimental features. This directory contains the MetaMask build system, which is used to build the MetaMask Extension such that it can be used in a supported browser. From the repository root, the build system entry file is located at [`./development/build/index.js`](https://github.com/MetaMask/metamask-extension/blob/develop/development/build/index.js). @@ -40,7 +41,8 @@ Commands: e2e tests. Options: - --build-type The "type" of build to create. One of: "beta", "main" + --build-type The "type" of build to create. One of: "beta", "flask", + "main" [string] [default: "main"] --lint-fence-files Whether files with code fences should be linted after fences have been removed by the code fencing transform. diff --git a/development/build/etc.js b/development/build/etc.js index fe30002d8..7b76e0b9c 100644 --- a/development/build/etc.js +++ b/development/build/etc.js @@ -4,13 +4,13 @@ const gulpZip = require('gulp-zip'); const del = require('del'); const pify = require('pify'); const pump = pify(require('pump')); -const { version } = require('../../package.json'); + +const { BuildType } = require('../lib/build-type'); const { createTask, composeParallel } = require('./task'); -const { BuildType } = require('./utils'); module.exports = createEtcTasks; -function createEtcTasks({ browserPlatforms, buildType, livereload }) { +function createEtcTasks({ browserPlatforms, buildType, livereload, version }) { const clean = createTask('clean', async function clean() { await del(['./dist/*']); await Promise.all( @@ -28,14 +28,16 @@ function createEtcTasks({ browserPlatforms, buildType, livereload }) { const zip = createTask( 'zip', composeParallel( - ...browserPlatforms.map((platform) => createZipTask(platform, buildType)), + ...browserPlatforms.map((platform) => + createZipTask(platform, buildType, version), + ), ), ); return { clean, reload, zip }; } -function createZipTask(platform, buildType) { +function createZipTask(platform, buildType, version) { return async () => { const path = buildType === BuildType.main diff --git a/development/build/index.js b/development/build/index.js index 987d99854..dd0e7b4c9 100755 --- a/development/build/index.js +++ b/development/build/index.js @@ -7,6 +7,8 @@ const path = require('path'); const livereload = require('gulp-livereload'); const minimist = require('minimist'); const { sync: globby } = require('globby'); +const { getVersion } = require('../lib/get-version'); +const { BuildType } = require('../lib/build-type'); const { createTask, composeSeries, @@ -18,7 +20,7 @@ const createScriptTasks = require('./scripts'); const createStyleTasks = require('./styles'); const createStaticAssetTasks = require('./static'); const createEtcTasks = require('./etc'); -const { BuildType, getBrowserVersionMap } = require('./utils'); +const { getBrowserVersionMap } = require('./utils'); // Packages required dynamically via browserify configuration in dependencies // Required for LavaMoat policy generation @@ -58,11 +60,12 @@ function defineAndRunBuildTasks() { shouldIncludeLockdown, shouldLintFenceFiles, skipStats, + version, } = parseArgv(); const browserPlatforms = ['firefox', 'chrome', 'brave', 'opera']; - const browserVersionMap = getBrowserVersionMap(browserPlatforms); + const browserVersionMap = getBrowserVersionMap(browserPlatforms, version); const ignoredFiles = getIgnoredFiles(buildType); @@ -89,12 +92,14 @@ function defineAndRunBuildTasks() { livereload, policyOnly, shouldLintFenceFiles, + version, }); const { clean, reload, zip } = createEtcTasks({ livereload, browserPlatforms, buildType, + version, }); // build for development (livereload) @@ -162,6 +167,7 @@ function defineAndRunBuildTasks() { function parseArgv() { const NamedArgs = { BuildType: 'build-type', + BuildVersion: 'build-version', LintFenceFiles: 'lint-fence-files', Lockdown: 'lockdown', PolicyOnly: 'policy-only', @@ -175,9 +181,10 @@ function parseArgv() { NamedArgs.PolicyOnly, NamedArgs.SkipStats, ], - string: [NamedArgs.BuildType], + string: [NamedArgs.BuildType, NamedArgs.BuildVersion], default: { [NamedArgs.BuildType]: BuildType.main, + [NamedArgs.BuildVersion]: '0', [NamedArgs.LintFenceFiles]: true, [NamedArgs.Lockdown]: true, [NamedArgs.PolicyOnly]: false, @@ -201,6 +208,14 @@ function parseArgv() { throw new Error(`MetaMask build: Invalid build type: "${buildType}"`); } + const rawBuildVersion = argv[NamedArgs.BuildVersion]; + const buildVersion = Number.parseInt(rawBuildVersion, 10); + if (rawBuildVersion.match(/^\d+$/u) === null || Number.isNaN(buildVersion)) { + throw new Error( + `MetaMask build: Invalid build version: "${rawBuildVersion}"`, + ); + } + // Manually default this to `false` for dev builds only. const shouldLintFenceFiles = process.argv.includes( `--${NamedArgs.LintFenceFiles}`, @@ -210,6 +225,8 @@ function parseArgv() { const policyOnly = argv[NamedArgs.PolicyOnly]; + const version = getVersion(buildType, buildVersion); + return { buildType, entryTask, @@ -218,6 +235,7 @@ function parseArgv() { shouldIncludeLockdown: argv[NamedArgs.Lockdown], shouldLintFenceFiles, skipStats: argv[NamedArgs.SkipStats], + version, }; } diff --git a/development/build/manifest.js b/development/build/manifest.js index 524f2ef3b..498ab2785 100644 --- a/development/build/manifest.js +++ b/development/build/manifest.js @@ -3,9 +3,9 @@ const path = require('path'); const { mergeWith, cloneDeep } = require('lodash'); const baseManifest = require('../../app/manifest/_base.json'); +const { BuildType } = require('../lib/build-type'); const { createTask, composeSeries } = require('./task'); -const { BuildType } = require('./utils'); module.exports = createManifestTasks; diff --git a/development/build/scripts.js b/development/build/scripts.js index d07f7bcfc..063fc5a7e 100644 --- a/development/build/scripts.js +++ b/development/build/scripts.js @@ -34,6 +34,7 @@ const metamaskrc = require('rc')('metamask', { INFURA_PROD_PROJECT_ID: process.env.INFURA_PROD_PROJECT_ID, ONBOARDING_V2: process.env.ONBOARDING_V2, COLLECTIBLES_V1: process.env.COLLECTIBLES_V1, + DARK_MODE_V1: process.env.DARK_MODE_V1, SEGMENT_HOST: process.env.SEGMENT_HOST, SEGMENT_WRITE_KEY: process.env.SEGMENT_WRITE_KEY, SEGMENT_BETA_WRITE_KEY: process.env.SEGMENT_BETA_WRITE_KEY, @@ -45,7 +46,7 @@ const metamaskrc = require('rc')('metamask', { }); const { streamFlatMap } = require('../stream-flat-map.js'); -const { version } = require('../../package.json'); +const { BuildType } = require('../lib/build-type'); const { createTask, @@ -56,7 +57,6 @@ const { const { createRemoveFencedCodeTransform, } = require('./transforms/remove-fenced-code'); -const { BuildType } = require('./utils'); /** * The build environment. This describes the environment this build was produced in. @@ -147,6 +147,7 @@ function createScriptTasks({ livereload, shouldLintFenceFiles, policyOnly, + version, }) { // internal tasks const core = { @@ -192,6 +193,7 @@ function createScriptTasks({ policyOnly, shouldLintFenceFiles, testing, + version, }), ); @@ -344,6 +346,7 @@ function createFactoredBuild({ policyOnly, shouldLintFenceFiles, testing, + version, }) { return async function () { // create bundler setup and apply defaults @@ -355,7 +358,12 @@ function createFactoredBuild({ const reloadOnChange = Boolean(devMode); const minify = Boolean(devMode) === false; - const envVars = getEnvironmentVariables({ buildType, devMode, testing }); + const envVars = getEnvironmentVariables({ + buildType, + devMode, + testing, + version, + }); setupBundlerDefaults(buildConfiguration, { buildType, devMode, @@ -780,7 +788,7 @@ async function bundleIt(buildConfiguration, { reloadOnChange }) { } } -function getEnvironmentVariables({ buildType, devMode, testing }) { +function getEnvironmentVariables({ buildType, devMode, testing, version }) { const environment = getEnvironment({ devMode, testing }); if (environment === ENVIRONMENT.PRODUCTION && !process.env.SENTRY_DSN) { throw new Error('Missing SENTRY_DSN environment variable'); @@ -803,6 +811,7 @@ function getEnvironmentVariables({ buildType, devMode, testing }) { SWAPS_USE_DEV_APIS: process.env.SWAPS_USE_DEV_APIS === '1', ONBOARDING_V2: metamaskrc.ONBOARDING_V2 === '1', COLLECTIBLES_V1: metamaskrc.COLLECTIBLES_V1 === '1', + DARK_MODE_V1: metamaskrc.DARK_MODE_V1 === '1', }; } diff --git a/development/build/static.js b/development/build/static.js index 1ec935502..7efde5a72 100644 --- a/development/build/static.js +++ b/development/build/static.js @@ -4,9 +4,9 @@ const watch = require('gulp-watch'); const glob = require('fast-glob'); const locales = require('../../app/_locales/index.json'); +const { BuildType } = require('../lib/build-type'); const { createTask, composeSeries } = require('./task'); -const { BuildType } = require('./utils'); const EMPTY_JS_FILE = './development/empty.js'; diff --git a/development/build/transforms/remove-fenced-code.js b/development/build/transforms/remove-fenced-code.js index 71236e179..90d49972e 100644 --- a/development/build/transforms/remove-fenced-code.js +++ b/development/build/transforms/remove-fenced-code.js @@ -1,6 +1,6 @@ const path = require('path'); const { PassThrough, Transform } = require('stream'); -const { BuildType } = require('../utils'); +const { BuildType } = require('../../lib/build-type'); const { lintTransformedFile } = require('./utils'); const hasKey = (obj, key) => Reflect.hasOwnProperty.call(obj, key); diff --git a/development/build/transforms/remove-fenced-code.test.js b/development/build/transforms/remove-fenced-code.test.js index b3ff511e3..3be3e401a 100644 --- a/development/build/transforms/remove-fenced-code.test.js +++ b/development/build/transforms/remove-fenced-code.test.js @@ -1,5 +1,5 @@ const deepFreeze = require('deep-freeze-strict'); -const { BuildType } = require('../utils'); +const { BuildType } = require('../../lib/build-type'); const { createRemoveFencedCodeTransform, removeFencedCode, diff --git a/development/build/transforms/utils.js b/development/build/transforms/utils.js index d7ab9654f..fb7f49c32 100644 --- a/development/build/transforms/utils.js +++ b/development/build/transforms/utils.js @@ -1,11 +1,17 @@ const { ESLint } = require('eslint'); const eslintrc = require('../../../.eslintrc.js'); -// We don't want linting to fail for purely stylistic reasons. -eslintrc.rules['prettier/prettier'] = 'off'; -// Sometimes we use `let` instead of `const` to assign variables depending on -// the build type. -eslintrc.rules['prefer-const'] = 'off'; +eslintrc.overrides.forEach((override) => { + const rules = override.rules ?? {}; + + // We don't want linting to fail for purely stylistic reasons. + rules['prettier/prettier'] = 'off'; + // Sometimes we use `let` instead of `const` to assign variables depending on + // the build type. + rules['prefer-const'] = 'off'; + + override.rules = rules; +}); // Remove all test-related overrides. We will never lint test files here. eslintrc.overrides = eslintrc.overrides.filter((override) => { diff --git a/development/build/utils.js b/development/build/utils.js index be33bf374..bd427d6bb 100644 --- a/development/build/utils.js +++ b/development/build/utils.js @@ -1,16 +1,5 @@ const semver = require('semver'); -const { version } = require('../../package.json'); - -/** - * The distribution this build is intended for. - * - * This should be kept in-sync with the `BuildType` map in `shared/constants/app.js`. - */ -const BuildType = { - beta: 'beta', - flask: 'flask', - main: 'main', -}; +const { BuildType } = require('../lib/build-type'); /** * Map the current version to a format that is compatible with each browser. @@ -20,11 +9,12 @@ const BuildType = { * where the build version is a positive integer. * * @param {string[]} platforms - A list of browsers to generate versions for. + * @param {string} version - The current version. * @returns {Object} An object with the browser as the key and the browser-specific version object * as the value. For example, the version `9.6.0-beta.1` would return the object * `{ firefox: { version: '9.6.0.beta1' }, chrome: { version: '9.6.0.1', version_name: '9.6.0-beta.1' } }`. */ -function getBrowserVersionMap(platforms) { +function getBrowserVersionMap(platforms, version) { const major = semver.major(version); const minor = semver.minor(version); const patch = semver.patch(version); @@ -62,6 +52,5 @@ function getBrowserVersionMap(platforms) { } module.exports = { - BuildType, getBrowserVersionMap, }; diff --git a/development/lib/build-type.js b/development/lib/build-type.js new file mode 100644 index 000000000..531ed18e9 --- /dev/null +++ b/development/lib/build-type.js @@ -0,0 +1,12 @@ +/** + * The distribution this build is intended for. + * + * This should be kept in-sync with the `BuildType` map in `shared/constants/app.js`. + */ +const BuildType = { + beta: 'beta', + flask: 'flask', + main: 'main', +}; + +module.exports = { BuildType }; diff --git a/development/lib/get-version.js b/development/lib/get-version.js new file mode 100644 index 000000000..92119c352 --- /dev/null +++ b/development/lib/get-version.js @@ -0,0 +1,21 @@ +const { version: manifestVersion } = require('../../package.json'); +const { BuildType } = require('./build-type'); + +/** + * Get the current version of the MetaMask extension. The base manifest version + * is modified according to the build type and version. + * + * The build version is needed because certain build types (such as beta) may + * be released multiple times during the release process. + * + * @param {BuildType} buildType - The build type. + * @param {number} buildVersion - The build version. + * @returns {string} The MetaMask extension version. + */ +function getVersion(buildType, buildVersion) { + return buildType === BuildType.main + ? manifestVersion + : `${manifestVersion}-${buildType}.${buildVersion}`; +} + +module.exports = { getVersion }; diff --git a/development/mock-e2e.js b/development/mock-e2e.js index 1e466d36e..4fde023d5 100644 --- a/development/mock-e2e.js +++ b/development/mock-e2e.js @@ -1,7 +1,7 @@ -function setupMocking(server) { - server.forAnyRequest().thenPassThrough(); +async function setupMocking(server, testSpecificMock) { + await server.forAnyRequest().thenPassThrough(); - server + await server .forOptions('https://gas-api.metaswap.codefi.network/networks/1/gasPrices') .thenCallback(() => { return { @@ -14,7 +14,7 @@ function setupMocking(server) { }; }); - server + await server .forGet('https://gas-api.metaswap.codefi.network/networks/1/gasPrices') .thenCallback(() => { return { @@ -27,6 +27,8 @@ function setupMocking(server) { }, }; }); + + testSpecificMock(server); } module.exports = { setupMocking }; diff --git a/docs/add-to-chrome.md b/docs/add-to-chrome.md index 82c1afed3..9e4d8c4a4 100644 --- a/docs/add-to-chrome.md +++ b/docs/add-to-chrome.md @@ -2,13 +2,16 @@ ![Load dev build](./load-dev-build-chrome.gif) +* Create a local build of MetaMask using your preferred method. + * You can find build instructions in the [readme](https://github.com/MetaMask/metamask-extension#readme). * Open `Settings` > `Extensions`. + * Or go straight to [chrome://extensions](chrome://extensions). * Check "Developer mode". -* Alternatively, use the URL `chrome://extensions/` in your address bar * At the top, click `Load Unpacked Extension`. -* Navigate to your `metamask-plugin/dist/chrome` folder. +* Navigate to your `metamask-extension/dist/chrome` folder. * Click `Select`. * Change to your locale via `chrome://settings/languages` -* Restart the browser and test the plugin in your locale +* Restart the browser and test the extension in your locale -You now have the plugin, and can click 'inspect views: background plugin' to view its dev console. +Your dev build is now added to Chrome, and you can click `Inspect views +background.html` in its card on the extension settings page to view its dev console. diff --git a/docs/add-to-firefox.md b/docs/add-to-firefox.md index 20810f9a6..424af6317 100644 --- a/docs/add-to-firefox.md +++ b/docs/add-to-firefox.md @@ -1,14 +1,11 @@ # Add Custom Build to Firefox -Go to the url `about:debugging#addons`. - -Click the button `Load Temporary Add-On`. - -Select the file `dist/firefox/manifest.json`. - -You can optionally enable debugging, and click `Debug`, for a console window that logs all of Metamask's processes to a single console. +* Create a local build of MetaMask using your preferred method. + * You can find build instructions in the [readme](https://github.com/MetaMask/metamask-extension#readme). +* Go to the url `about:debugging#addons`. +* Click the button `Load Temporary Add-On`. +* Select the file `metamask-extension/dist/firefox/manifest.json`. +* You can optionally enable debugging, and click `Debug`, for a console window that logs all of Metamask's processes to a single console. If you have problems debugging, try connecting to the IRC channel `#webextensions` on `irc.mozilla.org`. - For longer questions, use the StackOverflow tag `firefox-addons`. - diff --git a/lavamoat/browserify/beta/policy.json b/lavamoat/browserify/beta/policy.json index e4d29eb88..10a1dfc14 100644 --- a/lavamoat/browserify/beta/policy.json +++ b/lavamoat/browserify/beta/policy.json @@ -551,6 +551,7 @@ "abort-controller": true, "async-mutex": true, "buffer": true, + "deep-freeze-strict": true, "eth-ens-namehash": true, "eth-json-rpc-infura": true, "eth-keyring-controller": true, @@ -564,8 +565,10 @@ "ethers": true, "ethjs-unit": true, "events": true, + "fast-deep-equal": true, "immer": true, "isomorphic-fetch": true, + "json-rpc-engine": true, "jsonschema": true, "multiformats": true, "nanoid": true, diff --git a/lavamoat/browserify/flask/policy.json b/lavamoat/browserify/flask/policy.json index 72fa6de24..df637e627 100644 --- a/lavamoat/browserify/flask/policy.json +++ b/lavamoat/browserify/flask/policy.json @@ -551,6 +551,7 @@ "abort-controller": true, "async-mutex": true, "buffer": true, + "deep-freeze-strict": true, "eth-ens-namehash": true, "eth-json-rpc-infura": true, "eth-keyring-controller": true, @@ -564,8 +565,10 @@ "ethers": true, "ethjs-unit": true, "events": true, + "fast-deep-equal": true, "immer": true, "isomorphic-fetch": true, + "json-rpc-engine": true, "jsonschema": true, "multiformats": true, "nanoid": true, diff --git a/lavamoat/browserify/main/policy.json b/lavamoat/browserify/main/policy.json index e4d29eb88..10a1dfc14 100644 --- a/lavamoat/browserify/main/policy.json +++ b/lavamoat/browserify/main/policy.json @@ -551,6 +551,7 @@ "abort-controller": true, "async-mutex": true, "buffer": true, + "deep-freeze-strict": true, "eth-ens-namehash": true, "eth-json-rpc-infura": true, "eth-keyring-controller": true, @@ -564,8 +565,10 @@ "ethers": true, "ethjs-unit": true, "events": true, + "fast-deep-equal": true, "immer": true, "isomorphic-fetch": true, + "json-rpc-engine": true, "jsonschema": true, "multiformats": true, "nanoid": true, diff --git a/lavamoat/build-system/policy-override.json b/lavamoat/build-system/policy-override.json index 34a2f3527..282e26ff0 100644 --- a/lavamoat/build-system/policy-override.json +++ b/lavamoat/build-system/policy-override.json @@ -14,6 +14,7 @@ }, "@eslint/eslintrc": { "packages": { + "": true, "@babel/eslint-parser": true, "@babel/eslint-plugin": true, "@metamask/eslint-config": true, diff --git a/lavamoat/build-system/policy.json b/lavamoat/build-system/policy.json index e95acc4d6..7d6167325 100644 --- a/lavamoat/build-system/policy.json +++ b/lavamoat/build-system/policy.json @@ -1052,6 +1052,16 @@ "buffer-equal": true } }, + "are-we-there-yet": { + "builtin": { + "events.EventEmitter": true, + "util.inherits": true + }, + "packages": { + "delegates": true, + "readable-stream": true + } + }, "arr-diff": { "packages": { "arr-flatten": true, @@ -1460,6 +1470,7 @@ "anymatch": true, "async-each": true, "braces": true, + "fsevents": true, "glob-parent": true, "inherits": true, "is-binary-path": true, @@ -1726,6 +1737,16 @@ "through2": true } }, + "detect-libc": { + "builtin": { + "child_process.spawnSync": true, + "fs.readdirSync": true, + "os.platform": true + }, + "globals": { + "process.env": true + } + }, "detective": { "packages": { "acorn-node": true, @@ -2429,6 +2450,45 @@ "process.version": true } }, + "fsevents": { + "builtin": { + "events.EventEmitter": true, + "fs.stat": true, + "path.join": true, + "util.inherits": true + }, + "globals": { + "__dirname": true, + "process.nextTick": true, + "process.platform": true, + "setImmediate": true + }, + "native": true, + "packages": { + "node-pre-gyp": true + } + }, + "gauge": { + "builtin": { + "util.format": true + }, + "globals": { + "clearInterval": true, + "process": true, + "setImmediate": true, + "setInterval": true + }, + "packages": { + "aproba": true, + "console-control-strings": true, + "has-unicode": true, + "object-assign": true, + "signal-exit": true, + "string-width": true, + "strip-ansi": true, + "wide-align": true + } + }, "get-assigned-identifiers": { "builtin": { "assert.equal": true @@ -2807,6 +2867,16 @@ "process.argv": true } }, + "has-unicode": { + "builtin": { + "os.type": true + }, + "globals": { + "process.env.LANG": true, + "process.env.LC_ALL": true, + "process.env.LC_CTYPE": true + } + }, "has-value": { "packages": { "get-value": true, @@ -2978,6 +3048,11 @@ "is-plain-object": true } }, + "is-fullwidth-code-point": { + "packages": { + "number-is-nan": true + } + }, "is-glob": { "packages": { "is-extglob": true @@ -3508,6 +3583,56 @@ "setTimeout": true } }, + "node-pre-gyp": { + "builtin": { + "events.EventEmitter": true, + "fs.existsSync": true, + "fs.readFileSync": true, + "fs.renameSync": true, + "path.dirname": true, + "path.existsSync": true, + "path.join": true, + "path.resolve": true, + "url.parse": true, + "url.resolve": true, + "util.inherits": true + }, + "globals": { + "__dirname": true, + "console.log": true, + "process.arch": true, + "process.cwd": true, + "process.env": true, + "process.platform": true, + "process.version.substr": true, + "process.versions": true + }, + "packages": { + "detect-libc": true, + "nopt": true, + "npmlog": true, + "rimraf": true, + "semver": true + } + }, + "nopt": { + "builtin": { + "path": true, + "stream.Stream": true, + "url": true + }, + "globals": { + "console": true, + "process.argv": true, + "process.env.DEBUG_NOPT": true, + "process.env.NOPT_DEBUG": true, + "process.platform": true + }, + "packages": { + "abbrev": true, + "osenv": true + } + }, "normalize-package-data": { "builtin": { "url.parse": true, @@ -3535,6 +3660,22 @@ "once": true } }, + "npmlog": { + "builtin": { + "events.EventEmitter": true, + "util": true + }, + "globals": { + "process.nextTick": true, + "process.stderr": true + }, + "packages": { + "are-we-there-yet": true, + "console-control-strings": true, + "gauge": true, + "set-blocking": true + } + }, "object-copy": { "packages": { "copy-descriptor": true, @@ -3616,6 +3757,54 @@ "readable-stream": true } }, + "os-homedir": { + "builtin": { + "os.homedir": true + }, + "globals": { + "process.env": true, + "process.getuid": true, + "process.platform": true + } + }, + "os-tmpdir": { + "globals": { + "process.env.SystemRoot": true, + "process.env.TEMP": true, + "process.env.TMP": true, + "process.env.TMPDIR": true, + "process.env.windir": true, + "process.platform": true + } + }, + "osenv": { + "builtin": { + "child_process.exec": true, + "path": true + }, + "globals": { + "process.env.COMPUTERNAME": true, + "process.env.ComSpec": true, + "process.env.EDITOR": true, + "process.env.HOSTNAME": true, + "process.env.PATH": true, + "process.env.PROMPT": true, + "process.env.PS1": true, + "process.env.Path": true, + "process.env.SHELL": true, + "process.env.USER": true, + "process.env.USERDOMAIN": true, + "process.env.USERNAME": true, + "process.env.VISUAL": true, + "process.env.path": true, + "process.nextTick": true, + "process.platform": true + }, + "packages": { + "os-homedir": true, + "os-tmpdir": true + } + }, "p-limit": { "packages": { "p-try": true @@ -4325,6 +4514,12 @@ "lru-cache": true } }, + "set-blocking": { + "globals": { + "process.stderr": true, + "process.stdout": true + } + }, "set-value": { "packages": { "extend-shallow": true, @@ -4588,6 +4783,7 @@ }, "string-width": { "packages": { + "code-point-at": true, "emoji-regex": true, "is-fullwidth-code-point": true, "strip-ansi": true @@ -5240,6 +5436,11 @@ "isexe": true } }, + "wide-align": { + "packages": { + "string-width": true + } + }, "write": { "builtin": { "fs.createWriteStream": true, diff --git a/package.json b/package.json index fe00c5d76..d461d37f4 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "benchmark:chrome": "SELENIUM_BROWSER=chrome node test/e2e/benchmark.js", "benchmark:firefox": "SELENIUM_BROWSER=firefox node test/e2e/benchmark.js", "build:test": "yarn build test", + "build:test:flask": "yarn build test --build-type flask", "build:test:metrics": "SEGMENT_HOST='http://localhost:9090' SEGMENT_WRITE_KEY='FAKE' yarn build test", "test": "yarn lint && yarn test:unit && yarn test:unit:jest", "dapp": "node development/static-server.js node_modules/@metamask/test-dapp/dist --port 8080", @@ -30,8 +31,10 @@ "test:unit:mocha": "mocha './app/**/*.test.js'", "test:e2e:chrome": "SELENIUM_BROWSER=chrome node test/e2e/run-all.js", "test:e2e:chrome:metrics": "SELENIUM_BROWSER=chrome node test/e2e/run-e2e-test.js test/e2e/metrics.spec.js", + "test:e2e:chrome:snaps": "SELENIUM_BROWSER=chrome node test/e2e/run-all.js --snaps", "test:e2e:firefox": "SELENIUM_BROWSER=firefox node test/e2e/run-all.js", "test:e2e:firefox:metrics": "SELENIUM_BROWSER=firefox node test/e2e/run-e2e-test.js test/e2e/metrics.spec.js", + "test:e2e:firefox:snaps": "SELENIUM_BROWSER=firefox node test/e2e/run-all.js --snaps", "test:e2e:single": "node test/e2e/run-e2e-test.js", "test:coverage:mocha": "nyc --reporter=text --reporter=html yarn test:unit:mocha", "test:coverage:jest": "yarn test:unit:jest --coverage --maxWorkers=2", @@ -109,7 +112,8 @@ "@keystonehq/metamask-airgapped-keyring": "0.2.1", "@material-ui/core": "^4.11.0", "@metamask/contract-metadata": "^1.31.0", - "@metamask/controllers": "^25.0.0", + "@metamask/controllers": "^26.0.0", + "@metamask/design-tokens": "^1.3.0", "@metamask/eth-ledger-bridge-keyring": "^0.10.0", "@metamask/eth-token-tracker": "^4.0.0", "@metamask/etherscan-link": "^2.1.0", @@ -220,7 +224,8 @@ "uuid": "^8.3.2", "valid-url": "^1.0.9", "web3": "^0.20.7", - "web3-stream-provider": "^4.0.0" + "web3-stream-provider": "^4.0.0", + "zxcvbn": "^4.4.2" }, "devDependencies": { "@babel/code-frame": "^7.12.13", @@ -261,6 +266,7 @@ "@testing-library/jest-dom": "^5.11.10", "@testing-library/react": "^10.4.8", "@testing-library/react-hooks": "^3.2.1", + "@testing-library/user-event": "^14.0.0-beta.12", "@types/react": "^16.9.53", "addons-linter": "1.14.0", "babelify": "^10.0.0", @@ -269,7 +275,7 @@ "browser-util-inspect": "^0.2.0", "browserify": "^16.5.1", "chalk": "^3.0.0", - "chromedriver": "^98.0.0", + "chromedriver": "^99.0.0", "concurrently": "^5.2.0", "copy-webpack-plugin": "^6.0.3", "cross-spawn": "^7.0.3", @@ -347,6 +353,7 @@ "source-map": "^0.7.2", "source-map-explorer": "^2.4.2", "squirrelly": "^8.0.8", + "storybook-dark-mode": "^1.0.9", "string.prototype.matchall": "^4.0.2", "style-loader": "^0.21.0", "stylelint": "^13.6.1", diff --git a/shared/constants/hardware-wallets.js b/shared/constants/hardware-wallets.js index 195a1b488..48bc65d3d 100644 --- a/shared/constants/hardware-wallets.js +++ b/shared/constants/hardware-wallets.js @@ -8,6 +8,7 @@ export const KEYRING_TYPES = { TREZOR: 'Trezor Hardware', LATTICE: 'Lattice Hardware', QR: 'QR Hardware Wallet Device', + IMPORTED: 'Simple Key Pair', }; export const DEVICE_NAMES = { diff --git a/shared/modules/string-utils.js b/shared/modules/string-utils.js new file mode 100644 index 000000000..fc496227f --- /dev/null +++ b/shared/modules/string-utils.js @@ -0,0 +1,6 @@ +export function isEqualCaseInsensitive(value1, value2) { + if (typeof value1 !== 'string' || typeof value2 !== 'string') { + return false; + } + return value1.toLowerCase() === value2.toLowerCase(); +} diff --git a/shared/modules/transaction.utils.js b/shared/modules/transaction.utils.js index bd0b6fdf4..8995b6c02 100644 --- a/shared/modules/transaction.utils.js +++ b/shared/modules/transaction.utils.js @@ -1,4 +1,24 @@ import { isHexString } from 'ethereumjs-util'; +import { ethers } from 'ethers'; +import abi from 'human-standard-token-abi'; +import log from 'loglevel'; +import { TRANSACTION_TYPES } from '../constants/transaction'; +import { readAddressAsContract } from './contract-utils'; +import { isEqualCaseInsensitive } from './string-utils'; + +/** + * @typedef { 'transfer' | 'approve' | 'transferfrom' | 'contractInteraction'| 'simpleSend' } InferrableTransactionTypes + */ + +/** + * @typedef {Object} InferTransactionTypeResult + * @property {InferrableTransactionTypes} type - The type of transaction + * @property {string} getCodeResponse - The contract code, in hex format if + * it exists. '0x0' or '0x' are also indicators of non-existent contract + * code + */ + +const hstInterface = new ethers.utils.Interface(abi); export function transactionMatchesNetwork(transaction, chainId, networkId) { if (typeof transaction.chainId !== 'undefined') { @@ -61,3 +81,53 @@ export function txParamsAreDappSuggested(transaction) { transaction?.dappSuggestedGasFees?.maxFeePerGas === maxFeePerGas) ); } + +/** + * Determines the type of the transaction by analyzing the txParams. + * This method will return one of the types defined in shared/constants/transactions + * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these + * represent specific events that we control from the extension and are added manually + * at transaction creation. + * + * @param {Object} txParams - Parameters for the transaction + * @param {EthQuery} query - EthQuery instance + * @returns {InferTransactionTypeResult} + */ +export async function determineTransactionType(txParams, query) { + const { data, to } = txParams; + let name; + try { + name = data && hstInterface.parseTransaction({ data }).name; + } catch (error) { + log.debug('Failed to parse transaction data.', error, data); + } + + const tokenMethodName = [ + TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, + TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, + ].find((methodName) => isEqualCaseInsensitive(methodName, name)); + + let result; + if (data && tokenMethodName) { + result = tokenMethodName; + } else if (data && !to) { + result = TRANSACTION_TYPES.DEPLOY_CONTRACT; + } + + let contractCode; + + if (!result) { + const { + contractCode: resultCode, + isContractAddress, + } = await readAddressAsContract(query, to); + + contractCode = resultCode; + result = isContractAddress + ? TRANSACTION_TYPES.CONTRACT_INTERACTION + : TRANSACTION_TYPES.SIMPLE_SEND; + } + + return { type: result, getCodeResponse: contractCode }; +} diff --git a/shared/modules/transaction.utils.test.js b/shared/modules/transaction.utils.test.js index 3a333caa7..f6d816160 100644 --- a/shared/modules/transaction.utils.test.js +++ b/shared/modules/transaction.utils.test.js @@ -1,4 +1,11 @@ -import { isEIP1559Transaction, isLegacyTransaction } from './transaction.utils'; +import EthQuery from 'ethjs-query'; +import { createTestProviderTools } from '../../test/stub/provider'; +import { TRANSACTION_TYPES } from '../constants/transaction'; +import { + determineTransactionType, + isEIP1559Transaction, + isLegacyTransaction, +} from './transaction.utils'; describe('Transaction.utils', function () { describe('isEIP1559Transaction', function () { @@ -80,4 +87,143 @@ describe('Transaction.utils', function () { ).toBe(false); }); }); + + describe('determineTransactionType', function () { + const genericProvider = createTestProviderTools().provider; + const query = new EthQuery(genericProvider); + + it('should return a simple send type when to is truthy but data is falsy', async function () { + const result = await determineTransactionType( + { + to: '0xabc', + data: '', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.SIMPLE_SEND, + getCodeResponse: null, + }); + }); + + it('should return a token transfer type when data is for the respective method call', async function () { + const result = await determineTransactionType( + { + to: '0xabc', + data: + '0xa9059cbb0000000000000000000000002f318C334780961FB129D2a6c30D0763d9a5C970000000000000000000000000000000000000000000000000000000000000000a', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + getCodeResponse: undefined, + }); + }); + + it('should return a token approve type when data is for the respective method call', async function () { + const result = await determineTransactionType( + { + to: '0xabc', + data: + '0x095ea7b30000000000000000000000002f318C334780961FB129D2a6c30D0763d9a5C9700000000000000000000000000000000000000000000000000000000000000005', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, + getCodeResponse: undefined, + }); + }); + + it('should return a contract deployment type when to is falsy and there is data', async function () { + const result = await determineTransactionType( + { + to: '', + data: '0xabd', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.DEPLOY_CONTRACT, + getCodeResponse: undefined, + }); + }); + + it('should return a simple send type with a 0x getCodeResponse when there is data and but the to address is not a contract address', async function () { + const result = await determineTransactionType( + { + to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', + data: '0xabd', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.SIMPLE_SEND, + getCodeResponse: '0x', + }); + }); + + it('should return a simple send type with a null getCodeResponse when to is truthy and there is data and but getCode returns an error', async function () { + const result = await determineTransactionType( + { + to: '0xabc', + data: '0xabd', + }, + query, + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.SIMPLE_SEND, + getCodeResponse: null, + }); + }); + + it('should return a contract interaction type with the correct getCodeResponse when to is truthy and there is data and it is not a token transaction', async function () { + const _providerResultStub = { + // 1 gwei + eth_gasPrice: '0x0de0b6b3a7640000', + // by default, all accounts are external accounts (not contracts) + eth_getCode: '0xa', + }; + const _provider = createTestProviderTools({ + scaffold: _providerResultStub, + }).provider; + + const result = await determineTransactionType( + { + to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', + data: 'abd', + }, + new EthQuery(_provider), + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.CONTRACT_INTERACTION, + getCodeResponse: '0x0a', + }); + }); + + it('should return a contract interaction type with the correct getCodeResponse when to is a contract address and data is falsy', async function () { + const _providerResultStub = { + // 1 gwei + eth_gasPrice: '0x0de0b6b3a7640000', + // by default, all accounts are external accounts (not contracts) + eth_getCode: '0xa', + }; + const _provider = createTestProviderTools({ + scaffold: _providerResultStub, + }).provider; + + const result = await determineTransactionType( + { + to: '0x9e673399f795D01116e9A8B2dD2F156705131ee9', + data: '', + }, + new EthQuery(_provider), + ); + expect(result).toMatchObject({ + type: TRANSACTION_TYPES.CONTRACT_INTERACTION, + getCodeResponse: '0x0a', + }); + }); + }); }); diff --git a/test/e2e/helpers.js b/test/e2e/helpers.js index 148964b03..3d8e46f4a 100644 --- a/test/e2e/helpers.js +++ b/test/e2e/helpers.js @@ -7,6 +7,7 @@ const { createSegmentServer, } = require('../../development/lib/create-segment-server'); const { setupMocking } = require('../../development/mock-e2e'); +const enLocaleMessages = require('../../app/_locales/en/messages.json'); const Ganache = require('./ganache'); const FixtureServer = require('./fixture-server'); const { buildWebDriver } = require('./webdriver'); @@ -15,6 +16,7 @@ const { ensureXServerIsRunning } = require('./x-server'); const tinyDelayMs = 200; const regularDelayMs = tinyDelayMs * 2; const largeDelayMs = regularDelayMs * 2; +const veryLargeDelayMs = largeDelayMs * 2; const dappPort = 8080; const convertToHexValue = (val) => `0x${new BigNumber(val, 10).toString(16)}`; @@ -29,14 +31,18 @@ async function withFixtures(options, testSuite) { title, failOnConsoleError = true, dappPath = undefined, + testSpecificMock = function () { + // do nothing. + }, } = options; const fixtureServer = new FixtureServer(); const ganacheServer = new Ganache(); + const https = await mockttp.generateCACertificate(); + const mockServer = mockttp.getLocal({ https }); let secondaryGanacheServer; let dappServer; let segmentServer; let segmentStub; - let mockServer; let webDriver; let failed = false; @@ -87,10 +93,8 @@ async function withFixtures(options, testSuite) { }); await segmentServer.start(9090); } - const https = await mockttp.generateCACertificate(); - mockServer = mockttp.getLocal({ https }); + await setupMocking(mockServer, testSpecificMock); await mockServer.start(8000); - setupMocking(mockServer); if ( process.env.SELENIUM_BROWSER === 'chrome' && process.env.CI === 'true' @@ -153,9 +157,7 @@ async function withFixtures(options, testSuite) { if (segmentServer) { await segmentServer.stop(); } - if (mockServer) { - await mockServer.stop(); - } + await mockServer.stop(); } } } @@ -203,12 +205,80 @@ const connectDappWithExtensionPopup = async (driver) => { await driver.delay(regularDelayMs); }; +const completeImportSRPOnboardingFlow = async ( + driver, + seedPhrase, + password, +) => { + if (process.env.ONBOARDING_V2 === '1') { + // welcome + await driver.clickElement('[data-testid="onboarding-import-wallet"]'); + + // metrics + await driver.clickElement('[data-testid="metametrics-no-thanks"]'); + + // import with recovery phrase + await driver.fill('[data-testid="import-srp-text"]', seedPhrase); + await driver.clickElement('[data-testid="import-srp-confirm"]'); + + // create password + await driver.fill('[data-testid="create-password-new"]', password); + await driver.fill('[data-testid="create-password-confirm"]', password); + await driver.clickElement('[data-testid="create-password-terms"]'); + await driver.clickElement('[data-testid="create-password-import"]'); + + // complete + await driver.clickElement('[data-testid="onboarding-complete-done"]'); + + // pin extension + await driver.clickElement('[data-testid="pin-extension-next"]'); + await driver.clickElement('[data-testid="pin-extension-done"]'); + } else { + // clicks the continue button on the welcome screen + await driver.findElement('.welcome-page__header'); + await driver.clickElement({ + text: enLocaleMessages.getStarted.message, + tag: 'button', + }); + + // clicks the "Import Wallet" option + await driver.clickElement({ text: 'Import wallet', tag: 'button' }); + + // clicks the "No thanks" option on the metametrics opt-in screen + await driver.clickElement('.btn-secondary'); + + // Import Secret Recovery Phrase + await driver.fill( + 'input[placeholder="Enter your Secret Recovery Phrase"]', + seedPhrase, + ); + + await driver.fill('#password', password); + await driver.fill('#confirm-password', password); + + await driver.clickElement( + '[data-testid="create-new-vault__terms-checkbox"]', + ); + + await driver.clickElement({ text: 'Import', tag: 'button' }); + + // clicks through the success screen + await driver.findElement({ text: 'Congratulations', tag: 'div' }); + await driver.clickElement({ + text: enLocaleMessages.endOfFlowMessage10.message, + tag: 'button', + }); + } +}; + module.exports = { getWindowHandles, convertToHexValue, tinyDelayMs, regularDelayMs, largeDelayMs, + veryLargeDelayMs, withFixtures, connectDappWithExtensionPopup, + completeImportSRPOnboardingFlow, }; diff --git a/test/e2e/metamask-ui.spec.js b/test/e2e/metamask-ui.spec.js index 7dbc96271..30ca8d43b 100644 --- a/test/e2e/metamask-ui.spec.js +++ b/test/e2e/metamask-ui.spec.js @@ -3,7 +3,12 @@ const path = require('path'); const enLocaleMessages = require('../../app/_locales/en/messages.json'); const createStaticServer = require('../../development/create-static-server'); -const { tinyDelayMs, regularDelayMs, largeDelayMs } = require('./helpers'); +const { + tinyDelayMs, + regularDelayMs, + largeDelayMs, + veryLargeDelayMs, +} = require('./helpers'); const { buildWebDriver } = require('./webdriver'); const Ganache = require('./ganache'); const { ensureXServerIsRunning } = require('./x-server'); @@ -191,12 +196,9 @@ describe('MetaMask', function () { it('imports Secret Recovery Phrase', async function () { const restoreSeedLink = await driver.findClickableElement( - '.unlock-page__link--import', - ); - assert.equal( - await restoreSeedLink.getText(), - 'import using Secret Recovery Phrase', + '.unlock-page__link', ); + assert.equal(await restoreSeedLink.getText(), 'Forgot password?'); await restoreSeedLink.click(); await driver.delay(regularDelayMs); @@ -275,7 +277,7 @@ describe('MetaMask', function () { const gasPriceInput = inputs[1]; await gasLimitInput.fill('4700000'); await gasPriceInput.fill('20'); - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Save', tag: 'button' }); await driver.clickElement({ text: 'Confirm', tag: 'button' }); @@ -346,10 +348,11 @@ describe('MetaMask', function () { // Continue to next screen await driver.delay(largeDelayMs); await driver.clickElement({ text: 'Next', tag: 'button' }); - await driver.delay(regularDelayMs); + await driver.delay(largeDelayMs); }); it('displays the token transfer data', async function () { + await driver.delay(largeDelayMs); await driver.clickElement({ text: 'Hex', tag: 'button' }); await driver.delay(regularDelayMs); @@ -389,7 +392,7 @@ describe('MetaMask', function () { const gasPriceInput = inputs[1]; await gasLimitInput.fill('100000'); await gasPriceInput.fill('100'); - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Save', tag: 'button' }); }); @@ -452,19 +455,20 @@ describe('MetaMask', function () { }); it('customizes gas', async function () { + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Edit', tag: 'button' }); - await driver.delay(largeDelayMs); + await driver.delay(veryLargeDelayMs); await driver.clickElement( { text: 'Edit suggested gas fee', tag: 'button' }, 10000, ); - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); const inputs = await driver.findElements('input[type="number"]'); const gasLimitInput = inputs[0]; const gasPriceInput = inputs[1]; await gasLimitInput.fill('60000'); await gasPriceInput.fill('10'); - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Save', tag: 'button' }); await driver.findElement({ tag: 'span', text: '0.0006' }); }); @@ -589,7 +593,7 @@ describe('MetaMask', function () { await gasLimitInput.fill('60001'); - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Save', tag: 'button' }); @@ -755,7 +759,7 @@ describe('MetaMask', function () { }); it('submits the transaction', async function () { - await driver.delay(1000); + await driver.delay(veryLargeDelayMs); await driver.clickElement({ text: 'Confirm', tag: 'button' }); await driver.delay(regularDelayMs); }); diff --git a/test/e2e/run-all.js b/test/e2e/run-all.js index a73021bd4..70e184652 100644 --- a/test/e2e/run-all.js +++ b/test/e2e/run-all.js @@ -17,6 +17,10 @@ async function main() { type: 'string', choices: ['chrome', 'firefox'], }) + .option('snaps', { + description: `run snaps e2e tests`, + type: 'boolean', + }) .option('retries', { description: 'Set how many times the test should be retried upon failure.', @@ -26,16 +30,22 @@ async function main() { .strict() .help('help'); - const { browser, retries } = argv; + const { browser, retries, snaps } = argv; - const testDir = path.join(__dirname, 'tests'); - const metamaskUiTest = path.join(__dirname, 'metamask-ui.spec.js'); + let testDir = path.join(__dirname, 'tests'); + + if (snaps) { + testDir = path.join(__dirname, 'snaps'); + } const testFilenames = await fs.readdir(testDir); const testPaths = testFilenames.map((filename) => path.join(testDir, filename), ); - const allE2eTestPaths = [...testPaths, metamaskUiTest]; + + if (!snaps) { + testPaths.push(path.join(__dirname, 'metamask-ui.spec.js')); + } const runE2eTestPath = path.join(__dirname, 'run-e2e-test.js'); @@ -47,7 +57,7 @@ async function main() { args.push('--retries', retries); } - for (const testPath of allE2eTestPaths) { + for (const testPath of testPaths) { await runInShell('node', [...args, testPath]); } } diff --git a/test/e2e/snaps/test-snap-confirm.spec.js b/test/e2e/snaps/test-snap-confirm.spec.js new file mode 100644 index 000000000..2100c2ff5 --- /dev/null +++ b/test/e2e/snaps/test-snap-confirm.spec.js @@ -0,0 +1,98 @@ +const { strict: assert } = require('assert'); +const { withFixtures } = require('../helpers'); + +describe('Test Snap Confirm', function () { + it('can pop up a snap confirm and get its result', async function () { + const ganacheOptions = { + accounts: [ + { + secretKey: + '0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC', + balance: 25000000000000000000, + }, + ], + }; + await withFixtures( + { + fixtures: 'imported-account', + ganacheOptions, + title: this.test.title, + driverOptions: { + type: 'flask', + }, + }, + async ({ driver }) => { + await driver.navigate(); + + // enter pw into extension + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + + // navigate to test snaps page and connect + await driver.driver.get('https://metamask.github.io/test-snaps/'); + await driver.fill('.snapId', 'npm:@metamask/test-snap-confirm'); + await driver.clickElement({ + text: 'Connect To Confirm Snap', + tag: 'button', + }); + + // switch to metamask extension and click connect + await driver.waitUntilXWindowHandles(2, 5000, 10000); + let windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle( + 'MetaMask Notification', + windowHandles, + ); + await driver.clickElement( + { + text: 'Connect', + tag: 'button', + }, + 10000, + ); + + await driver.delay(2000); + + // approve install of snap + await driver.waitUntilXWindowHandles(2, 5000, 10000); + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle( + 'MetaMask Notification', + windowHandles, + ); + await driver.clickElement({ + text: 'Approve & Install', + tag: 'button', + }); + + // click send inputs on test snap page + await driver.waitUntilXWindowHandles(1, 5000, 10000); + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle('Test Snaps', windowHandles); + await driver.clickElement({ + text: 'Send Inputs to Hello Snap', + tag: 'button', + }); + + // hit 'approve' on the custom confirm + await driver.waitUntilXWindowHandles(2, 5000, 10000); + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle( + 'MetaMask Notification', + windowHandles, + ); + await driver.clickElement({ + text: 'Approve', + tag: 'button', + }); + + // check the results of the custom confirm + await driver.waitUntilXWindowHandles(1, 5000, 10000); + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle('Test Snaps', windowHandles); + const confirmResult = await driver.findElement('.sendResults'); + assert.equal(await confirmResult.getText(), 'true'); + }, + ); + }); +}); diff --git a/test/e2e/snaps/test-snap-error.spec.js b/test/e2e/snaps/test-snap-error.spec.js new file mode 100644 index 000000000..91ebd2ce1 --- /dev/null +++ b/test/e2e/snaps/test-snap-error.spec.js @@ -0,0 +1,90 @@ +const { strict: assert } = require('assert'); +const { withFixtures } = require('../helpers'); +const { PAGES } = require('../webdriver/driver'); + +describe('Test Snap Error', function () { + it('can pop up a snap error and see the error', async function () { + const ganacheOptions = { + accounts: [ + { + secretKey: + '0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC', + balance: 25000000000000000000, + }, + ], + }; + await withFixtures( + { + fixtures: 'imported-account', + ganacheOptions, + title: this.test.title, + driverOptions: { type: 'flask' }, + }, + async ({ driver }) => { + await driver.navigate(); + + // enter pw into extension + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + + // navigate to test snaps page and connect + await driver.driver.get('https://metamask.github.io/test-snaps/'); + await driver.fill('.snapId2', 'npm:@metamask/test-snap-error'); + await driver.clickElement({ + text: 'Connect Error Snap', + tag: 'button', + }); + + // switch to metamask extension and click connect + await driver.waitUntilXWindowHandles(2, 5000, 10000); + let windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle( + 'MetaMask Notification', + windowHandles, + ); + await driver.clickElement( + { + text: 'Connect', + tag: 'button', + }, + 10000, + ); + + await driver.delay(2000); + + // approve install of snap + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle( + 'MetaMask Notification', + windowHandles, + ); + await driver.clickElement({ + text: 'Approve & Install', + tag: 'button', + }); + + // click send inputs on test snap page + await driver.waitUntilXWindowHandles(1, 5000, 10000); + windowHandles = await driver.getAllWindowHandles(); + await driver.switchToWindowWithTitle('Test Snaps', windowHandles); + await driver.clickElement({ + text: 'Send Test to Error Snap', + tag: 'button', + }); + + await driver.navigate(PAGES.HOME); + + const error = await driver.findElement( + '.home-notification__content-container', + ); + const text = await error.getText(); + assert.equal( + text.includes( + "Snap Error: 'random error inside'. Error Code: '-32603'", + ), + true, + ); + }, + ); + }); +}); diff --git a/test/e2e/tests/add-account.spec.js b/test/e2e/tests/add-account.spec.js index e358660d0..5c0d3fcb9 100644 --- a/test/e2e/tests/add-account.spec.js +++ b/test/e2e/tests/add-account.spec.js @@ -1,16 +1,26 @@ const { strict: assert } = require('assert'); -const { convertToHexValue, withFixtures } = require('../helpers'); +const { + convertToHexValue, + withFixtures, + regularDelayMs, + completeImportSRPOnboardingFlow, +} = require('../helpers'); +const enLocaleMessages = require('../../../app/_locales/en/messages.json'); describe('Add account', function () { + const testSeedPhrase = + 'forum vessel pink push lonely enact gentle tail admit parrot grunt dress'; + const testPassword = 'correct horse battery staple'; const ganacheOptions = { accounts: [ { secretKey: - '0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC', + '0x53CB0AB5226EEBF4D872113D98332C1555DC304443BEE1CF759D15798D3C55A9', balance: convertToHexValue(25000000000000000000), }, ], }; + it('should display correct new account name after create', async function () { await withFixtures( { @@ -36,4 +46,213 @@ describe('Add account', function () { }, ); }); + + it('should add the same account addresses when a secret recovery phrase is imported, the account is locked, and the same secret recovery phrase is imported again', async function () { + await withFixtures( + { + fixtures: 'onboarding', + ganacheOptions, + title: this.test.title, + failOnConsoleError: false, + }, + async ({ driver }) => { + await driver.navigate(); + + await completeImportSRPOnboardingFlow( + driver, + testSeedPhrase, + testPassword, + ); + + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Create Account', tag: 'div' }); + await driver.fill('.new-account-create-form input', '2nd account'); + await driver.clickElement({ text: 'Create', tag: 'button' }); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + await driver.clickElement( + '[data-testid="account-options-menu__account-details"]', + ); + + const detailsModal = await driver.findVisibleElement('span .modal'); + // get the public address for the "second account" + const secondAccountAddress = await driver.findElement( + '.qr-code__address', + ); + const secondAccountPublicAddress = await secondAccountAddress.getText(); + + await driver.clickElement('.account-modal__close'); + await detailsModal.waitForElementState('hidden'); + + // generate a third accound + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Create Account', tag: 'div' }); + await driver.fill('.new-account-create-form input', '3rd account'); + await driver.clickElement({ text: 'Create', tag: 'button' }); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + await driver.clickElement( + '[data-testid="account-options-menu__account-details"]', + ); + + // get the public address for the "third account" + const secondDetailsModal = await driver.findVisibleElement( + 'span .modal', + ); + const thirdAccountAddress = await driver.findElement( + '.qr-code__address', + ); + const thirdAccountPublicAddress = await thirdAccountAddress.getText(); + + await driver.clickElement('.account-modal__close'); + await secondDetailsModal.waitForElementState('hidden'); + + // lock account + await driver.clickElement('.account-menu__icon'); + await driver.delay(regularDelayMs); + + const lockButton = await driver.findClickableElement( + '.account-menu__lock-button', + ); + await lockButton.click(); + await driver.delay(regularDelayMs); + + // restore same seed phrase + const restoreSeedLink = await driver.findClickableElement( + '.unlock-page__link', + ); + + await restoreSeedLink.click(); + await driver.delay(regularDelayMs); + + await driver.fill( + 'input[placeholder="Enter your Secret Recovery Phrase"]', + testSeedPhrase, + ); + await driver.delay(regularDelayMs); + + await driver.fill('#password', 'correct horse battery staple'); + await driver.fill('#confirm-password', 'correct horse battery staple'); + await driver.clickElement({ + text: enLocaleMessages.restore.message, + tag: 'button', + }); + await driver.delay(regularDelayMs); + + // recreate a "2nd account" + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Create Account', tag: 'div' }); + await driver.fill('.new-account-create-form input', '2nd account'); + await driver.clickElement({ text: 'Create', tag: 'button' }); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + await driver.clickElement( + '[data-testid="account-options-menu__account-details"]', + ); + const thirdDetailsModal = await driver.findVisibleElement( + 'span .modal', + ); + // get the public address for the "second account" + const recreatedSecondAccountAddress = await driver.findElement( + '.qr-code__address', + ); + + assert.equal( + await recreatedSecondAccountAddress.getText(), + secondAccountPublicAddress, + ); + + await driver.clickElement('.account-modal__close'); + await thirdDetailsModal.waitForElementState('hidden'); + + // re-generate a third accound + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Create Account', tag: 'div' }); + await driver.fill('.new-account-create-form input', '3rd account'); + await driver.clickElement({ text: 'Create', tag: 'button' }); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + await driver.clickElement( + '[data-testid="account-options-menu__account-details"]', + ); + + // get the public address for the "third account" + const recreatedThirdAccountAddress = await driver.findElement( + '.qr-code__address', + ); + assert.strictEqual( + await recreatedThirdAccountAddress.getText(), + thirdAccountPublicAddress, + ); + }, + ); + }); + + it('It should be possible to remove an account imported with a private key, but should not be possible to remove an account generated from the SRP imported in onboarding', async function () { + const testPrivateKey = + '14abe6f4aab7f9f626fe981c864d0adeb5685f289ac9270c27b8fd790b4235d6'; + + await withFixtures( + { + fixtures: 'imported-account', + ganacheOptions, + title: this.test.title, + }, + async ({ driver }) => { + await driver.navigate(); + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + + await driver.delay(regularDelayMs); + + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Create Account', tag: 'div' }); + await driver.fill('.new-account-create-form input', '2nd account'); + await driver.clickElement({ text: 'Create', tag: 'button' }); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + + const menuItems = await driver.findElements('.menu-item'); + assert.equal(menuItems.length, 3); + + // click out of menu + await driver.clickElement('.menu__background'); + + // import with private key + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Import Account', tag: 'div' }); + + // enter private key', + await driver.fill('#private-key-box', testPrivateKey); + await driver.clickElement({ text: 'Import', tag: 'button' }); + + // should show the correct account name + const importedAccountName = await driver.findElement( + '.selected-account__name', + ); + assert.equal(await importedAccountName.getText(), 'Account 3'); + + await driver.clickElement( + '[data-testid="account-options-menu-button"]', + ); + + const menuItems2 = await driver.findElements('.menu-item'); + assert.equal(menuItems2.length, 4); + + await driver.findElement( + '[data-testid="account-options-menu__remove-account"]', + ); + }, + ); + }); }); diff --git a/test/e2e/tests/add-hide-token.spec.js b/test/e2e/tests/add-hide-token.spec.js index 56fb2840c..066bd8782 100644 --- a/test/e2e/tests/add-hide-token.spec.js +++ b/test/e2e/tests/add-hide-token.spec.js @@ -55,6 +55,7 @@ describe('Hide token', function () { }); }); +/* eslint-disable-next-line mocha/max-top-level-suites */ describe('Add existing token using search', function () { const ganacheOptions = { accounts: [ diff --git a/test/e2e/tests/custom-rpc-history.spec.js b/test/e2e/tests/custom-rpc-history.spec.js index 025f7f53a..49dd59059 100644 --- a/test/e2e/tests/custom-rpc-history.spec.js +++ b/test/e2e/tests/custom-rpc-history.spec.js @@ -36,10 +36,10 @@ describe('Stores custom RPC history', function () { await driver.findElement('.networks-tab__sub-header-text'); const customRpcInputs = await driver.findElements('input[type="text"]'); - const networkNameInput = customRpcInputs[0]; - const rpcUrlInput = customRpcInputs[1]; - const chainIdInput = customRpcInputs[2]; - const symbolInput = customRpcInputs[3]; + const networkNameInput = customRpcInputs[1]; + const rpcUrlInput = customRpcInputs[2]; + const chainIdInput = customRpcInputs[3]; + const symbolInput = customRpcInputs[4]; await networkNameInput.clear(); await networkNameInput.sendKeys(networkName); @@ -84,7 +84,7 @@ describe('Stores custom RPC history', function () { await driver.findElement('.networks-tab__sub-header-text'); const customRpcInputs = await driver.findElements('input[type="text"]'); - const rpcUrlInput = customRpcInputs[1]; + const rpcUrlInput = customRpcInputs[2]; await rpcUrlInput.clear(); await rpcUrlInput.sendKeys(duplicateRpcUrl); @@ -120,8 +120,8 @@ describe('Stores custom RPC history', function () { await driver.findElement('.networks-tab__sub-header-text'); const customRpcInputs = await driver.findElements('input[type="text"]'); - const rpcUrlInput = customRpcInputs[1]; - const chainIdInput = customRpcInputs[2]; + const rpcUrlInput = customRpcInputs[2]; + const chainIdInput = customRpcInputs[3]; await chainIdInput.clear(); await chainIdInput.sendKeys(duplicateChainId); diff --git a/test/e2e/tests/from-import-ui.spec.js b/test/e2e/tests/from-import-ui.spec.js index a1a8e1da4..3157e6a43 100644 --- a/test/e2e/tests/from-import-ui.spec.js +++ b/test/e2e/tests/from-import-ui.spec.js @@ -4,8 +4,8 @@ const { withFixtures, regularDelayMs, largeDelayMs, + completeImportSRPOnboardingFlow, } = require('../helpers'); -const enLocaleMessages = require('../../../app/_locales/en/messages.json'); describe('Metamask Import UI', function () { it('Importing wallet using Secret Recovery Phrase', async function () { @@ -20,6 +20,7 @@ describe('Metamask Import UI', function () { }; const testSeedPhrase = 'forum vessel pink push lonely enact gentle tail admit parrot grunt dress'; + const testPassword = 'correct horse battery staple'; const testAddress = '0x0Cc5261AB8cE458dc977078A3623E2BaDD27afD3'; await withFixtures( @@ -32,74 +33,11 @@ describe('Metamask Import UI', function () { async ({ driver }) => { await driver.navigate(); - if (process.env.ONBOARDING_V2 === '1') { - // welcome - await driver.clickElement('[data-testid="onboarding-import-wallet"]'); - - // metrics - await driver.clickElement('[data-testid="metametrics-no-thanks"]'); - - // import with recovery phrase - await driver.fill('[data-testid="import-srp-text"]', testSeedPhrase); - await driver.clickElement('[data-testid="import-srp-confirm"]'); - - // create password - await driver.fill( - '[data-testid="create-password-new"]', - 'correct horse battery staple', - ); - await driver.fill( - '[data-testid="create-password-confirm"]', - 'correct horse battery staple', - ); - await driver.clickElement('[data-testid="create-password-terms"]'); - await driver.clickElement('[data-testid="create-password-import"]'); - - // complete - await driver.clickElement('[data-testid="onboarding-complete-done"]'); - - // pin extension - await driver.clickElement('[data-testid="pin-extension-next"]'); - await driver.clickElement('[data-testid="pin-extension-done"]'); - } else { - // clicks the continue button on the welcome screen - await driver.findElement('.welcome-page__header'); - await driver.clickElement({ - text: enLocaleMessages.getStarted.message, - tag: 'button', - }); - - // clicks the "Import Wallet" option - await driver.clickElement({ text: 'Import wallet', tag: 'button' }); - - // clicks the "No thanks" option on the metametrics opt-in screen - await driver.clickElement('.btn-secondary'); - - // Import Secret Recovery Phrase - await driver.fill( - 'input[placeholder="Enter your Secret Recovery Phrase"]', - testSeedPhrase, - ); - - await driver.fill('#password', 'correct horse battery staple'); - await driver.fill( - '#confirm-password', - 'correct horse battery staple', - ); - - await driver.clickElement( - '[data-testid="create-new-vault__terms-checkbox"]', - ); - - await driver.clickElement({ text: 'Import', tag: 'button' }); - - // clicks through the success screen - await driver.findElement({ text: 'Congratulations', tag: 'div' }); - await driver.clickElement({ - text: enLocaleMessages.endOfFlowMessage10.message, - tag: 'button', - }); - } + await completeImportSRPOnboardingFlow( + driver, + testSeedPhrase, + testPassword, + ); // Show account information await driver.clickElement( @@ -293,6 +231,47 @@ describe('Metamask Import UI', function () { }, ); }); + + it('Import Account using private key of an already active account should result in an error', async function () { + const testPrivateKey = + '0x53CB0AB5226EEBF4D872113D98332C1555DC304443BEE1CF759D15798D3C55A9'; + const ganacheOptions = { + accounts: [ + { + secretKey: testPrivateKey, + balance: convertToHexValue(25000000000000000000), + }, + ], + }; + + await withFixtures( + { + fixtures: 'import-ui', + ganacheOptions, + title: this.test.title, + }, + async ({ driver }) => { + await driver.navigate(); + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + + // choose Import Account from the account menu + await driver.clickElement('.account-menu__icon'); + await driver.clickElement({ text: 'Import Account', tag: 'div' }); + + // enter private key', + await driver.fill('#private-key-box', testPrivateKey); + await driver.clickElement({ text: 'Import', tag: 'button' }); + + // error should occur + await driver.waitForSelector({ + css: '.error', + text: "The account you're are trying to import is a duplicate", + }); + }, + ); + }); + it('Connects to a Hardware wallet', async function () { const ganacheOptions = { accounts: [ diff --git a/test/e2e/tests/metamask-responsive-ui.spec.js b/test/e2e/tests/metamask-responsive-ui.spec.js index 3bf8684fb..e01e5b307 100644 --- a/test/e2e/tests/metamask-responsive-ui.spec.js +++ b/test/e2e/tests/metamask-responsive-ui.spec.js @@ -164,12 +164,9 @@ describe('Metamask Responsive UI', function () { // Import Secret Recovery Phrase const restoreSeedLink = await driver.findClickableElement( - '.unlock-page__link--import', - ); - assert.equal( - await restoreSeedLink.getText(), - 'import using Secret Recovery Phrase', + '.unlock-page__link', ); + assert.equal(await restoreSeedLink.getText(), 'Forgot password?'); await restoreSeedLink.click(); await driver.fill( diff --git a/test/e2e/tests/phishing-detection.spec.js b/test/e2e/tests/phishing-detection.spec.js new file mode 100644 index 000000000..a198de3c0 --- /dev/null +++ b/test/e2e/tests/phishing-detection.spec.js @@ -0,0 +1,54 @@ +/* eslint-disable mocha/no-skipped-tests */ +const { strict: assert } = require('assert'); +const { convertToHexValue, withFixtures } = require('../helpers'); + +describe('Phishing Detection', function () { + async function mockPhishingDetection(mockServer) { + await mockServer + .forGet( + 'https://cdn.jsdelivr.net/gh/MetaMask/eth-phishing-detect@master/src/config.json', + ) + .thenCallback(() => { + return { + headers: { 'Access-Control-Allow-Origin': '*' }, + statusCode: 200, + json: { + version: 2, + tolerance: 2, + fuzzylist: [], + whitelist: [], + blacklist: ['example.com'], + }, + }; + }); + } + const ganacheOptions = { + accounts: [ + { + secretKey: + '0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC', + balance: convertToHexValue(25000000000000000000), + }, + ], + }; + it.skip('should display the MetaMask Phishing Detection page', async function () { + await withFixtures( + { + fixtures: 'imported-account', + ganacheOptions, + title: this.test.title, + testSpecificMock: mockPhishingDetection, + }, + async ({ driver }) => { + await driver.navigate(); + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + await driver.navigate(); + await driver.openNewPage('http://example.com'); + await driver.waitForSelector({ text: 'continuing at your own risk' }); + const header = await driver.findElement('h1'); + assert.equal(await header.getText(), 'MetaMask Phishing Detection'); + }, + ); + }); +}); diff --git a/test/e2e/tests/send-eth.spec.js b/test/e2e/tests/send-eth.spec.js index 7c12e321b..f17f116d9 100644 --- a/test/e2e/tests/send-eth.spec.js +++ b/test/e2e/tests/send-eth.spec.js @@ -91,6 +91,7 @@ describe('Send ETH from inside MetaMask using default gas', function () { }); }); +/* eslint-disable-next-line mocha/max-top-level-suites */ describe('Send ETH from inside MetaMask using advanced gas modal', function () { const ganacheOptions = { accounts: [ diff --git a/test/e2e/tests/signature-request.spec.js b/test/e2e/tests/signature-request.spec.js index 335826069..7cb53e233 100644 --- a/test/e2e/tests/signature-request.spec.js +++ b/test/e2e/tests/signature-request.spec.js @@ -86,6 +86,7 @@ describe('Sign Typed Data V4 Signature Request', function () { }); }); +/* eslint-disable-next-line mocha/max-top-level-suites */ describe('Sign Typed Data V3 Signature Request', function () { it('can initiate and confirm a Signature Request', async function () { const ganacheOptions = { diff --git a/test/e2e/tests/token-details.spec.js b/test/e2e/tests/token-details.spec.js new file mode 100644 index 000000000..6b182fc03 --- /dev/null +++ b/test/e2e/tests/token-details.spec.js @@ -0,0 +1,50 @@ +const { strict: assert } = require('assert'); +const { convertToHexValue, withFixtures } = require('../helpers'); + +describe('Token Details', function () { + const ganacheOptions = { + accounts: [ + { + secretKey: + '0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC', + balance: convertToHexValue(25000000000000000000), + }, + ], + }; + it('should show token details for an imported token', async function () { + await withFixtures( + { + fixtures: 'imported-account', + ganacheOptions, + title: this.test.title, + }, + async ({ driver }) => { + await driver.navigate(); + await driver.fill('#password', 'correct horse battery staple'); + await driver.press('#password', driver.Key.ENTER); + + await driver.clickElement({ text: 'import tokens', tag: 'a' }); + await driver.clickElement({ text: 'Custom Token', tag: 'button' }); + + const tokenAddress = '0x2EFA2Cb29C2341d8E5Ba7D3262C9e9d6f1Bf3711'; + const tokenSymbol = 'AAVE'; + + await driver.fill('#custom-address', tokenAddress); + await driver.waitForSelector('#custom-symbol-helper-text'); + await driver.fill('#custom-symbol', tokenSymbol); + await driver.clickElement({ text: 'Add Custom Token', tag: 'button' }); + await driver.clickElement({ text: 'Import Tokens', tag: 'button' }); + await driver.clickElement('[title="Asset options"]'); + await driver.clickElement({ text: 'Token details', tag: 'span' }); + + const tokenAddressFound = { + text: tokenAddress, + }; + + const exists = await driver.isElementPresent(tokenAddressFound); + + assert.ok(exists, 'Token details are not correct.'); + }, + ); + }); +}); diff --git a/test/e2e/webdriver/chrome.js b/test/e2e/webdriver/chrome.js index f5af2bad4..05ce2b65d 100644 --- a/test/e2e/webdriver/chrome.js +++ b/test/e2e/webdriver/chrome.js @@ -69,7 +69,7 @@ class ChromeDriver { for (let i = 0; i < extensions.length; i++) { const extension = extensions[i].shadowRoot const name = extension.querySelector('#name').textContent - if (name === "${extensionName}") { + if (name.startsWith("${extensionName}")) { return extensions[i].getAttribute("id") } } diff --git a/test/e2e/webdriver/driver.js b/test/e2e/webdriver/driver.js index 4971cef59..84342ae69 100644 --- a/test/e2e/webdriver/driver.js +++ b/test/e2e/webdriver/driver.js @@ -248,6 +248,15 @@ class Driver { assert.ok(!dataTab, 'Found element that should not be present'); } + async isElementPresent(element) { + try { + await this.findElement(element); + return true; + } catch (err) { + return false; + } + } + // Navigation async navigate(page = Driver.PAGES.HOME) { @@ -362,7 +371,7 @@ class Driver { const ignoredLogTypes = ['WARNING']; const ignoredErrorMessages = [ // Third-party Favicon 404s show up as errors - 'favicon.ico - Failed to load resource: the server responded with a status of 404 (Not Found)', + 'favicon.ico - Failed to load resource: the server responded with a status of 404', // Sentry rate limiting 'Failed to load resource: the server responded with a status of 429', // 4Byte diff --git a/test/e2e/webdriver/firefox.js b/test/e2e/webdriver/firefox.js index bde4564c2..71111df58 100644 --- a/test/e2e/webdriver/firefox.js +++ b/test/e2e/webdriver/firefox.js @@ -4,7 +4,8 @@ const path = require('path'); const { Builder, By, until } = require('selenium-webdriver'); const firefox = require('selenium-webdriver/firefox'); const proxy = require('selenium-webdriver/proxy'); -const { version } = require('../../../package.json'); +const { getVersion } = require('../../../development/lib/get-version'); +const { BuildType } = require('../../../development/lib/build-type'); /** * The prefix for temporary Firefox profiles. All Firefox profiles used for e2e tests @@ -31,9 +32,10 @@ class FirefoxDriver { * @param {Object} options - the options for the build * @param options.responsive * @param options.port + * @param options.type * @returns {Promise<{driver: !ThenableWebDriver, extensionUrl: string, extensionId: string}>} */ - static async build({ responsive, port }) { + static async build({ responsive, port, type }) { const templateProfile = fs.mkdtempSync(TEMP_PROFILE_PATH_PREFIX); const options = new firefox.Options().setProfile(templateProfile); options.setProxy(proxy.manual({ https: HTTPS_PROXY_HOST })); @@ -48,9 +50,14 @@ class FirefoxDriver { const driver = builder.build(); const fxDriver = new FirefoxDriver(driver); - const extensionId = await fxDriver.installExtension( - `builds/metamask-firefox-${version}.zip`, - ); + const version = getVersion(type || BuildType.main, 0); + let extensionString = `builds/metamask-firefox-${version}.zip`; + + if (type) { + extensionString = `builds/metamask-${type}-firefox-${version}.zip`; + } + + const extensionId = await fxDriver.installExtension(extensionString); const internalExtensionId = await fxDriver.getInternalId(); if (responsive) { diff --git a/test/e2e/webdriver/index.js b/test/e2e/webdriver/index.js index eb552f34d..fee966d8f 100644 --- a/test/e2e/webdriver/index.js +++ b/test/e2e/webdriver/index.js @@ -4,14 +4,14 @@ const Driver = require('./driver'); const ChromeDriver = require('./chrome'); const FirefoxDriver = require('./firefox'); -async function buildWebDriver({ responsive, port } = {}) { +async function buildWebDriver({ responsive, port, type } = {}) { const browser = process.env.SELENIUM_BROWSER; const { driver: seleniumDriver, extensionId, extensionUrl, - } = await buildBrowserWebDriver(browser, { responsive, port }); + } = await buildBrowserWebDriver(browser, { responsive, port, type }); await setupFetchMocking(seleniumDriver); const driver = new Driver(seleniumDriver, browser, extensionUrl); diff --git a/test/helpers/setup-helper.js b/test/helpers/setup-helper.js index f9d2112aa..9d4b7d892 100644 --- a/test/helpers/setup-helper.js +++ b/test/helpers/setup-helper.js @@ -79,3 +79,11 @@ if (!window.crypto.getRandomValues) { // eslint-disable-next-line node/global-require window.crypto.getRandomValues = require('polyfill-crypto.getrandomvalues'); } + +// Used to test `clearClipboard` function +if (!window.navigator.clipboard) { + window.navigator.clipboard = {}; +} +if (!window.navigator.clipboard.writeText) { + window.navigator.clipboard.writeText = () => undefined; +} diff --git a/test/lib/render-helpers.js b/test/lib/render-helpers.js index 37c5d6370..9fc7aad16 100644 --- a/test/lib/render-helpers.js +++ b/test/lib/render-helpers.js @@ -95,3 +95,17 @@ export function renderWithProvider(component, store) { return render(component, { wrapper: Wrapper }); } + +export function renderWithLocalization(component) { + const Wrapper = ({ children }) => ( + + {children} + + ); + + Wrapper.propTypes = { + children: PropTypes.node, + }; + + return render(component, { wrapper: Wrapper }); +} diff --git a/ui/components/app/account-menu/account-menu.component.js b/ui/components/app/account-menu/account-menu.component.js index 8105af35b..4c3ff209c 100644 --- a/ui/components/app/account-menu/account-menu.component.js +++ b/ui/components/app/account-menu/account-menu.component.js @@ -125,7 +125,7 @@ export default class AccountMenu extends Component { marginLeft: '8px', }} > - + ); diff --git a/ui/components/app/account-menu/keyring-label.js b/ui/components/app/account-menu/keyring-label.js index 794eed5e4..65007390c 100644 --- a/ui/components/app/account-menu/keyring-label.js +++ b/ui/components/app/account-menu/keyring-label.js @@ -22,7 +22,7 @@ export default function KeyRingLabel({ keyring }) { case KEYRING_TYPES.QR: label = KEYRING_NAMES.QR; break; - case 'Simple Key Pair': + case KEYRING_TYPES.IMPORTED: label = t('imported'); break; case KEYRING_TYPES.TREZOR: diff --git a/ui/components/app/add-network/add-network.js b/ui/components/app/add-network/add-network.js new file mode 100644 index 000000000..0bc911fed --- /dev/null +++ b/ui/components/app/add-network/add-network.js @@ -0,0 +1,133 @@ +import React, { useContext } from 'react'; +import PropTypes from 'prop-types'; +import { I18nContext } from '../../../contexts/i18n'; +import ActionableMessage from '../../ui/actionable-message'; +import Box from '../../ui/box'; +import Typography from '../../ui/typography'; +import { + ALIGN_ITEMS, + BLOCK_SIZES, + COLORS, + DISPLAY, + FLEX_DIRECTION, + TYPOGRAPHY, +} from '../../../helpers/constants/design-system'; +import Button from '../../ui/button'; +import IconCaretLeft from '../../ui/icon/icon-caret-left'; + +const AddNetwork = ({ + onBackClick, + onAddNetworkClick, + onAddNetworkManuallyClick, + featuredRPCS, +}) => { + const t = useContext(I18nContext); + + const nets = featuredRPCS + .sort((a, b) => (a.ticker > b.ticker ? 1 : -1)) + .slice(0, 5); + + return ( + + + + + {t('addNetwork')} + + + + + {t('addFromAListOfPopularNetworks')} + + + {t('customNetworks')} + + {nets.map((item, index) => ( + + {t('logo', + + {item.ticker} + + {`${t('add')} + + ))} + + + + + {t('onlyInteractWith')} + + {t('endOfFlowMessage9')} + + + } + iconFillColor="#f8c000" + useIcon + withRightButton + /> + + + ); +}; + +AddNetwork.propTypes = { + onBackClick: PropTypes.func, + onAddNetworkClick: PropTypes.func, + onAddNetworkManuallyClick: PropTypes.func, + featuredRPCS: PropTypes.array, +}; + +export default AddNetwork; diff --git a/ui/components/app/add-network/add-network.stories.js b/ui/components/app/add-network/add-network.stories.js new file mode 100644 index 000000000..5dbcc6bee --- /dev/null +++ b/ui/components/app/add-network/add-network.stories.js @@ -0,0 +1,53 @@ +import React from 'react'; +import AddNetwork from '.'; + +export default { + title: 'Components/APP/AddNetwork', + id: __filename, +}; + +export const DefaultStory = () => { + const MATIC_TOKEN_IMAGE_URL = './images/matic-token.png'; + const ARBITRUM_IMAGE_URL = './images/arbitrum.svg'; + const OPTIMISM_IMAGE_URL = './images/optimism.svg'; + + const FEATURED_RPCS = [ + { + chainId: '0x89', + nickname: 'Polygon Mumbai', + rpcUrl: + 'https://polygon-mainnet.infura.io/v3/2b6d4a83d89a438eb1b5d036788ab29c', + ticker: 'MATIC', + rpcPrefs: { + blockExplorerUrl: 'https://mumbai.polygonscan.com/', + imageUrl: MATIC_TOKEN_IMAGE_URL, + }, + }, + { + chainId: '0x99', + nickname: 'Optimism Testnet ', + rpcUrl: + 'https://optimism-kovan.infura.io/v3/2b6d4a83d89a438eb1b5d036788ab29c', + ticker: 'KOR', + rpcPrefs: { + blockExplorerUrl: 'https://kovan-optimistic.etherscan.io/', + imageUrl: OPTIMISM_IMAGE_URL, + }, + }, + { + chainId: '0x66eeb', + nickname: 'Arbitrum Testnet', + rpcUrl: + 'https://arbitrum-rinkeby.infura.io/v3/2b6d4a83d89a438eb1b5d036788ab29c', + ticker: 'ARETH', + rpcPrefs: { + blockExplorerUrl: 'https://testnet.arbiscan.io/', + imageUrl: ARBITRUM_IMAGE_URL, + }, + }, + ]; + + return ; +}; + +DefaultStory.storyName = 'Default'; diff --git a/ui/components/app/add-network/index.js b/ui/components/app/add-network/index.js new file mode 100644 index 000000000..8727c8809 --- /dev/null +++ b/ui/components/app/add-network/index.js @@ -0,0 +1 @@ +export { default } from './add-network'; diff --git a/ui/components/app/add-network/index.scss b/ui/components/app/add-network/index.scss new file mode 100644 index 000000000..9a087b259 --- /dev/null +++ b/ui/components/app/add-network/index.scss @@ -0,0 +1,42 @@ +.add-network { + &__header { + border-bottom: 1px solid var(--ui-grey); + + &__back-icon { + margin-left: 24px; + margin-right: 16px; + } + } + + &__token-image { + margin-right: 7px; + height: 24px; + width: 24px; + } + + &__add-icon { + height: 16px; + width: 12px; + color: var(--ui-4); + margin-left: auto; + margin-right: 0; + } + + &__footer { + border-top: 1px solid var(--ui-2); + + & .btn-link { + display: initial; + padding: 0; + } + + &__link { + color: var(--primary-1); + } + + & .actionable-message--warning .actionable-message__message, + .actionable-message--warning .actionable-message__action { + color: var(--ui-4); + } + } +} diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-defaults/advanced-gas-fee-defaults.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-defaults/advanced-gas-fee-defaults.js index cd21dd340..beefff4fa 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-defaults/advanced-gas-fee-defaults.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-defaults/advanced-gas-fee-defaults.js @@ -88,7 +88,11 @@ const AdvancedGasFeeDefaults = () => { onClick={handleUpdateDefaultSettings} disabled={gasErrors.maxFeePerGas || gasErrors.maxPriorityFeePerGas} /> - + {isDefaultSettingsSelected ? t('advancedGasFeeDefaultOptOut') : t('advancedGasFeeDefaultOptIn', [ diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.js index 91df48fde..51739f704 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.js @@ -1,42 +1,95 @@ -import React from 'react'; +import React, { useContext } from 'react'; import PropTypes from 'prop-types'; +import { isNullish } from '../../../../helpers/utils/util'; +import { formatGasFeeOrFeeRange } from '../../../../helpers/utils/gas'; +import { I18nContext } from '../../../../contexts/i18n'; import Box from '../../../ui/box'; -import I18nValue from '../../../ui/i18n-value'; import LoadingHeartBeat from '../../../ui/loading-heartbeat'; -const AdvancedGasFeeInputSubtext = ({ latest, historical, feeTrend }) => { +function determineTrendInfo(trend, t) { + switch (trend) { + case 'up': + return { + className: 'advanced-gas-fee-input-subtext__up', + imageSrc: '/images/up-arrow.svg', + imageAlt: t('upArrow'), + }; + case 'down': + return { + className: 'advanced-gas-fee-input-subtext__down', + imageSrc: '/images/down-arrow.svg', + imageAlt: t('downArrow'), + }; + case 'level': + return { + className: 'advanced-gas-fee-input-subtext__level', + imageSrc: '/images/level-arrow.svg', + imageAlt: t('levelArrow'), + }; + default: + return null; + } +} + +const AdvancedGasFeeInputSubtext = ({ latest, historical, trend }) => { + const t = useContext(I18nContext); + const trendInfo = determineTrendInfo(trend, t); return ( - - - - - - - - {latest} - - - feeTrend-arrow - - - - - - - - - {historical} - - + + {isNullish(latest) ? null : ( + + + {t('currentTitle')} + + + + {formatGasFeeOrFeeRange(latest)} + + {trendInfo === null ? null : ( + + {trendInfo.imageAlt} + + )} + + )} + {isNullish(historical) ? null : ( + + + {t('twelveHrTitle')} + + + + {formatGasFeeOrFeeRange(historical)} + + + )} ); }; AdvancedGasFeeInputSubtext.propTypes = { - latest: PropTypes.string, - historical: PropTypes.string, - feeTrend: PropTypes.string.isRequired, + latest: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.arrayOf(PropTypes.string), + ]), + historical: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.arrayOf(PropTypes.string), + ]), + trend: PropTypes.oneOf(['up', 'down', 'level']), }; export default AdvancedGasFeeInputSubtext; diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.test.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.test.js index ab3692de3..5d779b669 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.test.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/advanced-gas-fee-input-subtext.test.js @@ -1,55 +1,144 @@ import React from 'react'; -import { screen } from '@testing-library/react'; - -import { GAS_ESTIMATE_TYPES } from '../../../../../shared/constants/gas'; -import mockEstimates from '../../../../../test/data/mock-estimates.json'; -import mockState from '../../../../../test/data/mock-state.json'; -import { renderWithProvider } from '../../../../../test/lib/render-helpers'; +import { renderWithProvider, screen } from '../../../../../test/jest'; import configureStore from '../../../../store/store'; import AdvancedGasFeeInputSubtext from './advanced-gas-fee-input-subtext'; jest.mock('../../../../store/actions', () => ({ disconnectGasFeeEstimatePoller: jest.fn(), - getGasFeeEstimatesAndStartPolling: jest - .fn() - .mockImplementation(() => Promise.resolve()), + getGasFeeEstimatesAndStartPolling: jest.fn().mockResolvedValue(null), addPollingTokenToAppState: jest.fn(), removePollingTokenFromAppState: jest.fn(), })); -const render = () => { - const store = configureStore({ - metamask: { - ...mockState.metamask, - accounts: { - [mockState.metamask.selectedAddress]: { - address: mockState.metamask.selectedAddress, - balance: '0x1F4', - }, - }, - advancedGasFee: { priorityFee: 100 }, - featureFlags: { advancedInlineGas: true }, - gasFeeEstimates: - mockEstimates[GAS_ESTIMATE_TYPES.FEE_MARKET].gasFeeEstimates, - }, - }); - - return renderWithProvider( - , - store, - ); +const renderComponent = ({ props = {}, state = {} } = {}) => { + const store = configureStore(state); + return renderWithProvider(, store); }; describe('AdvancedGasFeeInputSubtext', () => { - it('should renders latest and historical values passed', () => { - render(); + describe('when "latest" is non-nullish', () => { + it('should render the latest fee if given a fee', () => { + renderComponent({ + props: { + latest: '123.12345', + }, + }); - expect(screen.queryByText('Latest Value')).toBeInTheDocument(); - expect(screen.queryByText('Historical value')).toBeInTheDocument(); - expect(screen.queryByAltText('feeTrend-arrow')).toBeInTheDocument(); + expect(screen.getByText('123.12 GWEI')).toBeInTheDocument(); + }); + + it('should render the latest fee range if given a fee range', () => { + renderComponent({ + props: { + latest: ['123.456', '456.789'], + }, + }); + + expect(screen.getByText('123.46 - 456.79 GWEI')).toBeInTheDocument(); + }); + + it('should render a fee trend arrow image if given "up" as the trend', () => { + renderComponent({ + props: { + latest: '123.12345', + trend: 'up', + }, + }); + + expect(screen.getByAltText('up arrow')).toBeInTheDocument(); + }); + + it('should render a fee trend arrow image if given "down" as the trend', () => { + renderComponent({ + props: { + latest: '123.12345', + trend: 'down', + }, + }); + + expect(screen.getByAltText('down arrow')).toBeInTheDocument(); + }); + + it('should render a fee trend arrow image if given "level" as the trend', () => { + renderComponent({ + props: { + latest: '123.12345', + trend: 'level', + }, + }); + + expect(screen.getByAltText('level arrow')).toBeInTheDocument(); + }); + + it('should not render a fee trend arrow image if given an invalid trend', () => { + // Suppress warning from PropTypes, which we expect + jest.spyOn(console, 'error').mockImplementation(); + + renderComponent({ + props: { + latest: '123.12345', + trend: 'whatever', + }, + }); + + expect(screen.queryByTestId('fee-arrow')).not.toBeInTheDocument(); + }); + + it('should not render a fee trend arrow image if given a nullish trend', () => { + renderComponent({ + props: { + latest: '123.12345', + trend: null, + }, + }); + + expect(screen.queryByTestId('fee-arrow')).not.toBeInTheDocument(); + }); + }); + + describe('when "latest" is nullish', () => { + it('should not render the container for the latest fee', () => { + renderComponent({ + props: { + latest: null, + }, + }); + + expect(screen.queryByTestId('latest')).not.toBeInTheDocument(); + }); + }); + + describe('when "historical" is not nullish', () => { + it('should render the historical fee if given a fee', () => { + renderComponent({ + props: { + historical: '123.12345', + }, + }); + + expect(screen.getByText('123.12 GWEI')).toBeInTheDocument(); + }); + + it('should render the historical fee range if given a fee range', () => { + renderComponent({ + props: { + historical: ['123.456', '456.789'], + }, + }); + + expect(screen.getByText('123.46 - 456.79 GWEI')).toBeInTheDocument(); + }); + }); + + describe('when "historical" is nullish', () => { + it('should not render the container for the historical fee', () => { + renderComponent({ + props: { + historical: null, + }, + }); + + expect(screen.queryByTestId('historical')).not.toBeInTheDocument(); + }); }); }); diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/index.scss b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/index.scss index 7a3f06509..c78f2c999 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/index.scss +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-input-subtext/index.scss @@ -1,6 +1,4 @@ .advanced-gas-fee-input-subtext { - display: flex; - align-items: center; margin-top: 2px; color: var(--ui-4); font-size: $font-size-h8; diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.js index 00b7cc30b..ee3737431 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.js @@ -6,12 +6,8 @@ import { EDIT_GAS_MODES, PRIORITY_LEVELS, } from '../../../../../../shared/constants/gas'; -import { SECONDARY } from '../../../../../helpers/constants/common'; -import { - bnGreaterThan, - bnLessThan, - roundToDecimalPlacesRemovingExtraZeroes, -} from '../../../../../helpers/utils/util'; +import { PRIMARY } from '../../../../../helpers/constants/common'; +import { bnGreaterThan, bnLessThan } from '../../../../../helpers/utils/util'; import { decGWEIToHexWEI } from '../../../../../helpers/utils/conversions.util'; import { getAdvancedGasFeeValues } from '../../../../../selectors'; import { useGasFeeContext } from '../../../../../contexts/gasFee'; @@ -23,7 +19,6 @@ import FormField from '../../../../ui/form-field'; import { useAdvancedGasFeePopoverContext } from '../../context'; import AdvancedGasFeeInputSubtext from '../../advanced-gas-fee-input-subtext'; -import { renderFeeRange } from '../utils'; const validateBaseFee = (value, gasFeeEstimates, maxPriorityFeePerGas) => { if (bnGreaterThan(maxPriorityFeePerGas, value)) { @@ -57,6 +52,7 @@ const BaseFeeInput = () => { editGasMode, } = useGasFeeContext(); const { + gasLimit, maxPriorityFeePerGas, setErrorValue, setMaxFeePerGas, @@ -69,7 +65,7 @@ const BaseFeeInput = () => { baseFeeTrend, } = gasFeeEstimates; const [baseFeeError, setBaseFeeError] = useState(); - const { currency, numberOfDecimals } = useUserPreferencedCurrency(SECONDARY); + const { currency, numberOfDecimals } = useUserPreferencedCurrency(PRIMARY); const advancedGasFeeValues = useSelector(getAdvancedGasFeeValues); @@ -85,8 +81,8 @@ const BaseFeeInput = () => { return maxFeePerGas; }); - const [, { value: baseFeeInFiat }] = useCurrencyDisplay( - decGWEIToHexWEI(baseFee), + const [baseFeeInPrimaryCurrency] = useCurrencyDisplay( + decGWEIToHexWEI(baseFee * gasLimit), { currency, numberOfDecimals }, ); @@ -128,16 +124,13 @@ const BaseFeeInput = () => { titleUnit={`(${t('gwei')})`} tooltipText={t('advancedBaseGasFeeToolTip')} value={baseFee} - detailText={`≈ ${baseFeeInFiat}`} + detailText={`≈ ${baseFeeInPrimaryCurrency}`} numeric /> ); diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.test.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.test.js index cf8268354..dbec8b725 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.test.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/base-fee-input/base-fee-input.test.js @@ -12,6 +12,7 @@ import { GasFeeContextProvider } from '../../../../../contexts/gasFee'; import configureStore from '../../../../../store/store'; import { AdvancedGasFeePopoverContextProvider } from '../../context'; +import AdvancedGasFeeGasLimit from '../../advanced-gas-fee-gas-limit'; import BaseFeeInput from './base-fee-input'; jest.mock('../../../../../store/actions', () => ({ @@ -50,6 +51,7 @@ const render = (txProps, contextProps) => { > + , store, @@ -60,24 +62,24 @@ describe('BaseFeeInput', () => { it('should renders advancedGasFee.baseFee value if current estimate used is not custom', () => { render({ userFeeLevel: 'high', - txParams: { - maxFeePerGas: '0x2E90EDD000', - }, }); expect(document.getElementsByTagName('input')[0]).toHaveValue(100); }); - it('should not advancedGasFee.baseFee value for swaps', () => { + it('should not use advancedGasFee.baseFee value for swaps', () => { render( { userFeeLevel: 'high', - txParams: { - maxFeePerGas: '0x2E90EDD000', - }, }, { editGasMode: EDIT_GAS_MODES.SWAPS }, ); - expect(document.getElementsByTagName('input')[0]).toHaveValue(200); + expect(document.getElementsByTagName('input')[0]).toHaveValue( + parseInt( + mockEstimates[GAS_ESTIMATE_TYPES.FEE_MARKET].gasFeeEstimates.high + .suggestedMaxFeePerGas, + 10, + ), + ); }); it('should renders baseFee values from transaction if current estimate used is custom', () => { @@ -88,22 +90,27 @@ describe('BaseFeeInput', () => { }); expect(document.getElementsByTagName('input')[0]).toHaveValue(200); }); - it('should show current value of estimatedBaseFee in subtext', () => { + + it('should show current value of estimatedBaseFee in users primary currency in right side of input box', () => { render({ txParams: { - maxFeePerGas: '0x174876E800', + gas: '0x5208', + maxFeePerGas: '0x2E90EDD000', }, }); + expect(screen.queryByText('≈ 0.0042 ETH')).toBeInTheDocument(); + }); + + it('should show current value of estimatedBaseFee in subtext', () => { + render(); expect(screen.queryByText('50 GWEI')).toBeInTheDocument(); }); + it('should show 12hr range value in subtext', () => { - render({ - txParams: { - maxFeePerGas: '0x174876E800', - }, - }); + render(); expect(screen.queryByText('50 - 100 GWEI')).toBeInTheDocument(); }); + it('should show error if base fee is less than suggested low value', () => { render({ txParams: { diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.js index de223da10..a2b13fe94 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.js @@ -6,7 +6,7 @@ import { EDIT_GAS_MODES, PRIORITY_LEVELS, } from '../../../../../../shared/constants/gas'; -import { SECONDARY } from '../../../../../helpers/constants/common'; +import { PRIMARY } from '../../../../../helpers/constants/common'; import { decGWEIToHexWEI } from '../../../../../helpers/utils/conversions.util'; import { getAdvancedGasFeeValues } from '../../../../../selectors'; import { useCurrencyDisplay } from '../../../../../hooks/useCurrencyDisplay'; @@ -19,7 +19,6 @@ import { bnGreaterThan, bnLessThan } from '../../../../../helpers/utils/util'; import { useAdvancedGasFeePopoverContext } from '../../context'; import AdvancedGasFeeInputSubtext from '../../advanced-gas-fee-input-subtext'; -import { renderFeeRange } from '../utils'; const validatePriorityFee = (value, gasFeeEstimates) => { if (value <= 0) { @@ -48,6 +47,7 @@ const PriorityFeeInput = () => { const t = useI18nContext(); const advancedGasFeeValues = useSelector(getAdvancedGasFeeValues); const { + gasLimit, setErrorValue, setMaxPriorityFeePerGas, } = useAdvancedGasFeePopoverContext(); @@ -75,10 +75,10 @@ const PriorityFeeInput = () => { return maxPriorityFeePerGas; }); - const { currency, numberOfDecimals } = useUserPreferencedCurrency(SECONDARY); + const { currency, numberOfDecimals } = useUserPreferencedCurrency(PRIMARY); - const [, { value: priorityFeeInFiat }] = useCurrencyDisplay( - decGWEIToHexWEI(priorityFee), + const [priorityFeeInPrimaryCurrency] = useCurrencyDisplay( + decGWEIToHexWEI(priorityFee * gasLimit), { currency, numberOfDecimals }, ); @@ -112,13 +112,13 @@ const PriorityFeeInput = () => { titleUnit={`(${t('gwei')})`} tooltipText={t('advancedPriorityFeeToolTip')} value={priorityFee} - detailText={`≈ ${priorityFeeInFiat}`} + detailText={`≈ ${priorityFeeInPrimaryCurrency}`} numeric /> ); diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.test.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.test.js index 91b875ea8..31ceb6821 100644 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.test.js +++ b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/priority-fee-input/priority-fee-input.test.js @@ -12,6 +12,7 @@ import { GasFeeContextProvider } from '../../../../../contexts/gasFee'; import configureStore from '../../../../../store/store'; import { AdvancedGasFeePopoverContextProvider } from '../../context'; +import AdvancedGasFeeGasLimit from '../../advanced-gas-fee-gas-limit'; import PriorityfeeInput from './priority-fee-input'; jest.mock('../../../../../store/actions', () => ({ @@ -50,6 +51,7 @@ const render = (txProps, contextProps) => { > + , store, @@ -60,24 +62,24 @@ describe('PriorityfeeInput', () => { it('should renders advancedGasFee.priorityfee value if current estimate used is not custom', () => { render({ userFeeLevel: 'high', - txParams: { - maxFeePerGas: '0x2E90EDD000', - }, }); expect(document.getElementsByTagName('input')[0]).toHaveValue(100); }); - it('should not advancedGasFee.baseFee value for swaps', () => { + it('should not use advancedGasFee.priorityfee value for swaps', () => { render( { userFeeLevel: 'high', - txParams: { - maxFeePerGas: '0x2E90EDD000', - }, }, { editGasMode: EDIT_GAS_MODES.SWAPS }, ); - expect(document.getElementsByTagName('input')[0]).toHaveValue(200); + expect(document.getElementsByTagName('input')[0]).toHaveValue( + parseInt( + mockEstimates[GAS_ESTIMATE_TYPES.FEE_MARKET].gasFeeEstimates.high + .suggestedMaxPriorityFeePerGas, + 10, + ), + ); }); it('should renders priorityfee value from transaction if current estimate used is custom', () => { @@ -88,22 +90,27 @@ describe('PriorityfeeInput', () => { }); expect(document.getElementsByTagName('input')[0]).toHaveValue(2); }); + it('should show current priority fee range in subtext', () => { - render({ - txParams: { - maxFeePerGas: '0x174876E800', - }, - }); + render(); expect(screen.queryByText('1 - 20 GWEI')).toBeInTheDocument(); }); - it('should show 12hr range value in subtext', () => { + + it('should show current value of priority fee in users primary currency in right side of input box', () => { render({ txParams: { - maxFeePerGas: '0x174876E800', + gas: '0x5208', + maxPriorityFeePerGas: '0x77359400', }, }); + expect(screen.queryByText('≈ 0.000042 ETH')).toBeInTheDocument(); + }); + + it('should show 12hr range value in subtext', () => { + render(); expect(screen.queryByText('2 - 125 GWEI')).toBeInTheDocument(); }); + it('should show error if value entered is 0', () => { render({ txParams: { diff --git a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/utils.js b/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/utils.js deleted file mode 100644 index 8782628f8..000000000 --- a/ui/components/app/advanced-gas-fee-popover/advanced-gas-fee-inputs/utils.js +++ /dev/null @@ -1,13 +0,0 @@ -import { uniq } from 'lodash'; - -import { roundToDecimalPlacesRemovingExtraZeroes } from '../../../../helpers/utils/util'; - -export const renderFeeRange = (feeRange) => { - if (feeRange) { - const formattedRange = uniq( - feeRange.map((fee) => roundToDecimalPlacesRemovingExtraZeroes(fee, 2)), - ).join(' - '); - return `${formattedRange} GWEI`; - } - return null; -}; diff --git a/ui/components/app/app-components.scss b/ui/components/app/app-components.scss index c11ff6027..664aa9523 100644 --- a/ui/components/app/app-components.scss +++ b/ui/components/app/app-components.scss @@ -1,6 +1,7 @@ /** Please import your files in alphabetical order **/ @import 'account-list-item/index'; @import 'account-menu/index'; +@import 'add-network/index'; @import 'app-loading-spinner/index'; @import 'import-token-link/index'; @import 'advanced-gas-controls/index'; @@ -30,6 +31,7 @@ @import 'edit-gas-fee-popover/edit-gas-tooltip/index'; @import 'flask/experimental-area/index'; @import 'flask/snap-install-warning/index'; +@import 'flask/snap-remove-warning/index'; @import 'flask/snap-settings-card/index'; @import 'flask/snaps-authorship-pill/index'; @import 'gas-customization/gas-modal-page-container/index'; @@ -54,6 +56,7 @@ @import 'selected-account/index'; @import 'signature-request/index'; @import 'signature-request-original/index'; +@import 'srp-input/srp-input'; @import 'tab-bar/index'; @import 'token-cell/token-cell'; @import 'token-list-display/token-list-display'; diff --git a/ui/components/app/app-header/app-header.component.js b/ui/components/app/app-header/app-header.component.js index 1694362c6..561ab518d 100644 --- a/ui/components/app/app-header/app-header.component.js +++ b/ui/components/app/app-header/app-header.component.js @@ -124,7 +124,6 @@ export default class AppHeader extends PureComponent { this.handleNetworkIndicatorClick(event)} disabled={disabled || disableNetworkIndicator} /> diff --git a/ui/components/app/app-header/index.scss b/ui/components/app/app-header/index.scss index 1cdd03b28..0e7c26f8e 100644 --- a/ui/components/app/app-header/index.scss +++ b/ui/components/app/app-header/index.scss @@ -97,11 +97,4 @@ width: 0; justify-content: flex-end; } - - &__network-down-arrow { - background-image: url(/images/icons/caret-down.svg); - background-repeat: no-repeat; - background-size: contain; - background-position: center; - } } diff --git a/ui/components/app/asset-list/asset-list.js b/ui/components/app/asset-list/asset-list.js index 193b22619..c0b1347d0 100644 --- a/ui/components/app/asset-list/asset-list.js +++ b/ui/components/app/asset-list/asset-list.js @@ -100,7 +100,7 @@ const AssetList = ({ onClickAsset }) => { diff --git a/ui/components/app/collectible-details/collectible-details.js b/ui/components/app/collectible-details/collectible-details.js index 195953545..be538d852 100644 --- a/ui/components/app/collectible-details/collectible-details.js +++ b/ui/components/app/collectible-details/collectible-details.js @@ -18,11 +18,7 @@ import { BLOCK_SIZES, } from '../../../helpers/constants/design-system'; import { useI18nContext } from '../../../hooks/useI18nContext'; -import { - getAssetImageURL, - isEqualCaseInsensitive, - shortenAddress, -} from '../../../helpers/utils/util'; +import { getAssetImageURL, shortenAddress } from '../../../helpers/utils/util'; import { getCurrentChainId, getIpfsGateway, @@ -54,6 +50,7 @@ import InfoTooltip from '../../ui/info-tooltip'; import { ERC721 } from '../../../helpers/constants/common'; import { usePrevious } from '../../../hooks/usePrevious'; import { useCopyToClipboard } from '../../../hooks/useCopyToClipboard'; +import { isEqualCaseInsensitive } from '../../../../shared/modules/string-utils'; export default function CollectibleDetails({ collectible }) { const { @@ -187,7 +184,7 @@ export default function CollectibleDetails({ collectible }) { >
@@ -229,7 +226,7 @@ export default function CollectibleDetails({ collectible }) { diff --git a/ui/components/app/collectibles-tab/collectibles-tab.js b/ui/components/app/collectibles-tab/collectibles-tab.js index 5f2703dd2..4252ba1f0 100644 --- a/ui/components/app/collectibles-tab/collectibles-tab.js +++ b/ui/components/app/collectibles-tab/collectibles-tab.js @@ -83,7 +83,7 @@ export default function CollectiblesTab({ onAddNFT }) { className="collectibles-tab__link" > @@ -134,7 +134,7 @@ export default function CollectiblesTab({ onAddNFT }) { )} diff --git a/ui/components/app/confirm-page-container/confirm-page-container-container.test.js b/ui/components/app/confirm-page-container/confirm-page-container-container.test.js index 92fa00dc4..da2025e12 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-container.test.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-container.test.js @@ -42,6 +42,7 @@ describe('Confirm Page Container Container Test', () => { identities: [], featureFlags: {}, enableEIP1559V2NoticeDismissed: true, + tokenList: {}, }, }; diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js index 665d1924f..16f89f91e 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js @@ -2,9 +2,16 @@ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { Tabs, Tab } from '../../../ui/tabs'; -import ErrorMessage from '../../../ui/error-message'; +import Button from '../../../ui/button'; import ActionableMessage from '../../../ui/actionable-message/actionable-message'; import { PageContainerFooter } from '../../../ui/page-container'; +import ErrorMessage from '../../../ui/error-message'; +import { INSUFFICIENT_FUNDS_ERROR_KEY } from '../../../../helpers/constants/error-keys'; +import Typography from '../../../ui/typography'; +import { TYPOGRAPHY } from '../../../../helpers/constants/design-system'; +import { TRANSACTION_TYPES } from '../../../../../shared/constants/transaction'; +import { MAINNET_CHAIN_ID } from '../../../../../shared/constants/network'; + import { ConfirmPageContainerSummary, ConfirmPageContainerWarning } from '.'; export default class ConfirmPageContainerContent extends Component { @@ -21,7 +28,7 @@ export default class ConfirmPageContainerContent extends Component { errorMessage: PropTypes.string, hasSimulationError: PropTypes.bool, hideSubtitle: PropTypes.bool, - identiconAddress: PropTypes.string, + tokenAddress: PropTypes.string, nonce: PropTypes.string, subtitleComponent: PropTypes.node, title: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), @@ -44,6 +51,12 @@ export default class ConfirmPageContainerContent extends Component { hideTitle: PropTypes.bool, supportsEIP1559V2: PropTypes.bool, hasTopBorder: PropTypes.bool, + currentTransaction: PropTypes.string, + nativeCurrency: PropTypes.string, + networkName: PropTypes.string, + showBuyModal: PropTypes.func, + toAddress: PropTypes.string, + transactionType: PropTypes.string, }; renderContent() { @@ -93,7 +106,7 @@ export default class ConfirmPageContainerContent extends Component { titleComponent, subtitleComponent, hideSubtitle, - identiconAddress, + tokenAddress, nonce, detailsComponent, dataComponent, @@ -113,6 +126,12 @@ export default class ConfirmPageContainerContent extends Component { hideUserAcknowledgedGasMissing, supportsEIP1559V2, hasTopBorder, + currentTransaction, + nativeCurrency, + networkName, + showBuyModal, + toAddress, + transactionType, } = this.props; const primaryAction = hideUserAcknowledgedGasMissing @@ -121,6 +140,14 @@ export default class ConfirmPageContainerContent extends Component { label: this.context.t('tryAnywayOption'), onClick: setUserAcknowledgedGasMissing, }; + const { t } = this.context; + + const showInsuffienctFundsError = + supportsEIP1559V2 && + !hasSimulationError && + (errorKey || errorMessage) && + errorKey === INSUFFICIENT_FUNDS_ERROR_KEY && + currentTransaction.type === TRANSACTION_TYPES.SIMPLE_SEND; return (
)} @@ -152,19 +179,63 @@ export default class ConfirmPageContainerContent extends Component { titleComponent={titleComponent} subtitleComponent={subtitleComponent} hideSubtitle={hideSubtitle} - identiconAddress={identiconAddress} + tokenAddress={tokenAddress} nonce={nonce} origin={origin} hideTitle={hideTitle} + toAddress={toAddress} + transactionType={transactionType} /> {this.renderContent()} {!supportsEIP1559V2 && !hasSimulationError && - (errorKey || errorMessage) && ( + (errorKey || errorMessage) && + currentTransaction.type !== TRANSACTION_TYPES.SIMPLE_SEND && (
)} + {showInsuffienctFundsError && ( +
+ {currentTransaction.chainId === MAINNET_CHAIN_ID ? ( + + {t('insufficientCurrency', [nativeCurrency, networkName])} + + + {t('orDeposit')} + + } + useIcon + iconFillColor="#d73a49" + type="danger" + /> + ) : ( + + {t('insufficientCurrency', [nativeCurrency, networkName])} + {t('buyOther', [nativeCurrency])} + + } + useIcon + iconFillColor="#d73a49" + type="danger" + /> + )} +
+ )} + { metamask: { provider: { type: 'test', + chainId: '0x3', }, eip1559V2Enabled: false, + addressBook: { + '0x3': { + '0x06195827297c7A80a443b6894d3BDB8824b43896': { + address: '0x06195827297c7A80a443b6894d3BDB8824b43896', + name: 'Address Book Account 1', + chainId: '0x3', + }, + }, + }, }, }; @@ -75,6 +86,9 @@ describe('Confirm Page Container Content', () => { props.hasSimulationError = false; props.disabled = true; props.errorKey = TRANSACTION_ERROR_KEY; + props.currentTransaction = { + type: 'transfer', + }; const { queryByText, getByText } = renderWithProvider( , store, @@ -122,4 +136,30 @@ describe('Confirm Page Container Content', () => { fireEvent.click(cancelButton); expect(props.onCancel).toHaveBeenCalledTimes(1); }); + + it('render contract address name from addressBook in title for contract', async () => { + props.hasSimulationError = false; + props.disabled = false; + props.toAddress = '0x06195827297c7A80a443b6894d3BDB8824b43896'; + props.transactionType = TRANSACTION_TYPES.CONTRACT_INTERACTION; + const { queryByText } = renderWithProvider( + , + store, + ); + + expect(queryByText('Address Book Account 1')).toBeInTheDocument(); + }); + + it('render simple title without address name for simple send', async () => { + props.hasSimulationError = false; + props.disabled = false; + props.toAddress = '0x06195827297c7A80a443b6894d3BDB8824b43896'; + props.transactionType = TRANSACTION_TYPES.SIMPLE_SEND; + const { queryByText } = renderWithProvider( + , + store, + ); + + expect(queryByText('Address Book Account 1')).not.toBeInTheDocument(); + }); }); diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js index d4878442f..7da4ddeba 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js @@ -1,8 +1,18 @@ /* eslint-disable no-negated-condition */ -import React from 'react'; +import React, { useState } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; + +import { TRANSACTION_TYPES } from '../../../../../../shared/constants/transaction'; +import { toChecksumHexAddress } from '../../../../../../shared/modules/hexstring-utils'; +import { useI18nContext } from '../../../../../hooks/useI18nContext'; +import useAddressDetails from '../../../../../hooks/useAddressDetails'; + import Identicon from '../../../../ui/identicon'; +import InfoTooltip from '../../../../ui/info-tooltip'; +import NicknamePopovers from '../../../modals/nickname-popovers'; +import Typography from '../../../../ui/typography'; +import { TYPOGRAPHY } from '../../../../../helpers/constants/design-system'; const ConfirmPageContainerSummary = (props) => { const { @@ -12,13 +22,41 @@ const ConfirmPageContainerSummary = (props) => { subtitleComponent, hideSubtitle, className, - identiconAddress, + tokenAddress, + toAddress, nonce, origin, hideTitle, image, + transactionType, } = props; + const [showNicknamePopovers, setShowNicknamePopovers] = useState(false); + const t = useI18nContext(); + + const contractInitiatedTransactionType = [ + TRANSACTION_TYPES.CONTRACT_INTERACTION, + TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, + ]; + const isContractTypeTransaction = contractInitiatedTransactionType.includes( + transactionType, + ); + let contractAddress; + if (isContractTypeTransaction) { + // If the transaction is TOKEN_METHOD_TRANSFER or TOKEN_METHOD_TRANSFER_FROM + // the contract address is passed down as tokenAddress, if it is anyother + // type of contract interaction it is passed as toAddress + contractAddress = + transactionType === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER || + transactionType === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM + ? tokenAddress + : toAddress; + } + + const { toName, isTrusted } = useAddressDetails(contractAddress); + const checksummedAddress = toChecksumHexAddress(contractAddress); + const renderImage = () => { if (image) { return ( @@ -28,12 +66,12 @@ const ConfirmPageContainerSummary = (props) => { src={image} /> ); - } else if (identiconAddress) { + } else if (contractAddress) { return ( ); @@ -47,7 +85,29 @@ const ConfirmPageContainerSummary = (props) => {
{origin}
)}
-
{action}
+
+ {isContractTypeTransaction && toName && ( + + + : + + )} + + {action} + + {isContractTypeTransaction && isTrusted === false && ( + + )} +
{nonce && (
{`#${nonce}`} @@ -58,9 +118,15 @@ const ConfirmPageContainerSummary = (props) => {
{renderImage()} {!hideTitle ? ( -
+ {titleComponent || title} -
+ ) : null}
{hideSubtitle ? null : ( @@ -69,6 +135,12 @@ const ConfirmPageContainerSummary = (props) => {
)} + {showNicknamePopovers && ( + setShowNicknamePopovers(false)} + address={checksummedAddress} + /> + )}
); }; @@ -81,10 +153,12 @@ ConfirmPageContainerSummary.propTypes = { subtitleComponent: PropTypes.node, hideSubtitle: PropTypes.bool, className: PropTypes.string, - identiconAddress: PropTypes.string, + tokenAddress: PropTypes.string, + toAddress: PropTypes.string, nonce: PropTypes.string, origin: PropTypes.string.isRequired, hideTitle: PropTypes.bool, + transactionType: PropTypes.string, }; export default ConfirmPageContainerSummary; diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/index.scss b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/index.scss index d8f7a307c..53fb24a22 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/index.scss +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/index.scss @@ -23,12 +23,36 @@ &__action { @include H7; - text-transform: uppercase; color: var(--oslo-gray); padding: 3px 8px; border: 1px solid var(--oslo-gray); border-radius: 4px; - display: inline-block; + display: inline-flex; + align-items: center; + + &__name { + text-transform: uppercase; + } + + .info-tooltip { + margin-inline-start: 4px; + + &__tooltip-container { + margin-bottom: -3px; + } + } + + &__contract-address { + margin-inline-end: 4px; + } + + &__contract-address-btn { + background: none; + border: none; + padding: 0; + margin-inline-end: 4px; + color: var(--primary-1); + } } &__nonce { @@ -53,6 +77,14 @@ text-overflow: ellipsis; } + &__title-text-long { + @include H3; + + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + &__subtitle { @include H5; diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/index.scss b/ui/components/app/confirm-page-container/confirm-page-container-content/index.scss index b932af183..f52888db2 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/index.scss +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/index.scss @@ -100,4 +100,12 @@ &__total-value { position: relative; } + + &__link { + background: transparent; + border: 0 transparent; + display: inline; + padding: 0; + font-size: $font-size-h7; + } } diff --git a/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js b/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js index 2d1ff99b0..eb33888e1 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js @@ -7,6 +7,7 @@ import { import { getEnvironmentType } from '../../../../../app/scripts/lib/util'; import NetworkDisplay from '../../network-display'; import Identicon from '../../../ui/identicon'; +import IconCaretLeft from '../../../ui/icon/icon-caret-left'; import { shortenAddress } from '../../../../helpers/utils/util'; import AccountMismatchWarning from '../../../ui/account-mismatch-warning/account-mismatch-warning.component'; import { useI18nContext } from '../../../../hooks/useI18nContext'; @@ -47,7 +48,7 @@ export default function ConfirmPageContainerHeader({ visibility: showEdit ? 'initial' : 'hidden', }} > - + onEdit()} diff --git a/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.stories.js b/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.stories.js new file mode 100644 index 000000000..2c8196b3b --- /dev/null +++ b/ui/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.stories.js @@ -0,0 +1,35 @@ +import React from 'react'; +import ConfirmPageContainerHeader from '.'; + +export default { + title: 'Components/App/ConfirmPageContainer/ConfirmPageContainerHeader', + id: __filename, + argTypes: { + accountAddress: { + control: 'text', + }, + showAccountInHeader: { + control: 'boolean', + }, + showEdit: { + control: 'boolean', + }, + onEdit: { + action: 'onEdit', + }, + children: { + control: 'text', + }, + }, +}; + +export const DefaultStory = (args) => ; + +DefaultStory.storyName = 'Default'; + +DefaultStory.args = { + showEdit: false, + showAccountInHeader: false, + accountAddress: '0xB8c77482e45F1F44dE1745F52C74426C631bDD52', + children: 'children', +}; diff --git a/ui/components/app/confirm-page-container/confirm-page-container-header/index.scss b/ui/components/app/confirm-page-container/confirm-page-container-header/index.scss index 0ad152205..1ffb8707a 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-header/index.scss +++ b/ui/components/app/confirm-page-container/confirm-page-container-header/index.scss @@ -21,6 +21,7 @@ display: flex; justify-content: center; align-items: center; + color: var(--color-primary-default); [dir='rtl'] & img { transform: rotate(180deg); @@ -30,7 +31,6 @@ &__back-button { @include Paragraph; - color: #2f9ae0; cursor: pointer; padding-left: 5px; } diff --git a/ui/components/app/confirm-page-container/confirm-page-container.component.js b/ui/components/app/confirm-page-container/confirm-page-container.component.js index 10f326594..641230df8 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container.component.js @@ -4,10 +4,15 @@ import PropTypes from 'prop-types'; import { EDIT_GAS_MODES } from '../../../../shared/constants/gas'; import { GasFeeContextProvider } from '../../../contexts/gasFee'; import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction'; +import { + NETWORK_TO_NAME_MAP, + MAINNET_CHAIN_ID, +} from '../../../../shared/constants/network'; import { PageContainerFooter } from '../../ui/page-container'; import Dialog from '../../ui/dialog'; -import ErrorMessage from '../../ui/error-message'; +import Button from '../../ui/button'; +import ActionableMessage from '../../ui/actionable-message/actionable-message'; import SenderToRecipient from '../../ui/sender-to-recipient'; import NicknamePopovers from '../modals/nickname-popovers'; @@ -15,6 +20,10 @@ import NicknamePopovers from '../modals/nickname-popovers'; import AdvancedGasFeePopover from '../advanced-gas-fee-popover'; import EditGasFeePopover from '../edit-gas-fee-popover/edit-gas-fee-popover'; import EditGasPopover from '../edit-gas-popover'; +import ErrorMessage from '../../ui/error-message'; +import { INSUFFICIENT_FUNDS_ERROR_KEY } from '../../../helpers/constants/error-keys'; +import Typography from '../../ui/typography'; +import { TYPOGRAPHY } from '../../../helpers/constants/design-system'; import EnableEIP1559V2Notice from './enableEIP1559V2-notice'; import { @@ -58,7 +67,7 @@ export default class ConfirmPageContainer extends Component { dataComponent: PropTypes.node, dataHexComponent: PropTypes.node, detailsComponent: PropTypes.node, - identiconAddress: PropTypes.string, + tokenAddress: PropTypes.string, nonce: PropTypes.string, warning: PropTypes.string, unapprovedTxCount: PropTypes.number, @@ -87,6 +96,8 @@ export default class ConfirmPageContainer extends Component { contact: PropTypes.object, isOwnedAccount: PropTypes.bool, supportsEIP1559V2: PropTypes.bool, + nativeCurrency: PropTypes.string, + showBuyModal: PropTypes.func, }; render() { @@ -115,7 +126,7 @@ export default class ConfirmPageContainer extends Component { onCancelAll, onCancel, onSubmit, - identiconAddress, + tokenAddress, nonce, unapprovedTxCount, warning, @@ -139,6 +150,8 @@ export default class ConfirmPageContainer extends Component { contact = {}, isOwnedAccount, supportsEIP1559V2, + nativeCurrency, + showBuyModal, } = this.props; const showAddToAddressDialog = @@ -152,6 +165,10 @@ export default class ConfirmPageContainer extends Component { currentTransaction.type === TRANSACTION_TYPES.DEPLOY_CONTRACT) && currentTransaction.txParams?.value === '0x0'; + const networkName = NETWORK_TO_NAME_MAP[currentTransaction.chainId]; + + const { t } = this.context; + return (
@@ -192,7 +209,7 @@ export default class ConfirmPageContainer extends Component { className="send__dialog" onClick={() => this.setState({ showNicknamePopovers: true })} > - {this.context.t('newAccountDetectedDialogMessage')} + {t('newAccountDetectedDialogMessage')} {this.state.showNicknamePopovers ? ( )} - {shouldDisplayWarning && ( + {shouldDisplayWarning && errorKey === INSUFFICIENT_FUNDS_ERROR_KEY && ( +
+ {currentTransaction.chainId === MAINNET_CHAIN_ID ? ( + + {t('insufficientCurrency', [nativeCurrency, networkName])} + + + {t('orDeposit')} + + } + useIcon + iconFillColor="#d73a49" + type="danger" + /> + ) : ( + + {t('insufficientCurrency', [nativeCurrency, networkName])} + {t('buyOther', [nativeCurrency])} + + } + useIcon + iconFillColor="#d73a49" + type="danger" + /> + )} +
+ )} + {shouldDisplayWarning && errorKey !== INSUFFICIENT_FUNDS_ERROR_KEY && (
@@ -245,14 +309,14 @@ export default class ConfirmPageContainer extends Component { {contentComponent && ( {unapprovedTxCount > 1 && ( - {this.context.t('rejectTxsN', [unapprovedTxCount])} + {t('rejectTxsN', [unapprovedTxCount])} )} diff --git a/ui/components/app/confirm-page-container/confirm-page-container.container.js b/ui/components/app/confirm-page-container/confirm-page-container.container.js index ec5ba84c0..d0d287aed 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container.container.js +++ b/ui/components/app/confirm-page-container/confirm-page-container.container.js @@ -1,5 +1,6 @@ import { connect } from 'react-redux'; import { getAccountsWithLabels, getAddressBookEntry } from '../../../selectors'; +import { showModal } from '../../../store/actions'; import ConfirmPageContainer from './confirm-page-container.component'; function mapStateToProps(state, ownProps) { @@ -16,4 +17,13 @@ function mapStateToProps(state, ownProps) { }; } -export default connect(mapStateToProps)(ConfirmPageContainer); +const mapDispatchToProps = (dispatch) => { + return { + showBuyModal: () => dispatch(showModal({ name: 'DEPOSIT_ETHER' })), + }; +}; + +export default connect( + mapStateToProps, + mapDispatchToProps, +)(ConfirmPageContainer); diff --git a/ui/components/app/confirm-page-container/enableEIP1559V2-notice/enableEIP1559V2-notice.js b/ui/components/app/confirm-page-container/enableEIP1559V2-notice/enableEIP1559V2-notice.js index f0b92ff03..b9019424e 100644 --- a/ui/components/app/confirm-page-container/enableEIP1559V2-notice/enableEIP1559V2-notice.js +++ b/ui/components/app/confirm-page-container/enableEIP1559V2-notice/enableEIP1559V2-notice.js @@ -50,7 +50,7 @@ export default function EnableEIP1559V2Notice({ isFirstAlert }) { { - let newSeedPhraseError = ''; - - if (rawSeedPhrase) { - const parsedSeedPhrase = parseSecretRecoveryPhrase(rawSeedPhrase); - const wordCount = parsedSeedPhrase.split(/\s/u).length; - if (wordCount % 3 !== 0 || wordCount > 24 || wordCount < 12) { - newSeedPhraseError = t('seedPhraseReq'); - } else if (!isValidMnemonic(parsedSeedPhrase)) { - newSeedPhraseError = t('invalidSeedPhrase'); - } - } - - setSeedPhrase(rawSeedPhrase); - setSeedPhraseError(newSeedPhraseError); - }, - [setSeedPhrase, setSeedPhraseError, t], - ); - const onPasswordChange = useCallback( (newPassword) => { let newConfirmPasswordError = ''; @@ -93,8 +66,7 @@ export default function CreateNewVault({ seedPhrase && (!includeTerms || termsChecked) && !passwordError && - !confirmPasswordError && - !seedPhraseError; + !confirmPasswordError; const onImport = useCallback( async (event) => { @@ -104,7 +76,7 @@ export default function CreateNewVault({ return; } - await onSubmit(password, parseSecretRecoveryPhrase(seedPhrase)); + await onSubmit(password, seedPhrase); }, [isValid, onSubmit, password, seedPhrase], ); @@ -121,10 +93,6 @@ export default function CreateNewVault({ setTermsChecked((currentTermsChecked) => !currentTermsChecked); }, [metricsEvent]); - const toggleShowSeedPhrase = useCallback(() => { - setShowSeedPhrase((currentShowSeedPhrase) => !currentShowSeedPhrase); - }, []); - const termsOfUse = t('acceptTermsOfUse', [
- - {showSeedPhrase ? ( -