Merge pull request #12732 from MetaMask/Version-v10.7.0

Version v10.7.0 RC
feature/default_network_editable
Dan J Miller 3 years ago committed by GitHub
commit 91f0ec1bab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      .circleci/config.yml
  2. 70
      .github/workflows/codeql-analysis.yml
  3. 2
      .prettierignore
  4. 29
      CHANGELOG.md
  5. 14
      README.md
  6. 53
      app/_locales/en/messages.json
  7. 2
      app/_locales/zh_CN/messages.json
  8. 4
      app/build-types/beta/manifest/_base.json
  9. 4
      app/build-types/flask/manifest/_base.json
  10. 71
      app/scripts/background.js
  11. 15
      app/scripts/controllers/network/createInfuraClient.js
  12. 16
      app/scripts/controllers/network/createJsonRpcClient.js
  13. 5
      app/scripts/controllers/network/createMetamaskMiddleware.js
  14. 4
      app/scripts/controllers/network/network.js
  15. 11
      app/scripts/controllers/preferences.js
  16. 24
      app/scripts/controllers/preferences.test.js
  17. 2
      app/scripts/controllers/swaps.js
  18. 2
      app/scripts/controllers/threebox.js
  19. 5
      app/scripts/controllers/transactions/index.js
  20. 11
      app/scripts/controllers/transactions/index.test.js
  21. 5
      app/scripts/lib/buy-eth-url.js
  22. 7
      app/scripts/lib/buy-eth-url.test.js
  23. 14
      app/scripts/lib/decrypt-message-manager.js
  24. 14
      app/scripts/lib/encryption-public-key-manager.js
  25. 16
      app/scripts/lib/message-manager.js
  26. 5
      app/scripts/lib/message-manager.test.js
  27. 16
      app/scripts/lib/notification-manager.js
  28. 16
      app/scripts/lib/personal-message-manager.js
  29. 3
      app/scripts/lib/personal-message-manager.test.js
  30. 37
      app/scripts/lib/rpc-method-middleware/createMethodMiddleware.js
  31. 8
      app/scripts/lib/rpc-method-middleware/handlers/add-ethereum-chain.js
  32. 3
      app/scripts/lib/rpc-method-middleware/handlers/get-provider-state.js
  33. 5
      app/scripts/lib/rpc-method-middleware/handlers/log-web3-shim-usage.js
  34. 7
      app/scripts/lib/rpc-method-middleware/handlers/switch-ethereum-chain.js
  35. 3
      app/scripts/lib/rpc-method-middleware/handlers/watch-asset.js
  36. 17
      app/scripts/lib/typed-message-manager.js
  37. 1
      app/scripts/lib/typed-message-manager.test.js
  38. 33
      app/scripts/metamask-controller.js
  39. 4
      app/scripts/platforms/extension.js
  40. 3
      development/build/README.md
  41. 11
      development/build/index.js
  42. 64
      development/build/scripts.js
  43. 4
      development/build/task.js
  44. 13
      development/generate-lavamoat-policies.sh
  45. 7
      development/verify-locale-strings.js
  46. 0
      lavamoat/browserify/beta/policy-override.json
  47. 5
      lavamoat/browserify/beta/policy.json
  48. 55
      lavamoat/browserify/flask/policy-override.json
  49. 4772
      lavamoat/browserify/flask/policy.json
  50. 55
      lavamoat/browserify/main/policy-override.json
  51. 4772
      lavamoat/browserify/main/policy.json
  52. 0
      lavamoat/build-system/policy-override.json
  53. 0
      lavamoat/build-system/policy.json
  54. 20
      package.json
  55. 4
      shared/constants/metametrics.js
  56. 10
      shared/constants/network.js
  57. 4
      test/data/mock-state.json
  58. 95
      test/e2e/tests/from-import-ui.spec.js
  59. 176
      test/e2e/tests/metamask-responsive-ui.spec.js
  60. 64
      test/e2e/tests/provider-api.spec.js
  61. 8
      test/e2e/webdriver/driver.js
  62. 7
      test/stub/provider.js
  63. 10
      ui/components/app/confirm-page-container/confirm-page-container-container.test.js
  64. 185
      ui/components/app/confirm-page-container/confirm-page-container.component.js
  65. 27
      ui/components/app/gas-timing/gas-timing.component.js
  66. 5
      ui/components/app/gas-timing/index.scss
  67. 4
      ui/components/app/modals/account-details-modal/account-details-modal.component.js
  68. 4
      ui/components/app/modals/account-details-modal/index.scss
  69. 2
      ui/components/app/modals/modal.js
  70. 6
      ui/components/app/multilayer-fee-message/multi-layer-fee-message.js
  71. 45
      ui/components/app/signature-request-original/signature-request-original.component.js
  72. 6
      ui/components/app/signature-request-original/signature-request-original.container.js
  73. 32
      ui/components/app/signature-request/signature-request.component.js
  74. 13
      ui/components/app/signature-request/signature-request.container.js
  75. 11
      ui/components/app/transaction-detail-item/index.scss
  76. 26
      ui/components/app/transaction-detail-item/transaction-detail-item.component.js
  77. 51
      ui/components/app/transaction-detail/index.scss
  78. 83
      ui/components/app/transaction-detail/transaction-detail.component.js
  79. 94
      ui/components/app/transaction-detail/transaction-detail.component.test.js
  80. 42
      ui/components/ui/card/README.mdx
  81. 23
      ui/components/ui/card/card.component.js
  82. 21
      ui/components/ui/card/card.component.test.js
  83. 60
      ui/components/ui/card/card.js
  84. 169
      ui/components/ui/card/card.stories.js
  85. 11
      ui/components/ui/card/card.test.js
  86. 2
      ui/components/ui/card/index.js
  87. 11
      ui/components/ui/card/index.scss
  88. 15
      ui/components/ui/chip/README.mdx
  89. 3
      ui/components/ui/chip/chip-with-input.js
  90. 42
      ui/components/ui/chip/chip.js
  91. 5
      ui/components/ui/chip/chip.scss
  92. 125
      ui/components/ui/chip/chip.stories.js
  93. 3
      ui/components/ui/form-field/form-field.js
  94. 35
      ui/components/ui/qr-code/index.scss
  95. 24
      ui/components/ui/qr-code/qr-code.js
  96. 6
      ui/components/ui/toggle-button/toggle-button.component.js
  97. 1
      ui/components/ui/ui-components.scss
  98. 37
      ui/contexts/gasFee.js
  99. 2
      ui/css/design-system/colors.scss
  100. 2
      ui/helpers/constants/routes.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -195,7 +195,7 @@ jobs:
- build-artifacts - build-artifacts
validate-lavamoat-config: validate-lavamoat-config:
executor: node-browsers executor: node-browsers-medium-plus
steps: steps:
- checkout - checkout
- attach_workspace: - attach_workspace:

@ -0,0 +1,70 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ develop, Version-v*, cla-signatures, master, snaps ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ develop ]
schedule:
- cron: '28 12 * * 0'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

@ -1,5 +1,5 @@
node_modules/** node_modules/**
lavamoat/*/policy.json lavamoat/**/policy.json
dist/** dist/**
builds/** builds/**
test-*/** test-*/**

@ -6,6 +6,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [10.7.0]
### Changed
- [#12643](https://github.com/MetaMask/metamask-extension/pull/12643): Reject popup confirmations on close
- [#12566](https://github.com/MetaMask/metamask-extension/pull/12566): Enable LavaMoat for the webapp background
- [#12399](https://github.com/MetaMask/metamask-extension/pull/12399): Update the "Account Details" view
- Change "Close" icon color from gray -> black
- Display the entire account address
- Use rounded style for "View on Etherscan" and "Export Private Key" buttons
- [#12824](https://github.com/MetaMask/metamask-extension/pull/12824): Add multilayer fee to token approval screen
### Fixed
- [#12696](https://github.com/MetaMask/metamask-extension/pull/12696): Show correct base asset for current network in the Signature Request view
- [#12727](https://github.com/MetaMask/metamask-extension/pull/12727): Make toggle buttons keyboard accessible
- [#12729](https://github.com/MetaMask/metamask-extension/pull/12729): Swaps: Fix issue with wrapping and unwrapping when an address contains uppercase characters
- [#12631](https://github.com/MetaMask/metamask-extension/pull/12631): Fix bug preventing sending high precision decimal amounts of tokens in the send flow
## [10.6.4] ## [10.6.4]
### Changed ### Changed
- [#12752](https://github.com/MetaMask/metamask-extension/pull/12752): Update link, in the add network flow, to the article with information about network security risks - [#12752](https://github.com/MetaMask/metamask-extension/pull/12752): Update link, in the add network flow, to the article with information about network security risks
@ -170,7 +186,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#11967](https://github.com/MetaMask/metamask-extension/pull/11967): Fix the display of long contact names on the contact settings pages. - [#11967](https://github.com/MetaMask/metamask-extension/pull/11967): Fix the display of long contact names on the contact settings pages.
- [#12122](https://github.com/MetaMask/metamask-extension/pull/12122): Ensure failed speedups don't prevent further speedup attempts, and hide the Base Fee and Priority Fee fields when we don't have that information - [#12122](https://github.com/MetaMask/metamask-extension/pull/12122): Ensure failed speedups don't prevent further speedup attempts, and hide the Base Fee and Priority Fee fields when we don't have that information
- [#11963](https://github.com/MetaMask/metamask-extension/pull/11963): Show scrollbar in the accounts menu - [#11963](https://github.com/MetaMask/metamask-extension/pull/11963): Show scrollbar in the accounts menu
- This makes the accounts list scrollable for users with no mouse scroll wheel. - This makes the accounts list scrollable for users with no mouse scroll wheel.
- [#12058](https://github.com/MetaMask/metamask-extension/pull/12058): Fix clipping issue with long network names in the network dropdown - [#12058](https://github.com/MetaMask/metamask-extension/pull/12058): Fix clipping issue with long network names in the network dropdown
- [#12039](https://github.com/MetaMask/metamask-extension/pull/12039): Add missing padding at the bottom of the custom network form in the popup view - [#12039](https://github.com/MetaMask/metamask-extension/pull/12039): Add missing padding at the bottom of the custom network form in the popup view
- [#11890](https://github.com/MetaMask/metamask-extension/pull/11890): Fix alignment of horizontal line shown under gas recommendations - [#11890](https://github.com/MetaMask/metamask-extension/pull/11890): Fix alignment of horizontal line shown under gas recommendations
@ -182,7 +198,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#12144](https://github.com/MetaMask/metamask-extension/pull/12144): Add What's New notification about ledger EIP-1559 support and firmware updates - [#12144](https://github.com/MetaMask/metamask-extension/pull/12144): Add What's New notification about ledger EIP-1559 support and firmware updates
### Fixed ### Fixed
- [#12069](https://github.com/MetaMask/metamask-extension/pull/12069): Fixes bug where suggestedGasFee api is called excessively. - [#12069](https://github.com/MetaMask/metamask-extension/pull/12069): Fixes bug where suggestedGasFee api is called excessively.
## [10.1.0] ## [10.1.0]
### Added ### Added
@ -337,7 +353,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#11118](https://github.com/MetaMask/metamask-extension/pull/11118): Removing support survey notification from What's New - [#11118](https://github.com/MetaMask/metamask-extension/pull/11118): Removing support survey notification from What's New
- [#11115](https://github.com/MetaMask/metamask-extension/pull/11115): Hide basic tab in advanced gas modal for speedup and cancel when on testnets - [#11115](https://github.com/MetaMask/metamask-extension/pull/11115): Hide basic tab in advanced gas modal for speedup and cancel when on testnets
- [#11030](https://github.com/MetaMask/metamask-extension/pull/11030): Return a specific error (code 4902) for switchEthereumChain requests for chains that aren't already in the user's wallet. - [#11030](https://github.com/MetaMask/metamask-extension/pull/11030): Return a specific error (code 4902) for switchEthereumChain requests for chains that aren't already in the user's wallet.
- [#11093](https://github.com/MetaMask/metamask-extension/pull/11093): Update all uses of "Seed Phrase" to "Secret Recovery Phrase" - [#11093](https://github.com/MetaMask/metamask-extension/pull/11093): Update all uses of "Seed Phrase" to "Secret Recovery Phrase"
### Fixed ### Fixed
- [#11025](https://github.com/MetaMask/metamask-extension/pull/11025): Fixed redirection to the build quotes page from the swaps page when failure has occured - [#11025](https://github.com/MetaMask/metamask-extension/pull/11025): Fixed redirection to the build quotes page from the swaps page when failure has occured
@ -357,14 +373,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Re-added "Add Ledger Live Support" ([#10293](https://github.com/MetaMask/metamask-extension/pull/10293)), which was reverted in the previous version - Re-added "Add Ledger Live Support" ([#10293](https://github.com/MetaMask/metamask-extension/pull/10293)), which was reverted in the previous version
### Fixed ### Fixed
- [#11225](https://github.com/MetaMask/metamask-extension/pull/11225) - Fix persistent display of chrome ledger What's New popup message - [#11225](https://github.com/MetaMask/metamask-extension/pull/11225) - Fix persistent display of chrome ledger What's New popup message
## [9.5.8] ## [9.5.8]
### Added ### Added
- Re-added "Add Ledger Live Support" ([#10293](https://github.com/MetaMask/metamask-extension/pull/10293)), which was reverted in the previous version - Re-added "Add Ledger Live Support" ([#10293](https://github.com/MetaMask/metamask-extension/pull/10293)), which was reverted in the previous version
### Fixed ### Fixed
- [#11207](https://github.com/MetaMask/metamask-extension/pull/11207) - Fix error causing crashes on some locales on v9.5.6 - [#11207](https://github.com/MetaMask/metamask-extension/pull/11207) - Fix error causing crashes on some locales on v9.5.6
## [9.5.7] ## [9.5.7]
### Fixed ### Fixed
@ -2613,7 +2629,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Uncategorized ### Uncategorized
- Added the ability to restore accounts from seed words. - Added the ability to restore accounts from seed words.
[Unreleased]: https://github.com/MetaMask/metamask-extension/compare/v10.6.4...HEAD [Unreleased]: https://github.com/MetaMask/metamask-extension/compare/v10.7.0...HEAD
[10.7.0]: https://github.com/MetaMask/metamask-extension/compare/v10.6.4...v10.7.0
[10.6.4]: https://github.com/MetaMask/metamask-extension/compare/v10.6.3...v10.6.4 [10.6.4]: https://github.com/MetaMask/metamask-extension/compare/v10.6.3...v10.6.4
[10.6.3]: https://github.com/MetaMask/metamask-extension/compare/v10.6.2...v10.6.3 [10.6.3]: https://github.com/MetaMask/metamask-extension/compare/v10.6.2...v10.6.3
[10.6.2]: https://github.com/MetaMask/metamask-extension/compare/v10.6.1...v10.6.2 [10.6.2]: https://github.com/MetaMask/metamask-extension/compare/v10.6.1...v10.6.2

@ -67,9 +67,17 @@ Whenever you change dependencies (adding, removing, or updating, either in `pack
* The `allow-scripts` configuration in `package.json` * The `allow-scripts` configuration in `package.json`
* Run `yarn allow-scripts auto` to update the `allow-scripts` configuration automatically. This config determines whether the package's install/postinstall scripts are allowed to run. Review each new package to determine whether the install script needs to run or not, testing if necessary. * Run `yarn allow-scripts auto` to update the `allow-scripts` configuration automatically. This config determines whether the package's install/postinstall scripts are allowed to run. Review each new package to determine whether the install script needs to run or not, testing if necessary.
* Unfortunately, `yarn allow-scripts auto` will behave inconsistently on different platforms. macOS and Windows users may see extraneous changes relating to optional dependencies. * Unfortunately, `yarn allow-scripts auto` will behave inconsistently on different platforms. macOS and Windows users may see extraneous changes relating to optional dependencies.
* The LavaMoat auto-generated policy in `lavamoat/node/policy.json` * The LavaMoat policy files. The _tl;dr_ is to run `yarn lavamoat:auto` to update these files, but there can be devils in the details. Continue reading for more information.
* Run `yarn lavamoat:auto` to re-generate this policy file. Review the changes to determine whether the access granted to each package seems appropriate. * There are two sets of LavaMoat policy files:
* Unfortunately, `yarn lavamoat:auto` will behave inconsistently on different platforms. macOS and Windows users may see extraneous changes relating to optional dependencies. * The production LavaMoat policy files (`lavamoat/browserify/*/policy.json`), which are re-generated using `yarn lavamoat:background:auto`.
* These should be regenerated whenever the production dependencies for the background change.
* The build system LavaMoat policy file (`lavamoat/build-system/policy.json`), which is re-generated using `yarn lavamoat:build:auto`.
* This should be regenerated whenever the dependencies used by the build system itself change.
* Whenever you regenerate a policy file, review the changes to determine whether the access granted to each package seems appropriate.
* Unfortunately, `yarn lavamoat:auto` will behave inconsistently on different platforms.
macOS and Windows users may see extraneous changes relating to optional dependencies.
* Keep in mind that any kind of dynamic import or dynamic use of globals may elude LavaMoat's static analysis.
Refer to the LavaMoat documentation or ask for help if you run into any issues.
## Architecture ## Architecture

@ -43,6 +43,9 @@
"activityLog": { "activityLog": {
"message": "activity log" "message": "activity log"
}, },
"add": {
"message": "Add"
},
"addANetwork": { "addANetwork": {
"message": "Add a network" "message": "Add a network"
}, },
@ -100,6 +103,9 @@
"addToken": { "addToken": {
"message": "Add Token" "message": "Add Token"
}, },
"address": {
"message": "Address"
},
"addressBookIcon": { "addressBookIcon": {
"message": "Address book icon" "message": "Address book icon"
}, },
@ -167,6 +173,14 @@
"message": "MetaMask", "message": "MetaMask",
"description": "The name of the application" "description": "The name of the application"
}, },
"appNameBeta": {
"message": "MetaMask Beta",
"description": "The name of the application (Beta)"
},
"appNameFlask": {
"message": "MetaMask Flask",
"description": "The name of the application (Flask)"
},
"approvalAndAggregatorTxFeeCost": { "approvalAndAggregatorTxFeeCost": {
"message": "Approval and aggregator network fee" "message": "Approval and aggregator network fee"
}, },
@ -549,6 +563,9 @@
"currentlyUnavailable": { "currentlyUnavailable": {
"message": "Unavailable on this network" "message": "Unavailable on this network"
}, },
"custom": {
"message": "Advanced"
},
"customGas": { "customGas": {
"message": "Customize Gas" "message": "Customize Gas"
}, },
@ -561,6 +578,13 @@
"customToken": { "customToken": {
"message": "Custom Token" "message": "Custom Token"
}, },
"dappSuggested": {
"message": "Site suggested"
},
"dappSuggestedTooltip": {
"message": "$1 has recommended this price.",
"description": "$1 represents the Dapp's origin"
},
"data": { "data": {
"message": "Data" "message": "Data"
}, },
@ -891,6 +915,9 @@
"etherscanView": { "etherscanView": {
"message": "View account on Etherscan" "message": "View account on Etherscan"
}, },
"etherscanViewOn": {
"message": "View on Etherscan"
},
"expandView": { "expandView": {
"message": "Expand view" "message": "Expand view"
}, },
@ -1002,6 +1029,9 @@
"gasPriceInfoTooltipContent": { "gasPriceInfoTooltipContent": {
"message": "Gas price specifies the amount of Ether you are willing to pay for each unit of gas." "message": "Gas price specifies the amount of Ether you are willing to pay for each unit of gas."
}, },
"gasPriceLabel": {
"message": "Gas price"
},
"gasTimingMinutes": { "gasTimingMinutes": {
"message": "$1 minutes", "message": "$1 minutes",
"description": "$1 represents a number of minutes" "description": "$1 represents a number of minutes"
@ -1100,9 +1130,15 @@
"hideZeroBalanceTokens": { "hideZeroBalanceTokens": {
"message": "Hide Tokens Without Balance" "message": "Hide Tokens Without Balance"
}, },
"high": {
"message": "Aggressive"
},
"history": { "history": {
"message": "History" "message": "History"
}, },
"id": {
"message": "ID"
},
"import": { "import": {
"message": "Import", "message": "Import",
"description": "Button to import an account from a selected file" "description": "Button to import an account from a selected file"
@ -1117,7 +1153,7 @@
"message": "import using Secret Recovery Phrase" "message": "import using Secret Recovery Phrase"
}, },
"importAccountMsg": { "importAccountMsg": {
"message": " Imported accounts will not be associated with your originally created MetaMask account Secret Recovery Phrase. Learn more about imported accounts " "message": "Imported accounts will not be associated with your originally created MetaMask account Secret Recovery Phrase. Learn more about imported accounts"
}, },
"importAccountSeedPhrase": { "importAccountSeedPhrase": {
"message": "Import a wallet with Secret Recovery Phrase" "message": "Import a wallet with Secret Recovery Phrase"
@ -1336,6 +1372,12 @@
"lockTimeTooGreat": { "lockTimeTooGreat": {
"message": "Lock time is too great" "message": "Lock time is too great"
}, },
"low": {
"message": "Low"
},
"lowPriorityMessage": {
"message": "Future transactions will queue after this one. This price was last seen was some time ago."
},
"mainnet": { "mainnet": {
"message": "Ethereum Mainnet" "message": "Ethereum Mainnet"
}, },
@ -1349,12 +1391,18 @@
"max": { "max": {
"message": "Max" "message": "Max"
}, },
"maxBaseFee": {
"message": "Max base fee"
},
"maxFee": { "maxFee": {
"message": "Max fee" "message": "Max fee"
}, },
"maxPriorityFee": { "maxPriorityFee": {
"message": "Max priority fee" "message": "Max priority fee"
}, },
"medium": {
"message": "Market"
},
"memo": { "memo": {
"message": "memo" "message": "memo"
}, },
@ -1560,6 +1608,9 @@
"message": "Nonce is higher than suggested nonce of $1", "message": "Nonce is higher than suggested nonce of $1",
"description": "The next nonce according to MetaMask's internal logic" "description": "The next nonce according to MetaMask's internal logic"
}, },
"nftTokenIdPlaceholder": {
"message": "Enter the collectible ID"
},
"nfts": { "nfts": {
"message": "NFTs" "message": "NFTs"
}, },

@ -503,7 +503,7 @@
"message": "编辑权限" "message": "编辑权限"
}, },
"encryptionPublicKeyNotice": { "encryptionPublicKeyNotice": {
"message": "$1 希望得到您的加密公钥。同意后该网站将可以您发送加密信息。", "message": "$1 希望得到您的加密公钥。同意后该网站将可以您发送加密信息。",
"description": "$1 is the web3 site name" "description": "$1 is the web3 site name"
}, },
"encryptionPublicKeyRequest": { "encryptionPublicKeyRequest": {

@ -21,6 +21,6 @@
"128": "images/icon-128.png", "128": "images/icon-128.png",
"512": "images/icon-512.png" "512": "images/icon-512.png"
}, },
"name": "__MSG_appName__ Beta", "name": "__MSG_appNameBeta__",
"short_name": "__MSG_appName__ Beta" "short_name": "__MSG_appNameBeta__"
} }

@ -21,6 +21,6 @@
"128": "images/icon-128.png", "128": "images/icon-128.png",
"512": "images/icon-512.png" "512": "images/icon-512.png"
}, },
"name": "__MSG_appName__ Flask", "name": "__MSG_appNameFlask__",
"short_name": "__MSG_appName__ Flask" "short_name": "__MSG_appNameFlask__"
} }

@ -17,13 +17,19 @@ import {
ENVIRONMENT_TYPE_FULLSCREEN, ENVIRONMENT_TYPE_FULLSCREEN,
} from '../../shared/constants/app'; } from '../../shared/constants/app';
import { SECOND } from '../../shared/constants/time'; import { SECOND } from '../../shared/constants/time';
import {
REJECT_NOTFICIATION_CLOSE,
REJECT_NOTFICIATION_CLOSE_SIG,
} from '../../shared/constants/metametrics';
import migrations from './migrations'; import migrations from './migrations';
import Migrator from './lib/migrator'; import Migrator from './lib/migrator';
import ExtensionPlatform from './platforms/extension'; import ExtensionPlatform from './platforms/extension';
import LocalStore from './lib/local-store'; import LocalStore from './lib/local-store';
import ReadOnlyNetworkStore from './lib/network-store'; import ReadOnlyNetworkStore from './lib/network-store';
import createStreamSink from './lib/createStreamSink'; import createStreamSink from './lib/createStreamSink';
import NotificationManager from './lib/notification-manager'; import NotificationManager, {
NOTIFICATION_MANAGER_EVENTS,
} from './lib/notification-manager';
import MetamaskController, { import MetamaskController, {
METAMASK_CONTROLLER_EVENTS, METAMASK_CONTROLLER_EVENTS,
} from './metamask-controller'; } from './metamask-controller';
@ -475,6 +481,69 @@ function setupController(initState, initLangCode) {
extension.browserAction.setBadgeBackgroundColor({ color: '#037DD6' }); extension.browserAction.setBadgeBackgroundColor({ color: '#037DD6' });
} }
notificationManager.on(
NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED,
rejectUnapprovedNotifications,
);
function rejectUnapprovedNotifications() {
Object.keys(
controller.txController.txStateManager.getUnapprovedTxList(),
).forEach((txId) =>
controller.txController.txStateManager.setTxStatusRejected(txId),
);
controller.messageManager.messages
.filter((msg) => msg.status === 'unapproved')
.forEach((tx) =>
controller.messageManager.rejectMsg(
tx.id,
REJECT_NOTFICIATION_CLOSE_SIG,
),
);
controller.personalMessageManager.messages
.filter((msg) => msg.status === 'unapproved')
.forEach((tx) =>
controller.personalMessageManager.rejectMsg(
tx.id,
REJECT_NOTFICIATION_CLOSE_SIG,
),
);
controller.typedMessageManager.messages
.filter((msg) => msg.status === 'unapproved')
.forEach((tx) =>
controller.typedMessageManager.rejectMsg(
tx.id,
REJECT_NOTFICIATION_CLOSE_SIG,
),
);
controller.decryptMessageManager.messages
.filter((msg) => msg.status === 'unapproved')
.forEach((tx) =>
controller.decryptMessageManager.rejectMsg(
tx.id,
REJECT_NOTFICIATION_CLOSE,
),
);
controller.encryptionPublicKeyManager.messages
.filter((msg) => msg.status === 'unapproved')
.forEach((tx) =>
controller.encryptionPublicKeyManager.rejectMsg(
tx.id,
REJECT_NOTFICIATION_CLOSE,
),
);
// We're specifcally avoid using approvalController directly for better
// Error support during rejection
Object.keys(
controller.permissionsController.approvals.state.pendingApprovals,
).forEach((approvalId) =>
controller.permissionsController.rejectPermissionsRequest(approvalId),
);
updateBadge();
}
return Promise.resolve(); return Promise.resolve();
} }

@ -1,10 +1,13 @@
import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine'; import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine';
import createBlockRefMiddleware from 'eth-json-rpc-middleware/block-ref'; import {
import createRetryOnEmptyMiddleware from 'eth-json-rpc-middleware/retryOnEmpty'; createBlockRefMiddleware,
import createBlockCacheMiddleware from 'eth-json-rpc-middleware/block-cache'; createRetryOnEmptyMiddleware,
import createInflightCacheMiddleware from 'eth-json-rpc-middleware/inflight-cache'; createBlockCacheMiddleware,
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector'; createInflightCacheMiddleware,
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware'; createBlockTrackerInspectorMiddleware,
providerFromMiddleware,
} from 'eth-json-rpc-middleware';
import createInfuraMiddleware from 'eth-json-rpc-infura'; import createInfuraMiddleware from 'eth-json-rpc-infura';
import { PollingBlockTracker } from 'eth-block-tracker'; import { PollingBlockTracker } from 'eth-block-tracker';

@ -1,10 +1,12 @@
import { createAsyncMiddleware, mergeMiddleware } from 'json-rpc-engine'; import { createAsyncMiddleware, mergeMiddleware } from 'json-rpc-engine';
import createFetchMiddleware from 'eth-json-rpc-middleware/fetch'; import {
import createBlockRefRewriteMiddleware from 'eth-json-rpc-middleware/block-ref-rewrite'; createFetchMiddleware,
import createBlockCacheMiddleware from 'eth-json-rpc-middleware/block-cache'; createBlockRefRewriteMiddleware,
import createInflightMiddleware from 'eth-json-rpc-middleware/inflight-cache'; createBlockCacheMiddleware,
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector'; createInflightCacheMiddleware,
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware'; createBlockTrackerInspectorMiddleware,
providerFromMiddleware,
} from 'eth-json-rpc-middleware';
import { PollingBlockTracker } from 'eth-block-tracker'; import { PollingBlockTracker } from 'eth-block-tracker';
import { SECOND } from '../../../../shared/constants/time'; import { SECOND } from '../../../../shared/constants/time';
@ -27,7 +29,7 @@ export default function createJsonRpcClient({ rpcUrl, chainId }) {
createChainIdMiddleware(chainId), createChainIdMiddleware(chainId),
createBlockRefRewriteMiddleware({ blockTracker }), createBlockRefRewriteMiddleware({ blockTracker }),
createBlockCacheMiddleware({ blockTracker }), createBlockCacheMiddleware({ blockTracker }),
createInflightMiddleware(), createInflightCacheMiddleware(),
createBlockTrackerInspectorMiddleware({ blockTracker }), createBlockTrackerInspectorMiddleware({ blockTracker }),
fetchMiddleware, fetchMiddleware,
]); ]);

@ -1,5 +1,5 @@
import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine'; import { createScaffoldMiddleware, mergeMiddleware } from 'json-rpc-engine';
import createWalletSubprovider from 'eth-json-rpc-middleware/wallet'; import { createWalletMiddleware } from 'eth-json-rpc-middleware';
import { import {
createPendingNonceMiddleware, createPendingNonceMiddleware,
createPendingTxMiddleware, createPendingTxMiddleware,
@ -21,11 +21,10 @@ export default function createMetamaskMiddleware({
}) { }) {
const metamaskMiddleware = mergeMiddleware([ const metamaskMiddleware = mergeMiddleware([
createScaffoldMiddleware({ createScaffoldMiddleware({
// staticSubprovider
eth_syncing: false, eth_syncing: false,
web3_clientVersion: `MetaMask/v${version}`, web3_clientVersion: `MetaMask/v${version}`,
}), }),
createWalletSubprovider({ createWalletMiddleware({
getAccounts, getAccounts,
processTransaction, processTransaction,
processEthSignMessage, processEthSignMessage,

@ -2,7 +2,7 @@ import { strict as assert } from 'assert';
import EventEmitter from 'events'; import EventEmitter from 'events';
import { ComposedStore, ObservableStore } from '@metamask/obs-store'; import { ComposedStore, ObservableStore } from '@metamask/obs-store';
import { JsonRpcEngine } from 'json-rpc-engine'; import { JsonRpcEngine } from 'json-rpc-engine';
import providerFromEngine from 'eth-json-rpc-middleware/providerFromEngine'; import { providerFromEngine } from 'eth-json-rpc-middleware';
import log from 'loglevel'; import log from 'loglevel';
import { import {
createSwappableProxy, createSwappableProxy,
@ -430,7 +430,7 @@ export default class NetworkController extends EventEmitter {
} }
_setProviderAndBlockTracker({ provider, blockTracker }) { _setProviderAndBlockTracker({ provider, blockTracker }) {
// update or intialize proxies // update or initialize proxies
if (this._providerProxy) { if (this._providerProxy) {
this._providerProxy.setTarget(provider); this._providerProxy.setTarget(provider);
} else { } else {

@ -37,6 +37,7 @@ export default class PreferencesController {
// set to true means the dynamic list from the API is being used // set to true means the dynamic list from the API is being used
// set to false will be using the static list from contract-metadata // set to false will be using the static list from contract-metadata
useTokenDetection: false, useTokenDetection: false,
advancedGasFee: null,
// WARNING: Do not use feature flags for security-sensitive things. // WARNING: Do not use feature flags for security-sensitive things.
// Feature flag toggling is available in the global namespace // Feature flag toggling is available in the global namespace
@ -129,6 +130,16 @@ export default class PreferencesController {
this.store.updateState({ useTokenDetection: val }); this.store.updateState({ useTokenDetection: val });
} }
/**
* Setter for the `advancedGasFee` property
*
* @param {object} val - holds the maxBaseFee and PriorityFee that the user set as default advanced settings.
*
*/
setAdvancedGasFee(val) {
this.store.updateState({ advancedGasFee: val });
}
/** /**
* Add new methodData to state, to avoid requesting this information again through Infura * Add new methodData to state, to avoid requesting this information again through Infura
* *

@ -266,4 +266,28 @@ describe('preferences controller', function () {
); );
}); });
}); });
describe('setAdvancedGasFee', function () {
it('should default to null', function () {
const state = preferencesController.store.getState();
assert.equal(state.advancedGasFee, null);
});
it('should set the setAdvancedGasFee property in state', function () {
const state = preferencesController.store.getState();
assert.equal(state.advancedGasFee, null);
preferencesController.setAdvancedGasFee({
maxBaseFee: '1.5',
priorityFee: '2',
});
assert.equal(
preferencesController.store.getState().advancedGasFee.maxBaseFee,
'1.5',
);
assert.equal(
preferencesController.store.getState().advancedGasFee.priorityFee,
'2',
);
});
});
}); });

@ -281,7 +281,7 @@ export default class SwapsController {
// For a user to be able to swap a token, they need to have approved the MetaSwap contract to withdraw that token. // For a user to be able to swap a token, they need to have approved the MetaSwap contract to withdraw that token.
// _getERC20Allowance() returns the amount of the token they have approved for withdrawal. If that amount is greater // _getERC20Allowance() returns the amount of the token they have approved for withdrawal. If that amount is greater
// than 0, it means that approval has already occured and is not needed. Otherwise, for tokens to be swapped, a new // than 0, it means that approval has already occurred and is not needed. Otherwise, for tokens to be swapped, a new
// call of the ERC-20 approve method is required. // call of the ERC-20 approve method is required.
approvalRequired = approvalRequired =
allowance.eq(0) && allowance.eq(0) &&

@ -8,7 +8,7 @@ const Box = process.env.IN_TEST
import log from 'loglevel'; import log from 'loglevel';
import { JsonRpcEngine } from 'json-rpc-engine'; import { JsonRpcEngine } from 'json-rpc-engine';
import providerFromEngine from 'eth-json-rpc-middleware/providerFromEngine'; import { providerFromEngine } from 'eth-json-rpc-middleware';
import Migrator from '../lib/migrator'; import Migrator from '../lib/migrator';
import migrations from '../migrations'; import migrations from '../migrations';
import createOriginMiddleware from '../lib/createOriginMiddleware'; import createOriginMiddleware from '../lib/createOriginMiddleware';

@ -26,6 +26,7 @@ import {
TRANSACTION_TYPES, TRANSACTION_TYPES,
TRANSACTION_ENVELOPE_TYPES, TRANSACTION_ENVELOPE_TYPES,
} from '../../../../shared/constants/transaction'; } from '../../../../shared/constants/transaction';
import { TRANSACTION_ENVELOPE_TYPE_NAMES } from '../../../../ui/helpers/constants/transactions';
import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller'; import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller';
import { import {
GAS_LIMITS, GAS_LIMITS,
@ -1447,8 +1448,8 @@ export default class TransactionController extends EventEmitter {
sensitiveProperties: { sensitiveProperties: {
status, status,
transaction_envelope_type: isEIP1559Transaction(txMeta) transaction_envelope_type: isEIP1559Transaction(txMeta)
? 'fee-market' ? TRANSACTION_ENVELOPE_TYPE_NAMES.FEE_MARKET
: 'legacy', : TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY,
first_seen: time, first_seen: time,
gas_limit: gasLimit, gas_limit: gasLimit,
...gasParamsInGwei, ...gasParamsInGwei,

@ -20,6 +20,7 @@ import {
GAS_ESTIMATE_TYPES, GAS_ESTIMATE_TYPES,
GAS_RECOMMENDATIONS, GAS_RECOMMENDATIONS,
} from '../../../../shared/constants/gas'; } from '../../../../shared/constants/gas';
import { TRANSACTION_ENVELOPE_TYPE_NAMES } from '../../../../ui/helpers/constants/transactions';
import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller'; import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller';
import TransactionController, { TRANSACTION_EVENTS } from '.'; import TransactionController, { TRANSACTION_EVENTS } from '.';
@ -774,7 +775,7 @@ describe('Transaction Controller', function () {
nonce: '0x4b', nonce: '0x4b',
}, },
type: TRANSACTION_TYPES.SIMPLE_SEND, type: TRANSACTION_TYPES.SIMPLE_SEND,
transaction_envelope_type: 'legacy', transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY,
origin: 'metamask', origin: 'metamask',
chainId: currentChainId, chainId: currentChainId,
time: 1624408066355, time: 1624408066355,
@ -1578,7 +1579,7 @@ describe('Transaction Controller', function () {
gas_price: '2', gas_price: '2',
gas_limit: '0x7b0d', gas_limit: '0x7b0d',
first_seen: 1624408066355, first_seen: 1624408066355,
transaction_envelope_type: 'legacy', transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY,
status: 'unapproved', status: 'unapproved',
}, },
}; };
@ -1625,7 +1626,7 @@ describe('Transaction Controller', function () {
gas_price: '2', gas_price: '2',
gas_limit: '0x7b0d', gas_limit: '0x7b0d',
first_seen: 1624408066355, first_seen: 1624408066355,
transaction_envelope_type: 'legacy', transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY,
status: 'unapproved', status: 'unapproved',
}, },
}; };
@ -1674,7 +1675,7 @@ describe('Transaction Controller', function () {
gas_price: '2', gas_price: '2',
gas_limit: '0x7b0d', gas_limit: '0x7b0d',
first_seen: 1624408066355, first_seen: 1624408066355,
transaction_envelope_type: 'legacy', transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY,
status: 'unapproved', status: 'unapproved',
}, },
}; };
@ -1731,7 +1732,7 @@ describe('Transaction Controller', function () {
max_priority_fee_per_gas: '2', max_priority_fee_per_gas: '2',
gas_limit: '0x7b0d', gas_limit: '0x7b0d',
first_seen: 1624408066355, first_seen: 1624408066355,
transaction_envelope_type: 'fee-market', transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.FEE_MARKET,
status: 'unapproved', status: 'unapproved',
estimate_suggested: GAS_RECOMMENDATIONS.MEDIUM, estimate_suggested: GAS_RECOMMENDATIONS.MEDIUM,
estimate_used: GAS_RECOMMENDATIONS.HIGH, estimate_used: GAS_RECOMMENDATIONS.HIGH,

@ -1,12 +1,13 @@
import log from 'loglevel'; import log from 'loglevel';
import { METASWAP_CHAINID_API_HOST_MAP } from '../../../shared/constants/swaps'; import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps';
import { import {
GOERLI_CHAIN_ID, GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID, KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID, MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID, RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID, ROPSTEN_CHAIN_ID,
MAINNET_NETWORK_ID,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import { SECOND } from '../../../shared/constants/time'; import { SECOND } from '../../../shared/constants/time';
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout'; import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';
@ -20,7 +21,7 @@ const fetchWithTimeout = getFetchWithTimeout(SECOND * 30);
* @returns String * @returns String
*/ */
const createWyrePurchaseUrl = async (address) => { const createWyrePurchaseUrl = async (address) => {
const fiatOnRampUrlApi = `${METASWAP_CHAINID_API_HOST_MAP[MAINNET_CHAIN_ID]}/fiatOnRampUrl?serviceName=wyre&destinationAddress=${address}`; const fiatOnRampUrlApi = `${SWAPS_API_V2_BASE_URL}/networks/${MAINNET_NETWORK_ID}/fiatOnRampUrl?serviceName=wyre&destinationAddress=${address}`;
const wyrePurchaseUrlFallback = `https://pay.sendwyre.com/purchase?dest=ethereum:${address}&destCurrency=ETH&accountId=AC-7AG3W4XH4N2&paymentMethod=debit-card`; const wyrePurchaseUrlFallback = `https://pay.sendwyre.com/purchase?dest=ethereum:${address}&destCurrency=ETH&accountId=AC-7AG3W4XH4N2&paymentMethod=debit-card`;
try { try {
const response = await fetchWithTimeout(fiatOnRampUrlApi, { const response = await fetchWithTimeout(fiatOnRampUrlApi, {

@ -7,6 +7,7 @@ import {
ROPSTEN_CHAIN_ID, ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import { TRANSAK_API_KEY } from '../constants/on-ramp'; import { TRANSAK_API_KEY } from '../constants/on-ramp';
import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps';
import getBuyEthUrl from './buy-eth-url'; import getBuyEthUrl from './buy-eth-url';
const WYRE_ACCOUNT_ID = 'AC-7AG3W4XH4N2'; const WYRE_ACCOUNT_ID = 'AC-7AG3W4XH4N2';
@ -28,8 +29,10 @@ const KOVAN = {
describe('buy-eth-url', function () { describe('buy-eth-url', function () {
it('returns Wyre url with an ETH address for Ethereum mainnet', async function () { it('returns Wyre url with an ETH address for Ethereum mainnet', async function () {
nock('https://api.metaswap.codefi.network') nock(SWAPS_API_V2_BASE_URL)
.get(`/fiatOnRampUrl?serviceName=wyre&destinationAddress=${ETH_ADDRESS}`) .get(
`/networks/1/fiatOnRampUrl?serviceName=wyre&destinationAddress=${ETH_ADDRESS}`,
)
.reply(200, { .reply(200, {
url: `https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=ETH&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`, url: `https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=ETH&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`,
}); });

@ -38,13 +38,14 @@ export default class DecryptMessageManager extends EventEmitter {
* @property {Array} messages Holds all messages that have been created by this DecryptMessageManager * @property {Array} messages Holds all messages that have been created by this DecryptMessageManager
* *
*/ */
constructor() { constructor(opts) {
super(); super();
this.memStore = new ObservableStore({ this.memStore = new ObservableStore({
unapprovedDecryptMsgs: {}, unapprovedDecryptMsgs: {},
unapprovedDecryptMsgCount: 0, unapprovedDecryptMsgCount: 0,
}); });
this.messages = []; this.messages = [];
this.metricsEvent = opts.metricsEvent;
} }
/** /**
@ -237,7 +238,16 @@ export default class DecryptMessageManager extends EventEmitter {
* @param {number} msgId The id of the DecryptMessage to reject. * @param {number} msgId The id of the DecryptMessage to reject.
* *
*/ */
rejectMsg(msgId) { rejectMsg(msgId, reason = undefined) {
if (reason) {
this.metricsEvent({
event: reason,
category: 'Messages',
properties: {
action: 'Decrypt Message Request',
},
});
}
this._setMsgStatus(msgId, 'rejected'); this._setMsgStatus(msgId, 'rejected');
} }

@ -34,13 +34,14 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* @property {Array} messages Holds all messages that have been created by this EncryptionPublicKeyManager * @property {Array} messages Holds all messages that have been created by this EncryptionPublicKeyManager
* *
*/ */
constructor() { constructor(opts) {
super(); super();
this.memStore = new ObservableStore({ this.memStore = new ObservableStore({
unapprovedEncryptionPublicKeyMsgs: {}, unapprovedEncryptionPublicKeyMsgs: {},
unapprovedEncryptionPublicKeyMsgCount: 0, unapprovedEncryptionPublicKeyMsgCount: 0,
}); });
this.messages = []; this.messages = [];
this.metricsEvent = opts.metricsEvent;
} }
/** /**
@ -226,7 +227,16 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* @param {number} msgId The id of the EncryptionPublicKey to reject. * @param {number} msgId The id of the EncryptionPublicKey to reject.
* *
*/ */
rejectMsg(msgId) { rejectMsg(msgId, reason = undefined) {
if (reason) {
this.metricsEvent({
event: reason,
category: 'Messages',
properties: {
action: 'Encryption public key Request',
},
});
}
this._setMsgStatus(msgId, 'rejected'); this._setMsgStatus(msgId, 'rejected');
} }

@ -35,13 +35,14 @@ export default class MessageManager extends EventEmitter {
* @property {Array} messages Holds all messages that have been created by this MessageManager * @property {Array} messages Holds all messages that have been created by this MessageManager
* *
*/ */
constructor() { constructor({ metricsEvent }) {
super(); super();
this.memStore = new ObservableStore({ this.memStore = new ObservableStore({
unapprovedMsgs: {}, unapprovedMsgs: {},
unapprovedMsgCount: 0, unapprovedMsgCount: 0,
}); });
this.messages = []; this.messages = [];
this.metricsEvent = metricsEvent;
} }
/** /**
@ -217,7 +218,18 @@ export default class MessageManager extends EventEmitter {
* @param {number} msgId - The id of the Message to reject. * @param {number} msgId - The id of the Message to reject.
* *
*/ */
rejectMsg(msgId) { rejectMsg(msgId, reason = undefined) {
if (reason) {
const msg = this.getMsg(msgId);
this.metricsEvent({
event: reason,
category: 'Transactions',
properties: {
action: 'Sign Request',
type: msg.type,
},
});
}
this._setMsgStatus(msgId, 'rejected'); this._setMsgStatus(msgId, 'rejected');
} }

@ -1,4 +1,5 @@
import { strict as assert } from 'assert'; import { strict as assert } from 'assert';
import sinon from 'sinon';
import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction';
import MessageManager from './message-manager'; import MessageManager from './message-manager';
@ -6,7 +7,9 @@ describe('Message Manager', function () {
let messageManager; let messageManager;
beforeEach(function () { beforeEach(function () {
messageManager = new MessageManager(); messageManager = new MessageManager({
metricsEvent: sinon.fake(),
});
}); });
describe('#getMsgList', function () { describe('#getMsgList', function () {

@ -1,9 +1,14 @@
import EventEmitter from 'safe-event-emitter';
import ExtensionPlatform from '../platforms/extension'; import ExtensionPlatform from '../platforms/extension';
const NOTIFICATION_HEIGHT = 620; const NOTIFICATION_HEIGHT = 620;
const NOTIFICATION_WIDTH = 360; const NOTIFICATION_WIDTH = 360;
export default class NotificationManager { export const NOTIFICATION_MANAGER_EVENTS = {
POPUP_CLOSED: 'onPopupClosed',
};
export default class NotificationManager extends EventEmitter {
/** /**
* A collection of methods for controlling the showing and hiding of the notification popup. * A collection of methods for controlling the showing and hiding of the notification popup.
* *
@ -12,7 +17,9 @@ export default class NotificationManager {
*/ */
constructor() { constructor() {
super();
this.platform = new ExtensionPlatform(); this.platform = new ExtensionPlatform();
this.platform.addOnRemovedListener(this._onWindowClosed.bind(this));
} }
/** /**
@ -62,6 +69,13 @@ export default class NotificationManager {
} }
} }
_onWindowClosed(windowId) {
if (windowId === this._popupId) {
this._popupId = undefined;
this.emit(NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED);
}
}
/** /**
* Checks all open MetaMask windows, and returns the first one it finds that is a notification window (i.e. has the * Checks all open MetaMask windows, and returns the first one it finds that is a notification window (i.e. has the
* type 'popup') * type 'popup')

@ -40,13 +40,14 @@ export default class PersonalMessageManager extends EventEmitter {
* @property {Array} messages Holds all messages that have been created by this PersonalMessageManager * @property {Array} messages Holds all messages that have been created by this PersonalMessageManager
* *
*/ */
constructor() { constructor({ metricsEvent }) {
super(); super();
this.memStore = new ObservableStore({ this.memStore = new ObservableStore({
unapprovedPersonalMsgs: {}, unapprovedPersonalMsgs: {},
unapprovedPersonalMsgCount: 0, unapprovedPersonalMsgCount: 0,
}); });
this.messages = []; this.messages = [];
this.metricsEvent = metricsEvent;
} }
/** /**
@ -238,7 +239,18 @@ export default class PersonalMessageManager extends EventEmitter {
* @param {number} msgId - The id of the PersonalMessage to reject. * @param {number} msgId - The id of the PersonalMessage to reject.
* *
*/ */
rejectMsg(msgId) { rejectMsg(msgId, reason = undefined) {
if (reason) {
const msg = this.getMsg(msgId);
this.metricsEvent({
event: reason,
category: 'Transactions',
properties: {
action: 'Sign Request',
type: msg.type,
},
});
}
this._setMsgStatus(msgId, 'rejected'); this._setMsgStatus(msgId, 'rejected');
} }

@ -1,4 +1,5 @@
import { strict as assert } from 'assert'; import { strict as assert } from 'assert';
import sinon from 'sinon';
import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction';
import PersonalMessageManager from './personal-message-manager'; import PersonalMessageManager from './personal-message-manager';
@ -6,7 +7,7 @@ describe('Personal Message Manager', function () {
let messageManager; let messageManager;
beforeEach(function () { beforeEach(function () {
messageManager = new PersonalMessageManager(); messageManager = new PersonalMessageManager({ metricsEvent: sinon.fake() });
}); });
describe('#getMsgList', function () { describe('#getMsgList', function () {

@ -1,8 +1,10 @@
import { ethErrors } from 'eth-rpc-errors';
import { UNSUPPORTED_RPC_METHODS } from '../../../../shared/constants/network';
import handlers from './handlers'; import handlers from './handlers';
const handlerMap = handlers.reduce((map, handler) => { const handlerMap = handlers.reduce((map, handler) => {
for (const methodName of handler.methodNames) { for (const methodName of handler.methodNames) {
map.set(methodName, handler.implementation); map.set(methodName, handler);
} }
return map; return map;
}, new Map()); }, new Map());
@ -21,14 +23,41 @@ const handlerMap = handlers.reduce((map, handler) => {
* Eventually, we'll want to extract this middleware into its own package. * Eventually, we'll want to extract this middleware into its own package.
* *
* @param {Object} opts - The middleware options * @param {Object} opts - The middleware options
* @param {Function} opts.sendMetrics - A function for sending a metrics event
* @returns {(req: Object, res: Object, next: Function, end: Function) => void} * @returns {(req: Object, res: Object, next: Function, end: Function) => void}
*/ */
export default function createMethodMiddleware(opts) { export default function createMethodMiddleware(opts) {
return function methodMiddleware(req, res, next, end) { return function methodMiddleware(req, res, next, end) {
if (handlerMap.has(req.method)) { // Reject unsupported methods.
return handlerMap.get(req.method)(req, res, next, end, opts); if (UNSUPPORTED_RPC_METHODS.has(req.method)) {
return end(ethErrors.rpc.methodNotSupported());
} }
const handler = handlerMap.get(req.method);
if (handler) {
const { implementation, hookNames } = handler;
return implementation(req, res, next, end, selectHooks(opts, hookNames));
}
return next(); return next();
}; };
} }
/**
* Returns the subset of the specified `hooks` that are included in the
* `hookNames` object. This is a Principle of Least Authority (POLA) measure
* to ensure that each RPC method implementation only has access to the
* API "hooks" it needs to do its job.
*
* @param {Record<string, unknown>} hooks - The hooks to select from.
* @param {Record<string, true>} hookNames - The names of the hooks to select.
* @returns {Record<string, unknown> | undefined} The selected hooks.
*/
function selectHooks(hooks, hookNames) {
if (hookNames) {
return Object.keys(hookNames).reduce((hookSubset, hookName) => {
hookSubset[hookName] = hooks[hookName];
return hookSubset;
}, {});
}
return undefined;
}

@ -12,6 +12,14 @@ import { CHAIN_ID_TO_NETWORK_ID_MAP } from '../../../../../shared/constants/netw
const addEthereumChain = { const addEthereumChain = {
methodNames: [MESSAGE_TYPE.ADD_ETHEREUM_CHAIN], methodNames: [MESSAGE_TYPE.ADD_ETHEREUM_CHAIN],
implementation: addEthereumChainHandler, implementation: addEthereumChainHandler,
hookNames: {
addCustomRpc: true,
getCurrentChainId: true,
findCustomRpcBy: true,
updateRpcTarget: true,
requestUserApproval: true,
sendMetrics: true,
},
}; };
export default addEthereumChain; export default addEthereumChain;

@ -9,6 +9,9 @@ import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
const getProviderState = { const getProviderState = {
methodNames: [MESSAGE_TYPE.GET_PROVIDER_STATE], methodNames: [MESSAGE_TYPE.GET_PROVIDER_STATE],
implementation: getProviderStateHandler, implementation: getProviderStateHandler,
hookNames: {
getProviderState: true,
},
}; };
export default getProviderState; export default getProviderState;

@ -10,6 +10,11 @@ import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
const logWeb3ShimUsage = { const logWeb3ShimUsage = {
methodNames: [MESSAGE_TYPE.LOG_WEB3_SHIM_USAGE], methodNames: [MESSAGE_TYPE.LOG_WEB3_SHIM_USAGE],
implementation: logWeb3ShimUsageHandler, implementation: logWeb3ShimUsageHandler,
hookNames: {
sendMetrics: true,
getWeb3ShimUsageState: true,
setWeb3ShimUsageRecorded: true,
},
}; };
export default logWeb3ShimUsage; export default logWeb3ShimUsage;

@ -15,6 +15,13 @@ import {
const switchEthereumChain = { const switchEthereumChain = {
methodNames: [MESSAGE_TYPE.SWITCH_ETHEREUM_CHAIN], methodNames: [MESSAGE_TYPE.SWITCH_ETHEREUM_CHAIN],
implementation: switchEthereumChainHandler, implementation: switchEthereumChainHandler,
hookNames: {
getCurrentChainId: true,
findCustomRpcBy: true,
setProviderType: true,
updateRpcTarget: true,
requestUserApproval: true,
},
}; };
export default switchEthereumChain; export default switchEthereumChain;

@ -3,6 +3,9 @@ import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
const watchAsset = { const watchAsset = {
methodNames: [MESSAGE_TYPE.WATCH_ASSET, MESSAGE_TYPE.WATCH_ASSET_LEGACY], methodNames: [MESSAGE_TYPE.WATCH_ASSET, MESSAGE_TYPE.WATCH_ASSET_LEGACY],
implementation: watchAssetHandler, implementation: watchAssetHandler,
hookNames: {
handleWatchAssetRequest: true,
},
}; };
export default watchAsset; export default watchAsset;

@ -32,7 +32,7 @@ export default class TypedMessageManager extends EventEmitter {
/** /**
* Controller in charge of managing - storing, adding, removing, updating - TypedMessage. * Controller in charge of managing - storing, adding, removing, updating - TypedMessage.
*/ */
constructor({ getCurrentChainId }) { constructor({ getCurrentChainId, metricEvents }) {
super(); super();
this._getCurrentChainId = getCurrentChainId; this._getCurrentChainId = getCurrentChainId;
this.memStore = new ObservableStore({ this.memStore = new ObservableStore({
@ -40,6 +40,7 @@ export default class TypedMessageManager extends EventEmitter {
unapprovedTypedMessagesCount: 0, unapprovedTypedMessagesCount: 0,
}); });
this.messages = []; this.messages = [];
this.metricEvents = metricEvents;
} }
/** /**
@ -301,7 +302,19 @@ export default class TypedMessageManager extends EventEmitter {
* @param {number} msgId - The id of the TypedMessage to reject. * @param {number} msgId - The id of the TypedMessage to reject.
* *
*/ */
rejectMsg(msgId) { rejectMsg(msgId, reason = undefined) {
if (reason) {
const msg = this.getMsg(msgId);
this.metricsEvent({
event: reason,
category: 'Transactions',
properties: {
action: 'Sign Request',
version: msg.msgParams.version,
type: msg.type,
},
});
}
this._setMsgStatus(msgId, 'rejected'); this._setMsgStatus(msgId, 'rejected');
} }

@ -17,6 +17,7 @@ describe('Typed Message Manager', function () {
beforeEach(async function () { beforeEach(async function () {
typedMessageManager = new TypedMessageManager({ typedMessageManager = new TypedMessageManager({
getCurrentChainId: sinon.fake.returns('0x1'), getCurrentChainId: sinon.fake.returns('0x1'),
metricsEvent: sinon.fake(),
}); });
msgParamsV1 = { msgParamsV1 = {

@ -7,7 +7,7 @@ import { debounce } from 'lodash';
import createEngineStream from 'json-rpc-middleware-stream/engineStream'; import createEngineStream from 'json-rpc-middleware-stream/engineStream';
import createFilterMiddleware from 'eth-json-rpc-filters'; import createFilterMiddleware from 'eth-json-rpc-filters';
import createSubscriptionManager from 'eth-json-rpc-filters/subscriptionManager'; import createSubscriptionManager from 'eth-json-rpc-filters/subscriptionManager';
import providerAsMiddleware from 'eth-json-rpc-middleware/providerAsMiddleware'; import { providerAsMiddleware } from 'eth-json-rpc-middleware';
import KeyringController from 'eth-keyring-controller'; import KeyringController from 'eth-keyring-controller';
import { Mutex } from 'await-semaphore'; import { Mutex } from 'await-semaphore';
import { stripHexPrefix } from 'ethereumjs-util'; import { stripHexPrefix } from 'ethereumjs-util';
@ -526,14 +526,33 @@ export default class MetamaskController extends EventEmitter {
} }
}); });
this.networkController.lookupNetwork(); this.networkController.lookupNetwork();
this.messageManager = new MessageManager(); this.messageManager = new MessageManager({
this.personalMessageManager = new PersonalMessageManager(); metricsEvent: this.metaMetricsController.trackEvent.bind(
this.decryptMessageManager = new DecryptMessageManager(); this.metaMetricsController,
this.encryptionPublicKeyManager = new EncryptionPublicKeyManager(); ),
});
this.personalMessageManager = new PersonalMessageManager({
metricsEvent: this.metaMetricsController.trackEvent.bind(
this.metaMetricsController,
),
});
this.decryptMessageManager = new DecryptMessageManager({
metricsEvent: this.metaMetricsController.trackEvent.bind(
this.metaMetricsController,
),
});
this.encryptionPublicKeyManager = new EncryptionPublicKeyManager({
metricsEvent: this.metaMetricsController.trackEvent.bind(
this.metaMetricsController,
),
});
this.typedMessageManager = new TypedMessageManager({ this.typedMessageManager = new TypedMessageManager({
getCurrentChainId: this.networkController.getCurrentChainId.bind( getCurrentChainId: this.networkController.getCurrentChainId.bind(
this.networkController, this.networkController,
), ),
metricsEvent: this.metaMetricsController.trackEvent.bind(
this.metaMetricsController,
),
}); });
this.swapsController = new SwapsController({ this.swapsController = new SwapsController({
@ -924,6 +943,10 @@ export default class MetamaskController extends EventEmitter {
this.preferencesController.setDismissSeedBackUpReminder, this.preferencesController.setDismissSeedBackUpReminder,
this.preferencesController, this.preferencesController,
), ),
setAdvancedGasFee: nodeify(
preferencesController.setAdvancedGasFee,
preferencesController,
),
// AddressController // AddressController
setAddressBook: nodeify( setAddressBook: nodeify(

@ -162,6 +162,10 @@ export default class ExtensionPlatform {
} }
} }
addOnRemovedListener(listener) {
extension.windows.onRemoved.addListener(listener);
}
getAllWindows() { getAllWindows() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
extension.windows.getAll((windows) => { extension.windows.getAll((windows) => {

@ -52,6 +52,9 @@ Options:
bundle. Setting this to `false` is useful e.g. when bundle. Setting this to `false` is useful e.g. when
linking dependencies that are incompatible with lockdown. linking dependencies that are incompatible with lockdown.
[boolean] [default: true] [boolean] [default: true]
--policy-only Stops the build after generating the LavaMoat policy,
skipping any writes to disk.
[boolean] [deafult: false]
--skip-stats Whether to refrain from logging build progress. Mostly --skip-stats Whether to refrain from logging build progress. Mostly
used internally. used internally.
[boolean] [default: false] [boolean] [default: false]

@ -52,6 +52,7 @@ function defineAndRunBuildTasks() {
buildType, buildType,
entryTask, entryTask,
isLavaMoat, isLavaMoat,
policyOnly,
shouldIncludeLockdown, shouldIncludeLockdown,
shouldLintFenceFiles, shouldLintFenceFiles,
skipStats, skipStats,
@ -84,6 +85,7 @@ function defineAndRunBuildTasks() {
ignoredFiles, ignoredFiles,
isLavaMoat, isLavaMoat,
livereload, livereload,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
}); });
@ -134,6 +136,9 @@ function defineAndRunBuildTasks() {
), ),
); );
// build just production scripts, for LavaMoat policy generation purposes
createTask('scripts:prod', scriptTasks.prod);
// build for CI testing // build for CI testing
createTask( createTask(
'test', 'test',
@ -157,6 +162,7 @@ function parseArgv() {
BuildType: 'build-type', BuildType: 'build-type',
LintFenceFiles: 'lint-fence-files', LintFenceFiles: 'lint-fence-files',
Lockdown: 'lockdown', Lockdown: 'lockdown',
PolicyOnly: 'policy-only',
SkipStats: 'skip-stats', SkipStats: 'skip-stats',
}; };
@ -164,6 +170,7 @@ function parseArgv() {
boolean: [ boolean: [
NamedArgs.LintFenceFiles, NamedArgs.LintFenceFiles,
NamedArgs.Lockdown, NamedArgs.Lockdown,
NamedArgs.PolicyOnly,
NamedArgs.SkipStats, NamedArgs.SkipStats,
], ],
string: [NamedArgs.BuildType], string: [NamedArgs.BuildType],
@ -171,6 +178,7 @@ function parseArgv() {
[NamedArgs.BuildType]: BuildType.main, [NamedArgs.BuildType]: BuildType.main,
[NamedArgs.LintFenceFiles]: true, [NamedArgs.LintFenceFiles]: true,
[NamedArgs.Lockdown]: true, [NamedArgs.Lockdown]: true,
[NamedArgs.PolicyOnly]: false,
[NamedArgs.SkipStats]: false, [NamedArgs.SkipStats]: false,
}, },
}); });
@ -198,10 +206,13 @@ function parseArgv() {
? argv[NamedArgs.LintFenceFiles] ? argv[NamedArgs.LintFenceFiles]
: !/dev/iu.test(entryTask); : !/dev/iu.test(entryTask);
const policyOnly = argv[NamedArgs.PolicyOnly];
return { return {
buildType, buildType,
entryTask, entryTask,
isLavaMoat: process.argv[0].includes('lavamoat'), isLavaMoat: process.argv[0].includes('lavamoat'),
policyOnly,
shouldIncludeLockdown: argv[NamedArgs.Lockdown], shouldIncludeLockdown: argv[NamedArgs.Lockdown],
shouldLintFenceFiles, shouldLintFenceFiles,
skipStats: argv[NamedArgs.SkipStats], skipStats: argv[NamedArgs.SkipStats],

@ -134,6 +134,10 @@ function getSegmentWriteKey({ buildType, environment }) {
throw new Error(`Invalid build type: '${buildType}'`); throw new Error(`Invalid build type: '${buildType}'`);
} }
const noopWriteStream = through.obj((_file, _fileEncoding, callback) =>
callback(),
);
module.exports = createScriptTasks; module.exports = createScriptTasks;
function createScriptTasks({ function createScriptTasks({
@ -143,6 +147,7 @@ function createScriptTasks({
isLavaMoat, isLavaMoat,
livereload, livereload,
shouldLintFenceFiles, shouldLintFenceFiles,
policyOnly,
}) { }) {
// internal tasks // internal tasks
const core = { const core = {
@ -185,6 +190,7 @@ function createScriptTasks({
return `./app/scripts/${label}.js`; return `./app/scripts/${label}.js`;
}), }),
ignoredFiles, ignoredFiles,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
testing, testing,
}), }),
@ -200,18 +206,18 @@ function createScriptTasks({
// this can run whenever // this can run whenever
const disableConsoleSubtask = createTask( const disableConsoleSubtask = createTask(
`${taskPrefix}:disable-console`, `${taskPrefix}:disable-console`,
createTaskForBundleDisableConsole({ devMode }), createTaskForBundleDisableConsole({ devMode, testing }),
); );
// this can run whenever // this can run whenever
const installSentrySubtask = createTask( const installSentrySubtask = createTask(
`${taskPrefix}:sentry`, `${taskPrefix}:sentry`,
createTaskForBundleSentry({ devMode }), createTaskForBundleSentry({ devMode, testing }),
); );
const phishingDetectSubtask = createTask( const phishingDetectSubtask = createTask(
`${taskPrefix}:phishing-detect`, `${taskPrefix}:phishing-detect`,
createTaskForBundlePhishingDetect({ devMode }), createTaskForBundlePhishingDetect({ devMode, testing }),
); );
// task for initiating browser livereload // task for initiating browser livereload
@ -241,6 +247,7 @@ function createScriptTasks({
runInChildProcess(subtask, { runInChildProcess(subtask, {
buildType, buildType,
isLavaMoat, isLavaMoat,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
}), }),
); );
@ -248,7 +255,7 @@ function createScriptTasks({
return composeParallel(initiateLiveReload, ...allSubtasks); return composeParallel(initiateLiveReload, ...allSubtasks);
} }
function createTaskForBundleDisableConsole({ devMode }) { function createTaskForBundleDisableConsole({ devMode, testing }) {
const label = 'disable-console'; const label = 'disable-console';
return createNormalBundle({ return createNormalBundle({
browserPlatforms, browserPlatforms,
@ -258,11 +265,13 @@ function createScriptTasks({
entryFilepath: `./app/scripts/${label}.js`, entryFilepath: `./app/scripts/${label}.js`,
ignoredFiles, ignoredFiles,
label, label,
testing,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
}); });
} }
function createTaskForBundleSentry({ devMode }) { function createTaskForBundleSentry({ devMode, testing }) {
const label = 'sentry-install'; const label = 'sentry-install';
return createNormalBundle({ return createNormalBundle({
browserPlatforms, browserPlatforms,
@ -272,11 +281,13 @@ function createScriptTasks({
entryFilepath: `./app/scripts/${label}.js`, entryFilepath: `./app/scripts/${label}.js`,
ignoredFiles, ignoredFiles,
label, label,
testing,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
}); });
} }
function createTaskForBundlePhishingDetect({ devMode }) { function createTaskForBundlePhishingDetect({ devMode, testing }) {
const label = 'phishing-detect'; const label = 'phishing-detect';
return createNormalBundle({ return createNormalBundle({
buildType, buildType,
@ -286,6 +297,8 @@ function createScriptTasks({
entryFilepath: `./app/scripts/${label}.js`, entryFilepath: `./app/scripts/${label}.js`,
ignoredFiles, ignoredFiles,
label, label,
testing,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
}); });
} }
@ -303,6 +316,7 @@ function createScriptTasks({
entryFilepath: `./app/scripts/${inpage}.js`, entryFilepath: `./app/scripts/${inpage}.js`,
label: inpage, label: inpage,
ignoredFiles, ignoredFiles,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
testing, testing,
}), }),
@ -314,6 +328,7 @@ function createScriptTasks({
entryFilepath: `./app/scripts/${contentscript}.js`, entryFilepath: `./app/scripts/${contentscript}.js`,
label: contentscript, label: contentscript,
ignoredFiles, ignoredFiles,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
testing, testing,
}), }),
@ -327,6 +342,7 @@ function createFactoredBuild({
devMode, devMode,
entryFiles, entryFiles,
ignoredFiles, ignoredFiles,
policyOnly,
shouldLintFenceFiles, shouldLintFenceFiles,
testing, testing,
}) { }) {
@ -346,6 +362,7 @@ function createFactoredBuild({
devMode, devMode,
envVars, envVars,
ignoredFiles, ignoredFiles,
policyOnly,
minify, minify,
reloadOnChange, reloadOnChange,
shouldLintFenceFiles, shouldLintFenceFiles,
@ -358,10 +375,14 @@ function createFactoredBuild({
// lavamoat will add lavapack but it will be removed by bify-module-groups // lavamoat will add lavapack but it will be removed by bify-module-groups
// we will re-add it later by installing a lavapack runtime // we will re-add it later by installing a lavapack runtime
const lavamoatOpts = { const lavamoatOpts = {
policy: path.resolve(__dirname, '../../lavamoat/browserify/policy.json'), policy: path.resolve(
__dirname,
`../../lavamoat/browserify/${buildType}/policy.json`,
),
policyName: buildType,
policyOverride: path.resolve( policyOverride: path.resolve(
__dirname, __dirname,
'../../lavamoat/browserify/policy-override.json', `../../lavamoat/browserify/${buildType}/policy-override.json`,
), ),
writeAutoPolicy: process.env.WRITE_AUTO_POLICY, writeAutoPolicy: process.env.WRITE_AUTO_POLICY,
}; };
@ -413,12 +434,17 @@ function createFactoredBuild({
// setup bundle destination // setup bundle destination
browserPlatforms.forEach((platform) => { browserPlatforms.forEach((platform) => {
const dest = `./dist/${platform}/`; const dest = `./dist/${platform}/`;
pipeline.get('dest').push(gulp.dest(dest)); const destination = policyOnly ? noopWriteStream : gulp.dest(dest);
pipeline.get('dest').push(destination);
}); });
}); });
// wait for bundle completion for postprocessing // wait for bundle completion for postprocessing
events.on('bundleDone', () => { events.on('bundleDone', () => {
// Skip HTML generation if nothing is to be written to disk
if (policyOnly) {
return;
}
const commonSet = sizeGroupMap.get('common'); const commonSet = sizeGroupMap.get('common');
// create entry points for each file // create entry points for each file
for (const [groupLabel, groupSet] of sizeGroupMap.entries()) { for (const [groupLabel, groupSet] of sizeGroupMap.entries()) {
@ -456,7 +482,7 @@ function createFactoredBuild({
groupSet, groupSet,
commonSet, commonSet,
browserPlatforms, browserPlatforms,
useLavamoat: false, useLavamoat: true,
}); });
break; break;
} }
@ -492,6 +518,7 @@ function createNormalBundle({
extraEntries = [], extraEntries = [],
ignoredFiles, ignoredFiles,
label, label,
policyOnly,
modulesToExpose, modulesToExpose,
shouldLintFenceFiles, shouldLintFenceFiles,
testing, testing,
@ -512,6 +539,7 @@ function createNormalBundle({
devMode, devMode,
envVars, envVars,
ignoredFiles, ignoredFiles,
policyOnly,
minify, minify,
reloadOnChange, reloadOnChange,
shouldLintFenceFiles, shouldLintFenceFiles,
@ -536,7 +564,8 @@ function createNormalBundle({
// setup bundle destination // setup bundle destination
browserPlatforms.forEach((platform) => { browserPlatforms.forEach((platform) => {
const dest = `./dist/${platform}/`; const dest = `./dist/${platform}/`;
pipeline.get('dest').push(gulp.dest(dest)); const destination = policyOnly ? noopWriteStream : gulp.dest(dest);
pipeline.get('dest').push(destination);
}); });
}); });
@ -566,6 +595,7 @@ function setupBundlerDefaults(
devMode, devMode,
envVars, envVars,
ignoredFiles, ignoredFiles,
policyOnly,
minify, minify,
reloadOnChange, reloadOnChange,
shouldLintFenceFiles, shouldLintFenceFiles,
@ -609,12 +639,14 @@ function setupBundlerDefaults(
setupReloadOnChange(buildConfiguration); setupReloadOnChange(buildConfiguration);
} }
if (minify) { if (!policyOnly) {
setupMinification(buildConfiguration); if (minify) {
} setupMinification(buildConfiguration);
}
// Setup source maps // Setup source maps
setupSourcemaps(buildConfiguration, { devMode }); setupSourcemaps(buildConfiguration, { devMode });
}
} }
function setupReloadOnChange({ bundlerOpts, events }) { function setupReloadOnChange({ bundlerOpts, events }) {

@ -50,7 +50,7 @@ function createTask(taskName, taskFn) {
function runInChildProcess( function runInChildProcess(
task, task,
{ buildType, isLavaMoat, shouldLintFenceFiles }, { buildType, isLavaMoat, policyOnly, shouldLintFenceFiles },
) { ) {
const taskName = typeof task === 'string' ? task : task.taskName; const taskName = typeof task === 'string' ? task : task.taskName;
if (!taskName) { if (!taskName) {
@ -74,6 +74,7 @@ function runInChildProcess(
'--lint-fence-files', '--lint-fence-files',
shouldLintFenceFiles, shouldLintFenceFiles,
'--skip-stats', '--skip-stats',
...(policyOnly ? ['--policy-only'] : []),
], ],
{ {
env: process.env, env: process.env,
@ -90,6 +91,7 @@ function runInChildProcess(
'--lint-fence-files', '--lint-fence-files',
shouldLintFenceFiles, shouldLintFenceFiles,
'--skip-stats', '--skip-stats',
...(policyOnly ? ['--policy-only'] : []),
], ],
{ {
env: process.env, env: process.env,

@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
# Generate LavaMoat policies for the extension background script for each build
# type.
# ATTN: This may tax your device when running it locally.
concurrently --kill-others-on-fail -n main,beta,flask \
"WRITE_AUTO_POLICY=1 yarn build scripts:prod --policy-only" \
"WRITE_AUTO_POLICY=1 yarn build scripts:prod --policy-only --build-type beta" \
"WRITE_AUTO_POLICY=1 yarn build scripts:prod --policy-only --build-type flask"

@ -216,7 +216,12 @@ async function verifyEnglishLocale() {
} }
// never consider these messages as unused // never consider these messages as unused
const messageExceptions = ['appName', 'appDescription']; const messageExceptions = [
'appName',
'appNameBeta',
'appNameFlask',
'appDescription',
];
const englishMessages = Object.keys(englishLocale); const englishMessages = Object.keys(englishLocale);
const unusedMessages = englishMessages.filter( const unusedMessages = englishMessages.filter(

@ -325,6 +325,7 @@
"@ethersproject/bignumber": true, "@ethersproject/bignumber": true,
"@ethersproject/bytes": true, "@ethersproject/bytes": true,
"@ethersproject/keccak256": true, "@ethersproject/keccak256": true,
"@ethersproject/logger": true,
"@ethersproject/sha2": true, "@ethersproject/sha2": true,
"@ethersproject/strings": true "@ethersproject/strings": true
} }
@ -1555,11 +1556,15 @@
}, },
"eth-json-rpc-middleware": { "eth-json-rpc-middleware": {
"globals": { "globals": {
"URL": true,
"btoa": true,
"console.error": true, "console.error": true,
"fetch": true, "fetch": true,
"setTimeout": true "setTimeout": true
}, },
"packages": { "packages": {
"@metamask/safe-event-emitter": true,
"browser-resolve": true,
"btoa": true, "btoa": true,
"clone": true, "clone": true,
"eth-rpc-errors": true, "eth-rpc-errors": true,

@ -0,0 +1,55 @@
{
"resources": {
"browser-resolve": {
"packages": {
"core-js": true
}
},
"babel-runtime": {
"packages": {
"@babel/runtime": true
}
},
"node-fetch": {
"globals": {
"fetch": true
}
},
"lodash": {
"globals": {
"setTimeout": true,
"clearTimeout": true
}
},
"@ethersproject/random": {
"globals": {
"crypto.getRandomValues": true
}
},
"browser-passworder": {
"globals": {
"crypto": true
}
},
"randombytes": {
"globals": {
"crypto.getRandomValues": true
}
},
"extensionizer": {
"globals": {
"console": true
}
},
"web3": {
"globals": {
"XMLHttpRequest": true
}
},
"storage": {
"globals": {
"localStorage": true
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,55 @@
{
"resources": {
"browser-resolve": {
"packages": {
"core-js": true
}
},
"babel-runtime": {
"packages": {
"@babel/runtime": true
}
},
"node-fetch": {
"globals": {
"fetch": true
}
},
"lodash": {
"globals": {
"setTimeout": true,
"clearTimeout": true
}
},
"@ethersproject/random": {
"globals": {
"crypto.getRandomValues": true
}
},
"browser-passworder": {
"globals": {
"crypto": true
}
},
"randombytes": {
"globals": {
"crypto.getRandomValues": true
}
},
"extensionizer": {
"globals": {
"console": true
}
},
"web3": {
"globals": {
"XMLHttpRequest": true
}
},
"storage": {
"globals": {
"localStorage": true
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
{ {
"name": "metamask-crx", "name": "metamask-crx",
"version": "10.6.4", "version": "10.7.0",
"private": true, "private": true,
"repository": { "repository": {
"type": "git", "type": "git",
@ -12,7 +12,7 @@
"start": "yarn build:dev dev", "start": "yarn build:dev dev",
"start:lavamoat": "yarn build dev", "start:lavamoat": "yarn build dev",
"dist": "yarn build prod", "dist": "yarn build prod",
"build": "lavamoat development/build/index.js", "build": "yarn lavamoat:build",
"build:dev": "node development/build/index.js", "build:dev": "node development/build/index.js",
"start:test": "yarn build testDev", "start:test": "yarn build testDev",
"benchmark:chrome": "SELENIUM_BROWSER=chrome node test/e2e/benchmark.js", "benchmark:chrome": "SELENIUM_BROWSER=chrome node test/e2e/benchmark.js",
@ -41,8 +41,9 @@
"test:coverage:path": "nyc --check-coverage yarn test:unit:path", "test:coverage:path": "nyc --check-coverage yarn test:unit:path",
"ganache:start": "./development/run-ganache.sh", "ganache:start": "./development/run-ganache.sh",
"sentry:publish": "node ./development/sentry-publish.js", "sentry:publish": "node ./development/sentry-publish.js",
"lint": "prettier --check '**/*.json' && eslint . --ext js,snap --cache && yarn lint:styles", "lint:prettier": "prettier '**/*.json'",
"lint:fix": "prettier --write '**/*.json' && eslint . --ext js --cache --fix", "lint": "yarn lint:prettier --check '**/*.json' && eslint . --ext js,snap --cache && yarn lint:styles",
"lint:fix": "yarn lint:prettier --write '**/*.json' && eslint . --ext js --cache --fix",
"lint:changed": "{ git ls-files --others --exclude-standard ; git diff-index --name-only --diff-filter=d HEAD ; } | grep --regexp='[.]js$' | tr '\\n' '\\0' | xargs -0 eslint", "lint:changed": "{ git ls-files --others --exclude-standard ; git diff-index --name-only --diff-filter=d HEAD ; } | grep --regexp='[.]js$' | tr '\\n' '\\0' | xargs -0 eslint",
"lint:changed:fix": "{ git ls-files --others --exclude-standard ; git diff-index --name-only --diff-filter=d HEAD ; } | grep --regexp='[.]js$' | tr '\\n' '\\0' | xargs -0 eslint --fix", "lint:changed:fix": "{ git ls-files --others --exclude-standard ; git diff-index --name-only --diff-filter=d HEAD ; } | grep --regexp='[.]js$' | tr '\\n' '\\0' | xargs -0 eslint --fix",
"lint:changelog": "auto-changelog validate", "lint:changelog": "auto-changelog validate",
@ -63,9 +64,10 @@
"storybook:deploy": "storybook-to-ghpages --existing-output-dir storybook-build --remote storybook --branch master", "storybook:deploy": "storybook-to-ghpages --existing-output-dir storybook-build --remote storybook --branch master",
"update-changelog": "auto-changelog update", "update-changelog": "auto-changelog update",
"generate:migration": "./development/generate-migration.sh", "generate:migration": "./development/generate-migration.sh",
"lavamoat:build:auto": "lavamoat ./development/build/index.js --writeAutoPolicy", "lavamoat:build": "lavamoat development/build/index.js --policy lavamoat/build-system/policy.json --policyOverride lavamoat/build-system/policy-override.json",
"lavamoat:debug:build": "lavamoat ./development/build/index.js --writeAutoPolicyDebug", "lavamoat:build:auto": "yarn lavamoat:build --writeAutoPolicy",
"lavamoat:background:auto": "WRITE_AUTO_POLICY=1 yarn build prod", "lavamoat:debug:build": "yarn lavamoat:build --writeAutoPolicyDebug --policydebug lavamoat/build-system/policy-debug.json",
"lavamoat:background:auto": "./development/generate-lavamoat-policies.sh",
"lavamoat:auto": "yarn lavamoat:build:auto && yarn lavamoat:background:auto" "lavamoat:auto": "yarn lavamoat:build:auto && yarn lavamoat:background:auto"
}, },
"resolutions": { "resolutions": {
@ -136,7 +138,7 @@
"eth-ens-namehash": "^2.0.8", "eth-ens-namehash": "^2.0.8",
"eth-json-rpc-filters": "^4.2.1", "eth-json-rpc-filters": "^4.2.1",
"eth-json-rpc-infura": "^5.1.0", "eth-json-rpc-infura": "^5.1.0",
"eth-json-rpc-middleware": "^6.0.0", "eth-json-rpc-middleware": "^8.0.0",
"eth-keyring-controller": "^6.2.0", "eth-keyring-controller": "^6.2.0",
"eth-lattice-keyring": "^0.4.0", "eth-lattice-keyring": "^0.4.0",
"eth-method-registry": "^2.0.0", "eth-method-registry": "^2.0.0",
@ -222,7 +224,7 @@
"@babel/preset-react": "^7.0.0", "@babel/preset-react": "^7.0.0",
"@babel/register": "^7.5.5", "@babel/register": "^7.5.5",
"@lavamoat/allow-scripts": "^1.0.6", "@lavamoat/allow-scripts": "^1.0.6",
"@lavamoat/lavapack": "^2.0.3", "@lavamoat/lavapack": "^2.0.4",
"@metamask/auto-changelog": "^2.1.0", "@metamask/auto-changelog": "^2.1.0",
"@metamask/eslint-config": "^6.0.0", "@metamask/eslint-config": "^6.0.0",
"@metamask/eslint-config-jest": "^6.0.0", "@metamask/eslint-config-jest": "^6.0.0",

@ -140,3 +140,7 @@ export const METAMETRICS_BACKGROUND_PAGE_OBJECT = {
* @property {() => void} identify - Identify an anonymous user. We do not * @property {() => void} identify - Identify an anonymous user. We do not
* currently use this method. * currently use this method.
*/ */
export const REJECT_NOTFICIATION_CLOSE = 'Cancel Via Notification Close';
export const REJECT_NOTFICIATION_CLOSE_SIG =
'Cancel Sig Request Via Notification Close';

@ -161,3 +161,13 @@ export const CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP = {
[OPTIMISM_CHAIN_ID]: 1, [OPTIMISM_CHAIN_ID]: 1,
[OPTIMISM_TESTNET_CHAIN_ID]: 1, [OPTIMISM_TESTNET_CHAIN_ID]: 1,
}; };
/**
* Ethereum JSON-RPC methods that are known to exist but that we intentionally
* do not support.
*/
export const UNSUPPORTED_RPC_METHODS = new Set([
// This is implemented later in our middleware stack – specifically, in
// eth-json-rpc-middleware – but our UI does not support it.
'eth_signTransaction',
]);

@ -160,6 +160,10 @@
"toNickname": "" "toNickname": ""
}, },
"useTokenDetection": true, "useTokenDetection": true,
"advancedGasFee": {
"maxBaseFee": "1.5",
"priorityFee": "2"
},
"tokenList": { "tokenList": {
"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599": { "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599": {
"address": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", "address": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",

@ -27,38 +27,72 @@ describe('Metamask Import UI', function () {
async ({ driver }) => { async ({ driver }) => {
await driver.navigate(); await driver.navigate();
// clicks the continue button on the welcome screen if (process.env.ONBOARDING_V2 === '1') {
await driver.findElement('.welcome-page__header'); // welcome
await driver.clickElement({ await driver.clickElement('[data-testid="onboarding-import-wallet"]');
text: enLocaleMessages.getStarted.message,
tag: 'button',
});
// clicks the "Import Wallet" option // metrics
await driver.clickElement({ text: 'Import wallet', tag: 'button' }); await driver.clickElement('[data-testid="metametrics-no-thanks"]');
// clicks the "No thanks" option on the metametrics opt-in screen // import with recovery phrase
await driver.clickElement('.btn-secondary'); await driver.fill('[data-testid="import-srp-text"]', testSeedPhrase);
await driver.clickElement('[data-testid="import-srp-confirm"]');
// Import Secret Recovery Phrase // create password
await driver.fill( await driver.fill(
'input[placeholder="Paste Secret Recovery Phrase from clipboard"]', '[data-testid="create-password-new"]',
testSeedPhrase, '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="Paste Secret Recovery Phrase from clipboard"]',
testSeedPhrase,
);
await driver.fill('#password', 'correct horse battery staple'); await driver.fill('#password', 'correct horse battery staple');
await driver.fill('#confirm-password', 'correct horse battery staple'); await driver.fill(
'#confirm-password',
'correct horse battery staple',
);
await driver.clickElement('.first-time-flow__terms'); await driver.clickElement('.first-time-flow__terms');
await driver.clickElement({ text: 'Import', tag: 'button' }); await driver.clickElement({ text: 'Import', tag: 'button' });
// clicks through the success screen // clicks through the success screen
await driver.findElement({ text: 'Congratulations', tag: 'div' }); await driver.findElement({ text: 'Congratulations', tag: 'div' });
await driver.clickElement({ await driver.clickElement({
text: enLocaleMessages.endOfFlowMessage10.message, text: enLocaleMessages.endOfFlowMessage10.message,
tag: 'button', tag: 'button',
}); });
}
// Show account information // Show account information
await driver.clickElement( await driver.clickElement(
@ -233,10 +267,15 @@ describe('Metamask Import UI', function () {
// should remove the account // should remove the account
await driver.clickElement({ text: 'Remove', tag: 'button' }); await driver.clickElement({ text: 'Remove', tag: 'button' });
const currentActiveAccountName = await driver.findElement( // Wait until selected account switches away from removed account to first account
'.selected-account__name', await driver.waitForSelector(
{
css: '.selected-account__name',
text: 'Account 1',
},
{ timeout: 10000 },
); );
assert.equal(await currentActiveAccountName.getText(), 'Account 1');
await driver.delay(regularDelayMs); await driver.delay(regularDelayMs);
await driver.clickElement('.account-menu__icon'); await driver.clickElement('.account-menu__icon');

@ -16,77 +16,133 @@ describe('Metamask Responsive UI', function () {
async ({ driver }) => { async ({ driver }) => {
await driver.navigate(); await driver.navigate();
// clicks the continue button on the welcome screen async function clickWordAndWait(word) {
await driver.findElement('.welcome-page__header'); await driver.clickElement(
await driver.clickElement({ `[data-testid="seed-phrase-sorted"] [data-testid="draggable-seed-${word}"]`,
text: enLocaleMessages.getStarted.message, );
tag: 'button', await driver.delay(tinyDelayMs);
}); }
await driver.delay(tinyDelayMs);
// clicks the "Create New Wallet" option if (process.env.ONBOARDING_V2 === '1') {
await driver.clickElement({ text: 'Create a Wallet', tag: 'button' }); // welcome
await driver.clickElement('[data-testid="onboarding-create-wallet"]');
// clicks the "I Agree" option on the metametrics opt-in screen // metrics
await driver.clickElement('.btn-primary'); await driver.clickElement('[data-testid="metametrics-no-thanks"]');
// accepts a secure password // create password
await driver.fill( await driver.fill(
'.first-time-flow__form #create-password', '[data-testid="create-password-new"]',
'correct horse battery staple', 'correct horse battery staple',
); );
await driver.fill( await driver.fill(
'.first-time-flow__form #confirm-password', '[data-testid="create-password-confirm"]',
'correct horse battery staple', 'correct horse battery staple',
); );
await driver.clickElement('.first-time-flow__checkbox'); await driver.clickElement('[data-testid="create-password-terms"]');
await driver.clickElement('.first-time-flow__form button'); await driver.clickElement('[data-testid="create-password-wallet"]');
// renders the Secret Recovery Phrase intro screen // secure wallet
await driver.clickElement('.seed-phrase-intro__left button'); await driver.clickElement(
'[data-testid="secure-wallet-recommended"]',
);
// reveals the Secret Recovery Phrase // review
await driver.clickElement( await driver.clickElement('[data-testid="recovery-phrase-reveal"]');
'.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button', const chipTwo = await (
); await driver.findElement('[data-testid="recovery-phrase-chip-2"]')
const revealedSeedPhrase = await driver.findElement( ).getText();
'.reveal-seed-phrase__secret-words', const chipThree = await (
); await driver.findElement('[data-testid="recovery-phrase-chip-3"]')
const seedPhrase = await revealedSeedPhrase.getText(); ).getText();
assert.equal(seedPhrase.split(' ').length, 12); const chipSeven = await (
await driver.findElement('[data-testid="recovery-phrase-chip-7"]')
).getText();
await driver.clickElement('[data-testid="recovery-phrase-next"]');
// confirm
await driver.fill('[data-testid="recovery-phrase-input-2"]', chipTwo);
await driver.fill(
'[data-testid="recovery-phrase-input-3"]',
chipThree,
);
await driver.fill(
'[data-testid="recovery-phrase-input-7"]',
chipSeven,
);
await driver.clickElement('[data-testid="recovery-phrase-confirm"]');
// 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',
});
await driver.delay(tinyDelayMs);
await driver.clickElement({ // clicks the "Create New Wallet" option
text: enLocaleMessages.next.message, await driver.clickElement({ text: 'Create a Wallet', tag: 'button' });
tag: 'button',
});
async function clickWordAndWait(word) { // clicks the "I Agree" option on the metametrics opt-in screen
await driver.clickElement( await driver.clickElement('.btn-primary');
`[data-testid="seed-phrase-sorted"] [data-testid="draggable-seed-${word}"]`,
// accepts a secure password
await driver.fill(
'.first-time-flow__form #create-password',
'correct horse battery staple',
); );
await driver.delay(tinyDelayMs); await driver.fill(
} '.first-time-flow__form #confirm-password',
'correct horse battery staple',
);
await driver.clickElement('.first-time-flow__checkbox');
await driver.clickElement('.first-time-flow__form button');
// can retype the Secret Recovery Phrase // renders the Secret Recovery Phrase intro screen
const words = seedPhrase.split(' '); await driver.clickElement('.seed-phrase-intro__left button');
for (const word of words) {
await clickWordAndWait(word);
}
await driver.clickElement({ text: 'Confirm', tag: 'button' });
// clicks through the success screen // reveals the Secret Recovery Phrase
await driver.findElement({ text: 'Congratulations', tag: 'div' }); await driver.clickElement(
await driver.clickElement({ '.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button',
text: enLocaleMessages.endOfFlowMessage10.message, );
tag: 'button', const revealedSeedPhrase = await driver.findElement(
}); '.reveal-seed-phrase__secret-words',
);
const seedPhrase = await revealedSeedPhrase.getText();
assert.equal(seedPhrase.split(' ').length, 12);
await driver.clickElement({
text: enLocaleMessages.next.message,
tag: 'button',
});
// can retype the Secret Recovery Phrase
const words = seedPhrase.split(' ');
for (const word of words) {
await clickWordAndWait(word);
}
await driver.clickElement({ text: 'Confirm', tag: 'button' });
// clicks through the success screen
await driver.findElement({ text: 'Congratulations', tag: 'div' });
await driver.clickElement({
text: enLocaleMessages.endOfFlowMessage10.message,
tag: 'button',
});
}
// Show account information // assert balance
// balance renders const balance = await driver.findElement(
await driver.waitForSelector({ '[data-testid="wallet-balance"]',
css: '[data-testid="eth-overview__primary-currency"]', );
text: '0 ETH', assert.ok(/^0\sETH$/u.test(await balance.getText()));
});
}, },
); );
}); });

@ -1,17 +1,19 @@
const { strict: assert } = require('assert'); const { strict: assert } = require('assert');
const { errorCodes } = require('eth-rpc-errors');
const { withFixtures } = require('../helpers'); const { withFixtures } = require('../helpers');
describe('MetaMask', function () { describe('MetaMask', function () {
const ganacheOptions = {
accounts: [
{
secretKey:
'0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC',
balance: 25000000000000000000,
},
],
};
it('provider should inform dapp when switching networks', async function () { it('provider should inform dapp when switching networks', async function () {
const ganacheOptions = {
accounts: [
{
secretKey:
'0x7C9529A67102755B7E6102D6D950AC5D5863C98713805CEC576B945B15B71EAC',
balance: 25000000000000000000,
},
],
};
await withFixtures( await withFixtures(
{ {
dapp: true, dapp: true,
@ -62,4 +64,48 @@ describe('MetaMask', function () {
}, },
); );
}); });
it('should reject unsupported methods', async function () {
await withFixtures(
{
dapp: true,
failOnConsoleError: false,
fixtures: 'connected-state',
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.openNewPage('http://127.0.0.1:8080/');
for (const unsupportedMethod of ['eth_signTransaction']) {
assert.equal(
await driver.executeAsyncScript(`
const webDriverCallback = arguments[arguments.length - 1];
window.ethereum.request({ method: '${unsupportedMethod}' })
.then(() => {
console.error('The unsupported method "${unsupportedMethod}" was not rejected.');
webDriverCallback(false);
})
.catch((error) => {
if (error.code === ${errorCodes.rpc.methodNotSupported}) {
webDriverCallback(true);
}
console.error(
'The unsupported method "${unsupportedMethod}" was rejected with an unexpected error.',
error,
);
webDriverCallback(false);
})
`),
true,
`The unsupported method "${unsupportedMethod}" should be rejected by the provider.`,
);
}
},
);
});
}); });

@ -29,6 +29,10 @@ function wrapElementWithAPI(element, driver) {
return element; return element;
} }
/**
* For Selenium WebDriver API documentation, see:
* https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html
*/
class Driver { class Driver {
/** /**
* @param {!ThenableWebDriver} driver - A {@code WebDriver} instance * @param {!ThenableWebDriver} driver - A {@code WebDriver} instance
@ -49,6 +53,10 @@ class Driver {
}; };
} }
async executeAsyncScript(script, ...args) {
return this.driver.executeAsyncScript(script, args);
}
async executeScript(script, ...args) { async executeScript(script, ...args) {
return this.driver.executeScript(script, args); return this.driver.executeScript(script, args);
} }

@ -1,6 +1,5 @@
import { JsonRpcEngine } from 'json-rpc-engine'; import { JsonRpcEngine, createScaffoldMiddleware } from 'json-rpc-engine';
import scaffoldMiddleware from 'eth-json-rpc-middleware/scaffold'; import { providerAsMiddleware } from 'eth-json-rpc-middleware';
import providerAsMiddleware from 'eth-json-rpc-middleware/providerAsMiddleware';
import GanacheCore from 'ganache-core'; import GanacheCore from 'ganache-core';
export function getTestSeed() { export function getTestSeed() {
@ -45,7 +44,7 @@ export function providerFromEngine(engine) {
export function createTestProviderTools(opts = {}) { export function createTestProviderTools(opts = {}) {
const engine = createEngineForTestData(); const engine = createEngineForTestData();
// handle provided hooks // handle provided hooks
engine.push(scaffoldMiddleware(opts.scaffold || {})); engine.push(createScaffoldMiddleware(opts.scaffold || {}));
// handle block tracker methods // handle block tracker methods
engine.push( engine.push(
providerAsMiddleware( providerAsMiddleware(

@ -10,6 +10,14 @@ import ConfirmPageContainer, {
ConfirmPageContainerNavigation, ConfirmPageContainerNavigation,
} from '.'; } from '.';
jest.mock('../../../store/actions', () => ({
disconnectGasFeeEstimatePoller: jest.fn(),
getGasFeeEstimatesAndStartPolling: jest
.fn()
.mockImplementation(() => Promise.resolve()),
addPollingTokenToAppState: jest.fn(),
}));
describe('Confirm Page Container Container Test', () => { describe('Confirm Page Container Container Test', () => {
let wrapper; let wrapper;
@ -31,6 +39,8 @@ describe('Confirm Page Container Container Test', () => {
selectedAddress: '0xd8f6a2ffb0fc5952d16c9768b71cfd35b6399aa5', selectedAddress: '0xd8f6a2ffb0fc5952d16c9768b71cfd35b6399aa5',
addressBook: [], addressBook: [],
chainId: 'test', chainId: 'test',
identities: [],
featureFlags: {},
}, },
}; };

@ -4,6 +4,7 @@ import SenderToRecipient from '../../ui/sender-to-recipient';
import { PageContainerFooter } from '../../ui/page-container'; import { PageContainerFooter } from '../../ui/page-container';
import EditGasPopover from '../edit-gas-popover'; import EditGasPopover from '../edit-gas-popover';
import { EDIT_GAS_MODES } from '../../../../shared/constants/gas'; import { EDIT_GAS_MODES } from '../../../../shared/constants/gas';
import { GasFeeContextProvider } from '../../../contexts/gasFee';
import ErrorMessage from '../../ui/error-message'; import ErrorMessage from '../../ui/error-message';
import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction'; import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction';
import Dialog from '../../ui/dialog'; import Dialog from '../../ui/dialog';
@ -135,102 +136,104 @@ export default class ConfirmPageContainer extends Component {
currentTransaction.txParams?.value === '0x0'; currentTransaction.txParams?.value === '0x0';
return ( return (
<div className="page-container"> <GasFeeContextProvider transaction={currentTransaction}>
<ConfirmPageContainerNavigation <div className="page-container">
totalTx={totalTx} <ConfirmPageContainerNavigation
positionOfCurrentTx={positionOfCurrentTx} totalTx={totalTx}
nextTxId={nextTxId} positionOfCurrentTx={positionOfCurrentTx}
prevTxId={prevTxId} nextTxId={nextTxId}
showNavigation={showNavigation} prevTxId={prevTxId}
onNextTx={(txId) => onNextTx(txId)} showNavigation={showNavigation}
firstTx={firstTx} onNextTx={(txId) => onNextTx(txId)}
lastTx={lastTx} firstTx={firstTx}
ofText={ofText} lastTx={lastTx}
requestsWaitingText={requestsWaitingText} ofText={ofText}
/> requestsWaitingText={requestsWaitingText}
<ConfirmPageContainerHeader />
showEdit={showEdit} <ConfirmPageContainerHeader
onEdit={() => onEdit()} showEdit={showEdit}
showAccountInHeader={showAccountInHeader} onEdit={() => onEdit()}
accountAddress={fromAddress} showAccountInHeader={showAccountInHeader}
> accountAddress={fromAddress}
{hideSenderToRecipient ? null : ( >
<SenderToRecipient {hideSenderToRecipient ? null : (
senderName={fromName} <SenderToRecipient
senderAddress={fromAddress} senderName={fromName}
recipientName={toName} senderAddress={fromAddress}
recipientAddress={toAddress} recipientName={toName}
recipientEns={toEns} recipientAddress={toAddress}
recipientNickname={toNickname} recipientEns={toEns}
recipientNickname={toNickname}
/>
)}
</ConfirmPageContainerHeader>
<div>
{showAddToAddressDialog && (
<Dialog
type="message"
className="send__dialog"
onClick={() => showAddToAddressBookModal()}
>
{this.context.t('newAccountDetectedDialogMessage')}
</Dialog>
)}
</div>
{contentComponent || (
<ConfirmPageContainerContent
action={action}
title={title}
titleComponent={titleComponent}
subtitleComponent={subtitleComponent}
hideSubtitle={hideSubtitle}
detailsComponent={detailsComponent}
dataComponent={dataComponent}
errorMessage={errorMessage}
errorKey={errorKey}
identiconAddress={identiconAddress}
nonce={nonce}
warning={warning}
onCancelAll={onCancelAll}
onCancel={onCancel}
cancelText={this.context.t('reject')}
onSubmit={onSubmit}
submitText={this.context.t('confirm')}
disabled={disabled}
unapprovedTxCount={unapprovedTxCount}
rejectNText={this.context.t('rejectTxsN', [unapprovedTxCount])}
origin={origin}
ethGasPriceWarning={ethGasPriceWarning}
hideTitle={hideTitle}
/> />
)} )}
</ConfirmPageContainerHeader> {shouldDisplayWarning && (
<div> <div className="confirm-approve-content__warning">
{showAddToAddressDialog && ( <ErrorMessage errorKey={errorKey} />
<Dialog </div>
type="message" )}
className="send__dialog" {contentComponent && (
onClick={() => showAddToAddressBookModal()} <PageContainerFooter
onCancel={onCancel}
cancelText={this.context.t('reject')}
onSubmit={onSubmit}
submitText={this.context.t('confirm')}
disabled={disabled}
> >
{this.context.t('newAccountDetectedDialogMessage')} {unapprovedTxCount > 1 && (
</Dialog> <a onClick={onCancelAll}>
{this.context.t('rejectTxsN', [unapprovedTxCount])}
</a>
)}
</PageContainerFooter>
)}
{editingGas && (
<EditGasPopover
mode={EDIT_GAS_MODES.MODIFY_IN_PLACE}
onClose={handleCloseEditGas}
transaction={currentTransaction}
/>
)} )}
</div> </div>
{contentComponent || ( </GasFeeContextProvider>
<ConfirmPageContainerContent
action={action}
title={title}
titleComponent={titleComponent}
subtitleComponent={subtitleComponent}
hideSubtitle={hideSubtitle}
detailsComponent={detailsComponent}
dataComponent={dataComponent}
errorMessage={errorMessage}
errorKey={errorKey}
identiconAddress={identiconAddress}
nonce={nonce}
warning={warning}
onCancelAll={onCancelAll}
onCancel={onCancel}
cancelText={this.context.t('reject')}
onSubmit={onSubmit}
submitText={this.context.t('confirm')}
disabled={disabled}
unapprovedTxCount={unapprovedTxCount}
rejectNText={this.context.t('rejectTxsN', [unapprovedTxCount])}
origin={origin}
ethGasPriceWarning={ethGasPriceWarning}
hideTitle={hideTitle}
/>
)}
{shouldDisplayWarning && (
<div className="confirm-approve-content__warning">
<ErrorMessage errorKey={errorKey} />
</div>
)}
{contentComponent && (
<PageContainerFooter
onCancel={onCancel}
cancelText={this.context.t('reject')}
onSubmit={onSubmit}
submitText={this.context.t('confirm')}
disabled={disabled}
>
{unapprovedTxCount > 1 && (
<a onClick={onCancelAll}>
{this.context.t('rejectTxsN', [unapprovedTxCount])}
</a>
)}
</PageContainerFooter>
)}
{editingGas && (
<EditGasPopover
mode={EDIT_GAS_MODES.MODIFY_IN_PLACE}
onClose={handleCloseEditGas}
transaction={currentTransaction}
/>
)}
</div>
); );
} }
} }

@ -24,6 +24,7 @@ import InfoTooltip from '../../ui/info-tooltip/info-tooltip';
import { getGasFeeTimeEstimate } from '../../../store/actions'; import { getGasFeeTimeEstimate } from '../../../store/actions';
import { GAS_FORM_ERRORS } from '../../../helpers/constants/gas'; import { GAS_FORM_ERRORS } from '../../../helpers/constants/gas';
import { useGasFeeContext } from '../../../contexts/gasFee';
// Once we reach this second threshold, we switch to minutes as a unit // Once we reach this second threshold, we switch to minutes as a unit
const SECOND_CUTOFF = 90; const SECOND_CUTOFF = 90;
@ -49,6 +50,7 @@ export default function GasTiming({
const [customEstimatedTime, setCustomEstimatedTime] = useState(null); const [customEstimatedTime, setCustomEstimatedTime] = useState(null);
const t = useContext(I18nContext); const t = useContext(I18nContext);
const { estimateToUse } = useGasFeeContext();
// If the user has chosen a value lower than the low gas fee estimate, // If the user has chosen a value lower than the low gas fee estimate,
// We'll need to use the useEffect hook below to make a call to calculate // We'll need to use the useEffect hook below to make a call to calculate
@ -94,12 +96,17 @@ export default function GasTiming({
previousIsUnknownLow, previousIsUnknownLow,
]); ]);
const unknownProcessingTimeText = ( let unknownProcessingTimeText;
<> if (EIP_1559_V2) {
{t('editGasTooLow')}{' '} unknownProcessingTimeText = t('editGasTooLow');
<InfoTooltip position="top" contentText={t('editGasTooLowTooltip')} /> } else {
</> unknownProcessingTimeText = (
); <>
{t('editGasTooLow')}{' '}
<InfoTooltip position="top" contentText={t('editGasTooLowTooltip')} />
</>
);
}
if ( if (
gasWarnings?.maxPriorityFee === GAS_FORM_ERRORS.MAX_PRIORITY_FEE_TOO_LOW || gasWarnings?.maxPriorityFee === GAS_FORM_ERRORS.MAX_PRIORITY_FEE_TOO_LOW ||
@ -148,8 +155,9 @@ export default function GasTiming({
]); ]);
} }
} else { } else {
attitude = 'negative'; if (!EIP_1559_V2 || estimateToUse === 'low') {
attitude = 'negative';
}
// If the user has chosen a value less than our low estimate, // If the user has chosen a value less than our low estimate,
// calculate a potential wait time // calculate a potential wait time
if (isUnknownLow) { if (isUnknownLow) {
@ -191,7 +199,8 @@ export default function GasTiming({
<Typography <Typography
variant={TYPOGRAPHY.H7} variant={TYPOGRAPHY.H7}
className={classNames('gas-timing', { className={classNames('gas-timing', {
[`gas-timing--${attitude}`]: attitude, [`gas-timing--${attitude}`]: attitude && !EIP_1559_V2,
[`gas-timing--${attitude}-V2`]: attitude && EIP_1559_V2,
})} })}
> >
{text} {text}

@ -14,6 +14,11 @@
font-weight: bold; font-weight: bold;
} }
&--negative-V2 {
color: $secondary-1;
font-weight: bold;
}
.info-tooltip { .info-tooltip {
display: inline-block; display: inline-block;
margin-inline-start: 4px; margin-inline-start: 4px;

@ -84,9 +84,7 @@ export default class AccountDetailsModal extends Component {
? this.context.t('blockExplorerView', [ ? this.context.t('blockExplorerView', [
getURLHostName(rpcPrefs.blockExplorerUrl), getURLHostName(rpcPrefs.blockExplorerUrl),
]) ])
: this.context.t('viewOnEtherscan', [ : this.context.t('etherscanViewOn')}
this.context.t('blockExplorerAccountAction'),
])}
</Button> </Button>
{exportPrivateKeyFeatureEnabled ? ( {exportPrivateKeyFeatureEnabled ? (

@ -8,13 +8,13 @@
& &__button { & &__button {
margin-top: 17px; margin-top: 17px;
padding: 10px 22px; padding: 10px 22px;
width: 286px; width: 284px;
} }
&__divider { &__divider {
width: 100%; width: 100%;
height: 1px; height: 1px;
margin: 19px 0 8px 0; margin: 16px 0 8px 0;
background-color: $alto; background-color: $alto;
} }

@ -64,7 +64,7 @@ const accountModalStyle = {
margin: '0 auto', margin: '0 auto',
}, },
laptopModalStyle: { laptopModalStyle: {
width: '360px', width: '335px',
// top: 'calc(33% + 45px)', // top: 'calc(33% + 45px)',
boxShadow: 'rgba(0, 0, 0, 0.15) 0px 2px 2px 2px', boxShadow: 'rgba(0, 0, 0, 0.15) 0px 2px 2px 2px',
borderRadius: '4px', borderRadius: '4px',

@ -14,6 +14,7 @@ export default function MultilayerFeeMessage({
transaction, transaction,
layer2fee, layer2fee,
nativeCurrency, nativeCurrency,
plainStyle,
}) { }) {
const t = useContext(I18nContext); const t = useContext(I18nContext);
@ -57,12 +58,16 @@ export default function MultilayerFeeMessage({
key="total-item" key="total-item"
detailTitle={t('layer1Fees')} detailTitle={t('layer1Fees')}
detailTotal={layer1Total} detailTotal={layer1Total}
noBold={plainStyle}
flexWidthValues={plainStyle}
/> />
<TransactionDetailItem <TransactionDetailItem
key="total-item" key="total-item"
detailTitle={t('total')} detailTitle={t('total')}
detailTotal={totalInEth} detailTotal={totalInEth}
subTitle={t('transactionDetailMultiLayerTotalSubtitle')} subTitle={t('transactionDetailMultiLayerTotalSubtitle')}
noBold={plainStyle}
flexWidthValues={plainStyle}
/> />
</> </>
); );
@ -72,4 +77,5 @@ MultilayerFeeMessage.propTypes = {
transaction: PropTypes.object, transaction: PropTypes.object,
layer2fee: PropTypes.string, layer2fee: PropTypes.string,
nativeCurrency: PropTypes.string, nativeCurrency: PropTypes.string,
plainStyle: PropTypes.bool,
}; };

@ -5,11 +5,7 @@ import classnames from 'classnames';
import { ObjectInspector } from 'react-inspector'; import { ObjectInspector } from 'react-inspector';
import LedgerInstructionField from '../ledger-instruction-field'; import LedgerInstructionField from '../ledger-instruction-field';
import { import { MESSAGE_TYPE } from '../../../../shared/constants/app';
ENVIRONMENT_TYPE_NOTIFICATION,
MESSAGE_TYPE,
} from '../../../../shared/constants/app';
import { getEnvironmentType } from '../../../../app/scripts/lib/util';
import Identicon from '../../ui/identicon'; import Identicon from '../../ui/identicon';
import AccountListItem from '../account-list-item'; import AccountListItem from '../account-list-item';
import { conversionUtil } from '../../../../shared/modules/conversion.utils'; import { conversionUtil } from '../../../../shared/modules/conversion.utils';
@ -39,42 +35,13 @@ export default class SignatureRequestOriginal extends Component {
domainMetadata: PropTypes.object, domainMetadata: PropTypes.object,
hardwareWalletRequiresConnection: PropTypes.bool, hardwareWalletRequiresConnection: PropTypes.bool,
isLedgerWallet: PropTypes.bool, isLedgerWallet: PropTypes.bool,
nativeCurrency: PropTypes.string.isRequired,
}; };
state = { state = {
fromAccount: this.props.fromAccount, fromAccount: this.props.fromAccount,
}; };
componentDidMount = () => {
if (getEnvironmentType() === ENVIRONMENT_TYPE_NOTIFICATION) {
window.addEventListener('beforeunload', this._beforeUnload);
}
};
componentWillUnmount = () => {
this._removeBeforeUnload();
};
_beforeUnload = (event) => {
const { clearConfirmTransaction, cancel } = this.props;
const { metricsEvent } = this.context;
metricsEvent({
eventOpts: {
category: 'Transactions',
action: 'Sign Request',
name: 'Cancel Sig Request Via Notification Close',
},
});
clearConfirmTransaction();
cancel(event);
};
_removeBeforeUnload = () => {
if (getEnvironmentType() === ENVIRONMENT_TYPE_NOTIFICATION) {
window.removeEventListener('beforeunload', this._beforeUnload);
}
};
renderHeader = () => { renderHeader = () => {
return ( return (
<div className="request-signature__header"> <div className="request-signature__header">
@ -108,12 +75,12 @@ export default class SignatureRequestOriginal extends Component {
}; };
renderBalance = () => { renderBalance = () => {
const { conversionRate } = this.props; const { conversionRate, nativeCurrency } = this.props;
const { const {
fromAccount: { balance }, fromAccount: { balance },
} = this.state; } = this.state;
const balanceInEther = conversionUtil(balance, { const balanceInBaseAsset = conversionUtil(balance, {
fromNumericBase: 'hex', fromNumericBase: 'hex',
toNumericBase: 'dec', toNumericBase: 'dec',
fromDenomination: 'WEI', fromDenomination: 'WEI',
@ -127,7 +94,7 @@ export default class SignatureRequestOriginal extends Component {
{`${this.context.t('balance')}:`} {`${this.context.t('balance')}:`}
</div> </div>
<div className="request-signature__balance-value"> <div className="request-signature__balance-value">
{`${balanceInEther} ETH`} {`${balanceInBaseAsset} ${nativeCurrency}`}
</div> </div>
</div> </div>
); );
@ -300,7 +267,6 @@ export default class SignatureRequestOriginal extends Component {
large large
className="request-signature__footer__cancel-button" className="request-signature__footer__cancel-button"
onClick={async (event) => { onClick={async (event) => {
this._removeBeforeUnload();
await cancel(event); await cancel(event);
metricsEvent({ metricsEvent({
eventOpts: { eventOpts: {
@ -325,7 +291,6 @@ export default class SignatureRequestOriginal extends Component {
className="request-signature__footer__sign-button" className="request-signature__footer__sign-button"
disabled={hardwareWalletRequiresConnection} disabled={hardwareWalletRequiresConnection}
onClick={async (event) => { onClick={async (event) => {
this._removeBeforeUnload();
await sign(event); await sign(event);
metricsEvent({ metricsEvent({
eventOpts: { eventOpts: {

@ -13,7 +13,10 @@ import {
import { getAccountByAddress } from '../../../helpers/utils/util'; import { getAccountByAddress } from '../../../helpers/utils/util';
import { clearConfirmTransaction } from '../../../ducks/confirm-transaction/confirm-transaction.duck'; import { clearConfirmTransaction } from '../../../ducks/confirm-transaction/confirm-transaction.duck';
import { getMostRecentOverviewPage } from '../../../ducks/history/history'; import { getMostRecentOverviewPage } from '../../../ducks/history/history';
import { isAddressLedger } from '../../../ducks/metamask/metamask'; import {
isAddressLedger,
getNativeCurrency,
} from '../../../ducks/metamask/metamask';
import SignatureRequestOriginal from './signature-request-original.component'; import SignatureRequestOriginal from './signature-request-original.component';
function mapStateToProps(state, ownProps) { function mapStateToProps(state, ownProps) {
@ -34,6 +37,7 @@ function mapStateToProps(state, ownProps) {
mostRecentOverviewPage: getMostRecentOverviewPage(state), mostRecentOverviewPage: getMostRecentOverviewPage(state),
hardwareWalletRequiresConnection, hardwareWalletRequiresConnection,
isLedgerWallet, isLedgerWallet,
nativeCurrency: getNativeCurrency(state),
// not passed to component // not passed to component
allAccounts: accountsWithSendEtherInfoSelector(state), allAccounts: accountsWithSendEtherInfoSelector(state),
domainMetadata: getDomainMetadata(state), domainMetadata: getDomainMetadata(state),

@ -1,12 +1,10 @@
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { getEnvironmentType } from '../../../../app/scripts/lib/util';
import Identicon from '../../ui/identicon'; import Identicon from '../../ui/identicon';
import LedgerInstructionField from '../ledger-instruction-field'; import LedgerInstructionField from '../ledger-instruction-field';
import Header from './signature-request-header'; import Header from './signature-request-header';
import Footer from './signature-request-footer'; import Footer from './signature-request-footer';
import Message from './signature-request-message'; import Message from './signature-request-message';
import { ENVIRONMENT_TYPE_NOTIFICATION } from './signature-request.constants';
export default class SignatureRequest extends PureComponent { export default class SignatureRequest extends PureComponent {
static propTypes = { static propTypes = {
@ -17,7 +15,6 @@ export default class SignatureRequest extends PureComponent {
name: PropTypes.string, name: PropTypes.string,
}).isRequired, }).isRequired,
isLedgerWallet: PropTypes.bool, isLedgerWallet: PropTypes.bool,
clearConfirmTransaction: PropTypes.func.isRequired,
cancel: PropTypes.func.isRequired, cancel: PropTypes.func.isRequired,
sign: PropTypes.func.isRequired, sign: PropTypes.func.isRequired,
hardwareWalletRequiresConnection: PropTypes.func.isRequired, hardwareWalletRequiresConnection: PropTypes.func.isRequired,
@ -28,33 +25,6 @@ export default class SignatureRequest extends PureComponent {
metricsEvent: PropTypes.func, metricsEvent: PropTypes.func,
}; };
componentDidMount() {
if (getEnvironmentType() === ENVIRONMENT_TYPE_NOTIFICATION) {
window.addEventListener('beforeunload', this._beforeUnload);
}
}
_beforeUnload = (event) => {
const {
clearConfirmTransaction,
cancel,
txData: { type },
} = this.props;
const { metricsEvent } = this.context;
metricsEvent({
eventOpts: {
category: 'Transactions',
action: 'Sign Request',
name: 'Cancel Sig Request Via Notification Close',
},
customVariables: {
type,
},
});
clearConfirmTransaction();
cancel(event);
};
formatWallet(wallet) { formatWallet(wallet) {
return `${wallet.slice(0, 8)}...${wallet.slice( return `${wallet.slice(0, 8)}...${wallet.slice(
wallet.length - 8, wallet.length - 8,
@ -79,7 +49,6 @@ export default class SignatureRequest extends PureComponent {
const { metricsEvent } = this.context; const { metricsEvent } = this.context;
const onSign = (event) => { const onSign = (event) => {
window.removeEventListener('beforeunload', this._beforeUnload);
sign(event); sign(event);
metricsEvent({ metricsEvent({
eventOpts: { eventOpts: {
@ -95,7 +64,6 @@ export default class SignatureRequest extends PureComponent {
}; };
const onCancel = (event) => { const onCancel = (event) => {
window.removeEventListener('beforeunload', this._beforeUnload);
cancel(event); cancel(event);
metricsEvent({ metricsEvent({
eventOpts: { eventOpts: {

@ -1,5 +1,4 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { clearConfirmTransaction } from '../../../ducks/confirm-transaction/confirm-transaction.duck';
import { import {
accountsWithSendEtherInfoSelector, accountsWithSendEtherInfoSelector,
doesAddressRequireLedgerHidConnection, doesAddressRequireLedgerHidConnection,
@ -28,12 +27,6 @@ function mapStateToProps(state, ownProps) {
}; };
} }
function mapDispatchToProps(dispatch) {
return {
clearConfirmTransaction: () => dispatch(clearConfirmTransaction()),
};
}
function mergeProps(stateProps, dispatchProps, ownProps) { function mergeProps(stateProps, dispatchProps, ownProps) {
const { const {
allAccounts, allAccounts,
@ -83,8 +76,4 @@ function mergeProps(stateProps, dispatchProps, ownProps) {
}; };
} }
export default connect( export default connect(mapStateToProps, null, mergeProps)(SignatureRequest);
mapStateToProps,
mapDispatchToProps,
mergeProps,
)(SignatureRequest);

@ -13,6 +13,17 @@
word-break: break-word; word-break: break-word;
} }
&__detail-values {
display: flex;
flex-wrap: wrap;
justify-content: end;
width: 55%;
&--flex-width {
width: auto;
}
}
.info-tooltip { .info-tooltip {
display: inline-block; display: inline-block;
margin-inline-start: 4px; margin-inline-start: 4px;

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import classnames from 'classnames';
import Typography from '../../ui/typography/typography'; import Typography from '../../ui/typography/typography';
import { import {
@ -15,26 +16,35 @@ export default function TransactionDetailItem({
detailTotal = '', detailTotal = '',
subTitle = '', subTitle = '',
subText = '', subText = '',
boldHeadings = true,
flexWidthValues = false,
}) { }) {
return ( return (
<div className="transaction-detail-item"> <div className="transaction-detail-item">
<div className="transaction-detail-item__row"> <div className="transaction-detail-item__row">
<Typography <Typography
color={detailTitleColor} color={detailTitleColor}
fontWeight={FONT_WEIGHT.BOLD} fontWeight={boldHeadings ? FONT_WEIGHT.BOLD : FONT_WEIGHT.NORMAL}
variant={TYPOGRAPHY.H6} variant={TYPOGRAPHY.H6}
className="transaction-detail-item__title" className="transaction-detail-item__title"
> >
{detailTitle} {detailTitle}
</Typography> </Typography>
{detailText && ( {detailText && (
<Typography <div
variant={TYPOGRAPHY.H6} className={classnames('transaction-detail-item__detail-values', {
className="transaction-detail-item__detail-text" 'transaction-detail-item__detail-values--flex-width': flexWidthValues,
color={COLORS.UI4} })}
> >
{detailText} <Typography
</Typography> fontWeight={boldHeadings ? FONT_WEIGHT.BOLD : FONT_WEIGHT.NORMAL}
variant={TYPOGRAPHY.H6}
className="transaction-detail-item__detail-text"
color={COLORS.UI4}
>
{detailText}
</Typography>
</div>
)} )}
<Typography <Typography
color={COLORS.BLACK} color={COLORS.BLACK}
@ -77,4 +87,6 @@ TransactionDetailItem.propTypes = {
detailTotal: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), detailTotal: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
subTitle: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), subTitle: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
subText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), subText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
boldHeadings: PropTypes.bool,
flexWidthValues: PropTypes.bool,
}; };

@ -15,4 +15,55 @@
text-transform: uppercase; text-transform: uppercase;
} }
} }
&-edit-V2 {
margin-bottom: 10px;
display: flex;
align-items: baseline;
justify-content: flex-end;
padding-top: 20px;
button {
@include H7;
display: flex;
align-items: baseline;
color: $primary-1;
background: transparent;
border: 0;
padding-inline-end: 0;
white-space: pre;
}
i {
color: $primary-1;
margin-right: 2px;
}
&__icon {
font-size: 1rem;
}
&__label {
font-size: 12px;
margin-right: 8px;
}
.info-tooltip {
align-self: center;
margin-left: 6px;
}
&__tooltip {
p {
color: $Grey-500;
}
b {
color: $neutral-black;
display: inline-block;
min-width: 60%;
}
}
}
} }

@ -2,11 +2,94 @@ import React, { useContext } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { I18nContext } from '../../../contexts/i18n'; import { I18nContext } from '../../../contexts/i18n';
import { useGasFeeContext } from '../../../contexts/gasFee';
import InfoTooltip from '../../ui/info-tooltip/info-tooltip';
import Typography from '../../ui/typography/typography';
import TransactionDetailItem from '../transaction-detail-item/transaction-detail-item.component'; import TransactionDetailItem from '../transaction-detail-item/transaction-detail-item.component';
import { COLORS } from '../../../helpers/constants/design-system';
const GasLevelIconMap = {
low: '🐢',
medium: '🦊',
high: '🦍',
dappSuggested: '🌐',
custom: '⚙',
};
export default function TransactionDetail({ rows = [], onEdit }) { export default function TransactionDetail({ rows = [], onEdit }) {
// eslint-disable-next-line prefer-destructuring
const EIP_1559_V2 = process.env.EIP_1559_V2;
const t = useContext(I18nContext); const t = useContext(I18nContext);
const {
estimateToUse,
gasLimit,
gasPrice,
isUsingDappSuggestedGasFees,
maxFeePerGas,
maxPriorityFeePerGas,
transaction,
supportsEIP1559,
} = useGasFeeContext();
const estimateUsed = isUsingDappSuggestedGasFees
? 'dappSuggested'
: estimateToUse;
if (EIP_1559_V2 && estimateUsed) {
return (
<div className="transaction-detail">
<div className="transaction-detail-edit-V2">
<button onClick={onEdit}>
<span className="transaction-detail-edit-V2__icon">
{`${GasLevelIconMap[estimateUsed]} `}
</span>
<span className="transaction-detail-edit-V2__label">
{t(estimateUsed)}
</span>
<i className="fas fa-chevron-right asset-list-item__chevron-right" />
</button>
{estimateUsed === 'custom' && onEdit && (
<button onClick={onEdit}>{t('edit')}</button>
)}
{estimateUsed === 'dappSuggested' && (
<InfoTooltip
contentText={
<div className="transaction-detail-edit-V2__tooltip">
<Typography fontSize="12px" color={COLORS.GREY}>
{t('dappSuggestedTooltip', [transaction.origin])}
</Typography>
{supportsEIP1559 ? (
<>
<Typography fontSize="12px">
<b>{t('maxBaseFee')}</b>
{maxFeePerGas}
</Typography>
<Typography fontSize="12px">
<b>{t('maxPriorityFee')}</b>
{maxPriorityFeePerGas}
</Typography>
</>
) : (
<Typography fontSize="12px">
<b>{t('gasPriceLabel')}</b>
{gasPrice}
</Typography>
)}
<Typography fontSize="12px">
<b>{t('gasLimit')}</b>
{gasLimit}
</Typography>
</div>
}
position="top"
/>
)}
</div>
<div className="transaction-detail-rows">{rows}</div>
</div>
);
}
return ( return (
<div className="transaction-detail"> <div className="transaction-detail">

@ -0,0 +1,94 @@
import React from 'react';
import { screen } from '@testing-library/react';
import { ETH } from '../../../helpers/constants/common';
import { GasFeeContextProvider } from '../../../contexts/gasFee';
import { renderWithProvider } from '../../../../test/jest';
import configureStore from '../../../store/store';
import TransactionDetail from './transaction-detail.component';
jest.mock('../../../store/actions', () => ({
disconnectGasFeeEstimatePoller: jest.fn(),
getGasFeeEstimatesAndStartPolling: jest
.fn()
.mockImplementation(() => Promise.resolve()),
addPollingTokenToAppState: jest.fn(),
}));
const render = (props) => {
const store = configureStore({
metamask: {
nativeCurrency: ETH,
preferences: {
useNativeCurrencyAsPrimaryCurrency: true,
},
provider: {},
cachedBalances: {},
accounts: {
'0xAddress': {
address: '0xAddress',
balance: '0x176e5b6f173ebe66',
},
},
selectedAddress: '0xAddress',
featureFlags: { advancedInlineGas: true },
},
});
return renderWithProvider(
<GasFeeContextProvider {...props}>
<TransactionDetail
onEdit={() => {
console.log('on edit');
}}
rows={[]}
{...props}
/>
</GasFeeContextProvider>,
store,
);
};
describe('TransactionDetail', () => {
beforeEach(() => {
process.env.EIP_1559_V2 = true;
});
afterEach(() => {
process.env.EIP_1559_V2 = false;
});
it('should render edit link with text low if low gas estimates are selected', () => {
render({ transaction: { userFeeLevel: 'low' } });
expect(screen.queryByText('🐢')).toBeInTheDocument();
expect(screen.queryByText('Low')).toBeInTheDocument();
});
it('should render edit link with text markey if medium gas estimates are selected', () => {
render({ transaction: { userFeeLevel: 'medium' } });
expect(screen.queryByText('🦊')).toBeInTheDocument();
expect(screen.queryByText('Market')).toBeInTheDocument();
});
it('should render edit link with text agressive if high gas estimates are selected', () => {
render({ transaction: { userFeeLevel: 'high' } });
expect(screen.queryByText('🦍')).toBeInTheDocument();
expect(screen.queryByText('Aggressive')).toBeInTheDocument();
});
it('should render edit link with text Site suggested if site suggested estimated are used', () => {
render({
transaction: {
dappSuggestedGasFees: { maxFeePerGas: 1, maxPriorityFeePerGas: 1 },
txParams: { maxFeePerGas: 1, maxPriorityFeePerGas: 1 },
},
});
expect(screen.queryByText('🌐')).toBeInTheDocument();
expect(screen.queryByText('Site suggested')).toBeInTheDocument();
expect(document.getElementsByClassName('info-tooltip')).toHaveLength(1);
});
it('should render edit link with text advance if custom gas estimates are used', () => {
render({
defaultEstimateToUse: 'custom',
});
expect(screen.queryByText('⚙')).toBeInTheDocument();
expect(screen.queryByText('Advanced')).toBeInTheDocument();
expect(screen.queryByText('Edit')).toBeInTheDocument();
});
});

@ -0,0 +1,42 @@
import { Story, Canvas, ArgsTable } from '@storybook/addon-docs';
import Card from '.';
# Card
Cards are used to group related content or actions together.
<Canvas>
<Story id="ui-components-ui-card-card-stories-js--default-story" />
</Canvas>
## Component API
The `Card` component extends the `Box` component. See the `Box` component for an extended list of props.
<ArgsTable of={Card} />
## Usage
The following describes the props and example usage for this component.
### Padding, Border and Background Color
The Card component has a set of default props that should meet most card use cases. There is a strong recommendation to not overwrite these to ensure our cards stay consistent across the app.
That being said all props can be overwritten if necessary.
```jsx
import { COLORS } from '../../../helpers/constants/design-system';
// To remove the border
<Card border={false} />
// All border related props of the Box component will work
// To remove or change padding
<Card padding={0} />
// All padding related props of the Box component will work
// To change the background color
<Card backgroundColor={COLORS.UI4} />
```

@ -1,23 +0,0 @@
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
export default class Card extends PureComponent {
static propTypes = {
className: PropTypes.string,
overrideClassName: PropTypes.bool,
title: PropTypes.string,
children: PropTypes.node,
};
render() {
const { className, overrideClassName, title } = this.props;
return (
<div className={classnames({ card: !overrideClassName }, className)}>
<div className="card__title">{title}</div>
{this.props.children}
</div>
);
}
}

@ -1,21 +0,0 @@
import React from 'react';
import { shallow } from 'enzyme';
import Card from './card.component';
describe('Card Component', () => {
it('should render a card with a title and child element', () => {
const wrapper = shallow(
<Card title="Test" className="card-test-class">
<div className="child-test-class">Child</div>
</Card>,
);
expect(wrapper.hasClass('card-test-class')).toStrictEqual(true);
const title = wrapper.find('.card__title');
expect(title).toHaveLength(1);
expect(title.text()).toStrictEqual('Test');
const child = wrapper.find('.child-test-class');
expect(child).toHaveLength(1);
expect(child.text()).toStrictEqual('Child');
});
});

@ -0,0 +1,60 @@
import React from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import {
BORDER_STYLE,
COLORS,
SIZES,
} from '../../../helpers/constants/design-system';
const Card = ({
border = true,
padding = 4,
backgroundColor = COLORS.WHITE,
children,
...props
}) => {
const defaultBorderProps = {
borderColor: border && COLORS.UI2,
borderRadius: border && SIZES.MD,
borderStyle: border && BORDER_STYLE.SOLID,
};
return (
<Box
{...{
padding,
backgroundColor,
...defaultBorderProps,
...props,
}}
>
{children}
</Box>
);
};
Card.propTypes = {
/**
* Whether the Card has a border or not.
* Defaults to true
*/
border: PropTypes.bool,
/**
* Padding of the Card component accepts number or an array of 2 numbers.
* Defaults to 4 (16px)
*/
padding: Box.propTypes.padding,
/**
* The background color of the card
* Defaults to COLORS.WHITE
*/
backgroundColor: Box.propTypes.backgroundColor,
/**
* The Card component accepts all Box component props
*/
...Box.propTypes,
};
export default Card;

@ -0,0 +1,169 @@
import React from 'react';
import {
ALIGN_ITEMS,
BLOCK_SIZES,
BORDER_STYLE,
COLORS,
DISPLAY,
JUSTIFY_CONTENT,
TEXT_ALIGN,
} from '../../../helpers/constants/design-system';
import README from './README.mdx';
import Card from '.';
const sizeOptions = [undefined, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
export default {
title: 'UI/Card',
id: __filename,
component: Card,
parameters: {
docs: {
page: README,
},
},
argTypes: {
children: { control: 'text' },
border: {
control: 'boolean',
},
borderStyle: {
control: {
type: 'select',
},
options: Object.values(BORDER_STYLE),
},
borderWidth: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
borderColor: {
control: {
type: 'select',
},
options: Object.values(COLORS),
},
backgroundColor: {
control: {
type: 'select',
},
options: Object.values(COLORS),
},
width: {
control: {
type: 'select',
},
options: Object.values(BLOCK_SIZES),
},
height: {
control: {
type: 'select',
},
options: Object.values(BLOCK_SIZES),
},
textAlign: {
control: {
type: 'select',
},
options: Object.values(TEXT_ALIGN),
},
margin: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
marginTop: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
marginRight: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
marginBottom: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
marginLeft: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
padding: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
paddingTop: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
paddingRight: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
paddingBottom: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
paddingLeft: {
control: {
type: 'select',
},
options: [...sizeOptions],
},
display: {
control: {
type: 'select',
},
options: Object.values(DISPLAY),
},
justifyContent: {
control: {
type: 'select',
},
options: Object.values(JUSTIFY_CONTENT),
},
alignItems: {
control: {
type: 'select',
},
options: Object.values(ALIGN_ITEMS),
},
},
args: {
children: 'Card children',
},
};
export const DefaultStory = (args) => <Card {...args}>{args.children}</Card>;
DefaultStory.storyName = 'Default';
DefaultStory.args = {
padding: 4,
border: true,
borderWidth: 1,
borderColor: COLORS.UI2,
borderStyle: BORDER_STYLE.SOLID,
backgroundColor: COLORS.WHITE,
display: DISPLAY.BLOCK,
};

@ -0,0 +1,11 @@
import * as React from 'react';
import { render } from '@testing-library/react';
import Card from '.';
describe('Card', () => {
it('should render the Card without crashing', () => {
const { getByText } = render(<Card>Card content</Card>);
expect(getByText('Card content')).toBeDefined();
});
});

@ -1 +1 @@
export { default } from './card.component'; export { default } from './card';

@ -1,11 +0,0 @@
.card {
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
padding: 8px;
&__title {
border-bottom: 1px solid #d8d8d8;
padding-bottom: 4px;
text-transform: capitalize;
}
}

@ -0,0 +1,15 @@
import { Story, Canvas, ArgsTable } from '@storybook/addon-docs';
import Chip from '.';
# Chip
Chips are compact elements that represent an input, status, or action.
<Canvas>
<Story id="ui-components-ui-chip-chip-stories-js--default-story" />
</Canvas>
## Component API
<ArgsTable of={Chip} />

@ -5,6 +5,7 @@ import { COLORS } from '../../../helpers/constants/design-system';
import Chip from '.'; import Chip from '.';
export function ChipWithInput({ export function ChipWithInput({
dataTestId,
className, className,
borderColor = COLORS.UI1, borderColor = COLORS.UI1,
inputValue, inputValue,
@ -17,6 +18,7 @@ export function ChipWithInput({
> >
{setInputValue && ( {setInputValue && (
<input <input
data-testid={dataTestId}
type="text" type="text"
className="chip__input" className="chip__input"
onChange={(e) => { onChange={(e) => {
@ -30,6 +32,7 @@ export function ChipWithInput({
} }
ChipWithInput.propTypes = { ChipWithInput.propTypes = {
dataTestId: PropTypes.string,
borderColor: PropTypes.oneOf(Object.values(COLORS)), borderColor: PropTypes.oneOf(Object.values(COLORS)),
className: PropTypes.string, className: PropTypes.string,
inputValue: PropTypes.string, inputValue: PropTypes.string,

@ -6,9 +6,11 @@ import Typography from '../typography';
import { COLORS, TYPOGRAPHY } from '../../../helpers/constants/design-system'; import { COLORS, TYPOGRAPHY } from '../../../helpers/constants/design-system';
export default function Chip({ export default function Chip({
dataTestId,
className, className,
children, children,
borderColor = COLORS.UI1, borderColor = COLORS.UI1,
backgroundColor,
label, label,
labelProps = {}, labelProps = {},
leftIcon, leftIcon,
@ -25,12 +27,14 @@ export default function Chip({
return ( return (
<div <div
data-testid={dataTestId}
onClick={onClick} onClick={onClick}
onKeyPress={onKeyPress} onKeyPress={onKeyPress}
className={classnames(className, 'chip', { className={classnames(className, 'chip', {
'chip--with-left-icon': Boolean(leftIcon), 'chip--with-left-icon': Boolean(leftIcon),
'chip--with-right-icon': Boolean(rightIcon), 'chip--with-right-icon': Boolean(rightIcon),
[`chip--${borderColor}`]: true, [`chip--border-color-${borderColor}`]: true,
[`chip--background-color-${backgroundColor}`]: true,
})} })}
role={isInteractive ? 'button' : undefined} role={isInteractive ? 'button' : undefined}
tabIndex={isInteractive ? 0 : undefined} tabIndex={isInteractive ? 0 : undefined}
@ -53,16 +57,46 @@ export default function Chip({
} }
Chip.propTypes = { Chip.propTypes = {
/**
* Data test id used for testing of the Chip component
*/
dataTestId: PropTypes.string,
/**
* The border color of the Chip
*/
borderColor: PropTypes.oneOf(Object.values(COLORS)), borderColor: PropTypes.oneOf(Object.values(COLORS)),
/**
* The background color of the Chip component
*/
backgroundColor: PropTypes.oneOf(Object.values(COLORS)),
/**
* The label of the Chip component has a default typography variant of h6 and is a span html element
*/
label: PropTypes.string, label: PropTypes.string,
children: PropTypes.node, /**
* The label props of the component. Most Typography props can be used
*/
labelProps: PropTypes.shape({ labelProps: PropTypes.shape({
...omit(Typography.propTypes, ['children', 'className']), ...omit(Typography.propTypes, ['children', 'className']),
}), }),
/**
* Children will replace the label of the Chip component.
*/
children: PropTypes.node,
/**
* An icon component that can be passed to appear on the left of the label
*/
leftIcon: PropTypes.node, leftIcon: PropTypes.node,
/**
* An icon component that can be passed to appear on the right of the label
*/
rightIcon: PropTypes.node, rightIcon: PropTypes.node,
/**
* The className of the Chip
*/
className: PropTypes.string, className: PropTypes.string,
/**
* The onClick handler to be passed to the Chip component
*/
onClick: PropTypes.func, onClick: PropTypes.func,
inputValue: PropTypes.string,
setInputValue: PropTypes.func,
}; };

@ -18,9 +18,12 @@
} }
@each $variant, $color in design-system.$color-map { @each $variant, $color in design-system.$color-map {
&--#{$variant} { &--border-color-#{$variant} {
border-color: $color; border-color: $color;
} }
&--background-color-#{$variant} {
background-color: $color;
}
} }
&--with-left-icon, &--with-left-icon,

@ -1,51 +1,111 @@
/* eslint-disable react/prop-types */
import React, { useState } from 'react'; import React, { useState } from 'react';
import { select, text } from '@storybook/addon-knobs';
import { COLORS, TYPOGRAPHY } from '../../../helpers/constants/design-system'; import { COLORS, TYPOGRAPHY } from '../../../helpers/constants/design-system';
import ApproveIcon from '../icon/approve-icon.component'; import ApproveIcon from '../icon/approve-icon.component';
import Identicon from '../identicon/identicon.component'; import Identicon from '../identicon/identicon.component';
import { ChipWithInput } from './chip-with-input'; import { ChipWithInput } from './chip-with-input';
import README from './README.mdx';
import Chip from '.'; import Chip from '.';
export default { export default {
title: 'Chip', title: 'UI/Chip',
id: __filename, id: __filename,
component: Chip,
parameters: {
docs: {
page: README,
},
},
argTypes: {
leftIcon: {
control: {
type: 'select',
},
options: ['ApproveIcon'],
mapping: {
ApproveIcon: <ApproveIcon size={24} color="#4cd964" />,
},
},
rightIcon: {
control: {
type: 'select',
},
options: ['Identicon'],
mapping: {
Identicon: (
<Identicon
address="0x5CfE73b6021E818B776b421B1c4Db2474086a7e1"
diameter={25}
/>
),
},
},
label: {
control: 'text',
},
labelProps: {
color: {
control: {
type: 'select',
},
options: Object.values(COLORS),
},
variant: {
color: {
control: {
type: 'select',
},
options: Object.values(TYPOGRAPHY),
},
},
},
borderColor: {
control: {
type: 'select',
},
options: Object.values(COLORS),
},
backgroundColor: {
control: {
type: 'select',
},
options: Object.values(COLORS),
},
children: {
control: 'text',
},
},
}; };
export const Plain = ({ export const DefaultStory = (args) => <Chip {...args} />;
leftIcon,
rightIcon, DefaultStory.storyName = 'Default';
label = 'Hello',
borderColor = COLORS.UI1, DefaultStory.args = {
fontColor = COLORS.BLACK, label: 'Chip',
}) => ( borderColor: COLORS.UI3,
<Chip backgroundColor: COLORS.UI1,
leftIcon={leftIcon} labelProps: {
rightIcon={rightIcon} color: COLORS.BLACK,
label={text('label', label)} variant: TYPOGRAPHY.H6,
labelProps={{ },
color: select('color', COLORS, fontColor), };
variant: select('typography', TYPOGRAPHY, TYPOGRAPHY.H6),
}}
borderColor={select('borderColor', COLORS, borderColor)}
/>
);
export const WithLeftIcon = () => ( export const WithLeftIcon = () => (
<Plain <Chip
label="Done!" label="Done!"
borderColor={COLORS.SUCCESS3} borderColor={COLORS.SUCCESS3}
fontColor={COLORS.SUCCESS3}
leftIcon={<ApproveIcon size={24} color="#4cd964" />} leftIcon={<ApproveIcon size={24} color="#4cd964" />}
/> />
); );
export const WithRightIcon = () => ( export const WithRightIcon = () => (
<Plain <Chip
label="0x5CfE73b6021E818B776b421B1c4Db2474086a7e1" label="0x5CfE73b6021E818B776b421B1c4Db2474086a7e1"
borderColor={COLORS.UI4} borderColor={COLORS.UI4}
fontColor={COLORS.UI4}
rightIcon={ rightIcon={
<Identicon <Identicon
address="0x5CfE73b6021E818B776b421B1c4Db2474086a7e1" address="0x5CfE73b6021E818B776b421B1c4Db2474086a7e1"
@ -56,10 +116,9 @@ export const WithRightIcon = () => (
); );
export const WithBothIcons = () => ( export const WithBothIcons = () => (
<Plain <Chip
label="Account 1" label="Account 1"
borderColor={COLORS.UI4} borderColor={COLORS.UI4}
fontColor={COLORS.UI4}
rightIcon={ rightIcon={
<svg <svg
width="10" width="10"
@ -82,13 +141,17 @@ export const WithBothIcons = () => (
} }
/> />
); );
export const WithInput = () => { export const WithInput = (args) => {
const [inputValue, setInputValue] = useState(''); const [inputValue, setInputValue] = useState('Chip with input');
return ( return (
<ChipWithInput <ChipWithInput
{...args}
inputValue={inputValue} inputValue={inputValue}
setInputValue={setInputValue} setInputValue={setInputValue}
borderColor={select('borderColor', COLORS, COLORS.UI3)}
/> />
); );
}; };
WithInput.args = {
borderColor: COLORS.UI3,
};

@ -16,6 +16,7 @@ import NumericInput from '../numeric-input/numeric-input.component';
import InfoTooltip from '../info-tooltip/info-tooltip'; import InfoTooltip from '../info-tooltip/info-tooltip';
export default function FormField({ export default function FormField({
dataTestId,
titleText, titleText,
titleUnit, titleUnit,
tooltipText, tooltipText,
@ -94,6 +95,7 @@ export default function FormField({
type={password ? 'password' : 'text'} type={password ? 'password' : 'text'}
autoFocus={autoFocus} autoFocus={autoFocus}
disabled={disabled} disabled={disabled}
data-testid={dataTestId}
/> />
)} )}
{error && ( {error && (
@ -111,6 +113,7 @@ export default function FormField({
} }
FormField.propTypes = { FormField.propTypes = {
dataTestId: PropTypes.string,
titleText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), titleText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
titleUnit: PropTypes.string, titleUnit: PropTypes.string,
tooltipText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), tooltipText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),

@ -25,10 +25,41 @@
margin-bottom: 9px; margin-bottom: 9px;
} }
&__address-container {
display: flex;
justify-content: center;
&__tooltip-wrapper {
width: 100%;
}
&:hover {
cursor: pointer;
.qr-code__copy-icon__svg {
fill: $primary-1;
}
}
}
&__address { &__address {
@include H7; @include H7;
background-color: $ui-1; background-color: $Grey-000;
padding: 12px; width: 76%;
padding: 8px 12px;
word-break: break-all;
text-align: center;
}
&__copy-icon {
height: 13px;
padding: 17px 0;
position: absolute;
right: 24px;
&__svg {
fill: $ui-5;
}
} }
} }

@ -3,7 +3,11 @@ import React from 'react';
import qrCode from 'qrcode-generator'; import qrCode from 'qrcode-generator';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { isHexPrefixed } from 'ethereumjs-util'; import { isHexPrefixed } from 'ethereumjs-util';
import { useCopyToClipboard } from '../../../hooks/useCopyToClipboard';
import { toChecksumHexAddress } from '../../../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../../../shared/modules/hexstring-utils';
import Tooltip from '../tooltip';
import CopyIcon from '../icon/copy-icon.component';
import { useI18nContext } from '../../../hooks/useI18nContext';
export default connect(mapStateToProps)(QrCodeView); export default connect(mapStateToProps)(QrCodeView);
@ -22,6 +26,8 @@ function QrCodeView(props) {
const address = `${ const address = `${
isHexPrefixed(data) ? 'ethereum:' : '' isHexPrefixed(data) ? 'ethereum:' : ''
}${toChecksumHexAddress(data)}`; }${toChecksumHexAddress(data)}`;
const [copied, handleCopy] = useCopyToClipboard();
const t = useI18nContext();
const qrImage = qrCode(4, 'M'); const qrImage = qrCode(4, 'M');
qrImage.addData(address); qrImage.addData(address);
qrImage.make(); qrImage.make();
@ -50,7 +56,23 @@ function QrCodeView(props) {
__html: qrImage.createTableTag(4), __html: qrImage.createTableTag(4),
}} }}
/> />
<div className="qr-code__address">{toChecksumHexAddress(data)}</div> <Tooltip
wrapperClassName="qr-code__address-container__tooltip-wrapper"
position="bottom"
title={copied ? t('copiedExclamation') : t('copyToClipboard')}
>
<div
className="qr-code__address-container"
onClick={() => {
handleCopy(toChecksumHexAddress(data));
}}
>
<div className="qr-code__address">{toChecksumHexAddress(data)}</div>
<div className="qr-code__copy-icon">
<CopyIcon size={11} className="qr-code__copy-icon__svg" color="" />
</div>
</div>
</Tooltip>
</div> </div>
); );
} }

@ -53,6 +53,12 @@ const ToggleButton = (props) => {
return ( return (
<div <div
tabIndex="0"
onKeyDown={(e) => {
if (e.key === 'Enter') {
onToggle(value);
}
}}
className={classnames('toggle-button', `toggle-button--${modifier}`, { className={classnames('toggle-button', `toggle-button--${modifier}`, {
'toggle-button--disabled': disabled, 'toggle-button--disabled': disabled,
})} })}

@ -8,7 +8,6 @@
@import 'button-group/index'; @import 'button-group/index';
@import 'button/buttons'; @import 'button/buttons';
@import 'callout/callout'; @import 'callout/callout';
@import 'card/index';
@import 'check-box/index'; @import 'check-box/index';
@import 'chip/chip'; @import 'chip/chip';
@import 'circle-icon/index'; @import 'circle-icon/index';

@ -0,0 +1,37 @@
import React, { createContext, useContext } from 'react';
import PropTypes from 'prop-types';
import { useGasFeeInputs } from '../hooks/gasFeeInput/useGasFeeInputs';
export const GasFeeContext = createContext({});
export const GasFeeContextProvider = ({
children,
defaultEstimateToUse,
transaction,
minimumGasLimit,
editGasMode,
}) => {
const gasFeeDetails = useGasFeeInputs(
defaultEstimateToUse,
transaction,
minimumGasLimit,
editGasMode,
);
return (
<GasFeeContext.Provider value={gasFeeDetails}>
{children}
</GasFeeContext.Provider>
);
};
export function useGasFeeContext() {
return useContext(GasFeeContext);
}
GasFeeContextProvider.propTypes = {
children: PropTypes.node.isRequired,
defaultEstimateToUse: PropTypes.string,
transaction: PropTypes.object.isRequired,
minimumGasLimit: PropTypes.string,
editGasMode: PropTypes.string,
};

@ -103,6 +103,7 @@ $ui-1: #f2f3f4;
$ui-2: #d6d9dc; $ui-2: #d6d9dc;
$ui-3: #bbc0c5; $ui-3: #bbc0c5;
$ui-4: #6a737d; $ui-4: #6a737d;
$ui-5: #c4c4c4;
$mainnet: #29b6af; $mainnet: #29b6af;
$ropsten: #ff4a8d; $ropsten: #ff4a8d;
@ -116,6 +117,7 @@ $color-map: (
'ui-2': $ui-2, 'ui-2': $ui-2,
'ui-3': $ui-3, 'ui-3': $ui-3,
'ui-4': $ui-4, 'ui-4': $ui-4,
'ui-5': $ui-5,
'white': $ui-white, 'white': $ui-white,
'black': $ui-black, 'black': $ui-black,
'grey': $ui-grey, 'grey': $ui-grey,

@ -38,6 +38,7 @@ const AWAITING_SIGNATURES_ROUTE = '/swaps/awaiting-signatures';
const AWAITING_SWAP_ROUTE = '/swaps/awaiting-swap'; const AWAITING_SWAP_ROUTE = '/swaps/awaiting-swap';
const SWAPS_ERROR_ROUTE = '/swaps/swaps-error'; const SWAPS_ERROR_ROUTE = '/swaps/swaps-error';
const SWAPS_MAINTENANCE_ROUTE = '/swaps/maintenance'; const SWAPS_MAINTENANCE_ROUTE = '/swaps/maintenance';
const ADD_COLLECTIBLE_ROUTE = '/add-collectible';
const INITIALIZE_ROUTE = '/initialize'; const INITIALIZE_ROUTE = '/initialize';
const INITIALIZE_WELCOME_ROUTE = '/initialize/welcome'; const INITIALIZE_WELCOME_ROUTE = '/initialize/welcome';
@ -218,6 +219,7 @@ export {
AWAITING_SIGNATURES_ROUTE, AWAITING_SIGNATURES_ROUTE,
SWAPS_ERROR_ROUTE, SWAPS_ERROR_ROUTE,
SWAPS_MAINTENANCE_ROUTE, SWAPS_MAINTENANCE_ROUTE,
ADD_COLLECTIBLE_ROUTE,
ONBOARDING_ROUTE, ONBOARDING_ROUTE,
ONBOARDING_HELP_US_IMPROVE_ROUTE, ONBOARDING_HELP_US_IMPROVE_ROUTE,
ONBOARDING_CREATE_PASSWORD_ROUTE, ONBOARDING_CREATE_PASSWORD_ROUTE,

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save