Merge remote-tracking branch 'upstream/develop' into HEAD

feature/default_network_editable
brunobar79 6 years ago
commit 595447ccac
  1. 111
      .circleci/config.yml
  2. 6
      .circleci/scripts/firefox-download.sh
  3. 8
      .circleci/scripts/firefox-install.sh
  4. 16
      .eslintignore
  5. 6
      .eslintrc
  6. 2
      .nvmrc
  7. 36
      CHANGELOG.md
  8. 1
      LICENSE
  9. 4
      README.md
  10. 16
      app/_locales/en/messages.json
  11. 41
      app/_locales/ja/messages.json
  12. 6
      app/manifest.json
  13. 13
      app/scripts/account-import-strategies/index.js
  14. 14
      app/scripts/background.js
  15. 5
      app/scripts/contentscript.js
  16. 11
      app/scripts/controllers/network/network.js
  17. 75
      app/scripts/controllers/preferences.js
  18. 13
      app/scripts/controllers/transactions/index.js
  19. 24
      app/scripts/controllers/transactions/lib/recipient-blacklist-checker.js
  20. 17
      app/scripts/controllers/transactions/lib/recipient-blacklist.js
  21. 10
      app/scripts/controllers/transactions/nonce-tracker.js
  22. 4
      app/scripts/controllers/transactions/pending-tx-tracker.js
  23. 17
      app/scripts/controllers/user-actions.js
  24. 23
      app/scripts/inpage.js
  25. 1
      app/scripts/lib/createErrorMiddleware.js
  26. 24
      app/scripts/lib/createStreamSink.js
  27. 71
      app/scripts/lib/diagnostics-reporter.js
  28. 20
      app/scripts/lib/get-first-preferred-lang-code.js
  29. 10
      app/scripts/lib/notification-manager.js
  30. 2
      app/scripts/lib/setupRaven.js
  31. 73
      app/scripts/metamask-controller.js
  32. 4
      app/scripts/migrations/023.js
  33. 2
      app/scripts/migrations/026.js
  34. 33
      app/scripts/notice-controller.js
  35. 2
      development/announcer.js
  36. 2
      development/backGroundConnectionModifiers.js
  37. 15
      development/beefy.js
  38. 4
      development/mock-dev.js
  39. 2
      development/mockExtension.js
  40. 2
      development/selector.js
  41. 15
      development/sourcemap-validator.js
  42. 6
      development/states/add-token.json
  43. 2
      development/states/conf-tx.json
  44. 7
      development/states/confirm-new-ui.json
  45. 6
      development/states/confirm-sig-requests.json
  46. 6
      development/states/currency-localization.json
  47. 2
      development/states/first-time.json
  48. 2
      development/states/notice.json
  49. 13
      development/states/send-edit.json
  50. 13
      development/states/send-new-ui.json
  51. 13
      development/states/tx-list-items.json
  52. 3
      development/ui-dev.js
  53. 12
      development/verify-locale-strings.js
  54. 8
      development/version-bump.js
  55. 28
      docs/publishing.md
  56. 241
      gentests.js
  57. 53
      gulpfile.js
  58. 4
      mascara/example/server.js
  59. 2
      mascara/src/app/first-time/breadcrumbs.js
  60. 76
      mascara/src/app/first-time/buy-ether-screen.js
  61. 17
      mascara/src/app/first-time/index.css
  62. 14
      mascara/src/app/first-time/notice-screen.js
  63. 42
      mascara/src/app/shapeshift-form/index.js
  64. 2
      mascara/test/helpers.js
  65. 6
      mascara/test/index.js
  66. 2
      mascara/test/test-ui.js
  67. 16
      mascara/test/util/mascara-test-helper.js
  68. 6
      notices/archive/notice_4.md
  69. 27
      notices/notice-delete.js
  70. 33
      notices/notice-generator.js
  71. 1
      notices/notice-nonce.json
  72. 35
      notices/notices.js
  73. 1
      notices/notices.json
  74. 6
      old-ui/app/app.js
  75. 5
      old-ui/app/components/account-dropdowns.js
  76. 4
      old-ui/app/components/transaction-list-item.js
  77. 6
      old-ui/app/components/typed-message-renderer.js
  78. 19340
      package-lock.json
  79. 33
      package.json
  80. 66
      test/e2e/beta/contract-test/contract.js
  81. 8
      test/e2e/beta/contract-test/index.html
  82. 238
      test/e2e/beta/from-import-beta-ui.spec.js
  83. 25
      test/e2e/beta/helpers.js
  84. 558
      test/e2e/beta/metamask-beta-ui.spec.js
  85. 4
      test/e2e/beta/run-all.sh
  86. 2
      test/e2e/func.js
  87. 36
      test/e2e/metamask.spec.js
  88. 2
      test/integration/lib/add-token.js
  89. 9
      test/integration/lib/confirm-sig-requests.js
  90. 2
      test/integration/lib/mascara-first-time.js
  91. 14
      test/integration/lib/send-new-ui.js
  92. 1
      test/integration/lib/tx-list-items.js
  93. 2
      test/lib/mock-encryptor.js
  94. 6
      test/lib/mock-tx-gen.js
  95. 100
      test/lib/react-trigger-change.js
  96. 2
      test/mascara.conf.js
  97. 10
      test/screens/new-ui.js
  98. 33
      test/unit/app/account-import-strategies.spec.js
  99. 2
      test/unit/app/controllers/address-book-controller.js
  100. 30
      test/unit/app/controllers/metamask-controller-test.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -30,6 +30,15 @@ workflows:
- prep-deps-npm
- prep-deps-firefox
- prep-build
- test-e2e-beta-chrome:
requires:
- prep-deps-npm
- prep-build
- test-e2e-beta-firefox:
requires:
- prep-deps-npm
- prep-deps-firefox
- prep-build
- test-unit:
requires:
- prep-deps-npm
@ -57,6 +66,8 @@ workflows:
- test-unit
- test-e2e-chrome
- test-e2e-firefox
- test-e2e-beta-chrome
- test-e2e-beta-firefox
- test-integration-mascara-chrome
- test-integration-mascara-firefox
- test-integration-flat-chrome
@ -86,7 +97,7 @@ workflows:
jobs:
prep-deps-npm:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -105,14 +116,12 @@ jobs:
prep-deps-firefox:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- run:
name: Download Firefox
command: >
wget https://ftp.mozilla.org/pub/firefox/releases/58.0/linux-x86_64/en-US/firefox-58.0.tar.bz2
&& tar xjf firefox-58.0.tar.bz2
command: ./.circleci/scripts/firefox-download.sh
- save_cache:
key: dependency-cache-firefox-{{ .Revision }}
paths:
@ -120,7 +129,7 @@ jobs:
prep-build:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -139,7 +148,7 @@ jobs:
prep-docs:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -154,7 +163,7 @@ jobs:
prep-scss:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -173,7 +182,7 @@ jobs:
test-lint:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -184,7 +193,7 @@ jobs:
test-deps:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -195,7 +204,7 @@ jobs:
test-e2e-chrome:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -203,28 +212,22 @@ jobs:
- restore_cache:
key: build-cache-{{ .Revision }}
- run:
name: Test
name: test:e2e:chrome
command: npm run test:e2e:chrome
- store_artifacts:
path: test-artifacts
destination: test-artifacts
test-e2e-firefox:
environment:
browsers: '["Firefox"]'
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: >
sudo rm -r /opt/firefox
&& sudo mv firefox /opt/firefox58
&& sudo mv /usr/bin/firefox /usr/bin/firefox-old
&& sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
command: ./.circleci/scripts/firefox-install.sh
- restore_cache:
key: dependency-cache-{{ .Revision }}
- restore_cache:
@ -236,9 +239,46 @@ jobs:
path: test-artifacts
destination: test-artifacts
test-e2e-beta-chrome:
docker:
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ .Revision }}
- restore_cache:
key: build-cache-{{ .Revision }}
- run:
name: test:e2e:chrome:beta
command: npm run test:e2e:chrome:beta
- store_artifacts:
path: test-artifacts
destination: test-artifacts
test-e2e-beta-firefox:
docker:
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: ./.circleci/scripts/firefox-install.sh
- restore_cache:
key: dependency-cache-{{ .Revision }}
- restore_cache:
key: build-cache-{{ .Revision }}
- run:
name: test:e2e:firefox:beta
command: npm run test:e2e:firefox:beta
- store_artifacts:
path: test-artifacts
destination: test-artifacts
job-screens:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -255,7 +295,7 @@ jobs:
job-publish-prerelease:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -282,7 +322,7 @@ jobs:
job-publish-release:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -305,7 +345,7 @@ jobs:
test-unit:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -318,18 +358,14 @@ jobs:
environment:
browsers: '["Firefox"]'
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: >
sudo rm -r /opt/firefox
&& sudo mv firefox /opt/firefox58
&& sudo mv /usr/bin/firefox /usr/bin/firefox-old
&& sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
command: ./.circleci/scripts/firefox-install.sh
- restore_cache:
key: dependency-cache-{{ .Revision }}
- run:
@ -346,7 +382,7 @@ jobs:
environment:
browsers: '["Chrome"]'
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -365,18 +401,14 @@ jobs:
environment:
browsers: '["Firefox"]'
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: >
sudo rm -r /opt/firefox
&& sudo mv firefox /opt/firefox58
&& sudo mv /usr/bin/firefox /usr/bin/firefox-old
&& sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
command: ./.circleci/scripts/firefox-install.sh
- restore_cache:
key: dependency-cache-{{ .Revision }}
- run:
@ -393,7 +425,7 @@ jobs:
environment:
browsers: '["Chrome"]'
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- checkout
- restore_cache:
@ -410,9 +442,8 @@ jobs:
all-tests-pass:
docker:
- image: circleci/node:8-browsers
- image: circleci/node:8.11.3-browsers
steps:
- run:
name: All Tests Passed
command: echo 'weew - everything passed!'

@ -0,0 +1,6 @@
#!/usr/bin/env bash
echo "Downloading firefox..."
wget https://ftp.mozilla.org/pub/firefox/releases/58.0/linux-x86_64/en-US/firefox-58.0.tar.bz2 \
&& tar xjf firefox-58.0.tar.bz2
echo "firefox download complete"

@ -0,0 +1,8 @@
#!/usr/bin/env bash
echo "Installing firefox..."
sudo rm -r /opt/firefox
sudo mv firefox /opt/firefox58
sudo mv /usr/bin/firefox /usr/bin/firefox-old
sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
echo "Firefox installed."

@ -1,6 +1,20 @@
node_modules/**
dist/**
builds/**
docs/**
development/bundle.js
development/states.js
app/scripts/lib/extension-instance.js
app/scripts/chromereload.js
ui/lib/blockies.js
mascara/src/app/first-time/spinner.js
mascara/test/jquery-3.1.0.min.js
test/integration/bundle.js
test/integration/jquery-3.1.0.min.js
test/integration/helpers.js
test/integration/lib/first-time.js
ui/lib/blockies.js

@ -37,7 +37,9 @@
"document": false,
"navigator": false,
"web3": true,
"window": false
"window": false,
"$": false,
"QUnit": false
},
"rules": {
@ -142,6 +144,7 @@
"operator-linebreak": [1, "after", { "overrides": { "?": "ignore", ":": "ignore" } }],
"padded-blocks": "off",
"quotes": [2, "single", {"avoidEscape": true, "allowTemplateLiterals": true}],
"react/no-deprecated": 0,
"semi": [2, "never"],
"semi-spacing": [2, { "before": false, "after": true }],
"space-before-blocks": [1, "always"],
@ -158,5 +161,6 @@
"yield-star-spacing": [2, "both"],
"yoda": [2, "never"],
"prefer-const": 1,
"mocha/no-exclusive-tests": "error"
}
}

@ -1 +1 @@
v6.3.1
v8.11.3

@ -2,6 +2,42 @@
## Current Master
## 4.8.0 Thur Jun 14 2018
- [#4513](https://github.com/MetaMask/metamask-extension/pull/4513): Attempting to import an empty private key will now show a clear error.
- [#4570](https://github.com/MetaMask/metamask-extension/pull/4570): Fix bug where metamask data would stop being written to disk after prolonged use.
- [#4523](https://github.com/MetaMask/metamask-extension/pull/4523): Fix bug where account reset did not work with custom RPC providers.
- [#4524](https://github.com/MetaMask/metamask-extension/pull/4524): Fix for Brave i18n getAcceptLanguages.
- [#4557](https://github.com/MetaMask/metamask-extension/pull/4557): Fix bug where nonce mutex was never released.
- [#4566](https://github.com/MetaMask/metamask-extension/pull/4566): Add phishing notice.
- [#4591](https://github.com/MetaMask/metamask-extension/pull/4591): Allow Copying Token Addresses and link to Token on Etherscan.
## 4.7.4 Tue Jun 05 2018
- Add diagnostic reporting for users with multiple HD keyrings
- Throw explicit error when selected account is unset
## 4.7.3 Mon Jun 04 2018
- Hide token now uses new modal
- Indicate the current selected account on the popup account view
- Reduce height of notice container in onboarding
- Fixes issue where old nicknames were kept around causing errors
## 4.7.2 Sun Jun 03 2018
- Fix bug preventing users from logging in. Internally accounts and identities were out of sync.
- Fix support links to point to new support system (Zendesk)
- Fix bug in migration #26 ( moving account nicknames to preferences )
- Clears account nicknames on restore from seedPhrase
## 4.7.1 Fri Jun 01 2018
- Fix bug where errors were not returned to Dapps.
## 4.7.0 Wed May 30 2018
- Fix Brave support
- Adds error messages when passwords don't match in onboarding flow.
- Adds modal notification if a retry in the process of being confirmed is dropped.
- New unlock screen design.

@ -18,3 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -27,7 +27,9 @@ If you're a web dapp developer, we've got two types of guides for you:
## Building locally
- Install [Node.js](https://nodejs.org/en/) version 6.3.1 or later.
- Install local dependencies with `npm install`.
- Install dependencies:
- For node versions up to and including 9, install local dependencies with `npm install`.
- For node versions 10 and later, install [Yarn](https://yarnpkg.com/lang/en/docs/install/) and use `yarn install`.
- Install gulp globally with `npm install -g gulp-cli`.
- Build the project to the `./dist/` folder with `gulp build`.
- Optionally, to rebuild on file changes, run `gulp dev`.

@ -146,6 +146,9 @@
"copy": {
"message": "Copy"
},
"copyContractAddress": {
"message": "Copy Contract Address"
},
"copyToClipboard": {
"message": "Copy to clipboard"
},
@ -253,12 +256,18 @@
"editAccountName": {
"message": "Edit Account Name"
},
"editingTransaction": {
"message": "Make changes to your transaction"
},
"emailUs": {
"message": "Email us!"
},
"encryptNewDen": {
"message": "Encrypt your new DEN"
},
"ensNameNotFound": {
"message": "ENS name not found"
},
"enterPassword": {
"message": "Enter password"
},
@ -771,6 +780,10 @@
"onlySendToEtherAddress": {
"message": "Only send ETH to an Ethereum address."
},
"onlySendTokensToAccountAddress": {
"message": "Only send $1 to an Ethereum account address.",
"description": "displays token symbol"
},
"searchTokens": {
"message": "Search Tokens"
},
@ -948,6 +961,9 @@
"viewAccount": {
"message": "View Account"
},
"viewOnEtherscan": {
"message": "View on Etherscan"
},
"visitWebSite": {
"message": "Visit our web site"
},

@ -62,6 +62,9 @@
"message": " $1以上 $2以下にして下さい。",
"description": "helper for inputting hex as decimal input"
},
"blockiesIdenticon": {
"message": "Blockies Identicon を使用"
},
"borrowDharma": {
"message": "Dharmaで借りる(ベータ版)"
},
@ -95,6 +98,9 @@
"confirmTransaction": {
"message": "トランザクションの確認"
},
"continue": {
"message": "続行"
},
"continueToCoinbase": {
"message": "Coinbaseを開く"
},
@ -359,6 +365,9 @@
"likeToAddTokens": {
"message": "トークンを追加しますか?"
},
"links": {
"message": "リンク"
},
"limit": {
"message": "リミット"
},
@ -371,12 +380,18 @@
"localhost": {
"message": "Localhost 8545"
},
"login": {
"message": "ログイン"
},
"logout": {
"message": "ログアウト"
},
"loose": {
"message": "外部秘密鍵"
},
"max": {
"message": "最大"
},
"mainnet": {
"message": "Ethereumメインネットワーク"
},
@ -417,7 +432,7 @@
"message": "新規コントラクト"
},
"newPassword": {
"message": "新規パスワード(最低文字)"
"message": "新規パスワード(最低8文字)"
},
"newRecipient": {
"message": "新規受取人"
@ -453,6 +468,9 @@
"message": "または",
"description": "choice between creating or importing a new account"
},
"password": {
"message": "パスワード"
},
"passwordMismatch": {
"message": "パスワードが一致しません。",
"description": "in password creation process, the two new password fields did not match"
@ -474,6 +492,9 @@
"popularTokens": {
"message": "人気のトークン"
},
"privacyMsg": {
"message": "プライバシーポリシー"
},
"privateKey": {
"message": "秘密鍵",
"description": "select this type of file to use to import an account"
@ -546,6 +567,12 @@
"message": "ファイルとして保存",
"description": "Account export process"
},
"search": {
"message": "検索"
},
"searchResults": {
"message": "検索結果"
},
"selectService": {
"message": "サービスを選択"
},
@ -609,6 +636,9 @@
"takesTooLong": {
"message": "送信に時間がかかりますか?"
},
"terms": {
"message": "利用規約"
},
"testFaucet": {
"message": "Faucetをテスト"
},
@ -619,6 +649,9 @@
"message": "ShapeShiftで $1をETHにする",
"description": "system will fill in deposit type in start of message"
},
"token": {
"message": "トークン"
},
"tokenAddress": {
"message": "トークンアドレス"
},
@ -690,6 +723,12 @@
"warning": {
"message": "警告"
},
"welcomeBack": {
"message": "おかえりなさい!"
},
"welcomeBeta": {
"message": "MetaMask ベータ版へようこそ!"
},
"whatsThis": {
"message": "この機能について"
},

@ -1,7 +1,7 @@
{
"name": "__MSG_appName__",
"short_name": "__MSG_appName__",
"version": "4.6.1",
"version": "4.8.0",
"manifest_version": 2,
"author": "https://metamask.io",
"description": "__MSG_appDescription__",
@ -71,6 +71,8 @@
"matches": [
"https://metamask.io/*"
],
"ids": ["*"]
"ids": [
"*"
]
}
}

@ -16,7 +16,18 @@ const accountImporter = {
strategies: {
'Private Key': (privateKey) => {
const stripped = ethUtil.stripHexPrefix(privateKey)
if (!privateKey) {
throw new Error('Cannot import an empty key.')
}
const prefixed = ethUtil.addHexPrefix(privateKey)
const buffer = ethUtil.toBuffer(prefixed)
if (!ethUtil.isValidPrivate(buffer)) {
throw new Error('Cannot import invalid private key.')
}
const stripped = ethUtil.stripHexPrefix(prefixed)
return stripped
},
'JSON File': (input, password) => {

@ -16,6 +16,7 @@ const ExtensionPlatform = require('./platforms/extension')
const Migrator = require('./lib/migrator/')
const migrations = require('./migrations/')
const PortStream = require('./lib/port-stream.js')
const createStreamSink = require('./lib/createStreamSink')
const NotificationManager = require('./lib/notification-manager.js')
const MetamaskController = require('./metamask-controller')
const firstTimeState = require('./first-time-state')
@ -279,7 +280,7 @@ function setupController (initState, initLangCode) {
asStream(controller.store),
debounce(1000),
storeTransform(versionifyData),
storeTransform(persistData),
createStreamSink(persistData),
(error) => {
log.error('MetaMask - Persistence pipeline failed', error)
}
@ -295,7 +296,7 @@ function setupController (initState, initLangCode) {
return versionedData
}
function persistData (state) {
async function persistData (state) {
if (!state) {
throw new Error('MetaMask - updated state is missing', state)
}
@ -303,12 +304,13 @@ function setupController (initState, initLangCode) {
throw new Error('MetaMask - updated state does not have data', state)
}
if (localStore.isSupported) {
localStore.set(state)
.catch((err) => {
try {
await localStore.set(state)
} catch (err) {
// log error so we dont break the pipeline
log.error('error setting state in local store:', err)
})
}
return state
}
}
//

@ -115,8 +115,8 @@ function logStreamDisconnectWarning (remoteLabel, err) {
* @returns {boolean} {@code true} if Web3 should be injected
*/
function shouldInjectWeb3 () {
return doctypeCheck() && suffixCheck()
&& documentElementCheck() && !blacklistedDomainCheck()
return doctypeCheck() && suffixCheck() &&
documentElementCheck() && !blacklistedDomainCheck()
}
/**
@ -176,6 +176,7 @@ function blacklistedDomainCheck () {
'webbyawards.com',
'cdn.shopify.com/s/javascripts/tricorder/xtld-read-only-frame.html',
'adyen.com',
'gravityforms.com',
]
var currentUrl = window.location.href
var currentRegex

@ -89,14 +89,21 @@ module.exports = class NetworkController extends EventEmitter {
type: 'rpc',
rpcTarget,
}
this.providerStore.updateState(providerConfig)
this._switchNetwork(providerConfig)
this.providerConfig = providerConfig
}
async setProviderType (type) {
assert.notEqual(type, 'rpc', `NetworkController - cannot call "setProviderType" with type 'rpc'. use "setRpcTarget"`)
assert(INFURA_PROVIDER_TYPES.includes(type) || type === LOCALHOST, `NetworkController - Unknown rpc type "${type}"`)
const providerConfig = { type }
this.providerConfig = providerConfig
}
resetConnection () {
this.providerConfig = this.getProviderConfig()
}
set providerConfig (providerConfig) {
this.providerStore.updateState(providerConfig)
this._switchNetwork(providerConfig)
}

@ -2,6 +2,7 @@ const ObservableStore = require('obs-store')
const normalizeAddress = require('eth-sig-util').normalize
const extend = require('xtend')
class PreferencesController {
/**
@ -28,7 +29,11 @@ class PreferencesController {
featureFlags: {},
currentLocale: opts.initLangCode,
identities: {},
lostIdentities: {},
}, opts.initState)
this.diagnostics = opts.diagnostics
this.store = new ObservableStore(initState)
}
// PUBLIC METHODS
@ -63,6 +68,13 @@ class PreferencesController {
this.store.updateState({ currentLocale: key })
}
/**
* Updates identities to only include specified addresses. Removes identities
* not included in addresses array
*
* @param {string[]} addresses An array of hex addresses
*
*/
setAddresses (addresses) {
const oldIdentities = this.store.getState().identities
const identities = addresses.reduce((ids, address, index) => {
@ -73,6 +85,68 @@ class PreferencesController {
this.store.updateState({ identities })
}
/**
* Adds addresses to the identities object without removing identities
*
* @param {string[]} addresses An array of hex addresses
*
*/
addAddresses (addresses) {
const identities = this.store.getState().identities
addresses.forEach((address) => {
// skip if already exists
if (identities[address]) return
// add missing identity
const identityCount = Object.keys(identities).length
identities[address] = { name: `Account ${identityCount + 1}`, address }
})
this.store.updateState({ identities })
}
/*
* Synchronizes identity entries with known accounts.
* Removes any unknown identities, and returns the resulting selected address.
*
* @param {Array<string>} addresses known to the vault.
* @returns {Promise<string>} selectedAddress the selected address.
*/
syncAddresses (addresses) {
const { identities, lostIdentities } = this.store.getState()
const newlyLost = {}
Object.keys(identities).forEach((identity) => {
if (!addresses.includes(identity)) {
newlyLost[identity] = identities[identity]
delete identities[identity]
}
})
// Identities are no longer present.
if (Object.keys(newlyLost).length > 0) {
// Notify our servers:
if (this.diagnostics) this.diagnostics.reportOrphans(newlyLost)
// store lost accounts
for (const key in newlyLost) {
lostIdentities[key] = newlyLost[key]
}
}
this.store.updateState({ identities, lostIdentities })
this.addAddresses(addresses)
// If the selected account is no longer valid,
// select an arbitrary other account:
let selected = this.getSelectedAddress()
if (!addresses.includes(selected)) {
selected = addresses[0]
this.setSelectedAddress(selected)
}
return selected
}
/**
* Setter for the `selectedAddress` property
*
@ -173,6 +247,7 @@ class PreferencesController {
* @return {Promise<string>}
*/
setAccountLabel (account, label) {
if (!account) throw new Error('setAccountLabel requires a valid address, got ' + String(account))
const address = normalizeAddress(account)
const {identities} = this.store.getState()
identities[address] = identities[address] || {}

@ -10,6 +10,7 @@ const NonceTracker = require('./nonce-tracker')
const txUtils = require('./lib/util')
const cleanErrorStack = require('../../lib/cleanErrorStack')
const log = require('loglevel')
const recipientBlacklistChecker = require('./lib/recipient-blacklist-checker')
/**
Transaction Controller is an aggregate of sub-controllers and trackers
@ -157,11 +158,14 @@ class TransactionController extends EventEmitter {
let txMeta = this.txStateManager.generateTxMeta({ txParams: normalizedTxParams })
this.addTx(txMeta)
this.emit('newUnapprovedTx', txMeta)
// add default tx params
try {
// check whether recipient account is blacklisted
recipientBlacklistChecker.checkAccount(txMeta.metamaskNetworkId, normalizedTxParams.to)
// add default tx params
txMeta = await this.addTxGasDefaults(txMeta)
} catch (error) {
console.log(error)
log.warn(error)
this.txStateManager.setTxStatusFailed(txMeta.id, error)
throw error
}
@ -260,7 +264,12 @@ class TransactionController extends EventEmitter {
// must set transaction to submitted/failed before releasing lock
nonceLock.releaseLock()
} catch (err) {
// this is try-catch wrapped so that we can guarantee that the nonceLock is released
try {
this.txStateManager.setTxStatusFailed(txId, err)
} catch (err) {
log.error(err)
}
// must set transaction to submitted/failed before releasing lock
if (nonceLock) nonceLock.releaseLock()
// continue with error chain

@ -0,0 +1,24 @@
const Config = require('./recipient-blacklist.js')
/** @module*/
module.exports = {
checkAccount,
}
/**
* Checks if a specified account on a specified network is blacklisted.
@param networkId {number}
@param account {string}
*/
function checkAccount (networkId, account) {
const mainnetId = 1
if (networkId !== mainnetId) {
return
}
const accountToCheck = account.toLowerCase()
if (Config.blacklist.includes(accountToCheck)) {
throw new Error('Recipient is a public account')
}
}

@ -0,0 +1,17 @@
module.exports = {
'blacklist': [
// IDEX phisher
'0x9bcb0A9d99d815Bb87ee3191b1399b1Bcc46dc77',
// Ganache default seed phrases
'0x627306090abab3a6e1400e9345bc60c78a8bef57',
'0xf17f52151ebef6c7334fad080c5704d77216b732',
'0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef',
'0x821aea9a577a9b44299b9c15c88cf3087f3b5544',
'0x0d1d4e623d10f9fba5db95830f7d3839406c6af2',
'0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e',
'0x2191ef87e392377ec08e7c08eb105ef5448eced5',
'0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5',
'0x6330a553fc93768f612722bb8c2ec78ac90b3bbc',
'0x5aeda56215b167893e80b4fe645ba6d5bab767de',
],
}

@ -49,6 +49,7 @@ class NonceTracker {
await this._globalMutexFree()
// await lock free, then take lock
const releaseLock = await this._takeMutex(address)
try {
// evaluate multiple nextNonce strategies
const nonceDetails = {}
const networkNonceResult = await this._getNetworkNextNonce(address)
@ -72,6 +73,11 @@ class NonceTracker {
// return nonce and release cb
return { nextNonce, nonceDetails, releaseLock }
} catch (err) {
// release lock if we encounter an error
releaseLock()
throw err
}
}
async _getCurrentBlock () {
@ -85,8 +91,8 @@ class NonceTracker {
async _globalMutexFree () {
const globalMutex = this._lookupMutex('global')
const release = await globalMutex.acquire()
release()
const releaseLock = await globalMutex.acquire()
releaseLock()
}
async _takeMutex (lockId) {

@ -196,14 +196,14 @@ class PendingTransactionTracker extends EventEmitter {
async _checkPendingTxs () {
const signedTxList = this.getPendingTransactions()
// in order to keep the nonceTracker accurate we block it while updating pending transactions
const nonceGlobalLock = await this.nonceTracker.getGlobalLock()
const { releaseLock } = await this.nonceTracker.getGlobalLock()
try {
await Promise.all(signedTxList.map((txMeta) => this._checkPendingTx(txMeta)))
} catch (err) {
log.error('PendingTransactionWatcher - Error updating pending transactions')
log.error(err)
}
nonceGlobalLock.releaseLock()
releaseLock()
}
/**

@ -0,0 +1,17 @@
const MessageManager = require('./lib/message-manager')
const PersonalMessageManager = require('./lib/personal-message-manager')
const TypedMessageManager = require('./lib/typed-message-manager')
class UserActionController {
constructor (opts = {}) {
this.messageManager = new MessageManager()
this.personalMessageManager = new PersonalMessageManager()
this.typedMessageManager = new TypedMessageManager()
}
}
module.exports = UserActionController

@ -38,9 +38,30 @@ web3.setProvider = function () {
log.debug('MetaMask - overrode web3.setProvider')
}
log.debug('MetaMask - injected web3')
// export global web3, with usage-detection
setupDappAutoReload(web3, inpageProvider.publicConfigStore)
// export global web3, with usage-detection and deprecation warning
/* TODO: Uncomment this area once auto-reload.js has been deprecated:
let hasBeenWarned = false
global.web3 = new Proxy(web3, {
get: (_web3, key) => {
// show warning once on web3 access
if (!hasBeenWarned && key !== 'currentProvider') {
console.warn('MetaMask: web3 will be deprecated in the near future in favor of the ethereumProvider \nhttps://github.com/MetaMask/faq/blob/master/detecting_metamask.md#web3-deprecation')
hasBeenWarned = true
}
// return value normally
return _web3[key]
},
set: (_web3, key, value) => {
// set value normally
_web3[key] = value
},
})
*/
// set web3 defaultAccount
inpageProvider.publicConfigStore.subscribe(function (state) {
web3.eth.defaultAccount = state.selectedAddress

@ -59,6 +59,7 @@ function createErrorMiddleware ({ override = true } = {}) {
if (!error) { return done() }
sanitizeRPCError(error)
log.error(`MetaMask - RPC Error: ${error.message}`, error)
done()
})
}
}

@ -0,0 +1,24 @@
const WritableStream = require('readable-stream').Writable
const promiseToCallback = require('promise-to-callback')
module.exports = createStreamSink
function createStreamSink (asyncWriteFn, _opts) {
return new AsyncWritableStream(asyncWriteFn, _opts)
}
class AsyncWritableStream extends WritableStream {
constructor (asyncWriteFn, _opts) {
const opts = Object.assign({ objectMode: true }, _opts)
super(opts)
this._asyncWriteFn = asyncWriteFn
}
// write from incomming stream to state
_write (chunk, encoding, callback) {
promiseToCallback(this._asyncWriteFn(chunk, encoding))(callback)
}
}

@ -0,0 +1,71 @@
class DiagnosticsReporter {
constructor ({ firstTimeInfo, version }) {
this.firstTimeInfo = firstTimeInfo
this.version = version
}
async reportOrphans (orphans) {
try {
return await this.submit({
accounts: Object.keys(orphans),
metadata: {
type: 'orphans',
},
})
} catch (err) {
console.error('DiagnosticsReporter - "reportOrphans" encountered an error:')
console.error(err)
}
}
async reportMultipleKeyrings (rawKeyrings) {
try {
const keyrings = await Promise.all(rawKeyrings.map(async (keyring, index) => {
return {
index,
type: keyring.type,
accounts: await keyring.getAccounts(),
}
}))
return await this.submit({
accounts: [],
metadata: {
type: 'keyrings',
keyrings,
},
})
} catch (err) {
console.error('DiagnosticsReporter - "reportMultipleKeyrings" encountered an error:')
console.error(err)
}
}
async submit (message) {
try {
// add metadata
message.metadata.version = this.version
message.metadata.firstTimeInfo = this.firstTimeInfo
return await postData(message)
} catch (err) {
console.error('DiagnosticsReporter - "submit" encountered an error:')
throw err
}
}
}
function postData (data) {
const uri = 'https://diagnostics.metamask.io/v1/orphanedAccounts'
return fetch(uri, {
body: JSON.stringify(data), // must match 'Content-Type' header
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'content-type': 'application/json',
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
})
}
module.exports = DiagnosticsReporter

@ -2,8 +2,7 @@ const extension = require('extensionizer')
const promisify = require('pify')
const allLocales = require('../../_locales/index.json')
const isSupported = extension.i18n && extension.i18n.getAcceptLanguages
const getPreferredLocales = isSupported ? promisify(
const getPreferredLocales = extension.i18n ? promisify(
extension.i18n.getAcceptLanguages,
{ errorFirst: false }
) : async () => []
@ -18,7 +17,21 @@ const existingLocaleCodes = allLocales.map(locale => locale.code.toLowerCase().r
*
*/
async function getFirstPreferredLangCode () {
const userPreferredLocaleCodes = await getPreferredLocales()
let userPreferredLocaleCodes
try {
userPreferredLocaleCodes = await getPreferredLocales()
} catch (e) {
// Brave currently throws when calling getAcceptLanguages, so this handles that.
userPreferredLocaleCodes = []
}
// safeguard for Brave Browser until they implement chrome.i18n.getAcceptLanguages
// https://github.com/MetaMask/metamask-extension/issues/4270
if (!userPreferredLocaleCodes) {
userPreferredLocaleCodes = []
}
const firstPreferredLangCode = userPreferredLocaleCodes
.map(code => code.toLowerCase())
.find(code => existingLocaleCodes.includes(code))
@ -26,3 +39,4 @@ async function getFirstPreferredLangCode () {
}
module.exports = getFirstPreferredLangCode

@ -26,13 +26,15 @@ class NotificationManager {
// bring focus to existing chrome popup
extension.windows.update(popup.id, { focused: true })
} else {
const cb = (currentPopup) => { this._popupId = currentPopup.id }
// create new notification popup
extension.windows.create({
const creation = extension.windows.create({
url: 'notification.html',
type: 'popup',
width,
height,
})
}, cb)
creation && creation.then && creation.then(cb)
}
})
}
@ -84,7 +86,7 @@ class NotificationManager {
}
/**
* Given an array of windows, returns the first that has a 'popup' type, or null if no such window exists.
* Given an array of windows, returns the 'popup' that has been opened by MetaMask, or null if no such window exists.
*
* @private
* @param {array} windows An array of objects containing data about the open MetaMask extension windows.
@ -93,7 +95,7 @@ class NotificationManager {
_getPopupIn (windows) {
return windows ? windows.find((win) => {
// Returns notification popup
return (win && win.type === 'popup')
return (win && win.type === 'popup' && win.id === this._popupId)
}) : null
}

@ -66,7 +66,7 @@ function simplifyErrorMessages(report) {
function rewriteErrorMessages (report, rewriteFn) {
// rewrite top level message
report.message = rewriteFn(report.message)
if (report.message) report.message = rewriteFn(report.message)
// rewrite each exception message
if (report.exception && report.exception.values) {
report.exception.values.forEach(item => {

@ -139,6 +139,8 @@ module.exports = class MetamaskController extends EventEmitter {
const address = addresses[0]
this.preferencesController.setSelectedAddress(address)
}
// ensure preferences + identities controller know about all addresses
this.preferencesController.addAddresses(addresses)
this.accountTracker.syncWithAddresses(addresses)
})
@ -179,9 +181,6 @@ module.exports = class MetamaskController extends EventEmitter {
version,
firstVersion: initState.firstTimeInfo.version,
})
this.noticeController.updateNoticesList()
// to be uncommented when retrieving notices from a remote server.
// this.noticeController.startPolling()
this.shapeshiftController = new ShapeShiftController({
initState: initState.ShapeShiftController,
@ -354,7 +353,7 @@ module.exports = class MetamaskController extends EventEmitter {
importAccountWithStrategy: nodeify(this.importAccountWithStrategy, this),
// vault management
submitPassword: nodeify(keyringController.submitPassword, keyringController),
submitPassword: nodeify(this.submitPassword, this),
// network management
setProviderType: nodeify(networkController.setProviderType, networkController),
@ -384,6 +383,8 @@ module.exports = class MetamaskController extends EventEmitter {
updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController),
retryTransaction: nodeify(this.retryTransaction, this),
getFilteredTxList: nodeify(txController.getFilteredTxList, txController),
isNonceTaken: nodeify(txController.isNonceTaken, txController),
estimateGas: nodeify(this.estimateGas, this),
// messageManager
signMessage: nodeify(this.signMessage, this),
@ -404,7 +405,6 @@ module.exports = class MetamaskController extends EventEmitter {
}
//=============================================================================
// VAULT / KEYRING RELATED METHODS
//=============================================================================
@ -424,28 +424,24 @@ module.exports = class MetamaskController extends EventEmitter {
* @returns {Object} vault
*/
async createNewVaultAndKeychain (password) {
const release = await this.createVaultMutex.acquire()
let vault
const releaseLock = await this.createVaultMutex.acquire()
try {
let vault
const accounts = await this.keyringController.getAccounts()
if (accounts.length > 0) {
vault = await this.keyringController.fullUpdate()
} else {
vault = await this.keyringController.createNewVaultAndKeychain(password)
const accounts = await this.keyringController.getAccounts()
this.preferencesController.setAddresses(accounts)
this.selectFirstIdentity()
}
release()
releaseLock()
return vault
} catch (err) {
release()
releaseLock()
throw err
}
return vault
}
/**
@ -454,20 +450,46 @@ module.exports = class MetamaskController extends EventEmitter {
* @param {} seed
*/
async createNewVaultAndRestore (password, seed) {
const release = await this.createVaultMutex.acquire()
const releaseLock = await this.createVaultMutex.acquire()
try {
// clear known identities
this.preferencesController.setAddresses([])
// create new vault
const vault = await this.keyringController.createNewVaultAndRestore(password, seed)
// set new identities
const accounts = await this.keyringController.getAccounts()
this.preferencesController.setAddresses(accounts)
this.selectFirstIdentity()
release()
releaseLock()
return vault
} catch (err) {
release()
releaseLock()
throw err
}
}
/*
* Submits the user's password and attempts to unlock the vault.
* Also synchronizes the preferencesController, to ensure its schema
* is up to date with known accounts once the vault is decrypted.
*
* @param {string} password - The user's password
* @returns {Promise<object>} - The keyringController update.
*/
async submitPassword (password) {
await this.keyringController.submitPassword(password)
const accounts = await this.keyringController.getAccounts()
// verify keyrings
const nonSimpleKeyrings = this.keyringController.keyrings.filter(keyring => keyring.type !== 'Simple Key Pair')
if (nonSimpleKeyrings.length > 1 && this.diagnostics) {
await this.diagnostics.reportMultipleKeyrings(nonSimpleKeyrings)
}
await this.preferencesController.syncAddresses(accounts)
return this.keyringController.fullUpdate()
}
/**
* @type Identity
* @property {string} name - The account nickname.
@ -592,10 +614,7 @@ module.exports = class MetamaskController extends EventEmitter {
async resetAccount () {
const selectedAddress = this.preferencesController.getSelectedAddress()
this.txController.wipeTransactions(selectedAddress)
const networkController = this.networkController
const oldType = networkController.getProviderConfig().type
await networkController.setProviderType(oldType, true)
this.networkController.resetConnection()
return selectedAddress
}
@ -922,6 +941,18 @@ module.exports = class MetamaskController extends EventEmitter {
return state
}
estimateGas (estimateGasParams) {
return new Promise((resolve, reject) => {
return this.txController.txGasUtil.query.estimateGas(estimateGasParams, (err, res) => {
if (err) {
return reject(err)
}
return resolve(res)
})
})
}
//=============================================================================
// PASSWORD MANAGEMENT
//=============================================================================

@ -35,10 +35,10 @@ function transformState (state) {
if (transactions.length <= 40) return newState
let reverseTxList = transactions.reverse()
const reverseTxList = transactions.reverse()
let stripping = true
while (reverseTxList.length > 40 && stripping) {
let txIndex = reverseTxList.findIndex((txMeta) => {
const txIndex = reverseTxList.findIndex((txMeta) => {
return (txMeta.status === 'failed' ||
txMeta.status === 'rejected' ||
txMeta.status === 'confirmed' ||

@ -27,7 +27,7 @@ module.exports = {
function transformState (state) {
if (!state.KeyringController || !state.PreferencesController) {
return
return state
}
if (!state.KeyringController.walletNicknames) {

@ -2,7 +2,7 @@ const EventEmitter = require('events').EventEmitter
const semver = require('semver')
const extend = require('xtend')
const ObservableStore = require('obs-store')
const hardCodedNotices = require('../../notices/notices.json')
const hardCodedNotices = require('../../notices/notices.js')
const uniqBy = require('lodash.uniqby')
module.exports = class NoticeController extends EventEmitter {
@ -16,8 +16,12 @@ module.exports = class NoticeController extends EventEmitter {
noticesList: [],
}, opts.initState)
this.store = new ObservableStore(initState)
// setup memStore
this.memStore = new ObservableStore({})
this.store.subscribe(() => this._updateMemstore())
this._updateMemstore()
// pull in latest notices
this.updateNoticesList()
}
getNoticesList () {
@ -29,9 +33,9 @@ module.exports = class NoticeController extends EventEmitter {
return notices.filter((notice) => notice.read === false)
}
getLatestUnreadNotice () {
getNextUnreadNotice () {
const unreadNotices = this.getUnreadNotices()
return unreadNotices[unreadNotices.length - 1]
return unreadNotices[0]
}
async setNoticesList (noticesList) {
@ -47,7 +51,7 @@ module.exports = class NoticeController extends EventEmitter {
notices[index].read = true
notices[index].body = ''
this.setNoticesList(notices)
const latestNotice = this.getLatestUnreadNotice()
const latestNotice = this.getNextUnreadNotice()
cb(null, latestNotice)
} catch (err) {
cb(err)
@ -64,15 +68,6 @@ module.exports = class NoticeController extends EventEmitter {
return result
}
startPolling () {
if (this.noticePoller) {
clearInterval(this.noticePoller)
}
this.noticePoller = setInterval(() => {
this.noticeController.updateNoticesList()
}, 300000)
}
_mergeNotices (oldNotices, newNotices) {
return uniqBy(oldNotices.concat(newNotices), 'id')
}
@ -91,19 +86,15 @@ module.exports = class NoticeController extends EventEmitter {
})
}
_mapNoticeIds (notices) {
return notices.map((notice) => notice.id)
}
async _retrieveNoticeData () {
// Placeholder for the API.
// Placeholder for remote notice API.
return hardCodedNotices
}
_updateMemstore () {
const lastUnreadNotice = this.getLatestUnreadNotice()
const noActiveNotices = !lastUnreadNotice
this.memStore.updateState({ lastUnreadNotice, noActiveNotices })
const nextUnreadNotice = this.getNextUnreadNotice()
const noActiveNotices = !nextUnreadNotice
this.memStore.updateState({ nextUnreadNotice, noActiveNotices })
}
}

@ -7,6 +7,6 @@ var changelog = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md')).toSt
var log = changelog.split(version)[1].split('##')[0].trim()
let msg = `*MetaMask ${version}* now published! It should auto-update soon!\n${log}`
const msg = `*MetaMask ${version}* now published! It should auto-update soon!\n${log}`
console.log(msg)

@ -1,5 +1,5 @@
module.exports = {
"confirm sig requests": {
'confirm sig requests': {
signMessage: (msgData, cb) => {
const stateUpdate = {
unapprovedMsgs: {},

@ -1,17 +1,14 @@
const beefy = require('beefy')
const http = require('http')
const fs = require('fs')
const path = require('path')
const port = 8124
const handler = beefy({
entries: {'mocker.js': 'bundle.js'}
, cwd: __dirname
, live: true
, open: true
, quiet: false
, bundlerFlags: ['-t', 'brfs']
entries: {'mocker.js': 'bundle.js'},
cwd: __dirname,
live: true,
open: true,
quiet: false,
bundlerFlags: ['-t', 'brfs'],
})

@ -12,7 +12,6 @@
* To use, run `npm run mock`.
*/
const extend = require('xtend')
const render = require('react-dom').render
const h = require('react-hyperscript')
const Root = require('../ui/app/root')
@ -24,7 +23,6 @@ const Selector = require('./selector')
const MetamaskController = require('../app/scripts/metamask-controller')
const firstTimeState = require('../app/scripts/first-time-state')
const ExtensionPlatform = require('../app/scripts/platforms/extension')
const extension = require('./mockExtension')
const noop = function () {}
const log = require('loglevel')
@ -81,7 +79,7 @@ const controller = new MetamaskController({
initState: firstTimeState,
})
global.metamaskController = controller
global.platform = new ExtensionPlatform
global.platform = new ExtensionPlatform()
//
// User Interface

@ -39,6 +39,6 @@ extension.runtime.reload = noop
extension.tabs.create = noop
extension.runtime.getManifest = function () {
return {
version: 'development'
version: 'development',
}
}

@ -11,7 +11,7 @@ function NewComponent () {
NewComponent.prototype.render = function () {
const props = this.props
let {
const {
states,
selectedKey,
actions,

@ -1,6 +1,6 @@
const fs = require('fs')
const { SourceMapConsumer } = require('source-map')
const path = require('path')
//
// Utility to help check if sourcemaps are working
//
@ -11,9 +11,11 @@ const { SourceMapConsumer } = require('source-map')
start()
async function start () {
const rawBuild = fs.readFileSync(__dirname + '/../dist/chrome/inpage.js', 'utf8')
const rawSourceMap = fs.readFileSync(__dirname + '/../dist/sourcemaps/inpage.js.map', 'utf8')
const rawBuild = fs.readFileSync(path.join(__dirname, '/../dist/chrome/', 'inpage.js')
, 'utf8')
const rawSourceMap = fs.readFileSync(path.join(__dirname, '/../dist/sourcemaps/', 'inpage.js.map'), 'utf8')
const consumer = await new SourceMapConsumer(rawSourceMap)
console.log('hasContentsOfAllSources:', consumer.hasContentsOfAllSources(), '\n')
@ -43,7 +45,8 @@ async function start() {
}
function indicesOf (substring, string) {
var a=[],i=-1;
while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
return a;
var a = []
var i = -1
while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i)
return a
}

@ -75,9 +75,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{

@ -52,7 +52,7 @@
"conversionRate": 12.7200827,
"conversionDate": 1487363041,
"noActiveNotices": true,
"lastUnreadNotice": {
"nextUnreadNotice": {
"read": true,
"date": "Thu Feb 09 2017",
"title": "Terms of Use",

@ -151,5 +151,10 @@
"scrollToBottom": false,
"forgottenPassword": null
},
"identities": {}
"identities": {},
"send": {
"fromDropdownOpen": false,
"toDropdownOpen": false,
"errors": {}
}
}

@ -115,9 +115,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{

@ -76,9 +76,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{

@ -12,7 +12,7 @@
"conversionRate": 12.7527416,
"conversionDate": 1487624341,
"noActiveNotices": false,
"lastUnreadNotice": {
"nextUnreadNotice": {
"read": false,
"date": "Thu Feb 09 2017",
"title": "Terms of Use",

@ -13,7 +13,7 @@
"conversionRate": 8.3533002,
"conversionDate": 1481671082,
"noActiveNotices": false,
"lastUnreadNotice": {
"nextUnreadNotice": {
"read": false,
"date": "Tue Dec 13 2016",
"title": "MultiVault Support",

@ -94,9 +94,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{
@ -151,5 +151,10 @@
"scrollToBottom": false,
"forgottenPassword": null
},
"identities": {}
"identities": {},
"send": {
"fromDropdownOpen": false,
"toDropdownOpen": false,
"errors": {}
}
}

@ -76,9 +76,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{
@ -130,5 +130,10 @@
"scrollToBottom": false,
"forgottenPassword": null
},
"identities": {}
"identities": {},
"send": {
"fromDropdownOpen": false,
"toDropdownOpen": false,
"errors": {}
}
}

@ -83,9 +83,9 @@
{
"type": "HD Key Tree",
"accounts": [
"fdea65c8e26263f6d9a1b5de9555d2931a33b825",
"c5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"2f8d4a878cfa04a6e60d46362f5644deab66572d"
"0xfdea65c8e26263f6d9a1b5de9555d2931a33b825",
"0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb",
"0x2f8d4a878cfa04a6e60d46362f5644deab66572d"
]
},
{
@ -124,5 +124,10 @@
"scrollToBottom": false,
"forgottenPassword": null
},
"identities": {}
"identities": {},
"send": {
"fromDropdownOpen": false,
"toDropdownOpen": false,
"errors": {}
}
}

@ -29,9 +29,8 @@ log.setDefaultLevel(1)
// Query String
const qs = require('qs')
let queryString = qs.parse(window.location.href.split('#')[1])
const queryString = qs.parse(window.location.href.split('#')[1])
let selectedView = queryString.view || 'first time'
const firstState = states[selectedView]
updateQueryParams(selectedView)
// CSS

@ -20,7 +20,7 @@ const specifiedLocale = process.argv[2]
if (specifiedLocale) {
console.log(`Verifying selected locale "${specifiedLocale}":\n\n`)
const locale = localeIndex.find(localeMeta => localeMeta.code === specifiedLocale)
verifyLocale({ localeMeta })
verifyLocale({ locale })
} else {
console.log('Verifying all locales:\n\n')
localeIndex.forEach(localeMeta => {
@ -30,16 +30,16 @@ if (specifiedLocale) {
}
function verifyLocale ({ localeMeta }) {
const localeCode = localeMeta.code
const localeName = localeMeta.name
let targetLocale, englishLocale
try {
const localeFilePath = path.join(process.cwd(), 'app', '_locales', localeCode, 'messages.json')
targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8'));
targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8'))
} catch (e) {
if (e.code == 'ENOENT') {
if (e.code === 'ENOENT') {
console.log('Locale file not found')
} else {
console.log(`Error opening your locale ("${localeCode}") file: `, e)
@ -49,9 +49,9 @@ function verifyLocale({ localeMeta }) {
try {
const englishFilePath = path.join(process.cwd(), 'app', '_locales', 'en', 'messages.json')
englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8'));
englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8'))
} catch (e) {
if(e.code == 'ENOENT') {
if (e.code === 'ENOENT') {
console.log('English File not found')
} else {
console.log('Error opening english locale file: ', e)

@ -19,13 +19,13 @@ async function versionBump(bumpType, changelog, oldManifest) {
return {
version: newVersion,
manifest: manifest,
changelog: logLines.join('\n')
changelog: logLines.join('\n'),
}
}
function newVersionFrom (manifest, bumpType) {
const string = manifest.version
let segments = string.split('.').map((str) => parseInt(str))
const segments = string.split('.').map((str) => parseInt(str))
switch (bumpType) {
case 'major':
@ -45,8 +45,4 @@ function newVersionFrom (manifest, bumpType) {
return segments.map(String).join('.')
}
function bumpManifest (manifest, bumpType) {
}
module.exports = versionBump

@ -2,18 +2,32 @@
When publishing a new version of MetaMask, we follow this procedure:
## Preparation
We try to ensure certain criteria are met before deploying:
- Deploy early in the week, to give time for emergency responses to unforeseen bugs.
- Deploy early in the day, for the same reason.
- Make sure at least one member of the support team is "on duty" to watch for new user issues coming through the support system.
- Roll out incrementally when possible, to a small number of users first, and gradually to more users.
## Incrementing Version & Changelog
Version can be automatically incremented [using our bump script](./bumping-version.md).
npm run version:bump $BUMP_TYPE` where `$BUMP_TYPE` is one of `major`, `minor`, or `patch`.
## Publishing
## Building
1. `npm run dist` to generate the latest build.
2. Publish to chrome store.
- Visit [the chrome developer dashboard](https://chrome.google.com/webstore/developer/dashboard?authuser=2).
3. Publish to firefox addon marketplace.
4. Post on Github releases page.
5. `npm run announce`, post that announcement in our public places.
While we develop on the main `develop` branch, our production version is maintained on the `master` branch.
With each pull request, the @MetaMaskBot will comment with a build of that new pull request, so after bumping the version on `develop`, open a pull request against `master`, and once the pull request is reviewed and merged, you can download those builds for publication.
## Publishing
1. Publish to chrome store.
2. Visit [the chrome developer dashboard](https://chrome.google.com/webstore/developer/dashboard?authuser=2).
3. Publish to [firefox addon marketplace](http://addons.mozilla.org/en-us/firefox/addon/ether-metamask).
4. Publish to [Opera store](https://addons.opera.com/en/extensions/details/metamask/).
5. Post on [Github releases](https://github.com/MetaMask/metamask-extension/releases) page.
6. Run the `npm run announce` script, and post that announcement in our public places.

@ -0,0 +1,241 @@
const fs = require('fs')
const path = require('path')
const async = require('async')
const promisify = require('pify')
// start(/\.selectors.js/, generateSelectorTest).catch(console.error)
// start(/\.utils.js/, generateUtilTest).catch(console.error)
startContainer(/\.container.js/, generateContainerTest).catch(console.error)
async function getAllFileNames (dirName) {
const allNames = (await promisify(fs.readdir)(dirName))
const fileNames = allNames.filter(name => name.match(/^.+\./))
const dirNames = allNames.filter(name => name.match(/^[^.]+$/))
const fullPathDirNames = dirNames.map(d => `${dirName}/${d}`)
const subNameArrays = await promisify(async.map)(fullPathDirNames, getAllFileNames)
let subNames = []
subNameArrays.forEach(subNameArray => { subNames = [...subNames, ...subNameArray] })
return [
...fileNames.map(name => dirName + '/' + name),
...subNames,
]
}
/*
async function start (fileRegEx, testGenerator) {
const fileNames = await getAllFileNames('./ui/app')
const sFiles = fileNames.filter(name => name.match(fileRegEx))
let sFileMethodNames
let testFilePath
async.each(sFiles, async (sFile, cb) => {
const [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/)
sFileMethodNames = Object.keys(require(__dirname + '/' + sFile))
testFilePath = sPath.replace('.', '-').replace('.', '.test.')
await promisify(fs.writeFile)(
`${__dirname}/${sRootPath}tests/${testFilePath}`,
testGenerator(sPath, sFileMethodNames),
'utf8'
)
}, (err) => {
console.log(err)
})
}
*/
async function startContainer (fileRegEx, testGenerator) {
const fileNames = await getAllFileNames('./ui/app')
const sFiles = fileNames.filter(name => name.match(fileRegEx))
async.each(sFiles, async (sFile, cb) => {
console.log(`sFile`, sFile)
const [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/)
const testFilePath = sPath.replace('.', '-').replace('.', '.test.')
await promisify(fs.readFile)(
path.join(__dirname, sFile),
'utf8',
async (err, result) => {
if (err) {
console.log('Error: ', err)
} else {
console.log(`result`, result.length)
const returnObjectStrings = result
.match(/return\s(\{[\s\S]+?})\n}/g)
.map(str => {
return str
.slice(0, str.length - 1)
.slice(7)
.replace(/\n/g, '')
.replace(/\s\s+/g, ' ')
})
const mapStateToPropsAssertionObject = returnObjectStrings[0]
.replace(/\w+:\s\w+\([\w,\s]+\),/g, str => {
const strKey = str.match(/^\w+/)[0]
return strKey + ': \'mock' + str.match(/^\w+/)[0].replace(/^./, c => c.toUpperCase()) + ':mockState\',\n'
})
.replace(/{\s\w.+/, firstLinePair => `{\n ${firstLinePair.slice(2)}`)
.replace(/\w+:.+,/g, s => ` ${s}`)
.replace(/}/g, s => ` ${s}`)
let mapDispatchToPropsMethodNames
if (returnObjectStrings[1]) {
mapDispatchToPropsMethodNames = returnObjectStrings[1].match(/\s\w+:\s/g).map(str => str.match(/\w+/)[0])
}
const proxyquireObject = ('{\n ' + result
.match(/import\s{[\s\S]+?}\sfrom\s.+/g)
.map(s => s.replace(/\n/g, ''))
.map((s, i) => {
const proxyKeys = s.match(/{.+}/)[0].match(/\w+/g)
return '\'' + s.match(/'(.+)'/)[1] + '\': { ' + (proxyKeys.length > 1
? '\n ' + proxyKeys.join(': () => {},\n ') + ': () => {},\n '
: proxyKeys[0] + ': () => {},') + ' }'
})
.join(',\n ') + '\n}')
.replace('{ connect: () => {}, },', `{
connect: (ms, md) => {
mapStateToProps = ms
mapDispatchToProps = md
return () => ({})
},
},`)
// console.log(`proxyquireObject`, proxyquireObject);
// console.log(`mapStateToPropsAssertionObject`, mapStateToPropsAssertionObject);
// console.log(`mapDispatchToPropsMethodNames`, mapDispatchToPropsMethodNames);
const containerTest = generateContainerTest(sPath, {
mapStateToPropsAssertionObject,
mapDispatchToPropsMethodNames,
proxyquireObject,
})
// console.log(`containerTest`, `${__dirname}/${sRootPath}tests/${testFilePath}`, containerTest);
console.log('----')
console.log(`sRootPath`, sRootPath)
console.log(`testFilePath`, testFilePath)
await promisify(fs.writeFile)(
`${__dirname}/${sRootPath}tests/${testFilePath}`,
containerTest,
'utf8'
)
}
}
)
}, (err) => {
console.log('123', err)
})
}
/*
function generateMethodList (methodArray) {
return methodArray.map(n => ' ' + n).join(',\n') + ','
}
function generateMethodDescribeBlock (methodName, index) {
const describeBlock =
`${index ? ' ' : ''}describe('${methodName}()', () => {
it('should', () => {
const state = {}
assert.equal(${methodName}(state), )
})
})`
return describeBlock
}
*/
function generateDispatchMethodDescribeBlock (methodName, index) {
const describeBlock =
`${index ? ' ' : ''}describe('${methodName}()', () => {
it('should dispatch an action', () => {
mapDispatchToPropsObject.${methodName}()
assert(dispatchSpy.calledOnce)
})
})`
return describeBlock
}
/*
function generateMethodDescribeBlocks (methodArray) {
return methodArray
.map((methodName, index) => generateMethodDescribeBlock(methodName, index))
.join('\n\n')
}
*/
function generateDispatchMethodDescribeBlocks (methodArray) {
return methodArray
.map((methodName, index) => generateDispatchMethodDescribeBlock(methodName, index))
.join('\n\n')
}
/*
function generateSelectorTest (name, methodArray) {
return `import assert from 'assert'
import {
${generateMethodList(methodArray)}
} from '../${name}'
describe('${name.match(/^[^.]+/)} selectors', () => {
${generateMethodDescribeBlocks(methodArray)}
})`
}
function generateUtilTest (name, methodArray) {
return `import assert from 'assert'
import {
${generateMethodList(methodArray)}
} from '../${name}'
describe('${name.match(/^[^.]+/)} utils', () => {
${generateMethodDescribeBlocks(methodArray)}
})`
}
*/
function generateContainerTest (sPath, {
mapStateToPropsAssertionObject,
mapDispatchToPropsMethodNames,
proxyquireObject,
}) {
return `import assert from 'assert'
import proxyquire from 'proxyquire'
import sinon from 'sinon'
let mapStateToProps
let mapDispatchToProps
proxyquire('../${sPath}', ${proxyquireObject})
describe('${sPath.match(/^[^.]+/)} container', () => {
describe('mapStateToProps()', () => {
it('should map the correct properties to props', () => {
assert.deepEqual(mapStateToProps('mockState'), ${mapStateToPropsAssertionObject})
})
})
describe('mapDispatchToProps()', () => {
let dispatchSpy
let mapDispatchToPropsObject
beforeEach(() => {
dispatchSpy = sinon.spy()
mapDispatchToPropsObject = mapDispatchToProps(dispatchSpy)
})
${mapDispatchToPropsMethodNames ? generateDispatchMethodDescribeBlocks(mapDispatchToPropsMethodNames) : 'delete'}
})
})`
}

@ -13,21 +13,15 @@ const zip = require('gulp-zip')
const assign = require('lodash.assign')
const livereload = require('gulp-livereload')
const del = require('del')
const eslint = require('gulp-eslint')
const fs = require('fs')
const path = require('path')
const manifest = require('./app/manifest.json')
const replace = require('gulp-replace')
const mkdirp = require('mkdirp')
const asyncEach = require('async/each')
const exec = require('child_process').exec
const sass = require('gulp-sass')
const autoprefixer = require('gulp-autoprefixer')
const gulpStylelint = require('gulp-stylelint')
const stylefmt = require('gulp-stylefmt')
const uglify = require('gulp-uglify-es').default
const babel = require('gulp-babel')
const debug = require('gulp-debug')
const pify = require('pify')
const gulpMultiProcess = require('gulp-multi-process')
const endOfStream = pify(require('end-of-stream'))
@ -48,7 +42,7 @@ const commonPlatforms = [
// browser webapp
'mascara',
// browser extensions
...browserPlatforms
...browserPlatforms,
]
// browser reload
@ -165,11 +159,11 @@ gulp.task('manifest:opera', function() {
return gulp.src('./dist/opera/manifest.json')
.pipe(jsoneditor(function (json) {
json.permissions = [
"storage",
"tabs",
"clipboardWrite",
"clipboardRead",
"http://localhost:8545/"
'storage',
'tabs',
'clipboardWrite',
'clipboardRead',
'http://localhost:8545/',
]
return json
}))
@ -212,29 +206,6 @@ gulp.task('dev:copy',
)
)
// lint js
const lintTargets = ['app/**/*.json', 'app/**/*.js', '!app/scripts/vendor/**/*.js', 'ui/**/*.js', 'old-ui/**/*.js', 'mascara/src/*.js', 'mascara/server/*.js', '!node_modules/**', '!dist/firefox/**', '!docs/**', '!app/scripts/chromereload.js', '!mascara/test/jquery-3.1.0.min.js']
gulp.task('lint', function () {
// Ignoring node_modules, dist/firefox, and docs folders:
return gulp.src(lintTargets)
.pipe(eslint(fs.readFileSync(path.join(__dirname, '.eslintrc'))))
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError())
});
gulp.task('lint:fix', function () {
return gulp.src(lintTargets)
.pipe(eslint(Object.assign(fs.readFileSync(path.join(__dirname, '.eslintrc')), {fix: true})))
.pipe(eslint.format())
.pipe(eslint.failAfterError())
});
// scss compilation and autoprefixing tasks
gulp.task('build:scss', createScssBuildTask({
@ -277,17 +248,17 @@ gulp.task('lint-scss', function() {
.src('ui/app/css/itcss/**/*.scss')
.pipe(gulpStylelint({
reporters: [
{ formatter: 'string', console: true }
{ formatter: 'string', console: true },
],
fix: true,
}));
});
}))
})
gulp.task('fmt-scss', function () {
return gulp.src('ui/app/css/itcss/**/*.scss')
.pipe(stylefmt())
.pipe(gulp.dest('ui/app/css/itcss'));
});
.pipe(gulp.dest('ui/app/css/itcss'))
})
// build js
@ -562,7 +533,7 @@ function bundleTask(opts) {
buildStream = buildStream
.pipe(uglify({
mangle: {
reserved: [ 'MetamaskInpageProvider' ]
reserved: [ 'MetamaskInpageProvider' ],
},
}))
}

@ -1,8 +1,8 @@
const express = require('express')
const path = require('path')
const createMetamascaraServer = require('../server/')
const createBundle = require('../server/util').createBundle
const serveBundle = require('../server/util').serveBundle
//
// Iframe Server
//
@ -23,7 +23,7 @@ const dappServer = express()
// serve dapp bundle
serveBundle(dappServer, '/app.js', createBundle(require.resolve('./app.js')))
dappServer.use(express.static(__dirname + '/app/'))
dappServer.use(express.static(path.join(__dirname, '/app/')))
// start the server
const dappPort = '9002'

@ -20,7 +20,7 @@ export default class Breadcrumbs extends Component {
/>
))}
</div>
);
)
}
}

@ -54,7 +54,7 @@ class BuyEtherScreen extends Component {
return (
<div
className='buy-ether__do-it-later'
className="buy-ether__do-it-later"
onClick={() => showAccountDetail(address)}
>
Do it later
@ -64,17 +64,17 @@ class BuyEtherScreen extends Component {
renderCoinbaseLogo () {
return (
<svg width='140px' height='49px' viewBox='0 0 579 126' version='1.1'>
<g id='Page-1' stroke='none' strokeWidth={1} fill='none' fillRule='evenodd'>
<g id='Imported-Layers' fill='#0081C9'>
<path d='M37.752,125.873 C18.824,125.873 0.369,112.307 0.369,81.549 C0.369,50.79 18.824,37.382 37.752,37.382 C47.059,37.382 54.315,39.749 59.52,43.219 L53.841,55.68 C50.371,53.156 45.166,51.579 39.961,51.579 C28.604,51.579 18.193,60.57 18.193,81.391 C18.193,102.212 28.919,111.361 39.961,111.361 C45.166,111.361 50.371,109.783 53.841,107.26 L59.52,120.036 C54.157,123.664 47.059,125.873 37.752,125.873' id='Fill-1' />
<path d='M102.898,125.873 C78.765,125.873 65.515,106.786 65.515,81.549 C65.515,56.311 78.765,37.382 102.898,37.382 C127.032,37.382 140.282,56.311 140.282,81.549 C140.282,106.786 127.032,125.873 102.898,125.873 L102.898,125.873 Z M102.898,51.105 C89.491,51.105 82.866,63.093 82.866,81.391 C82.866,99.688 89.491,111.834 102.898,111.834 C116.306,111.834 122.931,99.688 122.931,81.391 C122.931,63.093 116.306,51.105 102.898,51.105 L102.898,51.105 Z' id='Fill-2' />
<path d='M163.468,23.659 C157.79,23.659 153.215,19.243 153.215,13.88 C153.215,8.517 157.79,4.1 163.468,4.1 C169.146,4.1 173.721,8.517 173.721,13.88 C173.721,19.243 169.146,23.659 163.468,23.659 L163.468,23.659 Z M154.793,39.118 L172.144,39.118 L172.144,124.138 L154.793,124.138 L154.793,39.118 Z' id='Fill-3' />
<path d='M240.443,124.137 L240.443,67.352 C240.443,57.415 234.449,51.263 222.619,51.263 C216.31,51.263 210.473,52.367 207.003,53.787 L207.003,124.137 L189.81,124.137 L189.81,43.376 C198.328,39.906 209.212,37.382 222.461,37.382 C246.28,37.382 257.794,47.793 257.794,65.775 L257.794,124.137 L240.443,124.137' id='Fill-4' />
<path d='M303.536,125.873 C292.494,125.873 281.611,123.191 274.986,119.879 L274.986,0.314 L292.179,0.314 L292.179,41.326 C296.28,39.433 302.905,37.856 308.741,37.856 C330.667,37.856 345.494,53.629 345.494,79.656 C345.494,111.676 328.931,125.873 303.536,125.873 L303.536,125.873 Z M305.744,51.263 C301.012,51.263 295.491,52.367 292.179,54.103 L292.179,109.941 C294.703,111.045 299.593,112.149 304.482,112.149 C318.205,112.149 328.301,102.685 328.301,80.918 C328.301,62.305 319.467,51.263 305.744,51.263 L305.744,51.263 Z' id='Fill-5' />
<path d='M392.341,125.873 C367.892,125.873 355.589,115.935 355.589,99.215 C355.589,75.555 380.826,71.296 406.537,69.876 L406.537,64.513 C406.537,53.787 399.439,50.001 388.555,50.001 C380.511,50.001 370.731,52.525 365.053,55.207 L360.636,43.376 C367.419,40.379 378.933,37.382 390.29,37.382 C410.638,37.382 422.942,45.269 422.942,66.248 L422.942,119.879 C416.79,123.191 404.329,125.873 392.341,125.873 L392.341,125.873 Z M406.537,81.391 C389.186,82.337 371.835,83.757 371.835,98.9 C371.835,107.89 378.776,113.411 391.868,113.411 C397.389,113.411 403.856,112.465 406.537,111.203 L406.537,81.391 L406.537,81.391 Z' id='Fill-6' />
<path d='M461.743,125.873 C451.806,125.873 441.395,123.191 435.244,119.879 L441.08,106.629 C445.496,109.31 454.803,112.149 461.27,112.149 C470.576,112.149 476.728,107.575 476.728,100.477 C476.728,92.748 470.261,89.751 461.586,86.596 C450.228,82.337 437.452,77.132 437.452,61.201 C437.452,47.162 448.336,37.382 467.264,37.382 C477.517,37.382 486.035,39.906 492.029,43.376 L486.665,55.364 C482.88,52.998 475.309,50.317 469.157,50.317 C460.166,50.317 455.118,55.049 455.118,61.201 C455.118,68.93 461.428,71.611 469.788,74.766 C481.618,79.183 494.71,84.072 494.71,100.635 C494.71,115.935 483.038,125.873 461.743,125.873' id='Fill-7' />
<path d='M578.625,81.233 L522.155,89.12 C523.89,104.42 533.828,112.149 548.182,112.149 C556.699,112.149 565.848,110.099 571.684,106.944 L576.732,119.879 C570.107,123.349 558.75,125.873 547.078,125.873 C520.262,125.873 505.277,108.679 505.277,81.549 C505.277,55.522 519.789,37.382 543.607,37.382 C565.69,37.382 578.782,51.894 578.782,74.766 C578.782,76.816 578.782,79.025 578.625,81.233 L578.625,81.233 Z M543.292,50.001 C530.042,50.001 521.367,60.097 521.051,77.763 L562.22,72.084 C562.062,57.257 554.649,50.001 543.292,50.001 L543.292,50.001 Z' id='Fill-8' />
<svg width="140px" height="49px" viewBox="0 0 579 126" version="1.1">
<g id="Page-1" stroke="none" strokeWidth={1} fill="none" fillRule="evenodd">
<g id="Imported-Layers" fill="#0081C9">
<path d="M37.752,125.873 C18.824,125.873 0.369,112.307 0.369,81.549 C0.369,50.79 18.824,37.382 37.752,37.382 C47.059,37.382 54.315,39.749 59.52,43.219 L53.841,55.68 C50.371,53.156 45.166,51.579 39.961,51.579 C28.604,51.579 18.193,60.57 18.193,81.391 C18.193,102.212 28.919,111.361 39.961,111.361 C45.166,111.361 50.371,109.783 53.841,107.26 L59.52,120.036 C54.157,123.664 47.059,125.873 37.752,125.873" id="Fill-1" />
<path d="M102.898,125.873 C78.765,125.873 65.515,106.786 65.515,81.549 C65.515,56.311 78.765,37.382 102.898,37.382 C127.032,37.382 140.282,56.311 140.282,81.549 C140.282,106.786 127.032,125.873 102.898,125.873 L102.898,125.873 Z M102.898,51.105 C89.491,51.105 82.866,63.093 82.866,81.391 C82.866,99.688 89.491,111.834 102.898,111.834 C116.306,111.834 122.931,99.688 122.931,81.391 C122.931,63.093 116.306,51.105 102.898,51.105 L102.898,51.105 Z" id="Fill-2" />
<path d="M163.468,23.659 C157.79,23.659 153.215,19.243 153.215,13.88 C153.215,8.517 157.79,4.1 163.468,4.1 C169.146,4.1 173.721,8.517 173.721,13.88 C173.721,19.243 169.146,23.659 163.468,23.659 L163.468,23.659 Z M154.793,39.118 L172.144,39.118 L172.144,124.138 L154.793,124.138 L154.793,39.118 Z" id="Fill-3" />
<path d="M240.443,124.137 L240.443,67.352 C240.443,57.415 234.449,51.263 222.619,51.263 C216.31,51.263 210.473,52.367 207.003,53.787 L207.003,124.137 L189.81,124.137 L189.81,43.376 C198.328,39.906 209.212,37.382 222.461,37.382 C246.28,37.382 257.794,47.793 257.794,65.775 L257.794,124.137 L240.443,124.137" id="Fill-4" />
<path d="M303.536,125.873 C292.494,125.873 281.611,123.191 274.986,119.879 L274.986,0.314 L292.179,0.314 L292.179,41.326 C296.28,39.433 302.905,37.856 308.741,37.856 C330.667,37.856 345.494,53.629 345.494,79.656 C345.494,111.676 328.931,125.873 303.536,125.873 L303.536,125.873 Z M305.744,51.263 C301.012,51.263 295.491,52.367 292.179,54.103 L292.179,109.941 C294.703,111.045 299.593,112.149 304.482,112.149 C318.205,112.149 328.301,102.685 328.301,80.918 C328.301,62.305 319.467,51.263 305.744,51.263 L305.744,51.263 Z" id="Fill-5" />
<path d="M392.341,125.873 C367.892,125.873 355.589,115.935 355.589,99.215 C355.589,75.555 380.826,71.296 406.537,69.876 L406.537,64.513 C406.537,53.787 399.439,50.001 388.555,50.001 C380.511,50.001 370.731,52.525 365.053,55.207 L360.636,43.376 C367.419,40.379 378.933,37.382 390.29,37.382 C410.638,37.382 422.942,45.269 422.942,66.248 L422.942,119.879 C416.79,123.191 404.329,125.873 392.341,125.873 L392.341,125.873 Z M406.537,81.391 C389.186,82.337 371.835,83.757 371.835,98.9 C371.835,107.89 378.776,113.411 391.868,113.411 C397.389,113.411 403.856,112.465 406.537,111.203 L406.537,81.391 L406.537,81.391 Z" id="Fill-6" />
<path d="M461.743,125.873 C451.806,125.873 441.395,123.191 435.244,119.879 L441.08,106.629 C445.496,109.31 454.803,112.149 461.27,112.149 C470.576,112.149 476.728,107.575 476.728,100.477 C476.728,92.748 470.261,89.751 461.586,86.596 C450.228,82.337 437.452,77.132 437.452,61.201 C437.452,47.162 448.336,37.382 467.264,37.382 C477.517,37.382 486.035,39.906 492.029,43.376 L486.665,55.364 C482.88,52.998 475.309,50.317 469.157,50.317 C460.166,50.317 455.118,55.049 455.118,61.201 C455.118,68.93 461.428,71.611 469.788,74.766 C481.618,79.183 494.71,84.072 494.71,100.635 C494.71,115.935 483.038,125.873 461.743,125.873" id="Fill-7" />
<path d="M578.625,81.233 L522.155,89.12 C523.89,104.42 533.828,112.149 548.182,112.149 C556.699,112.149 565.848,110.099 571.684,106.944 L576.732,119.879 C570.107,123.349 558.75,125.873 547.078,125.873 C520.262,125.873 505.277,108.679 505.277,81.549 C505.277,55.522 519.789,37.382 543.607,37.382 C565.69,37.382 578.782,51.894 578.782,74.766 C578.782,76.816 578.782,79.025 578.625,81.233 L578.625,81.233 Z M543.292,50.001 C530.042,50.001 521.367,60.097 521.051,77.763 L562.22,72.084 C562.062,57.257 554.649,50.001 543.292,50.001 L543.292,50.001 Z" id="Fill-8" />
</g>
</g>
</svg>
@ -85,13 +85,13 @@ class BuyEtherScreen extends Component {
const {goToCoinbase, address} = this.props
return (
<div className='buy-ether__action-content-wrapper'>
<div className="buy-ether__action-content-wrapper">
<div>{this.renderCoinbaseLogo()}</div>
<div className='buy-ether__body-text'>Coinbase is the worlds most popular way to buy and sell bitcoin, ethereum, and litecoin.</div>
<a className='first-time-flow__link buy-ether__faq-link'>What is Ethereum?</a>
<div className='buy-ether__buttons'>
<div className="buy-ether__body-text">Coinbase is the worlds most popular way to buy and sell bitcoin, ethereum, and litecoin.</div>
<a className="first-time-flow__link buy-ether__faq-link">What is Ethereum?</a>
<div className="buy-ether__buttons">
<button
className='first-time-flow__button'
className="first-time-flow__button"
onClick={() => goToCoinbase(address)}
>
Buy
@ -114,23 +114,23 @@ class BuyEtherScreen extends Component {
return this.renderCoinbaseForm()
case OPTION_VALUES.SHAPESHIFT:
return (
<div className='buy-ether__action-content-wrapper'>
<div className='shapeshift-logo' />
<div className='buy-ether__body-text'>
<div className="buy-ether__action-content-wrapper">
<div className="shapeshift-logo" />
<div className="buy-ether__body-text">
Trade any leading blockchain asset for any other. Protection by Design. No Account Needed.
</div>
<ShapeShiftForm btnClass='first-time-flow__button' />
<ShapeShiftForm btnClass="first-time-flow__button" />
</div>
)
case OPTION_VALUES.QR_CODE:
return (
<div className='buy-ether__action-content-wrapper'>
<div className="buy-ether__action-content-wrapper">
<div dangerouslySetInnerHTML={{ __html: qrImage.createTableTag(4) }} />
<div className='buy-ether__body-text'>Deposit Ether directly into your account.</div>
<div className='buy-ether__small-body-text'>(This is the account address that MetaMask created for you to recieve funds.)</div>
<div className='buy-ether__buttons'>
<div className="buy-ether__body-text">Deposit Ether directly into your account.</div>
<div className="buy-ether__small-body-text">(This is the account address that MetaMask created for you to recieve funds.)</div>
<div className="buy-ether__buttons">
<button
className='first-time-flow__button'
className="first-time-flow__button"
onClick={this.copyToClipboard}
disabled={justCopied}
>
@ -149,19 +149,19 @@ class BuyEtherScreen extends Component {
const { selectedOption } = this.state
return (
<div className='buy-ether'>
<div className="buy-ether">
<Identicon address={this.props.address} diameter={70} />
<div className='buy-ether__title'>Deposit Ether</div>
<div className='buy-ether__body-text'>
<div className="buy-ether__title">Deposit Ether</div>
<div className="buy-ether__body-text">
MetaMask works best if you have Ether in your account to pay for transaction gas fees and more. To get Ether, choose from one of these methods.
</div>
<div className='buy-ether__content-wrapper'>
<div className='buy-ether__content-headline-wrapper'>
<div className='buy-ether__content-headline'>Deposit Options</div>
<div className="buy-ether__content-wrapper">
<div className="buy-ether__content-headline-wrapper">
<div className="buy-ether__content-headline">Deposit Options</div>
{this.renderSkip()}
</div>
<div className='buy-ether__content'>
<div className='buy-ether__side-panel'>
<div className="buy-ether__content">
<div className="buy-ether__side-panel">
{OPTIONS.map(({ name, value }) => (
<div
key={value}
@ -170,16 +170,16 @@ class BuyEtherScreen extends Component {
})}
onClick={() => this.setState({ selectedOption: value })}
>
<div className='buy-ether__side-panel-item-name'>{name}</div>
<div className="buy-ether__side-panel-item-name">{name}</div>
{value === selectedOption && (
<svg viewBox='0 0 574 1024' id='si-ant-right' width='15px' height='15px'>
<path d='M10 9Q0 19 0 32t10 23l482 457L10 969Q0 979 0 992t10 23q10 9 24 9t24-9l506-480q10-10 10-23t-10-23L58 9Q48 0 34 0T10 9z' />
<svg viewBox="0 0 574 1024" id="si-ant-right" width="15px" height="15px">
<path d="M10 9Q0 19 0 32t10 23l482 457L10 969Q0 979 0 992t10 23q10 9 24 9t24-9l506-480q10-10 10-23t-10-23L58 9Q48 0 34 0T10 9z" />
</svg>
)}
</div>
))}
</div>
<div className='buy-ether__action-content'>
<div className="buy-ether__action-content">
{this.renderContent()}
</div>
</div>

@ -123,10 +123,6 @@
width: calc(100vw - 80px);
}
.unique-image {
width: auto;
}
.create-password__title,
.unique-image__title,
.tou__title,
@ -148,7 +144,7 @@
height: 100%;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
justify-content: flex-start;
margin-top: 12px;
}
@ -181,7 +177,6 @@
margin: 0 !important;
padding: 16px 20px !important;
height: 30vh !important;
width: calc(100% - 48px) !important;
}
.backup-phrase__content-wrapper {
@ -280,6 +275,12 @@
width: 335px;
}
@media only screen and (max-width: 575px) {
.unique-image__body-text {
width: initial;
}
}
.unique-image__body-text +
.unique-image__body-text,
.backup-phrase__body-text +
@ -294,7 +295,7 @@
border-radius: 8px;
background-color: #FFFFFF;
margin: 0 142px 0 0;
height: 334px;
height: 200px;
overflow-y: auto;
color: #757575;
font-family: Roboto;
@ -679,7 +680,7 @@ button.backup-phrase__confirm-seed-option:hover {
}
.first-time-flow__input {
width: 350px;
max-width: 350px;
}
.first-time-flow__button {

@ -14,7 +14,7 @@ import LoadingScreen from './loading-screen'
class NoticeScreen extends Component {
static propTypes = {
address: PropTypes.string.isRequired,
lastUnreadNotice: PropTypes.shape({
nextUnreadNotice: PropTypes.shape({
title: PropTypes.string,
date: PropTypes.string,
body: PropTypes.string,
@ -31,7 +31,7 @@ class NoticeScreen extends Component {
};
static defaultProps = {
lastUnreadNotice: {},
nextUnreadNotice: {},
};
state = {
@ -47,8 +47,8 @@ class NoticeScreen extends Component {
}
acceptTerms = () => {
const { markNoticeRead, lastUnreadNotice, history } = this.props
markNoticeRead(lastUnreadNotice)
const { markNoticeRead, nextUnreadNotice, history } = this.props
markNoticeRead(nextUnreadNotice)
.then(hasActiveNotices => {
if (!hasActiveNotices) {
history.push(INITIALIZE_BACKUP_PHRASE_ROUTE)
@ -72,7 +72,7 @@ class NoticeScreen extends Component {
render () {
const {
address,
lastUnreadNotice: { title, body },
nextUnreadNotice: { title, body },
isLoading,
} = this.props
const { atBottom } = this.state
@ -113,12 +113,12 @@ class NoticeScreen extends Component {
}
const mapStateToProps = ({ metamask, appState }) => {
const { selectedAddress, lastUnreadNotice, noActiveNotices } = metamask
const { selectedAddress, nextUnreadNotice, noActiveNotices } = metamask
const { isLoading } = appState
return {
address: selectedAddress,
lastUnreadNotice,
nextUnreadNotice,
noActiveNotices,
isLoading,
}

@ -79,11 +79,11 @@ export class ShapeShiftForm extends Component {
renderMetadata (label, value) {
return (
<div className='shapeshift-form__metadata-wrapper'>
<div className='shapeshift-form__metadata-label'>
<div className="shapeshift-form__metadata-wrapper">
<div className="shapeshift-form__metadata-label">
{label}:
</div>
<div className='shapeshift-form__metadata-value'>
<div className="shapeshift-form__metadata-value">
{value}
</div>
</div>
@ -101,7 +101,7 @@ export class ShapeShiftForm extends Component {
} = tokenExchangeRates[coinPair] || {}
return (
<div className='shapeshift-form__metadata'>
<div className="shapeshift-form__metadata">
{this.renderMetadata('Status', limit ? 'Available' : 'Unavailable')}
{this.renderMetadata('Limit', limit)}
{this.renderMetadata('Exchange Rate', rate)}
@ -117,13 +117,13 @@ export class ShapeShiftForm extends Component {
qrImage.make()
return (
<div className='shapeshift-form'>
<div className='shapeshift-form__deposit-instruction'>
<div className="shapeshift-form">
<div className="shapeshift-form__deposit-instruction">
Deposit your BTC to the address bellow:
</div>
<div className='shapeshift-form__qr-code'>
<div className="shapeshift-form__qr-code">
{isLoading
? <img src='images/loading.svg' style={{ width: '60px' }} />
? <img src="images/loading.svg" style={{ width: '60px' }} />
: <div dangerouslySetInnerHTML={{ __html: qrImage.createTableTag(4) }} />
}
</div>
@ -141,14 +141,14 @@ export class ShapeShiftForm extends Component {
return showQrCode ? this.renderQrCode() : (
<div>
<div className='shapeshift-form'>
<div className='shapeshift-form__selectors'>
<div className='shapeshift-form__selector'>
<div className='shapeshift-form__selector-label'>
<div className="shapeshift-form">
<div className="shapeshift-form__selectors">
<div className="shapeshift-form__selector">
<div className="shapeshift-form__selector-label">
Deposit
</div>
<select
className='shapeshift-form__selector-input'
className="shapeshift-form__selector-input"
value={this.state.depositCoin}
onChange={this.onCoinChange}
>
@ -160,14 +160,14 @@ export class ShapeShiftForm extends Component {
</select>
</div>
<div
className='icon shapeshift-form__caret'
className="icon shapeshift-form__caret"
style={{ backgroundImage: 'url(images/caret-right.svg)'}}
/>
<div className='shapeshift-form__selector'>
<div className='shapeshift-form__selector-label'>
<div className="shapeshift-form__selector">
<div className="shapeshift-form__selector-label">
Receive
</div>
<div className='shapeshift-form__selector-input'>
<div className="shapeshift-form__selector-input">
ETH
</div>
</div>
@ -177,18 +177,18 @@ export class ShapeShiftForm extends Component {
'shapeshift-form__address-input-wrapper--error': errorMessage,
})}
>
<div className='shapeshift-form__address-input-label'>
<div className="shapeshift-form__address-input-label">
Your Refund Address
</div>
<input
type='text'
className='shapeshift-form__address-input'
type="text"
className="shapeshift-form__address-input"
onChange={e => this.setState({
refundAddress: e.target.value,
errorMessage: '',
})}
/>
<div className='shapeshift-form__address-input-error-message'>
<div className="shapeshift-form__address-input-error-message">
{errorMessage}
</div>
</div>

@ -1,4 +1,4 @@
function wait(time) {
export default function wait (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve()

@ -1,9 +1,9 @@
var fs = require('fs')
var path = require('path')
var browserify = require('browserify');
var browserify = require('browserify')
var tests = fs.readdirSync(path.join(__dirname, 'lib'))
var bundlePath = path.join(__dirname, 'test-bundle.js')
var b = browserify();
var b = browserify()
// Remove old bundle
try {
@ -18,5 +18,5 @@ tests.forEach(function(fileName) {
b.add(path.join(__dirname, 'lib', fileName))
})
b.bundle().pipe(writeStream);
b.bundle().pipe(writeStream)

@ -1,5 +1,3 @@
const Helper = require('./util/mascara-test-helper.js')
window.addEventListener('load', () => {
window.METAMASK_SKIP_RELOAD = true
// inject app container

@ -2,23 +2,25 @@ const EventEmitter = require('events')
const IDB = require('idb-global')
const KEY = 'metamask-test-config'
module.exports = class Helper extends EventEmitter {
constructor () {
super()
}
tryToCleanContext () {
this.unregister()
.then(() => this.clearDb())
.then(() => super.emit('complete'))
.catch((err) => super.emit('complete'))
.catch((err) => {
if (err) {
super.emit('complete')
}
})
}
unregister () {
return global.navigator.serviceWorker.getRegistration()
.then((registration) => {
if (registration) return registration.unregister()
if (registration) {
return registration.unregister()
.then((b) => b ? Promise.resolve() : Promise.reject())
else return Promise.resolve()
} else return Promise.resolve()
})
}
clearDb () {
@ -33,7 +35,7 @@ module.exports = class Helper extends EventEmitter {
const db = new IDB({
version: 2,
key: KEY,
initialState: state
initialState: state,
})
return db.open()
}

@ -0,0 +1,6 @@
Dear MetaMask Users,
There have been several instances of high-profile legitimate websites such as BTC Manager and Games Workshop that have had their websites temporarily compromised. This involves showing a fake MetaMask window on the page asking for user's seed phrases. MetaMask will never open itself in this way and users are encouraged to report these instances immediately to either [our phishing blacklist](https://github.com/MetaMask/eth-phishing-detect/issues) or our support email at [support@metamask.io](mailto:support@metamask.io).
Please read our full article on this ongoing issue at [https://medium.com/metamask/new-phishing-strategy-becoming-common-1b1123837168](https://medium.com/metamask/new-phishing-strategy-becoming-common-1b1123837168).

@ -1,27 +0,0 @@
var fs = require('fs')
var path = require('path')
var prompt = require('prompt')
var open = require('open')
var extend = require('extend')
var notices = require('./notices.json')
console.log('List of Notices')
console.log(`ID \t DATE \t\t\t TITLE`)
notices.forEach((notice) => {
console.log(`${(' ' + notice.id).slice(-2)} \t ${notice.date} \t ${notice.title}`)
})
prompt.get(['id'], (error, res) => {
prompt.start()
if (error) {
console.log("Exiting...")
process.exit()
}
var index = notices.findIndex((notice) => { return notice.id == res.id})
if (index === -1) {
console.log('Notice not found. Exiting...')
}
notices.splice(index, 1)
fs.unlink(`notices/archive/notice_${res.id}.md`)
fs.writeFile(`notices/notices.json`, JSON.stringify(notices))
})

@ -1,33 +0,0 @@
var fsp = require('fs-promise')
var path = require('path')
var prompt = require('prompt')
var open = require('open')
var extend = require('extend')
var notices = require('./notices.json')
var id = Number(require('./notice-nonce.json'))
var date = new Date().toDateString()
var notice = {
read: false,
date: date,
}
fsp.writeFile(`notices/archive/notice_${id}.md`,'Message goes here. Please write out your notice and save before proceeding at the command line.')
.then(() => {
open(`notices/archive/notice_${id}.md`)
prompt.start()
prompt.get(['title'], (err, result) => {
notice.title = result.title
fsp.readFile(`notices/archive/notice_${id}.md`)
.then((body) => {
notice.body = body.toString()
notice.id = id
notices.push(notice)
return fsp.writeFile(`notices/notices.json`, JSON.stringify(notices))
}).then((completion) => {
id += 1
return fsp.writeFile(`notices/notice-nonce.json`, id)
})
})
})

@ -0,0 +1,35 @@
// fs.readFileSync is inlined by browserify transform "brfs"
const fs = require('fs')
const path = require('path')
module.exports = [
{
id: 0,
read: false,
date: 'Thu Feb 09 2017',
title: 'Terms of Use',
body: fs.readFileSync(path.join(__dirname, '/archive', 'notice_0.md'), 'utf8'),
},
{
id: 2,
read: false,
date: 'Mon May 08 2017',
title: 'Privacy Notice',
body: fs.readFileSync(path.join(__dirname, '/archive', 'notice_2.md'), 'utf8'),
},
{
id: 3,
read: false,
date: 'Tue Nov 28 2017',
title: 'Seed Phrase Alert',
firstVersion: '<=3.12.0',
body: fs.readFileSync(path.join(__dirname, '/archive', 'notice_3.md'), 'utf8'),
},
{
id: 4,
read: false,
date: 'Wed Jun 13 2018',
title: 'Phishing Warning',
body: fs.readFileSync(path.join(__dirname, '/archive', 'notice_4.md'), 'utf8'),
},
]

File diff suppressed because one or more lines are too long

@ -73,7 +73,7 @@ function mapStateToProps (state) {
network: state.metamask.network,
provider: state.metamask.provider,
forgottenPassword: state.appState.forgottenPassword,
lastUnreadNotice: state.metamask.lastUnreadNotice,
nextUnreadNotice: state.metamask.nextUnreadNotice,
lostAccounts: state.metamask.lostAccounts,
frequentRpcList: state.metamask.frequentRpcList || [],
featureFlags,
@ -461,9 +461,9 @@ App.prototype.renderPrimary = function () {
}, [
h(NoticeScreen, {
notice: props.lastUnreadNotice,
notice: props.nextUnreadNotice,
key: 'NoticeScreen',
onConfirm: () => props.dispatch(actions.markNoticeRead(props.lastUnreadNotice)),
onConfirm: () => props.dispatch(actions.markNoticeRead(props.nextUnreadNotice)),
}),
!props.isInitialized && h('.flex-row.flex-center.flex-grow', [

@ -23,9 +23,10 @@ class AccountDropdowns extends Component {
renderAccounts () {
const { identities, selected, keyrings } = this.props
const accountOrder = keyrings.reduce((list, keyring) => list.concat(keyring.accounts), [])
return Object.keys(identities).map((key, index) => {
const identity = identities[key]
return accountOrder.map((address, index) => {
const identity = identities[address]
const isSelected = identity.address === selected
const simpleAddress = identity.address.substring(2).toLowerCase()

@ -40,8 +40,8 @@ TransactionListItem.prototype.showRetryButton = function () {
const currentNonceTxs = transactions.filter(tx => tx.txParams.nonce === currentNonce)
const currentNonceSubmittedTxs = currentNonceTxs.filter(tx => tx.status === 'submitted')
const lastSubmittedTxWithCurrentNonce = currentNonceSubmittedTxs[0]
const currentTxIsLatestWithNonce = lastSubmittedTxWithCurrentNonce
&& lastSubmittedTxWithCurrentNonce.id === transaction.id
const currentTxIsLatestWithNonce = lastSubmittedTxWithCurrentNonce &&
lastSubmittedTxWithCurrentNonce.id === transaction.id
return currentTxIsLatestWithNonce && Date.now() - submittedTime > 30000
}

@ -34,9 +34,13 @@ TypedMessageRenderer.prototype.render = function () {
function renderTypedData (values) {
return values.map(function (value) {
let v = value.value
if (typeof v === 'boolean') {
v = v.toString()
}
return h('div', {}, [
h('strong', {style: {display: 'block', fontWeight: 'bold'}}, String(value.name) + ':'),
h('div', {}, value.value),
h('div', {}, v),
])
})
}

19340
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -9,7 +9,8 @@
"dist": "gulp dist",
"doc": "jsdoc -c development/tools/.jsdoc.json",
"test": "npm run test:unit && npm run test:integration && npm run lint",
"test:unit": "cross-env METAMASK_ENV=test mocha --exit --require test/setup.js --recursive \"test/unit/**/*.js\" && dot-only-hunter",
"watch:test:unit": "nodemon --exec \"npm run test:unit\" ./test ./app ./ui",
"test:unit": "cross-env METAMASK_ENV=test mocha --exit --require test/setup.js --recursive \"test/unit/**/*.js\" \"ui/app/**/*.test.js\" && dot-only-hunter",
"test:single": "cross-env METAMASK_ENV=test mocha --require test/helper.js",
"test:integration": "npm run test:integration:build && npm run test:flat && npm run test:mascara",
"test:integration:build": "gulp build:scss",
@ -37,16 +38,14 @@
"test:mascara:build:tests": "browserify test/integration/lib/first-time.js -o dist/mascara/tests.js",
"ganache:start": "ganache-cli -m 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'",
"sentry:publish": "node ./development/sentry-publish.js",
"lint": "gulp lint",
"lint:fix": "gulp lint:fix",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"ui": "npm run test:flat:build:states && beefy development/ui-dev.js:bundle.js --live --open --index=./development/index.html --cwd ./",
"mock": "beefy development/mock-dev.js:bundle.js --live --open --index=./development/index.html --cwd ./",
"watch": "mocha watch --recursive \"test/unit/**/*.js\"",
"disc": "gulp disc --debug",
"announce": "node development/announcer.js",
"version:bump": "node development/run-version-bump.js",
"generateNotice": "node notices/notice-generator.js",
"deleteNotice": "node notices/notice-delete.js",
"storybook": "start-storybook -p 6006 -c .storybook"
},
"browserify": {
@ -94,7 +93,7 @@
"ensnare": "^1.0.0",
"eslint-plugin-react": "^7.4.0",
"eth-bin-to-ops": "^1.0.1",
"eth-contract-metadata": "^1.1.5",
"eth-contract-metadata": "github:MetaMask/eth-contract-metadata#master",
"eth-hd-keyring": "^1.2.1",
"eth-json-rpc-filters": "^1.2.6",
"eth-json-rpc-infura": "^3.0.0",
@ -108,7 +107,7 @@
"ethereumjs-wallet": "^0.6.0",
"etherscan-link": "^1.0.2",
"ethjs": "^0.4.0",
"ethjs-contract": "^0.2.0",
"ethjs-contract": "^0.2.3",
"ethjs-ens": "^2.0.0",
"ethjs-query": "^0.3.4",
"express": "^4.15.5",
@ -184,6 +183,7 @@
"semaphore": "^1.0.5",
"semver": "^5.4.1",
"shallow-copy": "0.0.1",
"superstatic": "^5.0.2",
"sw-controller": "^1.0.3",
"sw-stream": "^2.0.2",
"textarea-caret": "^3.0.1",
@ -211,7 +211,7 @@
"babel-register": "^6.7.2",
"babelify": "^8.0.0",
"beefy": "^2.1.5",
"brfs": "^1.4.3",
"brfs": "^1.6.1",
"browserify": "^16.1.1",
"chai": "^4.1.0",
"chromedriver": "2.36.0",
@ -235,13 +235,12 @@
"file-loader": "^1.1.11",
"fs-promise": "^2.0.3",
"ganache-cli": "^6.1.0",
"ganache-core": "^2.1.0",
"ganache-core": "^2.1.3",
"geckodriver": "^1.11.0",
"gh-pages": "^1.1.0",
"gh-pages": "^1.2.0",
"gifencoder": "^1.1.0",
"gulp": "github:gulpjs/gulp#6d71a658c61edb3090221579d8f97dbe086ba2ed",
"gulp-babel": "^7.0.0",
"gulp-eslint": "^4.0.0",
"gulp-json-editor": "^2.2.1",
"gulp-livereload": "^3.8.1",
"gulp-multi-process": "^1.3.1",
@ -254,13 +253,14 @@
"gulp-util": "^3.0.7",
"gulp-watch": "^5.0.0",
"gulp-zip": "^4.0.0",
"http-server": "^0.11.1",
"image-size": "^0.6.2",
"isomorphic-fetch": "^2.2.1",
"jsdoc": "^3.5.5",
"jsdom": "^11.2.0",
"jsdom-global": "^3.0.2",
"jshint-stylish": "~2.2.1",
"karma": "^2.0.0",
"karma": "^2.0.4",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-firefox-launcher": "^1.0.1",
@ -271,13 +271,14 @@
"mocha-jsdom": "^1.1.0",
"mocha-sinon": "^2.0.0",
"nock": "^9.0.14",
"node-sass": "^4.7.2",
"node-sass": "^4.9.0",
"nsp": "^3.2.1",
"nyc": "^11.0.3",
"nyc": "^13.0.0",
"open": "0.0.5",
"path": "^0.12.7",
"png-file-stream": "^1.0.0",
"prompt": "^1.0.0",
"proxyquire": "2.0.1",
"qs": "^6.2.0",
"qunitjs": "^2.4.1",
"radgrad-jsdoc-template": "^1.1.3",
@ -295,11 +296,11 @@
"style-loader": "^0.21.0",
"stylelint-config-standard": "^18.2.0",
"tape": "^4.5.1",
"testem": "^2.0.0",
"testem": "^2.8.0",
"through2": "^2.0.3",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0",
"watchify": "^3.9.0"
"watchify": "^3.11.0"
},
"engines": {
"node": ">=8.0.0"

@ -0,0 +1,66 @@
/*
The `piggybankContract` is compiled from:
pragma solidity ^0.4.0;
contract PiggyBank {
uint private balance;
address public owner;
function PiggyBank() public {
owner = msg.sender;
balance = 0;
}
function deposit() public payable returns (uint) {
balance += msg.value;
return balance;
}
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
require(msg.sender == owner);
balance -= withdrawAmount;
msg.sender.transfer(withdrawAmount);
return balance;
}
}
*/
var piggybankContract = web3.eth.contract([{'constant': false, 'inputs': [{'name': 'withdrawAmount', 'type': 'uint256'}], 'name': 'withdraw', 'outputs': [{'name': 'remainingBal', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'owner', 'outputs': [{'name': '', 'type': 'address'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [], 'name': 'deposit', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': true, 'stateMutability': 'payable', 'type': 'function'}, {'inputs': [], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor'}])
const deployButton = document.getElementById('deployButton')
const depositButton = document.getElementById('depositButton')
const withdrawButton = document.getElementById('withdrawButton')
deployButton.addEventListener('click', async function (event) {
var piggybank = await piggybankContract.new(
{
from: web3.eth.accounts[0],
data: '0x608060405234801561001057600080fd5b5033600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000808190555061023b806100686000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632e1a7d4d1461005c5780638da5cb5b1461009d578063d0e30db0146100f4575b600080fd5b34801561006857600080fd5b5061008760048036038101908080359060200190929190505050610112565b6040518082815260200191505060405180910390f35b3480156100a957600080fd5b506100b26101d0565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100fc6101f6565b6040518082815260200191505060405180910390f35b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561017057600080fd5b8160008082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f193505050501580156101c5573d6000803e3d6000fd5b506000549050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60003460008082825401925050819055506000549050905600a165627a7a72305820f237db3ec816a52589d82512117bc85bc08d3537683ffeff9059108caf3e5d400029',
gas: '4700000',
}, function (e, contract) {
console.log(e, contract)
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash)
console.log(`contract`, contract)
depositButton.addEventListener('click', function (event) {
contract.deposit({ from: web3.eth.accounts[0], value: '0x29a2241af62c0000' }, function (result) {
console.log(result)
})
})
withdrawButton.addEventListener('click', function (event) {
contract.withdraw('0xde0b6b3a7640000', { from: web3.eth.accounts[0] }, function (result) {
console.log(result)
})
})
}
})
console.log(piggybank)
})

@ -0,0 +1,8 @@
<html>
<body>
<button id="deployButton">Deploy Contract</button>
<button id="depositButton">Deposit</button>
<button id="withdrawButton">Withdraw</button>
</body>
<script src="contract.js"></script>
</html>

@ -1,7 +1,7 @@
const path = require('path')
const assert = require('assert')
const webdriver = require('selenium-webdriver')
const { By, Key } = webdriver
const { By, Key, until } = webdriver
const {
delay,
buildChromeWebDriver,
@ -12,20 +12,21 @@ const {
} = require('../func')
const {
checkBrowserForConsoleErrors,
loadExtension,
verboseReportOnFailure,
findElement,
findElements,
} = require('./helpers')
describe('Using MetaMask with an existing account', function () {
let extensionId
let driver
let tokenAddress
const testSeedPhrase = 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'
const testAddress = '0xE18035BF8712672935FDB4e5e431b1a0183d2DFC'
const testPrivateKey2 = '14abe6f4aab7f9f626fe981c864d0adeb5685f289ac9270c27b8fd790b4235d6'
const regularDelayMs = 1000
const largeDelayMs = regularDelayMs * 2
const waitingNewPageDelayMs = regularDelayMs * 10
this.timeout(0)
this.bail(true)
@ -79,30 +80,34 @@ describe('Using MetaMask with an existing account', function () {
})
it('use the local network', async function () {
const [networkSelector] = await driver.findElements(By.css('#network_component'))
const networkSelector = await findElement(driver, By.css('#network_component'))
await networkSelector.click()
await delay(regularDelayMs)
const [localhost] = await driver.findElements(By.xpath(`//li[contains(text(), 'Localhost')]`))
const [localhost] = await findElements(driver, By.xpath(`//li[contains(text(), 'Localhost')]`))
await localhost.click()
await delay(regularDelayMs)
})
it('selects the new UI option', async () => {
const button = await driver.findElement(By.xpath("//p[contains(text(), 'Try Beta Version')]"))
const button = await findElement(driver, By.xpath("//p[contains(text(), 'Try Beta Version')]"))
await button.click()
await delay(regularDelayMs)
// Close all other tabs
const [oldUi, infoPage, newUi] = await driver.getAllWindowHandles()
const newUiOrInfoPage = newUi || infoPage
await driver.switchTo().window(oldUi)
await driver.close()
if (infoPage !== newUiOrInfoPage) {
await driver.switchTo().window(infoPage)
await driver.close()
await driver.switchTo().window(newUi)
}
await driver.switchTo().window(newUiOrInfoPage)
await delay(regularDelayMs)
const [continueBtn] = await driver.findElements(By.css('.welcome-screen__button'))
const continueBtn = await findElement(driver, By.css('.welcome-screen__button'))
await continueBtn.click()
await delay(regularDelayMs)
})
@ -110,37 +115,50 @@ describe('Using MetaMask with an existing account', function () {
describe('First time flow starting from an existing seed phrase', () => {
it('imports a seed phrase', async () => {
const [seedPhrase] = await driver.findElements(By.xpath(`//a[contains(text(), 'Import with seed phrase')]`))
const [seedPhrase] = await findElements(driver, By.xpath(`//a[contains(text(), 'Import with seed phrase')]`))
await seedPhrase.click()
await delay(regularDelayMs)
const [seedTextArea] = await driver.findElements(By.css('textarea.import-account__secret-phrase'))
const [seedTextArea] = await findElements(driver, By.css('textarea.import-account__secret-phrase'))
await seedTextArea.sendKeys(testSeedPhrase)
await delay(regularDelayMs)
const [password] = await driver.findElements(By.id('password'))
const [password] = await findElements(driver, By.id('password'))
await password.sendKeys('correct horse battery staple')
const [confirmPassword] = await driver.findElements(By.id('confirm-password'))
const [confirmPassword] = await findElements(driver, By.id('confirm-password'))
confirmPassword.sendKeys('correct horse battery staple')
const [importButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Import')]`))
const [importButton] = await findElements(driver, By.xpath(`//button[contains(text(), 'Import')]`))
await importButton.click()
await delay(regularDelayMs)
})
it('clicks through the ToS', async () => {
// terms of use
const canClickThrough = await driver.findElement(By.css('.tou button')).isEnabled()
assert.equal(canClickThrough, false, 'disabled continue button')
const bottomOfTos = await findElement(driver, By.linkText('Attributions'))
await driver.executeScript('arguments[0].scrollIntoView(true)', bottomOfTos)
await delay(regularDelayMs)
const acceptTos = await findElement(driver, By.css('.tou button'))
await acceptTos.click()
await delay(regularDelayMs)
})
it('clicks through the privacy notice', async () => {
const [nextScreen] = await driver.findElements(By.css('.tou button'))
// privacy notice
const nextScreen = await findElement(driver, By.css('.tou button'))
await nextScreen.click()
await delay(regularDelayMs)
})
const canClickThrough = await driver.findElement(By.css('.tou button')).isEnabled()
assert.equal(canClickThrough, false, 'disabled continue button')
const element = await driver.findElement(By.linkText('Attributions'))
await driver.executeScript('arguments[0].scrollIntoView(true)', element)
it('clicks through the phishing notice', async () => {
// phishing notice
const noticeElement = await driver.findElement(By.css('.markdown'))
await driver.executeScript('arguments[0].scrollTop = arguments[0].scrollHeight', noticeElement)
await delay(regularDelayMs)
const [acceptTos] = await driver.findElements(By.css('.tou button'))
await acceptTos.click()
const nextScreen = await findElement(driver, By.css('.tou button'))
await nextScreen.click()
await delay(regularDelayMs)
})
})
@ -151,7 +169,7 @@ describe('Using MetaMask with an existing account', function () {
await driver.findElement(By.css('.qr-wrapper')).isDisplayed()
await delay(regularDelayMs)
const [address] = await driver.findElements(By.css('input.qr-ellip-address'))
const [address] = await findElements(driver, By.css('input.qr-ellip-address'))
assert.equal(await address.getAttribute('value'), testAddress)
await driver.executeScript("document.querySelector('.account-modal-close').click()")
@ -161,19 +179,22 @@ describe('Using MetaMask with an existing account', function () {
it('shows a QR code for the account', async () => {
await driver.findElement(By.css('.wallet-view__details-button')).click()
await driver.findElement(By.css('.qr-wrapper')).isDisplayed()
const detailModal = await driver.findElement(By.css('span .modal'))
await delay(regularDelayMs)
await driver.executeScript("document.querySelector('.account-modal-close').click()")
await driver.wait(until.stalenessOf(detailModal))
await delay(regularDelayMs)
})
})
describe('Log out and log back in', () => {
it('logs out of the account', async () => {
await driver.findElement(By.css('.account-menu__icon')).click()
const accountIdenticon = driver.findElement(By.css('.account-menu__icon .identicon'))
accountIdenticon.click()
await delay(regularDelayMs)
const [logoutButton] = await driver.findElements(By.css('.account-menu__logout-button'))
const [logoutButton] = await findElements(driver, By.css('.account-menu__logout-button'))
assert.equal(await logoutButton.getText(), 'Log out')
await logoutButton.click()
await delay(regularDelayMs)
@ -191,23 +212,23 @@ describe('Using MetaMask with an existing account', function () {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const [createAccount] = await driver.findElements(By.xpath(`//div[contains(text(), 'Create Account')]`))
const [createAccount] = await findElements(driver, By.xpath(`//div[contains(text(), 'Create Account')]`))
await createAccount.click()
await delay(regularDelayMs)
})
it('set account name', async () => {
const [accountName] = await driver.findElements(By.css('.new-account-create-form input'))
const [accountName] = await findElements(driver, By.css('.new-account-create-form input'))
await accountName.sendKeys('2nd account')
await delay(regularDelayMs)
const [createButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Create')]`))
const [createButton] = await findElements(driver, By.xpath(`//button[contains(text(), 'Create')]`))
await createButton.click()
await delay(regularDelayMs)
})
it('should show the correct account name', async () => {
const [accountName] = await driver.findElements(By.css('.account-name'))
const [accountName] = await findElements(driver, By.css('.account-name'))
assert.equal(await accountName.getText(), '2nd account')
await delay(regularDelayMs)
})
@ -218,7 +239,7 @@ describe('Using MetaMask with an existing account', function () {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const [originalAccountMenuItem] = await driver.findElements(By.css('.account-menu__name'))
const [originalAccountMenuItem] = await findElements(driver, By.css('.account-menu__name'))
await originalAccountMenuItem.click()
await delay(regularDelayMs)
})
@ -226,181 +247,78 @@ describe('Using MetaMask with an existing account', function () {
describe('Send ETH from inside MetaMask', () => {
it('starts to send a transaction', async function () {
const [sendButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Send')]`))
const sendButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Send')]`))
await sendButton.click()
await delay(regularDelayMs)
const [inputAddress] = await driver.findElements(By.css('input[placeholder="Recipient Address"]'))
const [inputAmount] = await driver.findElements(By.css('.currency-display__input'))
const inputAddress = await findElement(driver, By.css('input[placeholder="Recipient Address"]'))
const inputAmount = await findElement(driver, By.css('.currency-display__input'))
await inputAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
await inputAmount.sendKeys('1')
// Set the gas limit
const [configureGas] = await driver.findElements(By.css('.send-v2__gas-fee-display button'))
const configureGas = await findElement(driver, By.css('.send-v2__gas-fee-display button'))
await configureGas.click()
await delay(regularDelayMs)
const [save] = await driver.findElements(By.xpath(`//button[contains(text(), 'Save')]`))
const gasModal = await driver.findElement(By.css('span .modal'))
const save = await findElement(driver, By.xpath(`//button[contains(text(), 'Save')]`))
await save.click()
await driver.wait(until.stalenessOf(gasModal))
await delay(regularDelayMs)
// Continue to next screen
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
const nextScreen = await findElement(driver, By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
})
it('confirms the transaction', async function () {
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Confirm')]`))
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
})
it('finds the transaction in the transactions list', async function () {
const transactions = await driver.findElements(By.css('.tx-list-item'))
const transactions = await findElements(driver, By.css('.tx-list-item'))
assert.equal(transactions.length, 1)
const txValues = await driver.findElements(By.css('.tx-list-value'))
const txValues = await findElements(driver, By.css('.tx-list-value'))
assert.equal(txValues.length, 1)
assert.equal(await txValues[0].getText(), '1 ETH')
})
})
describe('Send ETH from Faucet', () => {
it('starts a send transaction inside Faucet', async () => {
await driver.executeScript('window.open("https://faucet.metamask.io")')
await delay(waitingNewPageDelayMs)
const [extension, faucet] = await driver.getAllWindowHandles()
await driver.switchTo().window(faucet)
await delay(regularDelayMs)
const [send1eth] = await driver.findElements(By.xpath(`//button[contains(text(), '10 ether')]`))
await send1eth.click()
await delay(regularDelayMs)
await driver.switchTo().window(extension)
await loadExtension(driver, extensionId)
await delay(regularDelayMs)
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(),'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
await driver.switchTo().window(faucet)
await delay(regularDelayMs)
await driver.close()
await delay(regularDelayMs)
await driver.switchTo().window(extension)
await delay(regularDelayMs)
await loadExtension(driver, extensionId)
describe('Imports an account with private key', () => {
it('choose Create Account from the account menu', async () => {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
})
})
describe('Add existing token using search', () => {
it('clicks on the Add Token button', async () => {
const [addToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Token')]`))
await addToken.click()
const [importAccount] = await findElements(driver, By.xpath(`//div[contains(text(), 'Import Account')]`))
await importAccount.click()
await delay(regularDelayMs)
})
it('picks an existing token', async () => {
const [tokenSearch] = await driver.findElements(By.css('input.add-token__input'))
await tokenSearch.sendKeys('BAT')
it('enter private key', async () => {
const privateKeyInput = await findElement(driver, By.css('#private-key-box'))
await privateKeyInput.sendKeys(testPrivateKey2)
await delay(regularDelayMs)
const [token] = await driver.findElements(By.xpath("//div[contains(text(), 'BAT')]"))
await token.click()
await delay(regularDelayMs)
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
const [addTokens] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Tokens')]`))
await addTokens.click()
await delay(largeDelayMs)
})
it('renders the balance for the new token', async () => {
const balance = await driver.findElement(By.css('.tx-view .balance-display .token-amount'))
const tokenAmount = await balance.getText()
assert.equal(tokenAmount, '0BAT')
const importButtons = await findElements(driver, By.xpath(`//button[contains(text(), 'Import')]`))
await importButtons[0].click()
await delay(regularDelayMs)
})
})
describe('Add a custom token from TokenFactory', () => {
it('creates a new token', async () => {
await driver.executeScript('window.open("https://tokenfactory.surge.sh/#/factory")')
await delay(waitingNewPageDelayMs)
const [extension, tokenFactory] = await driver.getAllWindowHandles()
await driver.switchTo().window(tokenFactory)
const [
totalSupply,
tokenName,
tokenDecimal,
tokenSymbol,
] = await driver.findElements(By.css('input'))
await totalSupply.sendKeys('100')
await tokenName.sendKeys('Test')
await tokenDecimal.sendKeys('0')
await tokenSymbol.sendKeys('TST')
const [createToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Create Token')]`))
await createToken.click()
await delay(regularDelayMs)
await driver.switchTo().window(extension)
await loadExtension(driver, extensionId)
await delay(regularDelayMs)
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(),'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
await driver.switchTo().window(tokenFactory)
await delay(regularDelayMs)
const tokenContactAddress = await driver.findElement(By.css('div > div > div:nth-child(2) > span:nth-child(3)'))
tokenAddress = await tokenContactAddress.getText()
await driver.close()
await driver.switchTo().window(extension)
await loadExtension(driver, extensionId)
it('should show the correct account name', async () => {
const [accountName] = await findElements(driver, By.css('.account-name'))
assert.equal(await accountName.getText(), 'Account 3')
await delay(regularDelayMs)
})
it('clicks on the Add Token button', async () => {
const [addToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Token')]`))
await addToken.click()
it('should show the imported label', async () => {
const [importedLabel] = await findElements(driver, By.css('.wallet-view__keyring-label'))
assert.equal(await importedLabel.getText(), 'IMPORTED')
await delay(regularDelayMs)
})
it('picks the new Test token', async () => {
const [addCustomToken] = await driver.findElements(By.xpath("//div[contains(text(), 'Custom Token')]"))
await addCustomToken.click()
await delay(regularDelayMs)
const [newTokenAddress] = await driver.findElements(By.css('.add-token__add-custom-form input'))
await newTokenAddress.sendKeys(tokenAddress)
await delay(regularDelayMs)
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
const [addTokens] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Tokens')]`))
await addTokens.click()
await delay(regularDelayMs)
})
it('renders the balance for the new token', async () => {
const [balance] = await driver.findElements(By.css('.tx-view .balance-display .token-amount'))
const tokenAmount = await balance.getText()
assert.equal(tokenAmount, '100TST')
await delay(regularDelayMs)
})
})
})

@ -1,11 +1,16 @@
const fs = require('fs')
const mkdirp = require('mkdirp')
const pify = require('pify')
const {until} = require('selenium-webdriver')
const { delay } = require('../func')
module.exports = {
checkBrowserForConsoleErrors,
loadExtension,
verboseReportOnFailure,
findElement,
findElements,
openNewPage,
}
async function loadExtension (driver, extensionId) {
@ -53,3 +58,23 @@ async function verboseReportOnFailure (driver, test) {
const htmlSource = await driver.getPageSource()
await pify(fs.writeFile)(`${filepathBase}-dom.html`, htmlSource)
}
async function findElement (driver, by, timeout = 10000) {
return driver.wait(until.elementLocated(by), timeout)
}
async function findElements (driver, by, timeout = 10000) {
return driver.wait(until.elementsLocated(by), timeout)
}
async function openNewPage (driver, url) {
await driver.executeScript('window.open()')
await delay(1000)
const handles = await driver.getAllWindowHandles()
const secondHandle = handles[1]
await driver.switchTo().window(secondHandle)
await driver.get(url)
await delay(1000)
}

@ -1,7 +1,7 @@
const path = require('path')
const assert = require('assert')
const webdriver = require('selenium-webdriver')
const { By, Key } = webdriver
const { By, Key, until } = webdriver
const {
delay,
buildChromeWebDriver,
@ -11,9 +11,12 @@ const {
getExtensionIdFirefox,
} = require('../func')
const {
findElement,
findElements,
checkBrowserForConsoleErrors,
loadExtension,
verboseReportOnFailure,
openNewPage,
} = require('./helpers')
describe('MetaMask', function () {
@ -22,10 +25,9 @@ describe('MetaMask', function () {
let tokenAddress
const testSeedPhrase = 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'
const tinyDelayMs = 500
const tinyDelayMs = 1000
const regularDelayMs = tinyDelayMs * 2
const largeDelayMs = regularDelayMs * 2
const waitingNewPageDelayMs = regularDelayMs * 10
this.timeout(0)
this.bail(true)
@ -60,7 +62,7 @@ describe('MetaMask', function () {
}
}
if (this.currentTest.state === 'failed') {
await verboseReportOnFailure(this.currentTest)
await verboseReportOnFailure(driver, this.currentTest)
}
})
@ -69,37 +71,52 @@ describe('MetaMask', function () {
})
describe('New UI setup', async function () {
let networkSelector
it('switches to first tab', async function () {
const [firstTab] = await driver.getAllWindowHandles()
await driver.switchTo().window(firstTab)
await delay(regularDelayMs)
try {
networkSelector = await findElement(driver, By.css('#network_component'))
} catch (e) {
await loadExtension(driver, extensionId)
}
await delay(regularDelayMs)
})
it('use the local network', async function () {
const [networkSelector] = await driver.findElements(By.css('#network_component'))
await networkSelector.click()
await delay(regularDelayMs)
const [localhost] = await driver.findElements(By.xpath(`//li[contains(text(), 'Localhost')]`))
const localhost = await findElement(driver, By.xpath(`//li[contains(text(), 'Localhost')]`))
await localhost.click()
await delay(regularDelayMs)
})
it('selects the new UI option', async () => {
const button = await driver.findElement(By.xpath("//p[contains(text(), 'Try Beta Version')]"))
const button = await findElement(driver, By.xpath("//p[contains(text(), 'Try Beta Version')]"))
await button.click()
await delay(regularDelayMs)
// Close all other tabs
const [oldUi, infoPage, newUi] = await driver.getAllWindowHandles()
const [oldUi, tab1, tab2] = await driver.getAllWindowHandles()
await driver.switchTo().window(oldUi)
await driver.close()
await driver.switchTo().window(infoPage)
await driver.switchTo().window(tab1)
const tab1Url = await driver.getCurrentUrl()
if (tab1Url.match(/metamask.io/)) {
await driver.switchTo().window(tab1)
await driver.close()
await driver.switchTo().window(newUi)
await driver.switchTo().window(tab2)
} else if (tab2) {
await driver.switchTo().window(tab2)
await driver.close()
await driver.switchTo().window(tab1)
}
await delay(regularDelayMs)
const [continueBtn] = await driver.findElements(By.css('.welcome-screen__button'))
const continueBtn = await findElement(driver, By.css('.welcome-screen__button'))
await continueBtn.click()
await delay(regularDelayMs)
})
@ -107,9 +124,9 @@ describe('MetaMask', function () {
describe('Going through the first time flow', () => {
it('accepts a secure password', async () => {
const [passwordBox] = await driver.findElements(By.css('.create-password #create-password'))
const [passwordBoxConfirm] = await driver.findElements(By.css('.create-password #confirm-password'))
const [button] = await driver.findElements(By.css('.create-password button'))
const passwordBox = await findElement(driver, By.css('.create-password #create-password'))
const passwordBoxConfirm = await findElement(driver, By.css('.create-password #confirm-password'))
const button = await findElement(driver, By.css('.create-password button'))
await passwordBox.sendKeys('correct horse battery staple')
await passwordBoxConfirm.sendKeys('correct horse battery staple')
@ -118,102 +135,141 @@ describe('MetaMask', function () {
})
it('clicks through the unique image screen', async () => {
const [nextScreen] = await driver.findElements(By.css('.unique-image button'))
const nextScreen = await findElement(driver, By.css('.unique-image button'))
await nextScreen.click()
await delay(regularDelayMs)
})
it('clicks through the privacy notice', async () => {
const [nextScreen] = await driver.findElements(By.css('.tou button'))
await nextScreen.click()
await delay(regularDelayMs)
it('clicks through the ToS', async () => {
// terms of use
const canClickThrough = await driver.findElement(By.css('.tou button')).isEnabled()
assert.equal(canClickThrough, false, 'disabled continue button')
const [bottomOfTos] = await driver.findElements(By.linkText('Attributions'))
const bottomOfTos = await findElement(driver, By.linkText('Attributions'))
await driver.executeScript('arguments[0].scrollIntoView(true)', bottomOfTos)
await delay(regularDelayMs)
const [acceptTos] = await driver.findElements(By.css('.tou button'))
const acceptTos = await findElement(driver, By.css('.tou button'))
driver.wait(until.elementIsEnabled(acceptTos))
await acceptTos.click()
await delay(regularDelayMs)
})
it('clicks through the privacy notice', async () => {
// privacy notice
const nextScreen = await findElement(driver, By.css('.tou button'))
await nextScreen.click()
await delay(regularDelayMs)
})
it('clicks through the phishing notice', async () => {
// phishing notice
const noticeElement = await driver.findElement(By.css('.markdown'))
await driver.executeScript('arguments[0].scrollTop = arguments[0].scrollHeight', noticeElement)
await delay(regularDelayMs)
const nextScreen = await findElement(driver, By.css('.tou button'))
await nextScreen.click()
await delay(regularDelayMs)
})
let seedPhrase
it('reveals the seed phrase', async () => {
const [revealSeedPhrase] = await driver.findElements(By.css('.backup-phrase__secret-blocker'))
await revealSeedPhrase.click()
const byRevealButton = By.css('.backup-phrase__secret-blocker .backup-phrase__reveal-button')
await driver.wait(until.elementLocated(byRevealButton, 10000))
const revealSeedPhraseButton = await findElement(driver, byRevealButton, 10000)
await revealSeedPhraseButton.click()
await delay(regularDelayMs)
seedPhrase = await driver.findElement(By.css('.backup-phrase__secret-words')).getText()
assert.equal(seedPhrase.split(' ').length, 12)
await delay(regularDelayMs)
const [nextScreen] = await driver.findElements(By.css('.backup-phrase button'))
const nextScreen = await findElement(driver, By.css('.backup-phrase button'))
await nextScreen.click()
await delay(regularDelayMs)
})
it('can retype the seed phrase', async () => {
const words = seedPhrase.split(' ')
async function retypeSeedPhrase (words) {
try {
const word0 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[0]}')]`), 10000)
const [word0] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[0]}')]`))
await word0.click()
await delay(tinyDelayMs)
const [word1] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[1]}')]`))
const word1 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[1]}')]`), 10000)
await word1.click()
await delay(tinyDelayMs)
const [word2] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[2]}')]`))
const word2 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[2]}')]`), 10000)
await word2.click()
await delay(tinyDelayMs)
const [word3] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[3]}')]`))
const word3 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[3]}')]`), 10000)
await word3.click()
await delay(tinyDelayMs)
const [word4] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[4]}')]`))
const word4 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[4]}')]`), 10000)
await word4.click()
await delay(tinyDelayMs)
const [word5] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[5]}')]`))
const word5 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[5]}')]`), 10000)
await word5.click()
await delay(tinyDelayMs)
const [word6] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[6]}')]`))
const word6 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[6]}')]`), 10000)
await word6.click()
await delay(tinyDelayMs)
const [word7] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[7]}')]`))
const word7 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[7]}')]`), 10000)
await word7.click()
await delay(tinyDelayMs)
const [word8] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[8]}')]`))
const word8 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[8]}')]`), 10000)
await word8.click()
await delay(tinyDelayMs)
const [word9] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[9]}')]`))
const word9 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[9]}')]`), 10000)
await word9.click()
await delay(tinyDelayMs)
const [word10] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[10]}')]`))
const word10 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[10]}')]`), 10000)
await word10.click()
await delay(tinyDelayMs)
const [word11] = await driver.findElements(By.xpath(`//button[contains(text(), '${words[11]}')]`))
const word11 = await findElement(driver, By.xpath(`//button[contains(text(), '${words[11]}')]`), 10000)
await word11.click()
await delay(tinyDelayMs)
} catch (e) {
await loadExtension(driver, extensionId)
await retypeSeedPhrase(words)
}
}
it('can retype the seed phrase', async () => {
const words = seedPhrase.split(' ')
const [confirm] = await driver.findElements(By.xpath(`//button[contains(text(), 'Confirm')]`))
await retypeSeedPhrase(words)
const confirm = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirm.click()
await delay(regularDelayMs)
})
it('clicks through the deposit modal', async () => {
const [closeModal] = await driver.findElements(By.css('.page-container__header-close'))
const byBuyModal = By.css('span .modal')
const buyModal = await driver.wait(until.elementLocated(byBuyModal))
const closeModal = await findElement(driver, By.css('.page-container__header-close'))
await closeModal.click()
await driver.wait(until.stalenessOf(buyModal))
await delay(regularDelayMs)
})
})
@ -224,8 +280,12 @@ describe('MetaMask', function () {
await driver.findElement(By.css('.qr-wrapper')).isDisplayed()
await delay(regularDelayMs)
const accountModal = await driver.findElement(By.css('span .modal'))
await driver.executeScript("document.querySelector('.account-modal-close').click()")
await delay(regularDelayMs * 4)
await driver.wait(until.stalenessOf(accountModal))
await delay(regularDelayMs)
})
})
@ -234,7 +294,7 @@ describe('MetaMask', function () {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const [logoutButton] = await driver.findElements(By.css('.account-menu__logout-button'))
const logoutButton = await findElement(driver, By.css('.account-menu__logout-button'))
assert.equal(await logoutButton.getText(), 'Log out')
await logoutButton.click()
await delay(regularDelayMs)
@ -252,23 +312,23 @@ describe('MetaMask', function () {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const [createAccount] = await driver.findElements(By.xpath(`//div[contains(text(), 'Create Account')]`))
const createAccount = await findElement(driver, By.xpath(`//div[contains(text(), 'Create Account')]`))
await createAccount.click()
await delay(regularDelayMs)
})
it('set account name', async () => {
const [accountName] = await driver.findElements(By.css('.new-account-create-form input'))
const accountName = await findElement(driver, By.css('.new-account-create-form input'))
await accountName.sendKeys('2nd account')
await delay(regularDelayMs)
const [create] = await driver.findElements(By.xpath(`//button[contains(text(), 'Create')]`))
const create = await findElement(driver, By.xpath(`//button[contains(text(), 'Create')]`))
await create.click()
await delay(regularDelayMs)
})
it('should correct account name', async () => {
const [accountName] = await driver.findElements(By.css('.account-name'))
const accountName = await findElement(driver, By.css('.account-name'))
assert.equal(await accountName.getText(), '2nd account')
await delay(regularDelayMs)
})
@ -279,19 +339,19 @@ describe('MetaMask', function () {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const [logoutButton] = await driver.findElements(By.css('.account-menu__logout-button'))
const logoutButton = await findElement(driver, By.css('.account-menu__logout-button'))
assert.equal(await logoutButton.getText(), 'Log out')
await logoutButton.click()
await delay(regularDelayMs)
})
it('imports seed phrase', async () => {
const [restoreSeedLink] = await driver.findElements(By.css('.unlock-page__link--import'))
const restoreSeedLink = await findElement(driver, By.css('.unlock-page__link--import'))
assert.equal(await restoreSeedLink.getText(), 'Import using account seed phrase')
await restoreSeedLink.click()
await delay(regularDelayMs)
const [seedTextArea] = await driver.findElements(By.css('textarea'))
const seedTextArea = await findElement(driver, By.css('textarea'))
await seedTextArea.sendKeys(testSeedPhrase)
await delay(regularDelayMs)
@ -302,7 +362,7 @@ describe('MetaMask', function () {
})
it('balance renders', async () => {
const balance = await driver.findElement(By.css('.balance-display .token-amount'))
const balance = await findElement(driver, By.css('.balance-display .token-amount'))
const tokenAmount = await balance.getText()
assert.equal(tokenAmount, '100.000 ETH')
await delay(regularDelayMs)
@ -311,56 +371,60 @@ describe('MetaMask', function () {
describe('Send ETH from inside MetaMask', () => {
it('starts to send a transaction', async function () {
const [sendButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Send')]`))
const sendButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Send')]`))
await sendButton.click()
await delay(regularDelayMs)
const [inputAddress] = await driver.findElements(By.css('input[placeholder="Recipient Address"]'))
const [inputAmount] = await driver.findElements(By.css('.currency-display__input'))
const inputAddress = await findElement(driver, By.css('input[placeholder="Recipient Address"]'))
const inputAmount = await findElement(driver, By.css('.currency-display__input'))
await inputAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
await inputAmount.sendKeys('1')
// Set the gas limit
const [configureGas] = await driver.findElements(By.css('.send-v2__gas-fee-display button'))
const configureGas = await findElement(driver, By.css('.send-v2__gas-fee-display button'))
await configureGas.click()
await delay(regularDelayMs)
const [save] = await driver.findElements(By.xpath(`//button[contains(text(), 'Save')]`))
const gasModal = await driver.findElement(By.css('span .modal'))
const save = await findElement(driver, By.xpath(`//button[contains(text(), 'Save')]`))
await save.click()
await driver.wait(until.stalenessOf(gasModal))
await delay(regularDelayMs)
// Continue to next screen
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
const nextScreen = await findElement(driver, By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
})
it('confirms the transaction', async function () {
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Confirm')]`))
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
})
it('finds the transaction in the transactions list', async function () {
const transactions = await driver.findElements(By.css('.tx-list-item'))
const transactions = await findElements(driver, By.css('.tx-list-item'))
assert.equal(transactions.length, 1)
const txValues = await driver.findElements(By.css('.tx-list-value'))
assert.equal(txValues.length, 1)
assert.equal(await txValues[0].getText(), '1 ETH')
const txValues = await findElement(driver, By.css('.tx-list-value'))
await driver.wait(until.elementTextMatches(txValues, /1\sETH/), 10000)
})
})
describe('Send ETH from Faucet', () => {
it('starts a send transaction inside Faucet', async () => {
await driver.executeScript('window.open("https://faucet.metamask.io")')
await delay(waitingNewPageDelayMs)
await openNewPage(driver, 'https://faucet.metamask.io')
const [extension, faucet] = await driver.getAllWindowHandles()
await driver.switchTo().window(faucet)
const faucetPageTitle = await findElement(driver, By.css('.container-fluid'))
await driver.wait(until.elementTextMatches(faucetPageTitle, /MetaMask/))
await delay(regularDelayMs)
const [send1eth] = await driver.findElements(By.xpath(`//button[contains(text(), '10 ether')]`))
const send1eth = await findElement(driver, By.xpath(`//button[contains(text(), '10 ether')]`), 14000)
await send1eth.click()
await delay(regularDelayMs)
@ -368,7 +432,7 @@ describe('MetaMask', function () {
await loadExtension(driver, extensionId)
await delay(regularDelayMs)
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Confirm')]`))
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`), 14000)
await confirmButton.click()
await delay(regularDelayMs)
@ -383,59 +447,146 @@ describe('MetaMask', function () {
})
})
describe('Add existing token using search', () => {
it('clicks on the Add Token button', async () => {
const [addToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Token')]`))
await addToken.click()
describe('Deploy contract and call contract methods', () => {
let extension
let contractTestPage
it('confirms a deploy contract transaction', async () => {
await openNewPage(driver, 'http://127.0.0.1:8080/');
[extension, contractTestPage] = await driver.getAllWindowHandles()
await delay(regularDelayMs)
const deployContractButton = await findElement(driver, By.css('#deployButton'))
await deployContractButton.click()
await delay(regularDelayMs)
await driver.switchTo().window(extension)
await delay(regularDelayMs)
const txListItem = await findElement(driver, By.css('.tx-list-item'))
await txListItem.click()
await delay(regularDelayMs)
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
const txStatuses = await findElements(driver, By.css('.tx-list-status'))
await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/))
const txAccounts = await findElements(driver, By.css('.tx-list-account'))
assert.equal(await txAccounts[0].getText(), 'Contract Deployment')
})
it('can pick a token from the existing options', async () => {
const [tokenSearch] = await driver.findElements(By.css('input.add-token__input'))
await tokenSearch.sendKeys('BAT')
it('calls and confirms a contract method where ETH is sent', async () => {
await driver.switchTo().window(contractTestPage)
await delay(regularDelayMs)
const [token] = await driver.findElements(By.xpath("//div[contains(text(), 'BAT')]"))
await token.click()
const depositButton = await findElement(driver, By.css('#depositButton'))
await depositButton.click()
await delay(regularDelayMs)
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await driver.switchTo().window(extension)
await delay(regularDelayMs)
const [addTokens] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Tokens')]`))
await addTokens.click()
await delay(largeDelayMs)
const txListItem = await findElement(driver, By.css('.tx-list-item'))
await txListItem.click()
await delay(regularDelayMs)
// Set the gas limit
const configureGas = await findElement(driver, By.css('.sliders-icon-container'))
await configureGas.click()
await delay(regularDelayMs)
const gasModal = await driver.findElement(By.css('span .modal'))
await driver.wait(until.elementLocated(By.css('.send-v2__customize-gas__title')))
const [gasPriceInput, gasLimitInput] = await findElements(driver, By.css('.customize-gas-input'))
await gasPriceInput.clear()
await gasPriceInput.sendKeys('10')
await gasLimitInput.clear()
await gasLimitInput.sendKeys('60001')
const save = await findElement(driver, By.xpath(`//button[contains(text(), 'Save')]`))
await save.click()
await delay(regularDelayMs)
await driver.wait(until.stalenessOf(gasModal))
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
const txStatuses = await findElements(driver, By.css('.tx-list-status'))
await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/))
const txValues = await findElement(driver, By.css('.tx-list-value'))
await driver.wait(until.elementTextMatches(txValues, /3\sETH/), 10000)
const txAccounts = await findElements(driver, By.css('.tx-list-account'))
const firstTxAddress = await txAccounts[0].getText()
assert(firstTxAddress.match(/^0x\w{8}\.{3}\w{4}$/))
})
it('renders the balance for the chosen token', async () => {
const balance = await driver.findElement(By.css('.tx-view .balance-display .token-amount'))
it('calls and confirms a contract method where ETH is received', async () => {
await driver.switchTo().window(contractTestPage)
await delay(regularDelayMs)
const withdrawButton = await findElement(driver, By.css('#withdrawButton'))
await withdrawButton.click()
await delay(regularDelayMs)
await driver.switchTo().window(extension)
await delay(regularDelayMs)
const txListItem = await findElement(driver, By.css('.tx-list-item'))
await txListItem.click()
await delay(regularDelayMs)
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
const txStatuses = await findElements(driver, By.css('.tx-list-status'))
await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/))
const txValues = await findElement(driver, By.css('.tx-list-value'))
await driver.wait(until.elementTextMatches(txValues, /0\sETH/), 10000)
await driver.switchTo().window(contractTestPage)
await driver.close()
await driver.switchTo().window(extension)
})
it('renders the correct ETH balance', async () => {
const balance = await findElement(driver, By.css('.tx-view .balance-display .token-amount'))
await driver.wait(until.elementTextMatches(balance, /^86.*ETH.*$/), 10000)
const tokenAmount = await balance.getText()
assert.equal(tokenAmount, '0BAT')
assert.ok(/^86.*ETH.*$/.test(tokenAmount))
await delay(regularDelayMs)
})
})
describe('Add a custom token from TokenFactory', () => {
it('creates a new token', async () => {
await driver.executeScript('window.open("https://tokenfactory.surge.sh/#/factory")')
await delay(waitingNewPageDelayMs)
openNewPage(driver, 'https://tokenfactory.surge.sh/#/factory')
await delay(regularDelayMs * 10)
const [extension, tokenFactory] = await driver.getAllWindowHandles()
await driver.switchTo().window(tokenFactory)
const [
totalSupply,
tokenName,
tokenDecimal,
tokenSymbol,
] = await driver.findElements(By.css('input'))
] = await findElements(driver, By.css('.form-control'))
await totalSupply.sendKeys('100')
await tokenName.sendKeys('Test')
await tokenDecimal.sendKeys('0')
await tokenSymbol.sendKeys('TST')
const [createToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Create Token')]`))
const createToken = await findElement(driver, By.xpath(`//button[contains(text(), 'Create Token')]`))
await createToken.click()
await delay(regularDelayMs)
@ -443,48 +594,261 @@ describe('MetaMask', function () {
await loadExtension(driver, extensionId)
await delay(regularDelayMs)
const [confirmButton] = await driver.findElements(By.xpath(`//button[contains(text(), 'Confirm')]`))
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
await driver.switchTo().window(tokenFactory)
await delay(regularDelayMs)
const tokenContactAddress = await driver.findElement(By.css('div > div > div:nth-child(2) > span:nth-child(3)'))
tokenAddress = await tokenContactAddress.getText()
await driver.close()
await driver.switchTo().window(extension)
await loadExtension(driver, extensionId)
await driver.switchTo().window(extension)
await delay(regularDelayMs)
})
it('clicks on the Add Token button', async () => {
const [addToken] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Token')]`))
const addToken = await findElement(driver, By.xpath(`//button[contains(text(), 'Add Token')]`))
await addToken.click()
await delay(regularDelayMs)
})
it('picks the newly created Test token', async () => {
const [addCustomToken] = await driver.findElements(By.xpath("//div[contains(text(), 'Custom Token')]"))
const addCustomToken = await findElement(driver, By.xpath("//div[contains(text(), 'Custom Token')]"))
await addCustomToken.click()
await delay(regularDelayMs)
const [newTokenAddress] = await driver.findElements(By.css('.add-token__add-custom-form input'))
const newTokenAddress = await findElement(driver, By.css('#custom-address'))
await newTokenAddress.sendKeys(tokenAddress)
await delay(regularDelayMs)
const [nextScreen] = await driver.findElements(By.xpath(`//button[contains(text(), 'Next')]`))
const nextScreen = await findElement(driver, By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
const [addTokens] = await driver.findElements(By.xpath(`//button[contains(text(), 'Add Tokens')]`))
const addTokens = await findElement(driver, By.xpath(`//button[contains(text(), 'Add Tokens')]`))
await addTokens.click()
await delay(regularDelayMs)
})
it('renders the balance for the new token', async () => {
const [balance] = await driver.findElements(By.css('.tx-view .balance-display .token-amount'))
const balance = await findElement(driver, By.css('.tx-view .balance-display .token-amount'))
await driver.wait(until.elementTextMatches(balance, /^100\s*TST\s*$/))
const tokenAmount = await balance.getText()
assert.equal(tokenAmount, '100TST')
assert.ok(/^100\s*TST\s*$/.test(tokenAmount))
await delay(regularDelayMs)
})
})
describe('Send token from inside MetaMask', () => {
let gasModal
it('starts to send a transaction', async function () {
const sendButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Send')]`))
await sendButton.click()
await delay(regularDelayMs)
const inputAddress = await findElement(driver, By.css('input[placeholder="Recipient Address"]'))
const inputAmount = await findElement(driver, By.css('.currency-display__input'))
await inputAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
await inputAmount.sendKeys('50')
// Set the gas limit
const configureGas = await findElement(driver, By.css('.send-v2__gas-fee-display button'))
await configureGas.click()
await delay(regularDelayMs)
gasModal = await driver.findElement(By.css('span .modal'))
})
it('customizes gas', async () => {
await driver.wait(until.elementLocated(By.css('.send-v2__customize-gas__title')))
const save = await findElement(driver, By.xpath(`//button[contains(text(), 'Save')]`))
await save.click()
await delay(regularDelayMs)
})
it('transitions to the confirm screen', async () => {
await driver.wait(until.stalenessOf(gasModal))
// Continue to next screen
const nextScreen = await findElement(driver, By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
})
it('submits the transaction', async function () {
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
})
it('finds the transaction in the transactions list', async function () {
const transactions = await findElements(driver, By.css('.tx-list-item'))
assert.equal(transactions.length, 1)
const txValues = await findElements(driver, By.css('.tx-list-value'))
assert.equal(txValues.length, 1)
// test cancelled on firefox until https://github.com/mozilla/geckodriver/issues/906 is resolved,
// or possibly until we use latest version of firefox in the tests
if (process.env.SELENIUM_BROWSER !== 'firefox') {
await driver.wait(until.elementTextMatches(txValues[0], /50\sTST/), 10000)
}
const txStatuses = await findElements(driver, By.css('.tx-list-status'))
const tx = await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed|Failed/), 10000)
assert.equal(await tx.getText(), 'Confirmed')
})
})
describe('Send a custom token from TokenFactory', () => {
let gasModal
it('sends an already created token', async () => {
openNewPage(driver, `https://tokenfactory.surge.sh/#/token/${tokenAddress}`)
const [extension] = await driver.getAllWindowHandles()
const [
transferToAddress,
transferToAmount,
] = await findElements(driver, By.css('.form-control'))
await transferToAddress.sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
await transferToAmount.sendKeys('26')
const transferAmountButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Transfer Amount')]`))
await transferAmountButton.click()
await delay(regularDelayMs)
const [,, popup] = await driver.getAllWindowHandles()
await driver.switchTo().window(popup)
await driver.close()
await driver.switchTo().window(extension)
await delay(regularDelayMs)
const [txListItem] = await findElements(driver, By.css('.tx-list-item'))
await txListItem.click()
await delay(regularDelayMs)
// Set the gas limit
const configureGas = await driver.wait(until.elementLocated(By.css('.send-v2__gas-fee-display button')))
await configureGas.click()
await delay(regularDelayMs)
gasModal = await driver.findElement(By.css('span .modal'))
})
it('customizes gas', async () => {
await driver.wait(until.elementLocated(By.css('.send-v2__customize-gas__title')))
const [gasPriceInput, gasLimitInput] = await findElements(driver, By.css('.customize-gas-input'))
await gasPriceInput.clear()
await delay(tinyDelayMs)
await gasPriceInput.sendKeys('10')
await delay(tinyDelayMs)
await gasLimitInput.clear()
await delay(tinyDelayMs)
await gasLimitInput.sendKeys(Key.chord(Key.CONTROL, 'a'))
await gasLimitInput.sendKeys('60000')
await gasLimitInput.sendKeys(Key.chord(Key.CONTROL, 'e'))
// Needed for different behaviour of input in different versions of firefox
const gasLimitInputValue = await gasLimitInput.getAttribute('value')
if (gasLimitInputValue === '600001') {
await gasLimitInput.sendKeys(Key.BACK_SPACE)
}
const save = await findElement(driver, By.css('.send-v2__customize-gas__save'))
await save.click()
await driver.wait(until.stalenessOf(gasModal))
const gasFeeInput = await findElement(driver, By.css('.currency-display__input'))
assert.equal(await gasFeeInput.getAttribute('value'), 0.0006)
})
it('submits the transaction', async function () {
const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirmButton.click()
await delay(regularDelayMs)
})
it('finds the transaction in the transactions list', async function () {
const transactions = await findElements(driver, By.css('.tx-list-item'))
assert.equal(transactions.length, 2)
const txValues = await findElements(driver, By.css('.tx-list-value'))
await driver.wait(until.elementTextMatches(txValues[0], /26\sTST/))
const txStatuses = await findElements(driver, By.css('.tx-list-status'))
await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/))
const walletBalance = await findElement(driver, By.css('.wallet-balance'))
await walletBalance.click()
const tokenListItems = await findElements(driver, By.css('.token-list-item'))
await tokenListItems[0].click()
// test cancelled on firefox until https://github.com/mozilla/geckodriver/issues/906 is resolved,
// or possibly until we use latest version of firefox in the tests
if (process.env.SELENIUM_BROWSER !== 'firefox') {
const tokenBalanceAmount = await findElement(driver, By.css('.token-balance__amount'))
assert.equal(await tokenBalanceAmount.getText(), '24')
}
})
})
describe('Hide token', () => {
it('hides the token when clicked', async () => {
const [hideTokenEllipsis] = await findElements(driver, By.css('.token-list-item__ellipsis'))
await hideTokenEllipsis.click()
const byTokenMenuDropdownOption = By.css('.menu__item--clickable')
const tokenMenuDropdownOption = await driver.wait(until.elementLocated(byTokenMenuDropdownOption))
await tokenMenuDropdownOption.click()
const confirmHideModal = await findElement(driver, By.css('span .modal'))
const byHideTokenConfirmationButton = By.css('.hide-token-confirmation__button')
const hideTokenConfirmationButton = await driver.wait(until.elementLocated(byHideTokenConfirmationButton))
await hideTokenConfirmationButton.click()
await driver.wait(until.stalenessOf(confirmHideModal))
})
})
describe('Add existing token using search', () => {
it('clicks on the Add Token button', async () => {
const addToken = await findElement(driver, By.xpath(`//button[contains(text(), 'Add Token')]`))
await addToken.click()
await delay(regularDelayMs)
})
it('can pick a token from the existing options', async () => {
const tokenSearch = await findElement(driver, By.css('#search-tokens'))
await tokenSearch.sendKeys('BAT')
await delay(regularDelayMs)
const token = await findElement(driver, By.xpath("//span[contains(text(), 'BAT')]"))
await token.click()
await delay(regularDelayMs)
const nextScreen = await findElement(driver, By.xpath(`//button[contains(text(), 'Next')]`))
await nextScreen.click()
await delay(regularDelayMs)
const addTokens = await findElement(driver, By.xpath(`//button[contains(text(), 'Add Tokens')]`))
await addTokens.click()
await delay(largeDelayMs)
})
it('renders the balance for the chosen token', async () => {
const balance = await findElement(driver, By.css('.tx-view .balance-display .token-amount'))
await driver.wait(until.elementTextMatches(balance, /0\sBAT/))
await delay(regularDelayMs)
})
})

@ -6,5 +6,5 @@ set -o pipefail
export PATH="$PATH:./node_modules/.bin"
shell-parallel -s 'npm run ganache:start' -x 'sleep 5 && mocha test/e2e/beta/metamask-beta-ui.spec'
shell-parallel -s 'npm run ganache:start' -x 'sleep 5 && mocha test/e2e/beta/from-import-beta-ui.spec'
shell-parallel -s 'npm run ganache:start' -x 'sleep 5 && superstatic test/e2e/beta/contract-test/ --port 8080 --host 127.0.0.1' -x 'sleep 5 && mocha test/e2e/beta/metamask-beta-ui.spec'
shell-parallel -s 'npm run ganache:start -- -d' -x 'sleep 5 && superstatic test/e2e/beta/contract-test/ --port 8080 --host 127.0.0.1' -x 'sleep 5 && mocha test/e2e/beta/from-import-beta-ui.spec'

@ -21,7 +21,7 @@ function delay (time) {
}
function buildChromeWebDriver (extPath) {
const tmpProfile = path.join(os.tmpdir(), fs.mkdtempSync('mm-chrome-profile'));
const tmpProfile = fs.mkdtempSync(path.join(os.tmpdir(), 'mm-chrome-profile'))
return new webdriver.Builder()
.withCapabilities({
chromeOptions: {

@ -4,7 +4,7 @@ const path = require('path')
const assert = require('assert')
const pify = require('pify')
const webdriver = require('selenium-webdriver')
const { By, Key } = webdriver
const { By, Key, until } = webdriver
const { delay, buildChromeWebDriver, buildFirefoxWebdriver, installWebExt, getExtensionIdChrome, getExtensionIdFirefox } = require('./func')
describe('Metamask popup page', function () {
@ -71,13 +71,6 @@ describe('Metamask popup page', function () {
it('matches MetaMask title', async () => {
const title = await driver.getTitle()
assert.equal(title, 'MetaMask', 'title matches MetaMask')
})
it('shows privacy notice', async () => {
await delay(300)
const privacy = await driver.findElement(By.css('.terms-header')).getText()
assert.equal(privacy, 'PRIVACY NOTICE', 'shows privacy notice')
await driver.findElement(By.css('button')).click()
await delay(300)
})
@ -100,6 +93,24 @@ describe('Metamask popup page', function () {
await button.click()
})
it('shows privacy notice', async () => {
const privacy = await driver.findElement(By.css('.terms-header')).getText()
assert.equal(privacy, 'PRIVACY NOTICE', 'shows privacy notice')
await driver.findElement(By.css('button')).click()
await delay(300)
})
it('shows phishing notice', async () => {
await delay(300)
const noticeHeader = await driver.findElement(By.css('.terms-header')).getText()
assert.equal(noticeHeader, 'PHISHING WARNING', 'shows phishing warning')
const element = await driver.findElement(By.css('.markdown'))
await driver.executeScript('arguments[0].scrollTop = arguments[0].scrollHeight', element)
await delay(300)
await driver.findElement(By.css('button')).click()
await delay(300)
})
it('accepts password with length of eight', async () => {
const passwordBox = await driver.findElement(By.id('password-box'))
const passwordBoxConfirm = await driver.findElement(By.id('password-box-confirm'))
@ -218,7 +229,11 @@ describe('Metamask popup page', function () {
it('confirms transaction', async function () {
await delay(300)
await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input')).click()
const bySubmitButton = By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input')
const submitButton = await driver.wait(until.elementLocated(bySubmitButton))
submitButton.click()
await delay(500)
})
@ -258,7 +273,8 @@ describe('Metamask popup page', function () {
it('confirms transaction in MetaMask popup', async function () {
const windowHandles = await driver.getAllWindowHandles()
await driver.switchTo().window(windowHandles[windowHandles.length - 1])
const metamaskSubmit = await driver.findElement(By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input'))
const byMetamaskSubmit = By.css('#pending-tx-form > div.flex-row.flex-space-around.conf-buttons > input')
const metamaskSubmit = await driver.wait(until.elementLocated(byMetamaskSubmit))
await metamaskSubmit.click()
await delay(1000)
})

@ -75,7 +75,7 @@ async function runAddTokenFlowTest (assert, done) {
tokenWrapper[0].click()
// Click Next button
let nextButton = await queryAsync($, 'button.btn-primary.btn--large')
const nextButton = await queryAsync($, 'button.btn-primary.btn--large')
assert.equal(nextButton[0].textContent, 'Next', 'next button rendered')
nextButton[0].click()

@ -1,10 +1,7 @@
const reactTriggerChange = require('react-trigger-change')
const {
timeout,
queryAsync,
findAsync,
} = require('../../lib/util')
const PASSWORD = 'password123'
QUnit.module('confirm sig requests')
@ -17,7 +14,7 @@ QUnit.test('successful confirmation of sig requests', (assert) => {
})
async function runConfirmSigRequestsTest (assert, done) {
let selectState = await queryAsync($, 'select')
const selectState = await queryAsync($, 'select')
selectState.val('confirm sig requests')
reactTriggerChange(selectState[0])
@ -32,7 +29,7 @@ async function runConfirmSigRequestsTest(assert, done) {
let confirmSigHeadline = await queryAsync($, '.request-signature__headline')
assert.equal(confirmSigHeadline[0].textContent, 'Your signature is being requested')
let confirmSigMessage = await queryAsync($, '.request-signature__notice')
const confirmSigMessage = await queryAsync($, '.request-signature__notice')
assert.ok(confirmSigMessage[0].textContent.match(/^Signing\sthis\smessage/))
let confirmSigRowValue = await queryAsync($, '.request-signature__row-value')
@ -45,7 +42,7 @@ async function runConfirmSigRequestsTest(assert, done) {
assert.equal(confirmSigHeadline[0].textContent, 'Your signature is being requested')
confirmSigRowValue = await queryAsync($, '.request-signature__row-value')
assert.ok(confirmSigRowValue[0].textContent.match(/^\#\sTerms\sof\sUse/))
assert.ok(confirmSigRowValue[0].textContent.match(/^#\sTerms\sof\sUse/))
confirmSigSignButton = await queryAsync($, 'button.btn-primary.btn--large')
confirmSigSignButton[0].click()

@ -42,7 +42,7 @@ async function runFirstTimeUsageTest (assert, done) {
assert.equal(created.textContent, 'Your unique account image', 'unique image screen')
// Agree button
let button = (await findAsync(app, 'button'))[0]
const button = (await findAsync(app, 'button'))[0]
assert.ok(button, 'button present')
button.click()

@ -5,8 +5,6 @@ const {
findAsync,
} = require('../../lib/util')
const PASSWORD = 'password123'
QUnit.module('new ui send flow')
QUnit.test('successful send flow', (assert) => {
@ -87,7 +85,7 @@ async function runSendFlowTest(assert, done) {
sendFromFieldItemAddress = await queryAsync($, '.account-list-item__account-name')
assert.equal(sendFromFieldItemAddress[0].textContent, 'Send Account 2', 'send from field dropdown changes account name')
let sendToFieldInput = await queryAsync($, '.send-v2__to-autocomplete__input')
const sendToFieldInput = await queryAsync($, '.send-v2__to-autocomplete__input')
sendToFieldInput[0].focus()
const sendToDropdownList = await queryAsync($, '.send-v2__from-dropdown__list')
@ -101,7 +99,7 @@ async function runSendFlowTest(assert, done) {
const sendAmountField = await queryAsync($, '.send-v2__form-row:eq(2)')
sendAmountField.find('.currency-display')[0].click()
const sendAmountFieldInput = await findAsync(sendAmountField, 'input:text')
const sendAmountFieldInput = await findAsync(sendAmountField, '.currency-display__input')
sendAmountFieldInput.val('5.1')
reactTriggerChange(sendAmountField.find('input')[0])
@ -117,17 +115,17 @@ async function runSendFlowTest(assert, done) {
const sendGasField = await queryAsync($, '.send-v2__gas-fee-display')
assert.equal(
sendGasField.find('.currency-display__input-wrapper > input').val(),
'0.000198',
'0.000021',
'send gas field should show estimated gas total'
)
assert.equal(
sendGasField.find('.currency-display__converted-value')[0].textContent,
'$0.24 USD',
'$0.03 USD',
'send gas field should show estimated gas total converted to USD'
)
await customizeGas(assert, 0, 21000, '0', '$0.00 USD')
await customizeGas(assert, 500, 60000, '0.003', '$3.60 USD')
await customizeGas(assert, 500, 60000, '0.03', '$36.03 USD')
const sendButton = await queryAsync($, 'button.btn-primary.btn--large.page-container__footer-button')
assert.equal(sendButton[0].textContent, 'Next', 'next button rendered')
@ -165,7 +163,7 @@ async function runSendFlowTest(assert, done) {
const sendAmountFieldInEdit = await queryAsync($, '.send-v2__form-row:eq(2)')
sendAmountFieldInEdit.find('.currency-display')[0].click()
const sendAmountFieldInputInEdit = sendAmountFieldInEdit.find('input:text')
const sendAmountFieldInputInEdit = sendAmountFieldInEdit.find('.currency-display__input')
sendAmountFieldInputInEdit.val('1.0')
reactTriggerChange(sendAmountFieldInputInEdit[0])

@ -1,6 +1,5 @@
const reactTriggerChange = require('../../lib/react-trigger-change')
const {
timeout,
queryAsync,
findAsync,
} = require('../../lib/util')

@ -31,6 +31,6 @@ module.exports = {
getRandomValues () {
return 'SOO RANDO!!!1'
}
},
}

@ -17,14 +17,14 @@ class TxGenerator {
}
generate (tx = {}, opts = {}) {
let { count, fromNonce } = opts
const { count, fromNonce } = opts
let nonce = fromNonce || this.txs.length
let txs = []
const txs = []
for (let i = 0; i < count; i++) {
txs.push(extend(template, {
txParams: {
nonce: hexify(nonce++),
}
},
}, tx))
}
this.txs = this.txs.concat(txs)

@ -13,7 +13,7 @@
/* our tests can pass in chrome and firefox. */
/** ************************************************/
'use strict';
'use strict'
// Constants and functions are declared inside the closure.
// In this way, reactTriggerChange can be passed directly to executeScript in Selenium.
@ -33,47 +33,47 @@ module.exports = function reactTriggerChange(node) {
text: true,
time: true,
url: true,
week: true
};
var nodeName = node.nodeName.toLowerCase();
var type = node.type;
var event;
var descriptor;
var initialValue;
var initialChecked;
var initialCheckedRadio;
week: true,
}
var nodeName = node.nodeName.toLowerCase()
var type = node.type
var event
var descriptor
var initialValue
var initialChecked
var initialCheckedRadio
// Do not try to delete non-configurable properties.
// Value and checked properties on DOM elements are non-configurable in PhantomJS.
function deletePropertySafe (elem, prop) {
var desc = Object.getOwnPropertyDescriptor(elem, prop);
var desc = Object.getOwnPropertyDescriptor(elem, prop)
if (desc && desc.configurable) {
delete elem[prop];
delete elem[prop]
}
}
function getCheckedRadio (radio) {
var name = radio.name;
var radios;
var i;
var name = radio.name
var radios
var i
if (name) {
radios = document.querySelectorAll('input[type="radio"][name="' + name + '"]');
radios = document.querySelectorAll('input[type="radio"][name="' + name + '"]')
for (i = 0; i < radios.length; i += 1) {
if (radios[i].checked) {
return radios[i] !== radio ? radios[i] : null;
return radios[i] !== radio ? radios[i] : null
}
}
}
return null;
return null
}
function preventChecking (e) {
e.preventDefault();
e.preventDefault()
if (!initialChecked) {
e.target.checked = false;
e.target.checked = false
}
if (initialCheckedRadio) {
initialCheckedRadio.checked = true;
initialCheckedRadio.checked = true
}
}
@ -81,81 +81,81 @@ module.exports = function reactTriggerChange(node) {
(nodeName === 'input' && type === 'file')) {
// IE9-IE11, non-IE
// Dispatch change.
event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
node.dispatchEvent(event);
event = document.createEvent('HTMLEvents')
event.initEvent('change', true, false)
node.dispatchEvent(event)
} else if ((nodeName === 'input' && supportedInputTypes[type]) ||
nodeName === 'textarea') {
// React 16
// Cache artificial value property descriptor.
// Property doesn't exist in React <16, descriptor is undefined.
descriptor = Object.getOwnPropertyDescriptor(node, 'value');
descriptor = Object.getOwnPropertyDescriptor(node, 'value')
// Update inputValueTracking cached value.
// Remove artificial value property.
// Restore initial value to trigger event with it.
initialValue = node.value;
node.value = initialValue + '#';
deletePropertySafe(node, 'value');
node.value = initialValue;
initialValue = node.value
node.value = initialValue + '#'
deletePropertySafe(node, 'value')
node.value = initialValue
// React 0.14: IE10-IE11, non-IE
// React 15: non-IE
// React 16: IE10-IE11, non-IE
event = document.createEvent('HTMLEvents');
event.initEvent('input', true, false);
node.dispatchEvent(event);
event = document.createEvent('HTMLEvents')
event.initEvent('input', true, false)
node.dispatchEvent(event)
// React 16
// Restore artificial value property descriptor.
if (descriptor) {
Object.defineProperty(node, 'value', descriptor);
Object.defineProperty(node, 'value', descriptor)
}
} else if (nodeName === 'input' && type === 'checkbox') {
// Invert inputValueTracking cached value.
node.checked = !node.checked;
node.checked = !node.checked
// Dispatch click.
// Click event inverts checked value.
event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
node.dispatchEvent(event);
event = document.createEvent('MouseEvents')
event.initEvent('click', true, true)
node.dispatchEvent(event)
} else if (nodeName === 'input' && type === 'radio') {
// Cache initial checked value.
initialChecked = node.checked;
initialChecked = node.checked
// Find and cache initially checked radio in the group.
initialCheckedRadio = getCheckedRadio(node);
initialCheckedRadio = getCheckedRadio(node)
// React 16
// Cache property descriptor.
// Invert inputValueTracking cached value.
// Remove artificial checked property.
// Restore initial value, otherwise preventDefault will eventually revert the value.
descriptor = Object.getOwnPropertyDescriptor(node, 'checked');
node.checked = !initialChecked;
deletePropertySafe(node, 'checked');
node.checked = initialChecked;
descriptor = Object.getOwnPropertyDescriptor(node, 'checked')
node.checked = !initialChecked
deletePropertySafe(node, 'checked')
node.checked = initialChecked
// Prevent toggling during event capturing phase.
// Set checked value to false if initialChecked is false,
// otherwise next listeners will see true.
// Restore initially checked radio in the group.
node.addEventListener('click', preventChecking, true);
node.addEventListener('click', preventChecking, true)
// Dispatch click.
// Click event inverts checked value.
event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
node.dispatchEvent(event);
event = document.createEvent('MouseEvents')
event.initEvent('click', true, true)
node.dispatchEvent(event)
// Remove listener to stop further change prevention.
node.removeEventListener('click', preventChecking, true);
node.removeEventListener('click', preventChecking, true)
// React 16
// Restore artificial checked property descriptor.
if (descriptor) {
Object.defineProperty(node, 'checked', descriptor);
Object.defineProperty(node, 'checked', descriptor)
}
}
}
};

@ -7,7 +7,7 @@ module.exports = function(config) {
settings.files.push('dist/mascara/ui.js')
settings.files.push('dist/mascara/tests.js')
// service worker background
settings.files.push({ pattern: 'dist/mascara/background.js', watched: false, included: false, served: true }),
settings.files.push({ pattern: 'dist/mascara/background.js', watched: false, included: false, served: true })
settings.proxies['/background.js'] = '/base/dist/mascara/background.js'
// use this to keep the browser open for debugging

@ -12,7 +12,7 @@ const pngFileStream = require('png-file-stream')
const sizeOfPng = require('image-size/lib/types/png')
const By = webdriver.By
const localesIndex = require('../../app/_locales/index.json')
const { delay, buildChromeWebDriver, buildFirefoxWebdriver, installWebExt, getExtensionIdChrome, getExtensionIdFirefox } = require('../e2e/func')
const { delay, buildChromeWebDriver, getExtensionIdChrome } = require('../e2e/func')
const eth = new Ethjs(new Ethjs.HttpProvider('http://localhost:8545'))
@ -43,9 +43,7 @@ captureAllScreens()
async function captureAllScreens () {
// common names
let button
let tabs
let element
await cleanScreenShotDir()
@ -108,7 +106,7 @@ async function captureAllScreens() {
await captureLanguageScreenShots('terms')
await delay(300)
element = driver.findElement(By.linkText('Attributions'))
const element = driver.findElement(By.linkText('Attributions'))
await driver.executeScript('arguments[0].scrollIntoView(true)', element)
await delay(300)
await captureLanguageScreenShots('terms-scrolled')
@ -134,7 +132,7 @@ async function captureAllScreens() {
// enter seed phrase
const seedPhraseButtons = await driver.findElements(By.css('.backup-phrase__confirm-seed-options > button'))
const seedPhraseButtonWords = await Promise.all(seedPhraseButtons.map(button => button.getText()))
for (let targetWord of seedPhraseWords) {
for (const targetWord of seedPhraseWords) {
const wordIndex = seedPhraseButtonWords.indexOf(targetWord)
if (wordIndex === -1) throw new Error(`Captured seed phrase word "${targetWord}" not in found seed phrase button options ${seedPhraseButtonWords.join(' ')}`)
await driver.findElement(By.css(`.backup-phrase__confirm-seed-options > button:nth-child(${wordIndex + 1})`)).click()
@ -195,7 +193,7 @@ async function captureLanguageScreenShots(label) {
const nonEnglishLocales = localesIndex.filter(localeMeta => localeMeta.code !== 'en')
// take english shot
await captureScreenShot(`${label} (en)`)
for (let localeMeta of nonEnglishLocales) {
for (const localeMeta of nonEnglishLocales) {
// set locale and take shot
await setLocale(localeMeta.code)
await delay(300)

@ -1,17 +1,44 @@
const assert = require('assert')
const path = require('path')
const accountImporter = require('../../../app/scripts/account-import-strategies/index')
const ethUtil = require('ethereumjs-util')
const accountImporter = require('../../../app/scripts/account-import-strategies/index')
const { assertRejects } = require('../test-utils')
describe('Account Import Strategies', function () {
const privkey = '0x4cfd3e90fc78b0f86bf7524722150bb8da9c60cd532564d7ff43f5716514f553'
const json = '{"version":3,"id":"dbb54385-0a99-437f-83c0-647de9f244c3","address":"a7f92ce3fba24196cf6f4bd2e1eb3db282ba998c","Crypto":{"ciphertext":"bde13d9ade5c82df80281ca363320ce254a8a3a06535bbf6ffdeaf0726b1312c","cipherparams":{"iv":"fbf93718a57f26051b292f072f2e5b41"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"dklen":32,"salt":"7ffe00488319dec48e4c49a120ca49c6afbde9272854c64d9541c83fc6acdffe","n":8192,"r":8,"p":1},"mac":"2adfd9c4bc1cdac4c85bddfb31d9e21a684e0e050247a70c5698facf6b7d4681"}}'
describe('private key import', function () {
it('imports a private key and strips 0x prefix', async function () {
const importPrivKey = await accountImporter.importAccount('Private Key', [ privkey ])
assert.equal(importPrivKey, ethUtil.stripHexPrefix(privkey))
})
it('throws an error for empty string private key', async () => {
assertRejects(async function () {
await accountImporter.importAccount('Private Key', [ '' ])
}, Error, 'no empty strings')
})
it('throws an error for undefined string private key', async () => {
assertRejects(async function () {
await accountImporter.importAccount('Private Key', [ undefined ])
})
})
it('throws an error for undefined string private key', async () => {
assertRejects(async function () {
await accountImporter.importAccount('Private Key', [])
})
})
it('throws an error for invalid private key', async () => {
assertRejects(async function () {
await accountImporter.importAccount('Private Key', [ 'popcorn' ])
})
})
})
describe('JSON keystore import', function () {
it('fails when password is incorrect for keystore', async function () {
const wrongPassword = 'password2'
@ -27,5 +54,5 @@ describe('Account Import Strategies', function () {
const importJson = await accountImporter.importAccount('JSON File', [ json, fileContentsPassword])
assert.equal(importJson, '0x5733876abe94146069ce8bcbabbde2677f2e35fa33e875e92041ed2ac87e5bc7')
})
})
})

@ -12,7 +12,7 @@ const stubPreferencesStore = {
},
}
},
};
}
describe('address-book-controller', function () {
var addressBookController

@ -45,7 +45,7 @@ describe('MetaMaskController', function () {
encryptor: {
encrypt: function (password, object) {
this.object = object
return Promise.resolve()
return Promise.resolve('mock-encrypted')
},
decrypt: function () {
return Promise.resolve(this.object)
@ -53,6 +53,9 @@ describe('MetaMaskController', function () {
},
initState: clone(firstTimeState),
})
// disable diagnostics
metamaskController.diagnostics = null
// add sinon method spies
sandbox.spy(metamaskController.keyringController, 'createNewVaultAndKeychain')
sandbox.spy(metamaskController.keyringController, 'createNewVaultAndRestore')
})
@ -62,6 +65,31 @@ describe('MetaMaskController', function () {
sandbox.restore()
})
describe('submitPassword', function () {
const password = 'password'
beforeEach(async function () {
await metamaskController.createNewVaultAndKeychain(password)
})
it('removes any identities that do not correspond to known accounts.', async function () {
const fakeAddress = '0xbad0'
metamaskController.preferencesController.addAddresses([fakeAddress])
await metamaskController.submitPassword(password)
const identities = Object.keys(metamaskController.preferencesController.store.getState().identities)
const addresses = await metamaskController.keyringController.getAccounts()
identities.forEach((identity) => {
assert.ok(addresses.includes(identity), `addresses should include all IDs: ${identity}`)
})
addresses.forEach((address) => {
assert.ok(identities.includes(address), `identities should include all Addresses: ${address}`)
})
})
})
describe('#getGasPrice', function () {
it('gives the 50th percentile lowest accepted gas price from recentBlocksController', async function () {

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

Loading…
Cancel
Save