diff --git a/.babelrc b/.babelrc index 628fe652c..9b1d5409b 100644 --- a/.babelrc +++ b/.babelrc @@ -1,4 +1,4 @@ { - "presets": [["env", { "debug": true }], "react", "stage-0"], + "presets": [["env", { "targets": { "browsers": [">0.25%", "not ie 11", "not op_mini all"] } } ], "react", "stage-0"], "plugins": ["transform-runtime", "transform-async-to-generator", "transform-class-properties"] } diff --git a/.circleci/scripts/firefox-download.sh b/.circleci/scripts/firefox-download.sh deleted file mode 100755 index bd8ac054c..000000000 --- a/.circleci/scripts/firefox-download.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash -echo "Checking if firefox was already downloaded" -if [ -d "firefox" ] -then - echo "Firefox found. No need to download" -else - FIREFOX_VERSION="61.0.2" - FIREFOX_BINARY="firefox-$FIREFOX_VERSION.tar.bz2" - echo "Downloading firefox..." - wget "https://ftp.mozilla.org/pub/firefox/releases/$FIREFOX_VERSION/linux-x86_64/en-US/$FIREFOX_BINARY" \ - && tar xjf "$FIREFOX_BINARY" - echo "firefox download complete" -fi diff --git a/.circleci/scripts/firefox-install b/.circleci/scripts/firefox-install new file mode 100755 index 000000000..7c785b987 --- /dev/null +++ b/.circleci/scripts/firefox-install @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +set -e +set -u +set -o pipefail + +FIREFOX_VERSION='62.0' +FIREFOX_BINARY="firefox-${FIREFOX_VERSION}.tar.bz2" +FIREFOX_BINARY_URL="https://ftp.mozilla.org/pub/firefox/releases/${FIREFOX_VERSION}/linux-x86_64/en-US/${FIREFOX_BINARY}" +FIREFOX_PATH='/opt/firefox' + +printf '%s\n' "Removing old Firefox installation" + +sudo rm -r "${FIREFOX_PATH}" + +printf '%s\n' "Downloading & installing Firefox ${FIREFOX_VERSION}" + +wget --quiet --show-progress -O- "${FIREFOX_BINARY_URL}" | sudo tar xj -C /opt + +printf '%s\n' "Firefox ${FIREFOX_VERSION} installed" + +{ + printf '%s\n' 'pref("general.config.filename", "firefox.cfg");' + printf '%s\n' 'pref("general.config.obscure_value", 0);' +} | sudo tee "${FIREFOX_PATH}/defaults/pref/autoconfig.js" + +sudo cp .circleci/scripts/firefox.cfg "${FIREFOX_PATH}" + +printf '%s\n' "Firefox ${FIREFOX_VERSION} configured" diff --git a/.circleci/scripts/firefox-install.sh b/.circleci/scripts/firefox-install.sh deleted file mode 100755 index 1c60f4de9..000000000 --- a/.circleci/scripts/firefox-install.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -echo "Installing firefox..." -sudo rm -r /opt/firefox -sudo mv firefox /opt/firefox61 -sudo mv /usr/bin/firefox /usr/bin/firefox-old -sudo ln -s /opt/firefox61/firefox /usr/bin/firefox -echo "Firefox installed." diff --git a/.circleci/scripts/firefox.cfg b/.circleci/scripts/firefox.cfg new file mode 100644 index 000000000..68dd285f2 --- /dev/null +++ b/.circleci/scripts/firefox.cfg @@ -0,0 +1,13 @@ +// IMPORTANT: Start your code on the 2nd line + +lockPref("app.update.enabled", false); +lockPref("app.update.auto", false); +lockPref("app.update.mode", 0); +lockPref("app.update.service.enabled", false); + +pref("browser.rights.3.shown", true); + +pref("browser.startup.homepage_override.mstone","ignore"); + +lockPref("plugins.hide_infobar_for_outdated_plugin", true); +clearPref("plugins.update.url"); diff --git a/.gitignore b/.gitignore index e53133361..4ee0c1c62 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ package # IDEs .idea .vscode +.sublime-project # VIM *.swp @@ -20,6 +21,7 @@ temp .DS_Store app/.DS_Store +coverage/ dist builds/ disc/ @@ -34,6 +36,7 @@ test/bundle.js test/test-bundle.js test-artifacts +test-builds #ignore css output and sourcemaps ui/app/css/output/ diff --git a/.yo-rc.json b/.yo-rc.json deleted file mode 100644 index 7a2135249..000000000 --- a/.yo-rc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "generator-mocha": {} -} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e58396d73..6d328d9ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,55 @@ - Allow to remove accounts (Imported and Hardware Wallets) - [#4840](https://github.com/MetaMask/metamask-extension/pull/4840): Now shows notifications when transactions are completed. - [#4855](https://github.com/MetaMask/metamask-extension/pull/4855): network.js: convert rpc protocol to lower case. +## Current Develop Branch + +## 4.10.0 Mon Sep 17 2018 + +- [#4803](https://github.com/MetaMask/metamask-extension/pull/4803): Implement EIP-712: Sign typed data, but continue to support v1. +- [#4898](https://github.com/MetaMask/metamask-extension/pull/4898): Restore multiple consecutive accounts with balances. +- [#4279](https://github.com/MetaMask/metamask-extension/pull/4279): New BlockTracker and Json-Rpc-Engine based Provider. +- [#5050](https://github.com/MetaMask/metamask-extension/pull/5050): Add Ledger hardware wallet support. +- [#4919](https://github.com/MetaMask/metamask-extension/pull/4919): Refactor and Redesign Transaction List. +- [#5182](https://github.com/MetaMask/metamask-extension/pull/5182): Add Transaction Details to the Transaction List view. +- [#5229](https://github.com/MetaMask/metamask-extension/pull/5229): Clear old seed words when importing new seed words. +- [#5264](https://github.com/MetaMask/metamask-extension/pull/5264): Improve click area for adjustment arrows buttons. +- [#4606](https://github.com/MetaMask/metamask-extension/pull/4606): Add new metamask_watchAsset method. +- [#5189](https://github.com/MetaMask/metamask-extension/pull/5189): Fix bug where Ropsten loading message is shown when connecting to Kovan. +- [#5256](https://github.com/MetaMask/metamask-extension/pull/5256): Add mock EIP-1102 support + +## 4.9.3 Wed Aug 15 2018 + +- [#4897](https://github.com/MetaMask/metamask-extension/pull/4897): QR code scan for recipient addresses. +- [#4961](https://github.com/MetaMask/metamask-extension/pull/4961): Add a download seed phrase link. +- [#5060](https://github.com/MetaMask/metamask-extension/pull/5060): Fix bug where gas was not updating properly. + +## 4.9.2 Mon Aug 09 2018 + +- [#5020](https://github.com/MetaMask/metamask-extension/pull/5020): Fix bug in migration #28 ( moving tokens to specific accounts ) + +## 4.9.1 Mon Aug 09 2018 + +- [#4884](https://github.com/MetaMask/metamask-extension/pull/4884): Allow to have tokens per account and network. +- [#4989](https://github.com/MetaMask/metamask-extension/pull/4989): Continue to use original signedTypedData. +- [#5010](https://github.com/MetaMask/metamask-extension/pull/5010): Fix ENS resolution issues. +- [#5000](https://github.com/MetaMask/metamask-extension/pull/5000): Show error while allowing confirmation of tx where simulation fails. +- [#4995](https://github.com/MetaMask/metamask-extension/pull/4995): Shows retry button on dApp initialized transactions. + +## 4.9.0 Mon Aug 07 2018 + +- [#4926](https://github.com/MetaMask/metamask-extension/pull/4926): Show retry button on the latest tx of the earliest nonce. +- [#4888](https://github.com/MetaMask/metamask-extension/pull/4888): Suggest using the new user interface. +- [#4947](https://github.com/MetaMask/metamask-extension/pull/4947): Prevent sending multiple transasctions on multiple confirm clicks. +- [#4844](https://github.com/MetaMask/metamask-extension/pull/4844): Add new tokens auto detection. +- [#4667](https://github.com/MetaMask/metamask-extension/pull/4667): Remove rejected transactions from transaction history. +- [#4625](https://github.com/MetaMask/metamask-extension/pull/4625): Add Trezor Support. +- [#4625](https://github.com/MetaMask/metamask-extension/pull/4625/commits/523cf9ad33d88719520ae5e7293329d133b64d4d): Allow to remove accounts (Imported and Hardware Wallets) +- [#4814](https://github.com/MetaMask/metamask-extension/pull/4814): Add hex data input to send screen. +- [#4691](https://github.com/MetaMask/metamask-extension/pull/4691): Redesign of the Confirm Transaction Screen. +- [#4840](https://github.com/MetaMask/metamask-extension/pull/4840): Now shows notifications when transactions are completed. +- [#4855](https://github.com/MetaMask/metamask-extension/pull/4855): Allow the use of HTTP prefix for custom rpc urls. +- [#4855](https://github.com/MetaMask/metamask-extension/pull/4855): network.js: convert rpc protocol to lower case. +- [#4898](https://github.com/MetaMask/metamask-extension/pull/4898): Restore multiple consecutive accounts with balances. ## 4.8.0 Thur Jun 14 2018 diff --git a/README.md b/README.md index 6e6a0b3d8..496e109c3 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,12 @@ If you're a web dapp developer, we've got two types of guides for you: Uncompressed builds can be found in `/dist`, compressed builds can be found in `/builds` once they're built. +## Contributing + +You can read [our internal docs here](https://metamask.github.io/metamask-extension/). + +You can re-generate the docs locally by running `npm run doc`, and contributors can update the hosted docs by running `npm run publish-docs`. + ### Running Tests Requires `mocha` installed. Run `npm install -g mocha`. diff --git a/app/_locales/cs/messages.json b/app/_locales/cs/messages.json index 69f96d4cd..9a35f67aa 100644 --- a/app/_locales/cs/messages.json +++ b/app/_locales/cs/messages.json @@ -802,7 +802,7 @@ "message": "Testovací faucet" }, "to": { - "message": "Komu: " + "message": "Komu" }, "toETHviaShapeShift": { "message": "$1 na ETH přes ShapeShift", diff --git a/app/_locales/de/messages.json b/app/_locales/de/messages.json index 2e556dc8d..2e56d2dfd 100644 --- a/app/_locales/de/messages.json +++ b/app/_locales/de/messages.json @@ -781,7 +781,7 @@ "message": "Testfaucet" }, "to": { - "message": "An:" + "message": "An" }, "toETHviaShapeShift": { "message": "$1 an ETH via ShapeShift", diff --git a/app/_locales/en/messages.json b/app/_locales/en/messages.json index 3a1115e15..de6fff53c 100644 --- a/app/_locales/en/messages.json +++ b/app/_locales/en/messages.json @@ -17,6 +17,9 @@ "accountSelectionRequired": { "message": "You need to select an account!" }, + "activityLog": { + "message": "activity log" + }, "address": { "message": "Address" }, @@ -29,6 +32,9 @@ "addTokens": { "message": "Add Tokens" }, + "addSuggestedTokens": { + "message": "Add Suggested Tokens" + }, "addAcquiredTokens": { "message": "Add the tokens you've acquired using Nifty Wallet" }, @@ -210,6 +216,9 @@ "currentConversion": { "message": "Current Conversion" }, + "currentLanguage": { + "message": "Current Language" + }, "currentNetwork": { "message": "Current Network" }, @@ -451,6 +460,9 @@ "hideTokenPrompt": { "message": "Hide Token?" }, + "history": { + "message": "History" + }, "howToDeposit": { "message": "How would you like to deposit Ether?" }, @@ -587,6 +599,9 @@ "metamaskSeedWords": { "message": "Nifty Wallet Seed Words" }, + "metamaskVersion": { + "message": "MetaMask Version" + }, "min": { "message": "Minimum" }, @@ -651,7 +666,7 @@ "message": "No transaction history." }, "noTransactions": { - "message": "No Transactions" + "message": "You have no transactions" }, "notFound": { "message": "Not Found" @@ -702,6 +717,9 @@ "pasteSeed": { "message": "Paste your seed phrase here!" }, + "pending": { + "message": "pending" + }, "personalAddressDetected": { "message": "Personal address detected. Input the token contract address." }, @@ -730,6 +748,9 @@ "qrCode": { "message": "Show QR Code" }, + "queue": { + "message": "Queue" + }, "readdToken": { "message": "You can add this token back in the future by going go to “Add token” in your accounts options menu." }, @@ -851,6 +872,9 @@ "save": { "message": "Save" }, + "speedUp": { + "message": "speed up" + }, "speedUpTitle": { "message": "Speed Up Transaction" }, @@ -876,6 +900,12 @@ "secretPhrase": { "message": "Enter your secret twelve word phrase here to restore your vault." }, + "showHexData": { + "message": "Show Hex Data" + }, + "showHexDataDescription": { + "message": "Select this to show the hex data field on the send screen" + }, "newPassword8Chars": { "message": "New Password (min 8 chars)" }, @@ -888,6 +918,9 @@ "selectCurrency": { "message": "Select Currency" }, + "selectLocale": { + "message": "Select Locale" + }, "selectService": { "message": "Select Service" }, @@ -903,6 +936,12 @@ "sendTokens": { "message": "Send Tokens" }, + "sentEther": { + "message": "sent ether" + }, + "sentTokens": { + "message": "sent tokens" + }, "separateEachWord": { "message": "Separate each word with a single space" }, @@ -916,6 +955,9 @@ "orderOneHere": { "message": "Order a Trezor or Ledger and keep your funds in cold storage" }, + "outgoing": { + "message": "Outgoing" + }, "searchTokens": { "message": "Search Tokens" }, @@ -979,6 +1021,9 @@ "sign": { "message": "Sign" }, + "signatureRequest": { + "message": "Signature Request" + }, "signed": { "message": "Signed" }, @@ -1031,7 +1076,7 @@ "message": "Test Faucet" }, "to": { - "message": "To: " + "message": "To" }, "toETHviaShapeShift": { "message": "$1 to ETH via ShapeShift", @@ -1061,6 +1106,27 @@ "total": { "message": "Total" }, + "transaction": { + "message": "transaction" + }, + "transactionConfirmed": { + "message": "Transaction confirmed on $2." + }, + "transactionCreated": { + "message": "Transaction created with a value of $1 on $2." + }, + "transactionDropped": { + "message": "Transaction dropped on $2." + }, + "transactionSubmitted": { + "message": "Transaction submitted on $2." + }, + "transactionUpdated": { + "message": "Transaction updated on $2." + }, + "transactionUpdatedGas": { + "message": "Transaction updated with a gas price of $1 on $2." + }, "transactions": { "message": "transactions" }, @@ -1107,6 +1173,9 @@ "unavailable": { "message": "Unavailable" }, + "units": { + "message": "units" + }, "unknown": { "message": "Unknown" }, @@ -1134,6 +1203,9 @@ "unlockMessage": { "message": "The decentralized web awaits" }, + "updatedWithDate": { + "message": "Updated $1" + }, "uriErrorMsg": { "message": "URIs require the appropriate HTTP/HTTPS prefix." }, diff --git a/app/_locales/es/messages.json b/app/_locales/es/messages.json index 8bd1912e5..b3231b5f7 100644 --- a/app/_locales/es/messages.json +++ b/app/_locales/es/messages.json @@ -778,7 +778,7 @@ "message": "Probar Faucet" }, "to": { - "message": "Para:" + "message": "Para" }, "toETHviaShapeShift": { "message": "$1 a ETH via ShapeShift", diff --git a/app/_locales/fr/messages.json b/app/_locales/fr/messages.json index a54208b51..ac3f2368d 100644 --- a/app/_locales/fr/messages.json +++ b/app/_locales/fr/messages.json @@ -493,7 +493,7 @@ "message": "Sélectionner un service" }, "send": { - "message": "Envoyé" + "message": "Envoyer" }, "sendTokens": { "message": "Envoyer des jetons" diff --git a/app/_locales/ko/messages.json b/app/_locales/ko/messages.json index 44b8f42c5..183e786d3 100644 --- a/app/_locales/ko/messages.json +++ b/app/_locales/ko/messages.json @@ -3,86 +3,125 @@ "message": "수락" }, "account": { - "message": "계좌" + "message": "계정" }, "accountDetails": { - "message": "계좌 상세보기" + "message": "계정 상세보기" }, "accountName": { - "message": "계좌 이름" + "message": "계정 이름" }, "address": { "message": "주소" }, + "addCustomToken": { + "message": "사용자 정의 토큰 추가" + }, "addToken": { "message": "토큰 추가" }, + "addTokens": { + "message": "토큰 추가" + }, + "addAcquiredTokens": { + "message": "메타마스크를 통해 획득한 토큰 추가" + }, "amount": { - "message": "금액" + "message": "수량" }, "amountPlusGas": { - "message": "금액 + 가스" + "message": "수량 + 가스" }, "appDescription": { "message": "이더리움 브라우저 확장 프로그램", - "description": "어플리케이션 내용" + "description": "어플리케이션 설명" }, "appName": { "message": "메타마스크", "description": "어플리케이션 이름" }, + "approved": { + "message": "수락" + }, "attemptingConnect": { - "message": "블록체인에 접속 시도 중입니다." + "message": "블록체인에 접속을 시도하는 중입니다." + }, + "attributions": { + "message": "속성" }, "available": { - "message": "사용 가능한" + "message": "사용 가능" }, "back": { - "message": "뒤로" + "message": "돌아가기" }, "balance": { - "message": "잔액:" + "message": "잔액" + }, + "balances": { + "message": "토큰 잔액" }, "balanceIsInsufficientGas": { - "message": "가스가 충분하지 않습니다." + "message": "현재 가스 총합에 대해 잔액이 부족합니다" }, "beta": { - "message": "베타" + "message": "BETA" }, "betweenMinAndMax": { "message": "$1 이상 $2 이하여야 합니다.", - "description": "helper for inputting hex as decimal input" + "description": "10진수 입력으로 hex값 입력을 도와줍니다" + }, + "blockiesIdenticon": { + "message": "Blockies 아이덴티콘 사용" }, "borrowDharma": { - "message": "Dharma에서 빌리기(베타)" + "message": "Dharma에서 대여하기(Beta)" + }, + "builtInCalifornia": { + "message": "메타마스크는 캘리포니아에서 디자인되고 만들어졌습니다." }, "buy": { "message": "구매" }, "buyCoinbase": { - "message": "코인베이스에서 구매" + "message": "코인베이스에서 구매하기" }, "buyCoinbaseExplainer": { - "message": "코인베이스에서 비트코인, 이더리움, 라이트코인을 구매하실 수 있습니다." + "message": "코인베이스는 비트코인, 이더리움, 라이트코인을 거래할 수 있는 유명한 거래소입니다." + }, + "ok": { + "message": "확인" }, "cancel": { "message": "취소" }, + "classicInterface": { + "message": "예전 인터페이스" + }, "clickCopy": { "message": "클릭하여 복사" }, + "close": { + "message": "닫기" + }, "confirm": { "message": "승인" }, + "confirmed": { + "message": "승인됨" + }, "confirmContract": { "message": "컨트랙트 승인" }, "confirmPassword": { - "message": "패스워드 승인" + "message": "비밀번호 확인" }, "confirmTransaction": { "message": "트랜잭션 승인" }, + "continue": { + "message": "계속" + }, "continueToCoinbase": { "message": "코인베이스로 계속하기" }, @@ -90,72 +129,93 @@ "message": "컨트랙트 배포" }, "conversionProgress": { - "message": "변환중.." + "message": "변환 진행중" }, "copiedButton": { - "message": "복사되었습니다." + "message": "복사됨" }, "copiedClipboard": { - "message": "클립보드에 복사되었습니다." + "message": "클립보드에 복사되었습니다" }, "copiedExclamation": { - "message": "복사되었습니다." + "message": "복사됨!" + }, + "copiedSafe": { + "message": "안전한 곳에 복사하였습니다" }, "copy": { - "message": "복사하기" + "message": "복사" + }, + "copyContractAddress": { + "message": "컨트랙트 주소 복사" }, "copyToClipboard": { - "message": "클립보드에 복사" + "message": "클립보드로 복사" }, "copyButton": { "message": " 복사 " }, "copyPrivateKey": { - "message": "비밀 키 (클릭하여 복사)" + "message": "비밀 키입니다 (클릭하여 복사)" }, "create": { "message": "생성" }, "createAccount": { - "message": "계좌 생성" + "message": "계정 생성" }, "createDen": { "message": "생성" }, "crypto": { "message": "암호화폐", - "description": "Exchange type (cryptocurrencies)" + "description": "거래 유형 (암호화폐)" + }, + "currentConversion": { + "message": "선택된 단위" + }, + "currentNetwork": { + "message": "현재 네트워크" }, "customGas": { "message": "가스 설정" }, + "customToken": { + "message": "사용자 정의 토큰" + }, "customize": { - "message": "커스터마이즈" + "message": "맞춤화 하기" }, "customRPC": { - "message": "커스텀 RPC" + "message": "사용자 정의 RPC" + }, + "decimalsMustZerotoTen": { + "message": "소수점은 0 이상이고 36 이하여야 합니다." + }, + "decimal": { + "message": "소수점 정확도" }, "defaultNetwork": { "message": "이더리움 트랜잭션의 기본 네트워크는 메인넷입니다." }, "denExplainer": { - "message": "DEN은 비밀번호가 암호화 된 Nifty Wallet의 스토리지입니다." + "message": "DEN은 비밀번호로 암호화 된 메타마스크의 저장소입니다." }, "deposit": { "message": "입금" }, "depositBTC": { - "message": "아래 주소로 BTC를 입급해주세요." + "message": "다음 주소로 BTC를 입급해주세요." }, "depositCoin": { - "message": "아래 주소로 $1를 입금해주세요.", - "description": "Tells the user what coin they have selected to deposit with shapeshift" + "message": "다음 주소로 $1 만큼 입금해주세요.", + "description": "사용자에게 shapeshift에서 어떤 코인을 선택해 입금했는지 알려줍니다" }, "depositEth": { - "message": "이더 입금" + "message": "이더 입금하기" }, "depositEther": { - "message": "이더 입금" + "message": "이더리움 입금하기" }, "depositFiat": { "message": "현금으로 입금하기" @@ -167,10 +227,10 @@ "message": "ShapeShift를 통해 입금하기" }, "depositShapeShiftExplainer": { - "message": "다른 암호화폐를 가지고 있으면, 계좌 생성 필요없이, 거래를 하거나 메타마스크 지갑을 통해 이더를 입금할 수 있습니다." + "message": "다른 암호화폐를 가지고 있으면, 계정을 생성할 필요없이 메타마스크 지갑에 이더리움을 바로 거래하거나 입금할 수 있습니다." }, "details": { - "message": "상세" + "message": "세부사항" }, "directDeposit": { "message": "즉시 입금" @@ -179,70 +239,103 @@ "message": "이더 즉시 입금" }, "directDepositEtherExplainer": { - "message": "이더를 이미 보유하고 있다면, 직접 입금을 통해 이더를 즉시 입금하실 수 있습니다." + "message": "약간의 이더를 이미 보유하고 있다면, 새로 만든 지갑에 직접 입금하여 이더를 보유할 수 있습니다." }, "done": { "message": "완료" }, + "downloadStateLogs": { + "message": "상태 로그 다운로드" + }, + "dropped": { + "message": "중단됨" + }, "edit": { "message": "수정" }, "editAccountName": { - "message": "계좌명 수정" + "message": "계정 이름 수정" + }, + "editingTransaction": { + "message": "트랜젝션을 변경합니다" + }, + "emailUs": { + "message": "저자에게 메일 보내기!" }, "encryptNewDen": { - "message": "새 DEN 암호화" + "message": "새로운 DEN을 암호화" }, "enterPassword": { - "message": "패스워드를 입력해주세요." + "message": "비밀번호를 입력해주세요" + }, + "enterPasswordConfirm": { + "message": "비밀번호를 다시 입력해 주세요" + }, + "enterPasswordContinue": { + "message": "계속하기 위해 비밀번호 입력" + }, + "passwordNotLongEnough": { + "message": "비밀번호가 충분히 길지 않습니다" + }, + "passwordsDontMatch": { + "message": "비밀번호가 맞지 않습니다" }, "etherscanView": { - "message": "이더스캔에서 계좌보기" + "message": "이더스캔에서 계정보기" }, "exchangeRate": { "message": "환율" }, "exportPrivateKey": { - "message": "비밀키 내보내기" + "message": "개인키 내보내기" }, "exportPrivateKeyWarning": { - "message": "Export private keys at your own risk." + "message": "개인키 내보내기는 위험을 감수해야 합니다." }, "failed": { "message": "실패" }, "fiat": { "message": "FIAT", - "description": "Exchange type" + "description": "거래 형식" }, "fileImportFail": { - "message": "파일을 가져올 수 없나요? 여기를 클릭해주세요!", - "description": "Helps user import their account from a JSON file" + "message": "파일을 가져올 수 없나요? 이곳을 클릭해주세요!", + "description": "JSON 파일로부터 계정 가져오기를 도와줍니다" + }, + "followTwitter": { + "message": "트위터에서 팔로우하세요" }, "from": { - "message": "보내는 사람" + "message": "보내는 이" + }, + "fromToSame": { + "message": "보내고 받는 주소는 동일할 수 없습니다" }, "fromShapeShift": { "message": "ShapeShift로 부터" }, "gas": { "message": "가스", - "description": "Short indication of gas cost" + "description": "가스 가격의 줄임" }, "gasFee": { "message": "가스 수수료" }, "gasLimit": { - "message": "가스 리밋" + "message": "가스 한도" }, "gasLimitCalculation": { - "message": "네트워크 성공률을 기반으로 적합한 가스 리밋을 계산합니다." + "message": "네트워크 성공률을 기반으로 적합한 가스 한도를 계산합니다." }, "gasLimitRequired": { - "message": "가스 리밋이 필요합니다." + "message": "가스 한도가 필요합니다." }, "gasLimitTooLow": { - "message": "가스 리밋은 21000 이상이여야 합니다." + "message": "가스 한도는 최소 21000 이상이여야 합니다." + }, + "generatingSeed": { + "message": "시드 생성중..." }, "gasPrice": { "message": "가스 가격 (GWEI)" @@ -253,21 +346,27 @@ "gasPriceRequired": { "message": "가스 가격이 필요합니다." }, + "generatingTransaction": { + "message": "트랜잭션 생성중" + }, "getEther": { "message": "이더 얻기" }, "getEtherFromFaucet": { - "message": "faucet에서 $1에 달하는 이더를 얻으세요.", - "description": "Displays network name for Ether faucet" + "message": "파우셋에서 $1에 달하는 이더를 얻으세요.", + "description": "이더 파우셋에 대한 네트워크 이름을 표시합니다" }, "greaterThanMin": { "message": "$1 이상이어야 합니다.", - "description": "helper for inputting hex as decimal input" + "description": "10진수 입력으로 hex값 입력을 도와줍니다" }, "here": { "message": "여기", "description": "as in -click here- for more information (goes with troubleTokenBalances)" }, + "hereList": { + "message": "리스트가 있습니다!!!!" + }, "hide": { "message": "숨기기" }, @@ -280,51 +379,96 @@ "howToDeposit": { "message": "어떤 방법으로 이더를 입금하시겠습니까?" }, + "holdEther": { + "message": "It allows you to hold ether & tokens, and serves as your bridge to decentralized applications." + }, "import": { - "message": "파일에서 가져오기", - "description": "Button to import an account from a selected file" + "message": "가져오기", + "description": "선택된 파일로부터 계정 가져오기 버튼" }, "importAccount": { - "message": "계좌 가져오기" + "message": "계정 가져오기" + }, + "importAccountMsg": { + "message": " 가져온 계정은 메타마스크에서 원래 생성된 계정의 시드구문과 연관성이 없습니다. 가져온 계정에 대해 더 배우기 " }, "importAnAccount": { - "message": "계좌 가져오기" + "message": "계정 가져오기" }, "importDen": { - "message": "기존 DEN 가져오기" + "message": "기존의 DEN 가져오기" }, "imported": { - "message": "가져오기 완료", - "description": "status showing that an account has been fully loaded into the keyring" + "message": "가져온 계정", + "description": "이 상태는 해당 계정이 keyring으로 완전히 적재된 상태임을 표시합니다" + }, + "importUsingSeed": { + "message": "계정 시드 구문으로 가져오기" }, "infoHelp": { "message": "정보 및 도움말" }, + "initialTransactionConfirmed": { + "message": "초기 트랜잭션이 네트워크를 통해 확정되었습니다. 확인을 누르고 이전으로 돌아갑니다." + }, + "insufficientFunds": { + "message": "충분하지 않은 자금." + }, + "insufficientTokens": { + "message": "충분하지 않은 토큰." + }, "invalidAddress": { - "message": "유효하지 않은 주소" + "message": "올바르지 않은 주소" + }, + "invalidAddressRecipient": { + "message": "수신 주소가 올바르지 않습니다" }, "invalidGasParams": { - "message": "유효하지 않은 가스 입력값" + "message": "올바르지 않은 가스 입력값" }, "invalidInput": { - "message": "유효하지 않은 입력값" + "message": "올바르지 않은 입력값" }, "invalidRequest": { "message": "유효하지 않은 요청" }, + "invalidRPC": { + "message": "올바르지 않은 RPC URI" + }, + "jsonFail": { + "message": "이상이 있습니다. JSON 파일이 올바른 파일인지 확인해주세요." + }, "jsonFile": { "message": "JSON 파일", - "description": "format for importing an account" + "description": "계정을 가져오기 위한 형식" + }, + "keepTrackTokens": { + "message": "메타마스크 계정을 통해 구입한 토큰 기록을 추적 및 보관합니다." }, "kovan": { "message": "Kovan 테스트넷" }, + "knowledgeDataBase": { + "message": "지식 베이스 방문" + }, + "max": { + "message": "최대" + }, + "learnMore": { + "message": "더 배우기." + }, "lessThanMax": { "message": "$1 이하여야합니다.", - "description": "helper for inputting hex as decimal input" + "description": "10진수 입력으로 hex값 입력을 도와줍니다" + }, + "likeToAddTokens": { + "message": "토큰을 추가하시겠습니까?" + }, + "links": { + "message": "링크" }, "limit": { - "message": "리밋" + "message": "한도" }, "loading": { "message": "로딩중..." @@ -335,11 +479,17 @@ "localhost": { "message": "로컬호스트 8545" }, + "login": { + "message": "로그인" + }, "logout": { "message": "로그아웃" }, "loose": { - "message": "외부 비밀키" + "message": "느슨함" + }, + "loweCaseWords": { + "message": "시드 단어는 소문자만 가능합니다" }, "mainnet": { "message": "이더리움 메인넷" @@ -347,94 +497,127 @@ "message": { "message": "메시지" }, + "metamaskDescription": { + "message": "메타마스크는 이더리움을 위한 안전한 신분 저장소입니다." + }, + "metamaskSeedWords": { + "message": "메타마스크 시드 단어" + }, "min": { "message": "최소" }, "myAccounts": { - "message": "내 계좌" + "message": "내 계정" + }, + "mustSelectOne": { + "message": "적어도 하나의 토큰을 선택하세요." }, "needEtherInWallet": { - "message": "dApp을 이용하기 위해서는 지갑에 이더가 있어야 합니다." + "message": "메타마스크를 통한 dApp을 이용하기 위해서는 지갑에 이더가 있어야 합니다." }, "needImportFile": { "message": "가져올 파일을 선택해주세요.", - "description": "User is important an account and needs to add a file to continue" + "description": "사용자는 계정을 가져오기 위해서 파일을 추가후 계속 진행해야 합니다" }, "needImportPassword": { - "message": "선택 된 파일에 패스워드를 입력해주세요.", - "description": "Password and file needed to import an account" + "message": "선택 된 파일에 대한 비밀번호를 입력해주세요.", + "description": "계정을 가져오기 위해서 비밀번호와 파일이 필요합니다." + }, + "negativeETH": { + "message": "음수값의 이더를 보낼 수 없습니다." }, "networks": { "message": "네트워크" }, + "nevermind": { + "message": "상관안함" + }, "newAccount": { - "message": "새 계좌" + "message": "새 계정" }, "newAccountNumberName": { - "message": "새 계좌 $1", - "description": "Default name of next account to be created on create account screen" + "message": "새 계정 $1", + "description": "계정 생성시 볼 수 있는 새 계정의 기본 이름" }, "newContract": { "message": "새 컨트랙트" }, "newPassword": { - "message": "새 패스워드 (최소 8자 이상)" + "message": "새 비밀번호 (최소 8자 이상)" }, "newRecipient": { "message": "받는 사람" }, + "newRPC": { + "message": "새로운 RPC URL" + }, "next": { "message": "다음" }, "noAddressForName": { - "message": "이 이름에는 주소가 설정되어 있지 않습니다." + "message": "이 이름에 대해 주소가 설정되어 있지 않습니다." }, "noDeposits": { - "message": "입금이 없습니다." + "message": "입금 내역이 없습니다." }, "noTransactionHistory": { "message": "트랜잭션 기록이 없습니다." }, "noTransactions": { - "message": "트랜잭션이 없습니다." + "message": "트랜잭션이 없습니다" }, "notStarted": { - "message": "시작되지 않음." + "message": "시작 안됨" }, "oldUI": { - "message": "구버전의 UI" + "message": "구버전 UI" }, "oldUIMessage": { - "message": "구버전 UI로 변경하셨습니다. 우 상단 드랍다운 메뉴에서 새 UI로 변경하실 수 있습니다." + "message": "구버전 UI로 변경하셨습니다. 우 상단 드롭다운 메뉴에서 새 UI로 변경하실 수 있습니다." }, "or": { "message": "또는", - "description": "choice between creating or importing a new account" + "description": "새 계정을 만들거나 가져오기중에 선택하기" + }, + "password": { + "message": "비밀번호" + }, + "passwordCorrect": { + "message": "비밀번호가 맞는지 확인해주세요." }, "passwordMismatch": { - "message": "패스워드가 일치하지 않습니다.", - "description": "in password creation process, the two new password fields did not match" + "message": "비밀번호가 일치하지 않습니다.", + "description": "비밀번호를 생성하는 과정에서 두개의 새 비밀번호 입력란이 일치하지 않습니다" }, "passwordShort": { - "message": "패스워드가 너무 짧습니다.", - "description": "in password creation process, the password is not long enough to be secure" + "message": "비밀번호가 짧습니다.", + "description": "비밀번호를 생성하는 과정에서 비밀번호가 짧으면 안전하지 않습니다" }, "pastePrivateKey": { - "message": "비밀키를 입력해주세요.", - "description": "For importing an account from a private key" + "message": "개인키를 입력해주세요:", + "description": "개인키로부터 계정을 가져오는 것입니다" }, "pasteSeed": { - "message": "시드 문장들을 붙여넣어주세요." + "message": "시드 구문을 이곳에 붙여넣어주세요!" + }, + "personalAddressDetected": { + "message": "개인 주소가 탐지됨. 토큰 컨트랙트 주소를 입력하세요." }, "pleaseReviewTransaction": { "message": "트랜잭션을 검토해주세요." }, + "popularTokens": { + "message": "인기있는 토큰" + }, + "privacyMsg": { + "message": "개인정보 보호 정책" + }, "privateKey": { - "message": "비밀키", - "description": "select this type of file to use to import an account" + "message": "개인키", + "description": "이 형식의 파일을 선택하여 계정을 가져올 수 있습니다" }, "privateKeyWarning": { - "message": " 절대 이 키를 노출하지 마십시오. 비밀키가 노출되면 누구나 당신의 계좌에서 자산을 빼갈 수 있습니다." + "message": " 절대 이 키를 노출하지 마십시오. 개인키가 노출되면 누구나 당신의 계정에서 자산을 빼갈 수 있습니다." }, "privateNetwork": { "message": "프라이빗 네트워크" @@ -446,28 +629,64 @@ "message": "옵션 메뉴에서 “토큰 추가”를 눌러서 추후에 다시 이 토큰을 추가하실 수 있습니다." }, "readMore": { - "message": "더 읽기." + "message": "여기서 더 보기." + }, + "readMore2": { + "message": "더 보기." }, "receive": { "message": "받기" }, "recipientAddress": { - "message": "받는 사람 주소" + "message": "받는 주소" }, "refundAddress": { "message": "환불받을 주소" }, "rejected": { - "message": "거부되었음." + "message": "거부됨" + }, + "reset": { + "message": "초기화" + }, + "resetAccount": { + "message": "계정 초기화" + }, + "resetAccountDescription": { + "message": "계정을 초기화 하는 경우에 트랜잭션 기록이 삭제됩니다." + }, + "restoreFromSeed": { + "message": "계정을 복구하시겠습니까?" + }, + "restoreVault": { + "message": "저장소 복구" }, "required": { - "message": "필요함." + "message": "필요함" }, "retryWithMoreGas": { - "message": "더 높은 가스 가격으로 다시 시도해주세요." + "message": "더 높은 가스 가격으로 다시 시도해주세요" + }, + "walletSeed": { + "message": "지갑 시드값" + }, + "revealSeedWords": { + "message": "시드 단어 보이기" + }, + "revealSeedWordsTitle": { + "message": "시드 단어" + }, + "revealSeedWordsDescription": { + "message": "브라우저를 바꾸거나 컴퓨터를 옮기는 경우 이 시드 구문이 필요하며 이를 통해 계정에 접근할 수 있습니다. 시드 구문을 안전한 곳에 보관하세요." + }, + "revealSeedWordsWarningTitle": { + "message": "이 구문을 다른사람과 절대로 공유하지 마세요!" + }, + "revealSeedWordsWarning": { + "message": "이 단어모음은 당신의 모든 계정을 훔치는데 사용할 수 있습니다." }, "revert": { - "message": "취소" + "message": "되돌림" }, "rinkeby": { "message": "Rinkeby 테스트넷" @@ -478,46 +697,122 @@ "ropsten": { "message": "Ropsten 테스트넷" }, + "rpc": { + "message": "사용자 정의 RPC" + }, + "currentRpc": { + "message": "현재 RPC" + }, + "connectingToMainnet": { + "message": "이더리움 메인넷 접속중" + }, + "connectingToRopsten": { + "message": "Ropsten 테스트넷 접속중" + }, + "connectingToKovan": { + "message": "Kovan 테스트넷 접속중" + }, + "connectingToRinkeby": { + "message": "Rinkeby 테스트넷 접속중" + }, + "connectingToUnknown": { + "message": "알려지지 않은 네트워크 접속중" + }, "sampleAccountName": { - "message": "예) 나의 새 계좌", - "description": "Help user understand concept of adding a human-readable name to their account" + "message": "예) 나의 새 계정", + "description": "각 계정에 대해서 구별하기 쉬운 이름을 지정하여 사용자가 쉽게 이해할 수 있게 합니다" }, "save": { "message": "저장" }, + "speedUpTitle": { + "message": "트랜잭션 속도 향상하기" + }, + "speedUpSubtitle": { + "message": "트랜잭션 가스 가격을 늘려서 해당 트랙잭션에 덮어쓰기 하여 속도를 빠르게 합니다" + }, + "saveAsCsvFile": { + "message": "CSV 파일로 저장" + }, "saveAsFile": { "message": "파일로 저장", - "description": "Account export process" + "description": "계정 내보내기 절차" + }, + "saveSeedAsFile": { + "message": "시드 단어를 파일로 저장하기" + }, + "search": { + "message": "검색" + }, + "searchResults": { + "message": "검색 결과" + }, + "secretPhrase": { + "message": "12개 단어로 구성된 비밀 구문을 입력하여 저장소를 복구하세요." + }, + "newPassword8Chars": { + "message": "새 비밀번호 (최소 8문자)" + }, + "seedPhraseReq": { + "message": "시드 구문은 12개의 단어입니다" + }, + "select": { + "message": "선택" + }, + "selectCurrency": { + "message": "통화 선택" }, "selectService": { "message": "서비스 선택" }, + "selectType": { + "message": "형식 선택" + }, "send": { "message": "전송" }, + "sendETH": { + "message": "ETH 보내기" + }, "sendTokens": { "message": "토큰 전송" }, + "onlySendToEtherAddress": { + "message": "이더리움 주소로 ETH만 송금하세요." + }, + "onlySendTokensToAccountAddress": { + "message": "이더리움계정 주소로 $1 만 보내기.", + "description": "토큰 심볼 보이기" + }, + "searchTokens": { + "message": "토큰 검색" + }, "sendTokensAnywhere": { - "message": "이더 계좌로 토큰 전송" + "message": "이더 계정로 토큰 전송" }, "settings": { "message": "설정" }, + "info": { + "message": "정보" + }, "shapeshiftBuy": { "message": "Shapeshift를 통해서 구매하기" }, "showPrivateKeys": { - "message": "비밀키 보기" + "message": "개인키 보기" }, "showQRCode": { - "message": "QR코드 보기" + "message": "QR 코드 보기" }, "sign": { "message": "서명" }, + "signed": { + "message": "서명됨" + }, "signMessage": { - "message": "서명 메시지" + "message": "메시지 서명" }, "signNotice": { "message": "이 메시지에 대한 서명은 위험할 수 있습니다.\n 완전히 신뢰할 수 있는 사이트에서만 서명해주세요.\n 안전을 위해 추후의 버전에서는 삭제될 기능입니다. " @@ -526,33 +821,81 @@ "message": "서명 요청" }, "sigRequested": { - "message": "서명이 요청되었습니다." + "message": "서명이 요청됨" + }, + "spaceBetween": { + "message": "단어 사이에는 공백만 올 수 있습니다" }, "status": { "message": "상태" }, + "stateLogs": { + "message": "상태 로그" + }, + "stateLogsDescription": { + "message": "상태 로그에는 공개 계정 주소와 송신 트랜잭션 정보가 들어있습니다." + }, + "stateLogError": { + "message": "상태 로그 받기 실패." + }, "submit": { "message": "제출" }, + "submitted": { + "message": "제출됨" + }, + "supportCenter": { + "message": "지원 센터에 방문하기" + }, + "symbolBetweenZeroTen": { + "message": "심볼은 0에서 10개 사이의 문자여야 합니다." + }, "takesTooLong": { "message": "너무 오래걸리나요?" }, + "terms": { + "message": "사용 지침" + }, "testFaucet": { - "message": "Faucet 테스트" + "message": "파우셋 테스트" }, "to": { - "message": "대상" + "message": "받는이: " }, "toETHviaShapeShift": { "message": "ShapeShift를 통해 $1를 ETH로 바꾸기", - "description": "system will fill in deposit type in start of message" + "description": "시스템이 시작할 때에 입금 유형을 입력해줍니다" + }, + "token": { + "message": "토큰" + }, + "tokenAddress": { + "message": "토큰 주소" + }, + "tokenAlreadyAdded": { + "message": "토큰이 이미 추가되어있습니다." }, "tokenBalance": { - "message": "현재 토큰 잔액: " + "message": "현재 토큰 잔액:" + }, + "tokenSelection": { + "message": "토큰을 검색하거나 유명한 토큰 리스트에서 선택하시기 바랍니다." + }, + "tokenSymbol": { + "message": "토큰 기호" + }, + "tokenWarning1": { + "message": "메타마스크 계좌를 통해 구입한 토큰을 추적합니다. 다른 계정으로 토큰을 구입한 경우 이곳에 나타나지 않습니다." }, "total": { "message": "합계" }, + "transactions": { + "message": "트랜잭션" + }, + "transactionError": { + "message": "트랜잭션 오류. 컨트랙트 코드에서 예외 발생(Exception thrown)." + }, "transactionMemo": { "message": "트랜잭션 메모 (선택사항)" }, @@ -563,23 +906,29 @@ "message": "전송" }, "troubleTokenBalances": { - "message": "토큰 잔액을 가져오는데에 문제가 생겼습니다. (여기)서 상세내용을 볼 수 있습니다.", - "description": "Followed by a link (here) to view token balances" + "message": "토큰 잔액을 가져오는데에 문제가 생겼습니다. 링크에서 상세내용을 볼 수 있습니다.", + "description": "토큰 잔액을 보려면 (here) 링크를 따라가세요" + }, + "twelveWords": { + "message": "12개의 단어는 메타마스크 계정을 복구하기 위한 유일한 방법입니다.\n안전한 장소에 보관하시기 바랍니다." }, "typePassword": { - "message": "패스워드를 입력하세요." + "message": "비밀번호를 입력하세요" }, "uiWelcome": { - "message": "새 UI에 오신 것을 환영합니다. (베타)" + "message": "새로운 UI에 오신 것을 환영합니다. (Beta)" }, "uiWelcomeMessage": { - "message": "새 메타마스크 UI를 사용하고 계십니다. 토큰 전송과 같은 새 기능들을 사용해보시면서 문제가 있다면 알려주세요." + "message": "새로운 메타마스크 UI를 사용하고 계십니다. 토큰 전송과 같은 새 기능들을 사용해보시면서 문제가 있다면 알려주세요." + }, + "unapproved": { + "message": "허가안됨" }, "unavailable": { - "message": "유효하지 않은" + "message": "유효하지 않음" }, "unknown": { - "message": "알려지지 않은" + "message": "알려지지 않음" }, "unknownNetwork": { "message": "알려지지 않은 프라이빗 네트워크" @@ -587,19 +936,46 @@ "unknownNetworkId": { "message": "알려지지 않은 네트워크 ID" }, + "unlockMessage": { + "message": "우리가 기다리던 분권형 웹입니다" + }, + "uriErrorMsg": { + "message": "URI는 HTTP/HTTPS로 시작해야 합니다." + }, "usaOnly": { "message": "USA 거주자 한정", - "description": "Using this exchange is limited to people inside the USA" + "description": "해당 거래소는 USA거주자에 한해서만 사용가능합니다" }, "usedByClients": { - "message": "다양한 클라이언트에서 사용되고 있습니다." + "message": "다양한 클라이언트에서 사용되고 있습니다" + }, + "useOldUI": { + "message": "예전 UI 사용" + }, + "validFileImport": { + "message": "가져오기 위해 유효한 파일을 선택해야 합니다." + }, + "vaultCreated": { + "message": "저장소가 생성됨" }, "viewAccount": { - "message": "계좌 보기" + "message": "계정 보기" + }, + "viewOnEtherscan": { + "message": "이터스캔에서 보기" + }, + "visitWebSite": { + "message": "웹사이트 방문" }, "warning": { "message": "경고" }, + "welcomeBack": { + "message": "환영합니다!" + }, + "welcomeBeta": { + "message": "메타마스크 Beta에 오신 것을 환영합니다" + }, "whatsThis": { "message": "이것은 무엇인가요?" }, @@ -607,6 +983,204 @@ "message": "서명이 요청되고 있습니다." }, "youSign": { - "message": "서명 중입니다." + "message": "서명 중입니다" + }, + "yourPrivateSeedPhrase": { + "message": "개인 시드 구문" + }, + "accessingYourCamera": { + "message": "카메라 접근중..." + }, + "accountSelectionRequired": { + "message": "계정을 선택하셔야 합니다!" + }, + "approve": { + "message": "수락" + }, + "browserNotSupported": { + "message": "브라우저가 지원하지 않습니다..." + }, + "bytes": { + "message": "바이트" + }, + "chromeRequiredForHardwareWallets": { + "message": "하드웨어 지갑을 연결하기 위해서는 구글 크롬에서 메타마스크를 사용하셔야 합니다." + }, + "connectHardwareWallet": { + "message": "하드웨어 지갑 연결" + }, + "connect": { + "message": "연결" + }, + "connecting": { + "message": "연결중..." + }, + "connectToLedger": { + "message": "Ledger 연결" + }, + "connectToTrezor": { + "message": "Trezor 연결" + }, + "copyAddress": { + "message": "클립보드로 주소 복사" + }, + "downloadGoogleChrome": { + "message": "구글 크롬 다운로드" + }, + "dontHaveAHardwareWallet": { + "message": "하드웨어 지갑이 없나요?" + }, + "ensNameNotFound": { + "message": "ENS 이름을 찾을 수 없습니다" + }, + "parameters": { + "message": "매개변수" + }, + "forgetDevice": { + "message": "장치 연결 해제" + }, + "functionType": { + "message": "함수 유형" + }, + "getHelp": { + "message": "도움말" + }, + "hardware": { + "message": "하드웨어" + }, + "hardwareWalletConnected": { + "message": "하드웨어 지갑이 연결됨" + }, + "hardwareWallets": { + "message": "하드웨어 지갑 연결" + }, + "hardwareWalletsMsg": { + "message": "메타마스크에서 사용할 하드웨어 지갑을 선택해주세요" + }, + "havingTroubleConnecting": { + "message": "연결에 문제가 있나요?" + }, + "hexData": { + "message": "Hex 데이터" + }, + "invalidSeedPhrase": { + "message": "잘못된 시드 구문" + }, + "ledgerAccountRestriction": { + "message": "새 계정을 추가하려면 최소 마지막 계정을 사용해야 합니다." + }, + "menu": { + "message": "메뉴" + }, + "noConversionRateAvailable": { + "message": "변환 비율을 찾을 수 없습니다" + }, + "notFound": { + "message": "찾을 수 없음" + }, + "noWebcamFoundTitle": { + "message": "웹캠이 없습니다" + }, + "noWebcamFound": { + "message": "컴퓨터의 웹캠을 찾을 수 없습니다. 다시 시도해보세요." + }, + "openInTab": { + "message": "탭으로 열기" + }, + "origin": { + "message": "Origin" + }, + "prev": { + "message": "이전" + }, + "restoreAccountWithSeed": { + "message": "시드 구문으로 계정 복구하기" + }, + "restore": { + "message": "복구" + }, + "remove": { + "message": "제거" + }, + "removeAccount": { + "message": "계정 제거" + }, + "removeAccountDescription": { + "message": "이 계정한 지갑에서 삭제될 것입니다. 지우기 전에 이 계정에 대한 개인 키 혹은 시드 구문을 가지고 있는지 확인하세요. 계정 드랍다운 메뉴를 통해서 계정을 가져오거나 생성할 수 있습니다." + }, + "readyToConnect": { + "message": "접속 준비되었나요?" + }, + "separateEachWord": { + "message": "각 단어는 공백 한칸으로 분리합니다" + }, + "orderOneHere": { + "message": "Trezor 혹은 Ledger를 구입하고 자금을 콜드 스토리지에 저장합니다" + }, + "selectAnAddress": { + "message": "주소 선택" + }, + "selectAnAccount": { + "message": "계정 선택" + }, + "selectAnAccountHelp": { + "message": "메타마스크에서 보기위한 계정 선택" + }, + "selectHdPath": { + "message": "HD 경로 지정" + }, + "selectPathHelp": { + "message": "하단에서 Ledger지갑 계정을 찾지 못하겠으면 \"Legacy (MEW / MyCrypto)\" 경로로 바꿔보세요" + }, + "step1HardwareWallet": { + "message": "1. 하드웨어 지갑 연결" + }, + "step1HardwareWalletMsg": { + "message": "하드웨어 지갑을 컴퓨터에 연결해주세요." + }, + "step2HardwareWallet": { + "message": "2. 계정 선택" + }, + "step2HardwareWalletMsg": { + "message": "보고 싶은 계정을 선택합니다. 한번에 하나의 계정만 선택할 수 있습니다." + }, + "step3HardwareWallet": { + "message": "3. dApps을 사용하거나 다른 것을 합니다!" + }, + "step3HardwareWalletMsg": { + "message": "다른 이더리움 계정을 사용하듯 하드웨어 계정을 사용합니다. dApps을 로그인하거나, 이더를 보내거나, ERC20토큰 혹은 대체가능하지 않은 토큰 (예를 들어 CryptoKitties)을 사거나 저장하거나 합니다." + }, + "scanInstructions": { + "message": "QR 코드를 카메라 앞에 가져다 놓아주세요" + }, + "scanQrCode": { + "message": "QR 코드 스캔" + }, + "transfer": { + "message": "전송" + }, + "trezorHardwareWallet": { + "message": "TREZOR 하드웨어 지갑" + }, + "tryAgain": { + "message": "다시 시도하세요" + }, + "unknownFunction": { + "message": "알 수 없는 함수" + }, + "unknownQrCode": { + "message": "오류: QR 코드를 확인할 수 없습니다" + }, + "unknownCameraErrorTitle": { + "message": "이런! 뭔가 잘못되었습니다...." + }, + "unknownCameraError": { + "message": "카메라를 접근하는 중 오류가 발생했습니다. 다시 시도해 주세요..." + }, + "unlock": { + "message": "잠금 해제" + }, + "youNeedToAllowCameraAccess": { + "message": "이 기능을 사용하려면 카메라 접근을 허용해야 합니다." } } diff --git a/app/_locales/ru/messages.json b/app/_locales/ru/messages.json index 5b5cc1f17..d349013f1 100644 --- a/app/_locales/ru/messages.json +++ b/app/_locales/ru/messages.json @@ -790,7 +790,7 @@ "message": "Тестовый кран" }, "to": { - "message": "Получатель: " + "message": "Получатель" }, "toETHviaShapeShift": { "message": "$1 в ETH через ShapeShift", diff --git a/app/_locales/tml/messages.json b/app/_locales/tml/messages.json index 8961de5a2..ca9778a79 100644 --- a/app/_locales/tml/messages.json +++ b/app/_locales/tml/messages.json @@ -802,7 +802,7 @@ "message": "சோதனை குழாய்" }, "to": { - "message": "பெறுநர்: " + "message": "பெறுநர்" }, "toETHviaShapeShift": { "message": "$ 1 முதல் ETH வரை வடிவம்", diff --git a/app/_locales/tr/messages.json b/app/_locales/tr/messages.json index 3c6cfed4e..d699dc9ab 100644 --- a/app/_locales/tr/messages.json +++ b/app/_locales/tr/messages.json @@ -802,7 +802,7 @@ "message": "Test Musluğu" }, "to": { - "message": "Kime: " + "message": "Kime" }, "toETHviaShapeShift": { "message": "ShapeShift üstünden $1'dan ETH'e", diff --git a/app/_locales/zh_CN/messages.json b/app/_locales/zh_CN/messages.json index 5da9806a0..a8d50238b 100644 --- a/app/_locales/zh_CN/messages.json +++ b/app/_locales/zh_CN/messages.json @@ -23,6 +23,9 @@ "addTokens": { "message": "添加代币" }, + "addAcquiredTokens": { + "message": "在Metamask上添加已用的代币" + }, "amount": { "message": "数量" }, @@ -116,6 +119,9 @@ "confirmTransaction": { "message": "确认交易" }, + "connectHardwareWallet": { + "message": "链接硬件钱包" + }, "continue": { "message": "继续" }, @@ -720,6 +726,9 @@ "search": { "message": "搜索" }, + "searchResults": { + "message": "搜索结果" + }, "secretPhrase": { "message": "输入12位助记词以恢复金库." }, diff --git a/app/images/arrow-popout.svg b/app/images/arrow-popout.svg new file mode 100644 index 000000000..7e25f7cd2 --- /dev/null +++ b/app/images/arrow-popout.svg @@ -0,0 +1,3 @@ + + + diff --git a/app/images/metamask-fox.svg b/app/images/logo/metamask-fox.svg similarity index 100% rename from app/images/metamask-fox.svg rename to app/images/logo/metamask-fox.svg diff --git a/app/images/logo/metamask-logo-horizontal-beta.svg b/app/images/logo/metamask-logo-horizontal-beta.svg new file mode 100644 index 000000000..b1fa040ac --- /dev/null +++ b/app/images/logo/metamask-logo-horizontal-beta.svg @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/phishing.html b/app/phishing.html index e20c9ac9c..dc8f61a93 100644 --- a/app/phishing.html +++ b/app/phishing.html @@ -43,7 +43,7 @@ ga('create', 'UA-68598031-1', 'auto' {'allowLinker':true}); ga('send', 'pageview'); ga('require', 'linker'); - ga('linker:autoLink', ['harrydenley.com', 'metamask.io'], false, true); + ga('linker:autoLink', ['metamask.io'], false, true); diff --git a/app/scripts/background.js b/app/scripts/background.js index 77bd9a373..46b26f1c0 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -15,11 +15,11 @@ const asStream = require('obs-store/lib/asStream') const ExtensionPlatform = require('./platforms/extension') const Migrator = require('./lib/migrator/') const migrations = require('./migrations/') -const PortStream = require('./lib/port-stream.js') +const PortStream = require('extension-port-stream') const createStreamSink = require('./lib/createStreamSink') const NotificationManager = require('./lib/notification-manager.js') const MetamaskController = require('./metamask-controller') -const firstTimeState = require('./first-time-state') +const rawFirstTimeState = require('./first-time-state') const setupRaven = require('./lib/setupRaven') const reportFailedTxToSentry = require('./lib/reportFailedTxToSentry') const setupMetamaskMeshMetrics = require('./lib/setupMetamaskMeshMetrics') @@ -34,6 +34,9 @@ const { ENVIRONMENT_TYPE_FULLSCREEN, } = require('./lib/enums') +// METAMASK_TEST_CONFIG is used in e2e tests to set the default network to localhost +const firstTimeState = Object.assign({}, rawFirstTimeState, global.METAMASK_TEST_CONFIG) + const STORAGE_KEY = 'metamask-config' const METAMASK_DEBUG = process.env.METAMASK_DEBUG @@ -253,6 +256,7 @@ function setupController (initState, initLangCode) { showUnconfirmedMessage: triggerUi, unlockAccountMessage: triggerUi, showUnapprovedTx: triggerUi, + showWatchAssetUi: showWatchAssetUi, // initial state initState, // initial locale code @@ -445,3 +449,28 @@ function triggerUi () { } }) } + +/** + * Opens the browser popup for user confirmation of watchAsset + * then it waits until user interact with the UI + */ +function showWatchAssetUi () { + triggerUi() + return new Promise( + (resolve) => { + var interval = setInterval(() => { + if (!notificationIsOpen) { + clearInterval(interval) + resolve() + } + }, 1000) + } + ) +} + +// On first install, open a window to MetaMask website to how-it-works. +extension.runtime.onInstalled.addListener(function (details) { + if ((details.reason === 'install') && (!METAMASK_DEBUG)) { + extension.tabs.create({url: 'https://metamask.io/#how-it-works'}) + } +}) diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index f2131f272..1a5f6efa0 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -5,7 +5,7 @@ const LocalMessageDuplexStream = require('post-message-stream') const PongStream = require('ping-pong-stream/pong') const ObjectMultiplex = require('obj-multiplex') const extension = require('extensionizer') -const PortStream = require('./lib/port-stream.js') +const PortStream = require('extension-port-stream') const inpageContent = fs.readFileSync(path.join(__dirname, '..', '..', 'dist', 'chrome', 'inpage.js')).toString() const inpageSuffix = '//# sourceURL=' + extension.extension.getURL('inpage.js') + '\n' diff --git a/app/scripts/controllers/balance.js b/app/scripts/controllers/balance.js index 4c97810a3..465751e61 100644 --- a/app/scripts/controllers/balance.js +++ b/app/scripts/controllers/balance.js @@ -80,7 +80,7 @@ class BalanceController { } }) this.accountTracker.store.subscribe(update) - this.blockTracker.on('block', update) + this.blockTracker.on('latest', update) } /** diff --git a/app/scripts/controllers/currency.js b/app/scripts/controllers/currency.js index 810c8d518..00e6ef117 100644 --- a/app/scripts/controllers/currency.js +++ b/app/scripts/controllers/currency.js @@ -1,4 +1,4 @@ - const ObservableStore = require('obs-store') +const ObservableStore = require('obs-store') const extend = require('xtend') const log = require('loglevel') diff --git a/app/scripts/controllers/network/createInfuraClient.js b/app/scripts/controllers/network/createInfuraClient.js new file mode 100644 index 000000000..41af4d9f9 --- /dev/null +++ b/app/scripts/controllers/network/createInfuraClient.js @@ -0,0 +1,25 @@ +const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware') +const createBlockReEmitMiddleware = require('eth-json-rpc-middleware/block-reemit') +const createBlockCacheMiddleware = require('eth-json-rpc-middleware/block-cache') +const createInflightMiddleware = require('eth-json-rpc-middleware/inflight-cache') +const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector') +const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware') +const createInfuraMiddleware = require('eth-json-rpc-infura') +const BlockTracker = require('eth-block-tracker') + +module.exports = createInfuraClient + +function createInfuraClient ({ network }) { + const infuraMiddleware = createInfuraMiddleware({ network }) + const blockProvider = providerFromMiddleware(infuraMiddleware) + const blockTracker = new BlockTracker({ provider: blockProvider }) + + const networkMiddleware = mergeMiddleware([ + createBlockCacheMiddleware({ blockTracker }), + createInflightMiddleware(), + createBlockReEmitMiddleware({ blockTracker, provider: blockProvider }), + createBlockTrackerInspectorMiddleware({ blockTracker }), + infuraMiddleware, + ]) + return { networkMiddleware, blockTracker } +} diff --git a/app/scripts/controllers/network/createJsonRpcClient.js b/app/scripts/controllers/network/createJsonRpcClient.js new file mode 100644 index 000000000..40c353f7f --- /dev/null +++ b/app/scripts/controllers/network/createJsonRpcClient.js @@ -0,0 +1,25 @@ +const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware') +const createFetchMiddleware = require('eth-json-rpc-middleware/fetch') +const createBlockRefMiddleware = require('eth-json-rpc-middleware/block-ref') +const createBlockCacheMiddleware = require('eth-json-rpc-middleware/block-cache') +const createInflightMiddleware = require('eth-json-rpc-middleware/inflight-cache') +const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector') +const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware') +const BlockTracker = require('eth-block-tracker') + +module.exports = createJsonRpcClient + +function createJsonRpcClient ({ rpcUrl }) { + const fetchMiddleware = createFetchMiddleware({ rpcUrl }) + const blockProvider = providerFromMiddleware(fetchMiddleware) + const blockTracker = new BlockTracker({ provider: blockProvider }) + + const networkMiddleware = mergeMiddleware([ + createBlockRefMiddleware({ blockTracker }), + createBlockCacheMiddleware({ blockTracker }), + createInflightMiddleware(), + createBlockTrackerInspectorMiddleware({ blockTracker }), + fetchMiddleware, + ]) + return { networkMiddleware, blockTracker } +} diff --git a/app/scripts/controllers/network/createLocalhostClient.js b/app/scripts/controllers/network/createLocalhostClient.js new file mode 100644 index 000000000..fecc512e8 --- /dev/null +++ b/app/scripts/controllers/network/createLocalhostClient.js @@ -0,0 +1,21 @@ +const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware') +const createFetchMiddleware = require('eth-json-rpc-middleware/fetch') +const createBlockRefMiddleware = require('eth-json-rpc-middleware/block-ref') +const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector') +const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware') +const BlockTracker = require('eth-block-tracker') + +module.exports = createLocalhostClient + +function createLocalhostClient () { + const fetchMiddleware = createFetchMiddleware({ rpcUrl: 'http://localhost:8545/' }) + const blockProvider = providerFromMiddleware(fetchMiddleware) + const blockTracker = new BlockTracker({ provider: blockProvider, pollingInterval: 1000 }) + + const networkMiddleware = mergeMiddleware([ + createBlockRefMiddleware({ blockTracker }), + createBlockTrackerInspectorMiddleware({ blockTracker }), + fetchMiddleware, + ]) + return { networkMiddleware, blockTracker } +} diff --git a/app/scripts/controllers/network/createMetamaskMiddleware.js b/app/scripts/controllers/network/createMetamaskMiddleware.js new file mode 100644 index 000000000..8b17829b7 --- /dev/null +++ b/app/scripts/controllers/network/createMetamaskMiddleware.js @@ -0,0 +1,43 @@ +const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware') +const createScaffoldMiddleware = require('json-rpc-engine/src/createScaffoldMiddleware') +const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') +const createWalletSubprovider = require('eth-json-rpc-middleware/wallet') + +module.exports = createMetamaskMiddleware + +function createMetamaskMiddleware ({ + version, + getAccounts, + processTransaction, + processEthSignMessage, + processTypedMessage, + processPersonalMessage, + getPendingNonce, +}) { + const metamaskMiddleware = mergeMiddleware([ + createScaffoldMiddleware({ + // staticSubprovider + eth_syncing: false, + web3_clientVersion: `MetaMask/v${version}`, + }), + createWalletSubprovider({ + getAccounts, + processTransaction, + processEthSignMessage, + processTypedMessage, + processPersonalMessage, + }), + createPendingNonceMiddleware({ getPendingNonce }), + ]) + return metamaskMiddleware +} + +function createPendingNonceMiddleware ({ getPendingNonce }) { + return createAsyncMiddleware(async (req, res, next) => { + if (req.method !== 'eth_getTransactionCount') return next() + const address = req.params[0] + const blockRef = req.params[1] + if (blockRef !== 'pending') return next() + req.result = await getPendingNonce(address) + }) +} diff --git a/app/scripts/controllers/network/network.js b/app/scripts/controllers/network/network.js index 1f04ce73f..97eea4cbc 100644 --- a/app/scripts/controllers/network/network.js +++ b/app/scripts/controllers/network/network.js @@ -1,15 +1,17 @@ const assert = require('assert') const EventEmitter = require('events') -const createMetamaskProvider = require('web3-provider-engine/zero.js') -const SubproviderFromProvider = require('web3-provider-engine/subproviders/provider.js') -const createInfuraProvider = require('eth-json-rpc-infura/src/createProvider') const ObservableStore = require('obs-store') const ComposedStore = require('obs-store/lib/composed') -const extend = require('xtend') const EthQuery = require('eth-query') -const createEventEmitterProxy = require('../../lib/events-proxy.js') +const JsonRpcEngine = require('json-rpc-engine') +const providerFromEngine = require('eth-json-rpc-middleware/providerFromEngine') const log = require('loglevel') -const urlUtil = require('url') +const createMetamaskMiddleware = require('./createMetamaskMiddleware') +const createInfuraClient = require('./createInfuraClient') +const createJsonRpcClient = require('./createJsonRpcClient') +const createLocalhostClient = require('./createLocalhostClient') +const { createSwappableProxy, createEventEmitterProxy } = require('swappable-obj-proxy') + const { ROPSTEN, RINKEBY, @@ -20,7 +22,6 @@ const { POA, DAI, } = require('./enums') -const LOCALHOST_RPC_URL = 'http://localhost:8545' const POA_RPC_URL = 'https://core.poa.network' const DAI_RPC_URL = 'https://dai.poa.network' const SOKOL_RPC_URL = 'https://sokol.poa.network' @@ -45,21 +46,27 @@ module.exports = class NetworkController extends EventEmitter { this.providerStore = new ObservableStore(providerConfig) this.networkStore = new ObservableStore('loading') this.store = new ComposedStore({ provider: this.providerStore, network: this.networkStore }) - // create event emitter proxy - this._proxy = createEventEmitterProxy() - this.on('networkDidChange', this.lookupNetwork) + // provider and block tracker + this._provider = null + this._blockTracker = null + // provider and block tracker proxies - because the network changes + this._providerProxy = null + this._blockTrackerProxy = null } - initializeProvider (_providerParams) { - this._baseProviderParams = _providerParams + initializeProvider (providerParams) { + this._baseProviderParams = providerParams const { type, rpcTarget } = this.providerStore.getState() this._configureProvider({ type, rpcTarget }) - this._proxy.on('block', this._logBlock.bind(this)) - this._proxy.on('error', this.verifyNetwork.bind(this)) - this.ethQuery = new EthQuery(this._proxy) this.lookupNetwork() - return this._proxy + } + + // return the proxies so the references will always be good + getProviderAndBlockTracker () { + const provider = this._providerProxy + const blockTracker = this._blockTrackerProxy + return { provider, blockTracker } } verifyNetwork () { @@ -81,10 +88,11 @@ module.exports = class NetworkController extends EventEmitter { lookupNetwork () { // Prevent firing when provider is not defined. - if (!this.ethQuery || !this.ethQuery.sendAsync) { - return log.warn('NetworkController - lookupNetwork aborted due to missing ethQuery') + if (!this._provider) { + return log.warn('NetworkController - lookupNetwork aborted due to missing provider') } - this.ethQuery.sendAsync({ method: 'net_version' }, (err, network) => { + const ethQuery = new EthQuery(this._provider) + ethQuery.sendAsync({ method: 'net_version' }, (err, network) => { if (err) return this.setNetworkState('loading') log.info('web3.getNetwork returned ' + network) this.setNetworkState(network) @@ -143,7 +151,7 @@ module.exports = class NetworkController extends EventEmitter { } else if (type === POA_SOKOL) { this._configureStandardProvider({ rpcUrl: SOKOL_RPC_URL }) } else if (type === LOCALHOST) { - this._configureStandardProvider({ rpcUrl: LOCALHOST_RPC_URL }) + this._configureLocalhostProvider() // url-based rpc endpoints } else if (type === 'rpc') { this._configureStandardProvider({ rpcUrl: rpcTarget }) @@ -153,49 +161,47 @@ module.exports = class NetworkController extends EventEmitter { } _configureInfuraProvider ({ type }) { - log.info('_configureInfuraProvider', type) - const infuraProvider = createInfuraProvider({ network: type }) - const infuraSubprovider = new SubproviderFromProvider(infuraProvider) - const providerParams = extend(this._baseProviderParams, { - engineParams: { - pollingInterval: 8000, - blockTrackerProvider: infuraProvider, - }, - dataSubprovider: infuraSubprovider, - }) - const provider = createMetamaskProvider(providerParams) - this._setProvider(provider) + log.info('NetworkController - configureInfuraProvider', type) + const networkClient = createInfuraClient({ network: type }) + this._setNetworkClient(networkClient) + } + + _configureLocalhostProvider () { + log.info('NetworkController - configureLocalhostProvider') + const networkClient = createLocalhostClient() + this._setNetworkClient(networkClient) } _configureStandardProvider ({ rpcUrl }) { - // urlUtil handles malformed urls - rpcUrl = urlUtil.parse(rpcUrl).format() - const providerParams = extend(this._baseProviderParams, { - rpcUrl, - engineParams: { - pollingInterval: 8000, - }, - }) - const provider = createMetamaskProvider(providerParams) - this._setProvider(provider) + log.info('NetworkController - configureStandardProvider', rpcUrl) + const networkClient = createJsonRpcClient({ rpcUrl }) + this._setNetworkClient(networkClient) } - _setProvider (provider) { - // collect old block tracker events - const oldProvider = this._provider - let blockTrackerHandlers - if (oldProvider) { - // capture old block handlers - blockTrackerHandlers = oldProvider._blockTracker.proxyEventHandlers - // tear down - oldProvider.removeAllListeners() - oldProvider.stop() + _setNetworkClient ({ networkMiddleware, blockTracker }) { + const metamaskMiddleware = createMetamaskMiddleware(this._baseProviderParams) + const engine = new JsonRpcEngine() + engine.push(metamaskMiddleware) + engine.push(networkMiddleware) + const provider = providerFromEngine(engine) + this._setProviderAndBlockTracker({ provider, blockTracker }) + } + + _setProviderAndBlockTracker ({ provider, blockTracker }) { + // update or intialize proxies + if (this._providerProxy) { + this._providerProxy.setTarget(provider) + } else { + this._providerProxy = createSwappableProxy(provider) } - // override block tracler - provider._blockTracker = createEventEmitterProxy(provider._blockTracker, blockTrackerHandlers) - // set as new provider + if (this._blockTrackerProxy) { + this._blockTrackerProxy.setTarget(blockTracker) + } else { + this._blockTrackerProxy = createEventEmitterProxy(blockTracker, { eventFilter: 'skipInternal' }) + } + // set new provider and blockTracker this._provider = provider - this._proxy.setTarget(provider) + this._blockTracker = blockTracker } _logBlock (block) { diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 0b1d6a8e9..5b3e1c1d9 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -1,5 +1,6 @@ const ObservableStore = require('obs-store') const normalizeAddress = require('eth-sig-util').normalize +const { isValidAddress } = require('ethereumjs-util') const extend = require('xtend') @@ -14,6 +15,7 @@ class PreferencesController { * @property {string} store.currentAccountTab Indicates the selected tab in the ui * @property {array} store.tokens The tokens the user wants display in their token lists * @property {object} store.accountTokens The tokens stored per account and then per network type + * @property {object} store.assetImages Contains assets objects related to assets added * @property {boolean} store.useBlockie The users preference for blockie identicons within the UI * @property {object} store.featureFlags A key-boolean map, where keys refer to features and booleans to whether the * user wishes to see that feature @@ -26,21 +28,42 @@ class PreferencesController { frequentRpcList: [], currentAccountTab: 'history', accountTokens: {}, + assetImages: {}, tokens: [], + suggestedTokens: {}, useBlockie: false, featureFlags: {}, currentLocale: opts.initLangCode, identities: {}, lostIdentities: {}, + seedWords: null, + forgottenPassword: false, }, opts.initState) this.diagnostics = opts.diagnostics this.network = opts.network this.store = new ObservableStore(initState) + this.showWatchAssetUi = opts.showWatchAssetUi this._subscribeProviderType() } // PUBLIC METHODS + /** + * Sets the {@code forgottenPassword} state property + * @param {boolean} forgottenPassword whether or not the user has forgotten their password + */ + setPasswordForgotten (forgottenPassword) { + this.store.updateState({ forgottenPassword }) + } + + /** + * Sets the {@code seedWords} seed words + * @param {string|null} seedWords the seed words + */ + setSeedWords (seedWords) { + this.store.updateState({ seedWords }) + } + /** * Setter for the `useBlockie` property * @@ -51,6 +74,53 @@ class PreferencesController { this.store.updateState({ useBlockie: val }) } + getSuggestedTokens () { + return this.store.getState().suggestedTokens + } + + getAssetImages () { + return this.store.getState().assetImages + } + + addSuggestedERC20Asset (tokenOpts) { + this._validateERC20AssetParams(tokenOpts) + const suggested = this.getSuggestedTokens() + const { rawAddress, symbol, decimals, image } = tokenOpts + const address = normalizeAddress(rawAddress) + const newEntry = { address, symbol, decimals, image } + suggested[address] = newEntry + this.store.updateState({ suggestedTokens: suggested }) + } + + /** + * RPC engine middleware for requesting new asset added + * + * @param req + * @param res + * @param {Function} - next + * @param {Function} - end + */ + async requestWatchAsset (req, res, next, end) { + if (req.method === 'metamask_watchAsset') { + const { type, options } = req.params + switch (type) { + case 'ERC20': + const result = await this._handleWatchAssetERC20(options) + if (result instanceof Error) { + end(result) + } else { + res.result = result + end() + } + break + default: + end(new Error(`Asset of type ${type} not supported`)) + } + } else { + next() + } + } + /** * Getter for the `useBlockie` property * @@ -186,6 +256,13 @@ class PreferencesController { return selected } + removeSuggestedTokens () { + return new Promise((resolve, reject) => { + this.store.updateState({ suggestedTokens: {} }) + resolve({}) + }) + } + /** * Setter for the `selectedAddress` property * @@ -232,11 +309,12 @@ class PreferencesController { * @returns {Promise} Promises the new array of AddedToken objects. * */ - async addToken (rawAddress, symbol, decimals, network) { + async addToken (rawAddress, symbol, decimals, image, network) { const address = normalizeAddress(rawAddress) const newEntry = { address, symbol, decimals, network } const tokens = this.store.getState().tokens + const assetImages = this.getAssetImages() const previousEntry = tokens.find((token, index) => { return (token.address === address && parseInt(token.network) === parseInt(network)) }) @@ -247,7 +325,8 @@ class PreferencesController { } else { tokens.push(newEntry) } - this._updateAccountTokens(tokens) + assetImages[address] = image + this._updateAccountTokens(tokens, assetImages) return Promise.resolve(tokens) } @@ -260,8 +339,10 @@ class PreferencesController { */ removeToken (rawAddress) { const tokens = this.store.getState().tokens + const assetImages = this.getAssetImages() const updatedTokens = tokens.filter(token => token.address !== rawAddress) - this._updateAccountTokens(updatedTokens) + delete assetImages[rawAddress] + this._updateAccountTokens(updatedTokens, assetImages) return Promise.resolve(updatedTokens) } @@ -398,6 +479,7 @@ class PreferencesController { // // PRIVATE METHODS // + /** * Subscription to network provider type. * @@ -416,10 +498,10 @@ class PreferencesController { * @param {array} tokens Array of tokens to be updated. * */ - _updateAccountTokens (tokens) { + _updateAccountTokens (tokens, assetImages) { const { accountTokens, providerType, selectedAddress } = this._getTokenRelatedStates() accountTokens[selectedAddress][providerType] = tokens - this.store.updateState({ accountTokens, tokens }) + this.store.updateState({ accountTokens, tokens, assetImages }) } /** @@ -449,6 +531,47 @@ class PreferencesController { const tokens = accountTokens[selectedAddress][providerType] return { tokens, accountTokens, providerType, selectedAddress } } + + /** + * Handle the suggestion of an ERC20 asset through `watchAsset` + * * + * @param {Promise} promise Promise according to addition of ERC20 token + * + */ + async _handleWatchAssetERC20 (options) { + const { address, symbol, decimals, image } = options + const rawAddress = address + try { + this._validateERC20AssetParams({ rawAddress, symbol, decimals }) + } catch (err) { + return err + } + const tokenOpts = { rawAddress, decimals, symbol, image } + this.addSuggestedERC20Asset(tokenOpts) + return this.showWatchAssetUi().then(() => { + const tokenAddresses = this.getTokens().filter(token => token.address === normalizeAddress(rawAddress)) + return tokenAddresses.length > 0 + }) + } + + /** + * Validates that the passed options for suggested token have all required properties. + * + * @param {Object} opts The options object to validate + * @throws {string} Throw a custom error indicating that address, symbol and/or decimals + * doesn't fulfill requirements + * + */ + _validateERC20AssetParams (opts) { + const { rawAddress, symbol, decimals } = opts + if (!rawAddress || !symbol || !decimals) throw new Error(`Cannot suggest token without address, symbol, and decimals`) + if (!(symbol.length < 6)) throw new Error(`Invalid symbol ${symbol} more than five characters`) + const numDecimals = parseInt(decimals, 10) + if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) { + throw new Error(`Invalid decimals ${decimals} must be at least 0, and not over 36`) + } + if (!isValidAddress(rawAddress)) throw new Error(`Invalid address ${rawAddress}`) + } } module.exports = PreferencesController diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js index 926268691..d270f6f44 100644 --- a/app/scripts/controllers/recent-blocks.js +++ b/app/scripts/controllers/recent-blocks.js @@ -1,14 +1,14 @@ const ObservableStore = require('obs-store') const extend = require('xtend') -const BN = require('ethereumjs-util').BN const EthQuery = require('eth-query') const log = require('loglevel') +const pify = require('pify') class RecentBlocksController { /** * Controller responsible for storing, updating and managing the recent history of blocks. Blocks are back filled - * upon the controller's construction and then the list is updated when the given block tracker gets a 'block' event + * upon the controller's construction and then the list is updated when the given block tracker gets a 'latest' event * (indicating that there is a new block to process). * * @typedef {Object} RecentBlocksController @@ -16,7 +16,7 @@ class RecentBlocksController { * @param {BlockTracker} opts.blockTracker Contains objects necessary for tracking blocks and querying the blockchain * @param {BlockTracker} opts.provider The provider used to create a new EthQuery instance. * @property {BlockTracker} blockTracker Points to the passed BlockTracker. On RecentBlocksController construction, - * listens for 'block' events so that new blocks can be processed and added to storage. + * listens for 'latest' events so that new blocks can be processed and added to storage. * @property {EthQuery} ethQuery Points to the EthQuery instance created with the passed provider * @property {number} historyLength The maximum length of blocks to track * @property {object} store Stores the recentBlocks @@ -34,7 +34,13 @@ class RecentBlocksController { }, opts.initState) this.store = new ObservableStore(initState) - this.blockTracker.on('block', this.processBlock.bind(this)) + this.blockTracker.on('latest', async (newBlockNumberHex) => { + try { + await this.processBlock(newBlockNumberHex) + } catch (err) { + log.error(err) + } + }) this.backfill() } @@ -55,7 +61,11 @@ class RecentBlocksController { * @param {object} newBlock The new block to modify and add to the recentBlocks array * */ - processBlock (newBlock) { + async processBlock (newBlockNumberHex) { + const newBlockNumber = Number.parseInt(newBlockNumberHex, 16) + const newBlock = await this.getBlockByNumber(newBlockNumber, true) + if (!newBlock) return + const block = this.mapTransactionsToPrices(newBlock) const state = this.store.getState() @@ -108,9 +118,9 @@ class RecentBlocksController { } /** - * On this.blockTracker's first 'block' event after this RecentBlocksController's instantiation, the store.recentBlocks + * On this.blockTracker's first 'latest' event after this RecentBlocksController's instantiation, the store.recentBlocks * array is populated with this.historyLength number of blocks. The block number of the this.blockTracker's first - * 'block' event is used to iteratively generate all the numbers of the previous blocks, which are obtained by querying + * 'latest' event is used to iteratively generate all the numbers of the previous blocks, which are obtained by querying * the blockchain. These blocks are backfilled so that the recentBlocks array is ordered from oldest to newest. * * Each iteration over the block numbers is delayed by 100 milliseconds. @@ -118,18 +128,17 @@ class RecentBlocksController { * @returns {Promise} Promises undefined */ async backfill () { - this.blockTracker.once('block', async (block) => { - const currentBlockNumber = Number.parseInt(block.number, 16) + this.blockTracker.once('latest', async (blockNumberHex) => { + const currentBlockNumber = Number.parseInt(blockNumberHex, 16) const blocksToFetch = Math.min(currentBlockNumber, this.historyLength) const prevBlockNumber = currentBlockNumber - 1 const targetBlockNumbers = Array(blocksToFetch).fill().map((_, index) => prevBlockNumber - index) await Promise.all(targetBlockNumbers.map(async (targetBlockNumber) => { try { - const newBlock = await this.getBlockByNumber(targetBlockNumber) + const newBlock = await this.getBlockByNumber(targetBlockNumber, true) + if (!newBlock) return - if (newBlock) { - this.backfillBlock(newBlock) - } + this.backfillBlock(newBlock) } catch (e) { log.error(e) } @@ -137,18 +146,6 @@ class RecentBlocksController { }) } - /** - * A helper for this.backfill. Provides an easy way to ensure a 100 millisecond delay using await - * - * @returns {Promise} Promises undefined - * - */ - async wait () { - return new Promise((resolve) => { - setTimeout(resolve, 100) - }) - } - /** * Uses EthQuery to get a block that has a given block number. * @@ -157,13 +154,8 @@ class RecentBlocksController { * */ async getBlockByNumber (number) { - const bn = new BN(number) - return new Promise((resolve, reject) => { - this.ethQuery.getBlockByNumber('0x' + bn.toString(16), true, (err, block) => { - if (err) reject(err) - resolve(block) - }) - }) + const blockNumberHex = '0x' + number.toString(16) + return await pify(this.ethQuery.getBlockByNumber).call(this.ethQuery, blockNumberHex, true) } } diff --git a/app/scripts/controllers/transactions/enums.js b/app/scripts/controllers/transactions/enums.js new file mode 100644 index 000000000..be6f16e0d --- /dev/null +++ b/app/scripts/controllers/transactions/enums.js @@ -0,0 +1,12 @@ +const TRANSACTION_TYPE_CANCEL = 'cancel' +const TRANSACTION_TYPE_RETRY = 'retry' +const TRANSACTION_TYPE_STANDARD = 'standard' + +const TRANSACTION_STATUS_APPROVED = 'approved' + +module.exports = { + TRANSACTION_TYPE_CANCEL, + TRANSACTION_TYPE_RETRY, + TRANSACTION_TYPE_STANDARD, + TRANSACTION_STATUS_APPROVED, +} diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index d9536213f..932bf0688 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -11,6 +11,14 @@ const txUtils = require('./lib/util') const cleanErrorStack = require('../../lib/cleanErrorStack') const log = require('loglevel') const recipientBlacklistChecker = require('./lib/recipient-blacklist-checker') +const { + TRANSACTION_TYPE_CANCEL, + TRANSACTION_TYPE_RETRY, + TRANSACTION_TYPE_STANDARD, + TRANSACTION_STATUS_APPROVED, +} = require('./enums') + +const { hexToBn, bnToHex } = require('../../lib/util') /** Transaction Controller is an aggregate of sub-controllers and trackers @@ -65,6 +73,7 @@ class TransactionController extends EventEmitter { this.store = this.txStateManager.store this.nonceTracker = new NonceTracker({ provider: this.provider, + blockTracker: this.blockTracker, getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), getConfirmedTransactions: this.txStateManager.getConfirmedTransactions.bind(this.txStateManager), }) @@ -78,13 +87,17 @@ class TransactionController extends EventEmitter { }) this.txStateManager.store.subscribe(() => this.emit('update:badge')) - this._setupListners() + this._setupListeners() // memstore is computed from a few different stores this._updateMemstore() this.txStateManager.store.subscribe(() => this._updateMemstore()) this.networkStore.subscribe(() => this._updateMemstore()) this.preferencesStore.subscribe(() => this._updateMemstore()) + + // request state update to finalize initialization + this._updatePendingTxsAfterFirstBlock() } + /** @returns {number} the chainId*/ getChainId () { const networkState = this.networkStore.getState() @@ -155,7 +168,10 @@ class TransactionController extends EventEmitter { const normalizedTxParams = txUtils.normalizeTxParams(txParams) txUtils.validateTxParams(normalizedTxParams) // construct txMeta - let txMeta = this.txStateManager.generateTxMeta({ txParams: normalizedTxParams }) + let txMeta = this.txStateManager.generateTxMeta({ + txParams: normalizedTxParams, + type: TRANSACTION_TYPE_STANDARD, + }) this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) @@ -209,12 +225,46 @@ class TransactionController extends EventEmitter { txParams: originalTxMeta.txParams, lastGasPrice, loadingDefaults: false, + type: TRANSACTION_TYPE_RETRY, }) this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) return txMeta } + /** + * Creates a new approved transaction to attempt to cancel a previously submitted transaction. The + * new transaction contains the same nonce as the previous, is a basic ETH transfer of 0x value to + * the sender's address, and has a higher gasPrice than that of the previous transaction. + * @param {number} originalTxId - the id of the txMeta that you want to attempt to cancel + * @param {string=} customGasPrice - the hex value to use for the cancel transaction + * @returns {txMeta} + */ + async createCancelTransaction (originalTxId, customGasPrice) { + const originalTxMeta = this.txStateManager.getTx(originalTxId) + const { txParams } = originalTxMeta + const { gasPrice: lastGasPrice, from, nonce } = txParams + const newGasPrice = customGasPrice || bnToHex(hexToBn(lastGasPrice).mul(1.1)) + const newTxMeta = this.txStateManager.generateTxMeta({ + txParams: { + from, + to: from, + nonce, + gas: '0x5208', + value: '0x0', + gasPrice: newGasPrice, + }, + lastGasPrice, + loadingDefaults: false, + status: TRANSACTION_STATUS_APPROVED, + type: TRANSACTION_TYPE_CANCEL, + }) + + this.addTx(newTxMeta) + await this.approveTransaction(newTxMeta.id) + return newTxMeta + } + /** updates the txMeta in the txStateManager @param txMeta {Object} - the updated txMeta @@ -311,6 +361,11 @@ class TransactionController extends EventEmitter { this.txStateManager.setTxStatusSubmitted(txId) } + confirmTransaction (txId) { + this.txStateManager.setTxStatusConfirmed(txId) + this._markNonceDuplicatesDropped(txId) + } + /** Convenience method for the ui thats sets the transaction to rejected @param txId {number} - the tx's Id @@ -354,6 +409,14 @@ class TransactionController extends EventEmitter { this.getFilteredTxList = (opts) => this.txStateManager.getFilteredTxList(opts) } + // called once on startup + async _updatePendingTxsAfterFirstBlock () { + // wait for first block so we know we're ready + await this.blockTracker.getLatestBlock() + // get status update for all pending transactions (for the current network) + await this.pendingTxTracker.updatePendingTxs() + } + /** If transaction controller was rebooted with transactions that are uncompleted in steps of the transaction signing or user confirmation process it will either @@ -375,7 +438,7 @@ class TransactionController extends EventEmitter { }) this.txStateManager.getFilteredTxList({ - status: 'approved', + status: TRANSACTION_STATUS_APPROVED, }).forEach((txMeta) => { const txSignError = new Error('Transaction found as "approved" during boot - possibly stuck during signing') this.txStateManager.setTxStatusFailed(txMeta.id, txSignError) @@ -386,14 +449,14 @@ class TransactionController extends EventEmitter { is called in constructor applies the listeners for pendingTxTracker txStateManager and blockTracker */ - _setupListners () { + _setupListeners () { this.txStateManager.on('tx:status-update', this.emit.bind(this, 'tx:status-update')) + this._setupBlockTrackerListener() this.pendingTxTracker.on('tx:warning', (txMeta) => { this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning') }) - this.pendingTxTracker.on('tx:confirmed', (txId) => this.txStateManager.setTxStatusConfirmed(txId)) - this.pendingTxTracker.on('tx:confirmed', (txId) => this._markNonceDuplicatesDropped(txId)) this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) + this.pendingTxTracker.on('tx:confirmed', (txId) => this.confirmTransaction(txId)) this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => { if (!txMeta.firstRetryBlockNumber) { txMeta.firstRetryBlockNumber = latestBlockNumber @@ -405,13 +468,6 @@ class TransactionController extends EventEmitter { txMeta.retryCount++ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:retry') }) - - this.blockTracker.on('block', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker)) - // this is a little messy but until ethstore has been either - // removed or redone this is to guard against the race condition - this.blockTracker.on('latest', this.pendingTxTracker.resubmitPendingTxs.bind(this.pendingTxTracker)) - this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker)) - } /** @@ -435,6 +491,40 @@ class TransactionController extends EventEmitter { }) } + _setupBlockTrackerListener () { + let listenersAreActive = false + const latestBlockHandler = this._onLatestBlock.bind(this) + const blockTracker = this.blockTracker + const txStateManager = this.txStateManager + + txStateManager.on('tx:status-update', updateSubscription) + updateSubscription() + + function updateSubscription () { + const pendingTxs = txStateManager.getPendingTransactions() + if (!listenersAreActive && pendingTxs.length > 0) { + blockTracker.on('latest', latestBlockHandler) + listenersAreActive = true + } else if (listenersAreActive && !pendingTxs.length) { + blockTracker.removeListener('latest', latestBlockHandler) + listenersAreActive = false + } + } + } + + async _onLatestBlock (blockNumber) { + try { + await this.pendingTxTracker.updatePendingTxs() + } catch (err) { + log.error(err) + } + try { + await this.pendingTxTracker.resubmitPendingTxs(blockNumber) + } catch (err) { + log.error(err) + } + } + /** Updates the memStore in transaction controller */ diff --git a/app/scripts/controllers/transactions/nonce-tracker.js b/app/scripts/controllers/transactions/nonce-tracker.js index 06f336eaa..421036368 100644 --- a/app/scripts/controllers/transactions/nonce-tracker.js +++ b/app/scripts/controllers/transactions/nonce-tracker.js @@ -12,8 +12,9 @@ const Mutex = require('await-semaphore').Mutex */ class NonceTracker { - constructor ({ provider, getPendingTransactions, getConfirmedTransactions }) { + constructor ({ provider, blockTracker, getPendingTransactions, getConfirmedTransactions }) { this.provider = provider + this.blockTracker = blockTracker this.ethQuery = new EthQuery(provider) this.getPendingTransactions = getPendingTransactions this.getConfirmedTransactions = getConfirmedTransactions @@ -34,7 +35,7 @@ class NonceTracker { * @typedef NonceDetails * @property {number} highestLocallyConfirmed - A hex string of the highest nonce on a confirmed transaction. * @property {number} nextNetworkNonce - The next nonce suggested by the eth_getTransactionCount method. - * @property {number} highetSuggested - The maximum between the other two, the number returned. + * @property {number} highestSuggested - The maximum between the other two, the number returned. */ /** @@ -80,15 +81,6 @@ class NonceTracker { } } - async _getCurrentBlock () { - const blockTracker = this._getBlockTracker() - const currentBlock = blockTracker.getCurrentBlock() - if (currentBlock) return currentBlock - return await new Promise((reject, resolve) => { - blockTracker.once('latest', resolve) - }) - } - async _globalMutexFree () { const globalMutex = this._lookupMutex('global') const releaseLock = await globalMutex.acquire() @@ -114,9 +106,8 @@ class NonceTracker { // calculate next nonce // we need to make sure our base count // and pending count are from the same block - const currentBlock = await this._getCurrentBlock() - const blockNumber = currentBlock.blockNumber - const baseCountBN = await this.ethQuery.getTransactionCount(address, blockNumber || 'latest') + const blockNumber = await this.blockTracker.getLatestBlock() + const baseCountBN = await this.ethQuery.getTransactionCount(address, blockNumber) const baseCount = baseCountBN.toNumber() assert(Number.isInteger(baseCount), `nonce-tracker - baseCount is not an integer - got: (${typeof baseCount}) "${baseCount}"`) const nonceDetails = { blockNumber, baseCount } @@ -165,15 +156,6 @@ class NonceTracker { return { name: 'local', nonce: highest, details: { startPoint, highest } } } - // this is a hotfix for the fact that the blockTracker will - // change when the network changes - - /** - @returns {Object} the current blockTracker - */ - _getBlockTracker () { - return this.provider._blockTracker - } } module.exports = NonceTracker diff --git a/app/scripts/controllers/transactions/pending-tx-tracker.js b/app/scripts/controllers/transactions/pending-tx-tracker.js index 4e41cdaf8..70cac096b 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.js @@ -1,6 +1,7 @@ const EventEmitter = require('events') const log = require('loglevel') const EthQuery = require('ethjs-query') + /** Event emitter utility class for tracking the transactions as they
@@ -23,55 +24,26 @@ class PendingTransactionTracker extends EventEmitter { super() this.query = new EthQuery(config.provider) this.nonceTracker = config.nonceTracker - // default is one day this.getPendingTransactions = config.getPendingTransactions this.getCompletedTransactions = config.getCompletedTransactions this.publishTransaction = config.publishTransaction - this._checkPendingTxs() + this.confirmTransaction = config.confirmTransaction } /** - checks if a signed tx is in a block and - if it is included emits tx status as 'confirmed' - @param block {object}, a full block - @emits tx:confirmed - @emits tx:failed + checks the network for signed txs and releases the nonce global lock if it is */ - checkForTxInBlock (block) { - const signedTxList = this.getPendingTransactions() - if (!signedTxList.length) return - signedTxList.forEach((txMeta) => { - const txHash = txMeta.hash - const txId = txMeta.id - - if (!txHash) { - const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.') - noTxHashErr.name = 'NoTxHashError' - this.emit('tx:failed', txId, noTxHashErr) - return - } - - - block.transactions.forEach((tx) => { - if (tx.hash === txHash) this.emit('tx:confirmed', txId) - }) - }) - } - - /** - asks the network for the transaction to see if a block number is included on it - if we have skipped/missed blocks - @param object - oldBlock newBlock - */ - queryPendingTxs ({ oldBlock, newBlock }) { - // check pending transactions on start - if (!oldBlock) { - this._checkPendingTxs() - return + async updatePendingTxs () { + // in order to keep the nonceTracker accurate we block it while updating pending transactions + const nonceGlobalLock = await this.nonceTracker.getGlobalLock() + try { + const pendingTxs = this.getPendingTransactions() + await Promise.all(pendingTxs.map((txMeta) => this._checkPendingTx(txMeta))) + } catch (err) { + log.error('PendingTransactionTracker - Error updating pending transactions') + log.error(err) } - // if we synced by more than one block, check for missed pending transactions - const diff = Number.parseInt(newBlock.number, 16) - Number.parseInt(oldBlock.number, 16) - if (diff > 1) this._checkPendingTxs() + nonceGlobalLock.releaseLock() } /** @@ -79,11 +51,11 @@ class PendingTransactionTracker extends EventEmitter { @param block {object} - a block object @emits tx:warning */ - resubmitPendingTxs (block) { + resubmitPendingTxs (blockNumber) { const pending = this.getPendingTransactions() // only try resubmitting if their are transactions to resubmit if (!pending.length) return - pending.forEach((txMeta) => this._resubmitTx(txMeta, block.number).catch((err) => { + pending.forEach((txMeta) => this._resubmitTx(txMeta, blockNumber).catch((err) => { /* Dont marked as failed if the error is a "known" transaction warning "there is already a transaction with the same sender-nonce @@ -145,6 +117,7 @@ class PendingTransactionTracker extends EventEmitter { this.emit('tx:retry', txMeta) return txHash } + /** Ask the network for the transaction to see if it has been include in a block @param txMeta {Object} - the txMeta object @@ -174,9 +147,8 @@ class PendingTransactionTracker extends EventEmitter { } // get latest transaction status - let txParams try { - txParams = await this.query.getTransactionByHash(txHash) + const txParams = await this.query.getTransactionByHash(txHash) if (!txParams) return if (txParams.blockNumber) { this.emit('tx:confirmed', txId) @@ -190,27 +162,13 @@ class PendingTransactionTracker extends EventEmitter { } } - /** - checks the network for signed txs and releases the nonce global lock if it is - */ - async _checkPendingTxs () { - const signedTxList = this.getPendingTransactions() - // in order to keep the nonceTracker accurate we block it while updating pending transactions - 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) - } - releaseLock() - } - /** checks to see if a confirmed txMeta has the same nonce @param txMeta {Object} - txMeta object @returns {boolean} */ + + async _checkIfNonceIsTaken (txMeta) { const address = txMeta.txParams.from const completed = this.getCompletedTransactions(address) diff --git a/app/scripts/controllers/transactions/tx-gas-utils.js b/app/scripts/controllers/transactions/tx-gas-utils.js index 5cd0f5407..3dd45507f 100644 --- a/app/scripts/controllers/transactions/tx-gas-utils.js +++ b/app/scripts/controllers/transactions/tx-gas-utils.js @@ -25,7 +25,7 @@ class TxGasUtil { @returns {object} the txMeta object with the gas written to the txParams */ async analyzeGasUsage (txMeta) { - const block = await this.query.getBlockByNumber('latest', true) + const block = await this.query.getBlockByNumber('latest', false) let estimatedGasHex try { estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit) diff --git a/app/scripts/controllers/transactions/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js index 28a18ca2e..daa6cc388 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.js +++ b/app/scripts/controllers/transactions/tx-state-manager.js @@ -353,6 +353,7 @@ class TransactionStateManager extends EventEmitter { const txMeta = this.getTx(txId) txMeta.err = { message: err.toString(), + rpc: err.value, stack: err.stack, } this.updateTx(txMeta) diff --git a/app/scripts/inpage.js b/app/scripts/inpage.js index 50c7b1ea1..a895b7834 100644 --- a/app/scripts/inpage.js +++ b/app/scripts/inpage.js @@ -4,7 +4,7 @@ require('web3/dist/web3.min.js') const log = require('loglevel') const LocalMessageDuplexStream = require('post-message-stream') const setupDappAutoReload = require('./lib/auto-reload.js') -const MetamaskInpageProvider = require('./lib/inpage-provider.js') +const MetamaskInpageProvider = require('metamask-inpage-provider') restoreContextAfterImports() log.setDefaultLevel(process.env.METAMASK_DEBUG ? 'debug' : 'warn') @@ -22,6 +22,25 @@ var metamaskStream = new LocalMessageDuplexStream({ // compose the inpage provider var inpageProvider = new MetamaskInpageProvider(metamaskStream) +// Augment the provider with its enable method +inpageProvider.enable = function (options = {}) { + return new Promise((resolve, reject) => { + if (options.mockRejection) { + reject('User rejected account access') + } else { + inpageProvider.sendAsync({ method: 'eth_accounts', params: [] }, (error, response) => { + if (error) { + reject(error) + } else { + resolve(response.result) + } + }) + } + }) +} + +window.ethereum = inpageProvider + // // setup web3 // diff --git a/app/scripts/lib/account-tracker.js b/app/scripts/lib/account-tracker.js index 0f7b3d865..2e9340018 100644 --- a/app/scripts/lib/account-tracker.js +++ b/app/scripts/lib/account-tracker.js @@ -7,14 +7,13 @@ * on each new block. */ -const async = require('async') const EthQuery = require('eth-query') const ObservableStore = require('obs-store') -const EventEmitter = require('events').EventEmitter -function noop () {} +const log = require('loglevel') +const pify = require('pify') -class AccountTracker extends EventEmitter { +class AccountTracker { /** * This module is responsible for tracking any number of accounts and caching their current balances & transaction @@ -35,8 +34,6 @@ class AccountTracker extends EventEmitter { * */ constructor (opts = {}) { - super() - const initState = { accounts: {}, currentBlockGasLimit: '', @@ -44,12 +41,29 @@ class AccountTracker extends EventEmitter { this.store = new ObservableStore(initState) this._provider = opts.provider - this._query = new EthQuery(this._provider) + this._query = pify(new EthQuery(this._provider)) this._blockTracker = opts.blockTracker - // subscribe to latest block - this._blockTracker.on('block', this._updateForBlock.bind(this)) // blockTracker.currentBlock may be null - this._currentBlockNumber = this._blockTracker.currentBlock + this._currentBlockNumber = this._blockTracker.getCurrentBlock() + this._blockTracker.once('latest', blockNumber => { + this._currentBlockNumber = blockNumber + }) + // bind function for easier listener syntax + this._updateForBlock = this._updateForBlock.bind(this) + } + + start () { + // remove first to avoid double add + this._blockTracker.removeListener('latest', this._updateForBlock) + // add listener + this._blockTracker.addListener('latest', this._updateForBlock) + // fetch account balances + this._updateAccounts() + } + + stop () { + // remove listener + this._blockTracker.removeListener('latest', this._updateForBlock) } /** @@ -67,49 +81,57 @@ class AccountTracker extends EventEmitter { const accounts = this.store.getState().accounts const locals = Object.keys(accounts) - const toAdd = [] + const accountsToAdd = [] addresses.forEach((upstream) => { if (!locals.includes(upstream)) { - toAdd.push(upstream) + accountsToAdd.push(upstream) } }) - const toRemove = [] + const accountsToRemove = [] locals.forEach((local) => { if (!addresses.includes(local)) { - toRemove.push(local) + accountsToRemove.push(local) } }) - toAdd.forEach(upstream => this.addAccount(upstream)) - toRemove.forEach(local => this.removeAccount(local)) - this._updateAccounts() + this.addAccounts(accountsToAdd) + this.removeAccount(accountsToRemove) } /** - * Adds a new address to this AccountTracker's accounts object, which points to an empty object. This object will be + * Adds new addresses to track the balances of * given a balance as long this._currentBlockNumber is defined. * - * @param {string} address A hex address of a new account to store in this AccountTracker's accounts object + * @param {array} addresses An array of hex addresses of new accounts to track * */ - addAccount (address) { + addAccounts (addresses) { const accounts = this.store.getState().accounts - accounts[address] = {} + // add initial state for addresses + addresses.forEach(address => { + accounts[address] = {} + }) + // save accounts state this.store.updateState({ accounts }) + // fetch balances for the accounts if there is block number ready if (!this._currentBlockNumber) return - this._updateAccount(address) + addresses.forEach(address => this._updateAccount(address)) } /** - * Removes an account from this AccountTracker's accounts object + * Removes accounts from being tracked * - * @param {string} address A hex address of a the account to remove + * @param {array} an array of hex addresses to stop tracking * */ - removeAccount (address) { + removeAccount (addresses) { const accounts = this.store.getState().accounts - delete accounts[address] + // remove each state object + addresses.forEach(address => { + delete accounts[address] + }) + // save accounts state this.store.updateState({ accounts }) } @@ -118,71 +140,56 @@ class AccountTracker extends EventEmitter { * via EthQuery * * @private - * @param {object} block Data about the block that contains the data to update to. + * @param {number} blockNumber the block number to update to. * @fires 'block' The updated state, if all account updates are successful * */ - _updateForBlock (block) { - this._currentBlockNumber = block.number - const currentBlockGasLimit = block.gasLimit + async _updateForBlock (blockNumber) { + this._currentBlockNumber = blockNumber + // block gasLimit polling shouldn't be in account-tracker shouldn't be here... + const currentBlock = await this._query.getBlockByNumber(blockNumber, false) + if (!currentBlock) return + const currentBlockGasLimit = currentBlock.gasLimit this.store.updateState({ currentBlockGasLimit }) - async.parallel([ - this._updateAccounts.bind(this), - ], (err) => { - if (err) return console.error(err) - this.emit('block', this.store.getState()) - }) + try { + await this._updateAccounts() + } catch (err) { + log.error(err) + } } /** * Calls this._updateAccount for each account in this.store * - * @param {Function} cb A callback to pass to this._updateAccount, called after each account is successfully updated + * @returns {Promise} after all account balances updated * */ - _updateAccounts (cb = noop) { + async _updateAccounts () { const accounts = this.store.getState().accounts const addresses = Object.keys(accounts) - async.each(addresses, this._updateAccount.bind(this), cb) + await Promise.all(addresses.map(this._updateAccount.bind(this))) } /** - * Updates the current balance of an account. Gets an updated balance via this._getAccount. + * Updates the current balance of an account. * * @private * @param {string} address A hex address of a the account to be updated - * @param {Function} cb A callback to call once the account at address is successfully update + * @returns {Promise} after the account balance is updated * */ - _updateAccount (address, cb = noop) { - this._getAccount(address, (err, result) => { - if (err) return cb(err) - result.address = address - const accounts = this.store.getState().accounts - // only populate if the entry is still present - if (accounts[address]) { - accounts[address] = result - this.store.updateState({ accounts }) - } - cb(null, result) - }) - } - - /** - * Gets the current balance of an account via EthQuery. - * - * @private - * @param {string} address A hex address of a the account to query - * @param {Function} cb A callback to call once the account at address is successfully update - * - */ - _getAccount (address, cb = noop) { - const query = this._query - async.parallel({ - balance: query.getBalance.bind(query, address), - }, cb) + async _updateAccount (address) { + // query balance + const balance = await this._query.getBalance(address) + const result = { address, balance } + // update accounts state + const { accounts } = this.store.getState() + // only populate if the entry is still present + if (!accounts[address]) return + accounts[address] = result + this.store.updateState({ accounts }) } } diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js deleted file mode 100644 index 12fa26813..000000000 --- a/app/scripts/lib/config-manager.js +++ /dev/null @@ -1,226 +0,0 @@ -const ethUtil = require('ethereumjs-util') -const normalize = require('eth-sig-util').normalize - -/* The config-manager is a convenience object - * wrapping a pojo-migrator. - * - * It exists mostly to allow the creation of - * convenience methods to access and persist - * particular portions of the state. - */ -module.exports = ConfigManager -function ConfigManager (opts) { - // ConfigManager is observable and will emit updates - this._subs = [] - this.store = opts.store -} - -ConfigManager.prototype.setConfig = function (config) { - var data = this.getData() - data.config = config - this.setData(data) - this._emitUpdates(config) -} - -ConfigManager.prototype.getConfig = function () { - var data = this.getData() - return data.config -} - -ConfigManager.prototype.setData = function (data) { - this.store.putState(data) -} - -ConfigManager.prototype.getData = function () { - return this.store.getState() -} - -ConfigManager.prototype.setPasswordForgotten = function (passwordForgottenState) { - const data = this.getData() - data.forgottenPassword = passwordForgottenState - this.setData(data) -} - -ConfigManager.prototype.getPasswordForgotten = function (passwordForgottenState) { - const data = this.getData() - return data.forgottenPassword -} - -ConfigManager.prototype.setWallet = function (wallet) { - var data = this.getData() - data.wallet = wallet - this.setData(data) -} - -ConfigManager.prototype.setVault = function (encryptedString) { - var data = this.getData() - data.vault = encryptedString - this.setData(data) -} - -ConfigManager.prototype.getVault = function () { - var data = this.getData() - return data.vault -} - -ConfigManager.prototype.getKeychains = function () { - return this.getData().keychains || [] -} - -ConfigManager.prototype.setKeychains = function (keychains) { - var data = this.getData() - data.keychains = keychains - this.setData(data) -} - -ConfigManager.prototype.getSelectedAccount = function () { - var config = this.getConfig() - return config.selectedAccount -} - -ConfigManager.prototype.setSelectedAccount = function (address) { - var config = this.getConfig() - config.selectedAccount = ethUtil.addHexPrefix(address) - this.setConfig(config) -} - -ConfigManager.prototype.getWallet = function () { - return this.getData().wallet -} - -// Takes a boolean -ConfigManager.prototype.setShowSeedWords = function (should) { - var data = this.getData() - data.showSeedWords = should - this.setData(data) -} - - -ConfigManager.prototype.getShouldShowSeedWords = function () { - var data = this.getData() - return data.showSeedWords -} - -ConfigManager.prototype.setSeedWords = function (words) { - var data = this.getData() - data.seedWords = words - this.setData(data) -} - -ConfigManager.prototype.getSeedWords = function () { - var data = this.getData() - return data.seedWords -} -ConfigManager.prototype.setRpcTarget = function (rpcUrl) { - var config = this.getConfig() - config.provider = { - type: 'rpc', - rpcTarget: rpcUrl, - } - this.setConfig(config) -} - -ConfigManager.prototype.setProviderType = function (type) { - var config = this.getConfig() - config.provider = { - type: type, - } - this.setConfig(config) -} - -ConfigManager.prototype.useEtherscanProvider = function () { - var config = this.getConfig() - config.provider = { - type: 'etherscan', - } - this.setConfig(config) -} - -ConfigManager.prototype.getProvider = function () { - var config = this.getConfig() - return config.provider -} - -// -// Tx -// - -ConfigManager.prototype.getTxList = function () { - var data = this.getData() - if (data.transactions !== undefined) { - return data.transactions - } else { - return [] - } -} - -ConfigManager.prototype.setTxList = function (txList) { - var data = this.getData() - data.transactions = txList - this.setData(data) -} - - -// wallet nickname methods - -ConfigManager.prototype.getWalletNicknames = function () { - var data = this.getData() - const nicknames = ('walletNicknames' in data) ? data.walletNicknames : {} - return nicknames -} - -ConfigManager.prototype.nicknameForWallet = function (account) { - const address = normalize(account) - const nicknames = this.getWalletNicknames() - return nicknames[address] -} - -ConfigManager.prototype.setNicknameForWallet = function (account, nickname) { - const address = normalize(account) - const nicknames = this.getWalletNicknames() - nicknames[address] = nickname - var data = this.getData() - data.walletNicknames = nicknames - this.setData(data) -} - -// observable - -ConfigManager.prototype.getSalt = function () { - var data = this.getData() - return data.salt -} - -ConfigManager.prototype.setSalt = function (salt) { - var data = this.getData() - data.salt = salt - this.setData(data) -} - -ConfigManager.prototype.subscribe = function (fn) { - this._subs.push(fn) - var unsubscribe = this.unsubscribe.bind(this, fn) - return unsubscribe -} - -ConfigManager.prototype.unsubscribe = function (fn) { - var index = this._subs.indexOf(fn) - if (index !== -1) this._subs.splice(index, 1) -} - -ConfigManager.prototype._emitUpdates = function (state) { - this._subs.forEach(function (handler) { - handler(state) - }) -} - -ConfigManager.prototype.setLostAccounts = function (lostAccounts) { - var data = this.getData() - data.lostAccounts = lostAccounts - this.setData(data) -} - -ConfigManager.prototype.getLostAccounts = function () { - var data = this.getData() - return data.lostAccounts || [] -} diff --git a/app/scripts/lib/createErrorMiddleware.js b/app/scripts/lib/createErrorMiddleware.js deleted file mode 100644 index 3bd7cf322..000000000 --- a/app/scripts/lib/createErrorMiddleware.js +++ /dev/null @@ -1,67 +0,0 @@ -const log = require('loglevel') - -/** - * JSON-RPC error object - * - * @typedef {Object} RpcError - * @property {number} code - Indicates the error type that occurred - * @property {Object} [data] - Contains additional information about the error - * @property {string} [message] - Short description of the error - */ - -/** - * Middleware configuration object - * - * @typedef {Object} MiddlewareConfig - * @property {boolean} [override] - Use RPC_ERRORS message in place of provider message - */ - -/** - * Map of standard and non-standard RPC error codes to messages - */ -const RPC_ERRORS = { - 1: 'An unauthorized action was attempted.', - 2: 'A disallowed action was attempted.', - 3: 'An execution error occurred.', - [-32600]: 'The JSON sent is not a valid Request object.', - [-32601]: 'The method does not exist / is not available.', - [-32602]: 'Invalid method parameter(s).', - [-32603]: 'Internal JSON-RPC error.', - [-32700]: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.', - internal: 'Internal server error.', - unknown: 'Unknown JSON-RPC error.', -} - -/** - * Modifies a JSON-RPC error object in-place to add a human-readable message, - * optionally overriding any provider-supplied message - * - * @param {RpcError} error - JSON-RPC error object - * @param {boolean} override - Use RPC_ERRORS message in place of provider message - */ -function sanitizeRPCError (error, override) { - if (error.message && !override) { return error } - const message = error.code > -31099 && error.code < -32100 ? RPC_ERRORS.internal : RPC_ERRORS[error.code] - error.message = message || RPC_ERRORS.unknown -} - -/** - * json-rpc-engine middleware that both logs standard and non-standard error - * messages and ends middleware stack traversal if an error is encountered - * - * @param {MiddlewareConfig} [config={override:true}] - Middleware configuration - * @returns {Function} json-rpc-engine middleware function - */ -function createErrorMiddleware ({ override = true } = {}) { - return (req, res, next) => { - next(done => { - const { error } = res - if (!error) { return done() } - sanitizeRPCError(error) - log.error(`Nifty Wallet - RPC Error: ${error.message}`, error) - done() - }) - } -} - -module.exports = createErrorMiddleware diff --git a/app/scripts/lib/events-proxy.js b/app/scripts/lib/events-proxy.js deleted file mode 100644 index f83773ccc..000000000 --- a/app/scripts/lib/events-proxy.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Returns an EventEmitter that proxies events from the given event emitter - * @param {any} eventEmitter - * @param {object} listeners - The listeners to proxy to - * @returns {any} - */ -module.exports = function createEventEmitterProxy (eventEmitter, listeners) { - let target = eventEmitter - const eventHandlers = listeners || {} - const proxy = /** @type {any} */ (new Proxy({}, { - get: (_, name) => { - // intercept listeners - if (name === 'on') return addListener - if (name === 'setTarget') return setTarget - if (name === 'proxyEventHandlers') return eventHandlers - return (/** @type {any} */ (target))[name] - }, - set: (_, name, value) => { - target[name] = value - return true - }, - })) - function setTarget (/** @type {EventEmitter} */ eventEmitter) { - target = eventEmitter - // migrate listeners - Object.keys(eventHandlers).forEach((name) => { - /** @type {Array} */ (eventHandlers[name]).forEach((handler) => target.on(name, handler)) - }) - } - /** - * Attaches a function to be called whenever the specified event is emitted - * @param {string} name - * @param {Function} handler - */ - function addListener (name, handler) { - if (!eventHandlers[name]) eventHandlers[name] = [] - eventHandlers[name].push(handler) - target.on(name, handler) - } - if (listeners) proxy.setTarget(eventEmitter) - return proxy -} diff --git a/app/scripts/lib/inpage-provider.js b/app/scripts/lib/inpage-provider.js deleted file mode 100644 index 53f254797..000000000 --- a/app/scripts/lib/inpage-provider.js +++ /dev/null @@ -1,125 +0,0 @@ -const pump = require('pump') -const RpcEngine = require('json-rpc-engine') -const createErrorMiddleware = require('./createErrorMiddleware') -const createIdRemapMiddleware = require('json-rpc-engine/src/idRemapMiddleware') -const createStreamMiddleware = require('json-rpc-middleware-stream') -const LocalStorageStore = require('obs-store') -const asStream = require('obs-store/lib/asStream') -const ObjectMultiplex = require('obj-multiplex') - -module.exports = MetamaskInpageProvider - -function MetamaskInpageProvider (connectionStream) { - const self = this - - // setup connectionStream multiplexing - const mux = self.mux = new ObjectMultiplex() - pump( - connectionStream, - mux, - connectionStream, - (err) => logStreamDisconnectWarning('MetaMask', err) - ) - - // subscribe to metamask public config (one-way) - self.publicConfigStore = new LocalStorageStore({ storageKey: 'MetaMask-Config' }) - - pump( - mux.createStream('publicConfig'), - asStream(self.publicConfigStore), - (err) => logStreamDisconnectWarning('Nifty Wallet PublicConfigStore', err) - ) - - // ignore phishing warning message (handled elsewhere) - mux.ignoreStream('phishing') - - // connect to async provider - const streamMiddleware = createStreamMiddleware() - pump( - streamMiddleware.stream, - mux.createStream('provider'), - streamMiddleware.stream, - (err) => logStreamDisconnectWarning('Nifty Wallet RpcProvider', err) - ) - - // handle sendAsync requests via dapp-side rpc engine - const rpcEngine = new RpcEngine() - rpcEngine.push(createIdRemapMiddleware()) - rpcEngine.push(createErrorMiddleware()) - rpcEngine.push(streamMiddleware) - self.rpcEngine = rpcEngine -} - -// handle sendAsync requests via asyncProvider -// also remap ids inbound and outbound -MetamaskInpageProvider.prototype.sendAsync = function (payload, cb) { - const self = this - - if (payload.method === 'eth_signTypedData') { - console.warn('MetaMask: This experimental version of eth_signTypedData will be deprecated in the next release in favor of the standard as defined in EIP-712. See https://git.io/fNzPl for more information on the new standard.') - } - - self.rpcEngine.handle(payload, cb) -} - - -MetamaskInpageProvider.prototype.send = function (payload) { - const self = this - - let selectedAddress - let result = null - switch (payload.method) { - - case 'eth_accounts': - // read from localStorage - selectedAddress = self.publicConfigStore.getState().selectedAddress - result = selectedAddress ? [selectedAddress] : [] - break - - case 'eth_coinbase': - // read from localStorage - selectedAddress = self.publicConfigStore.getState().selectedAddress - result = selectedAddress || null - break - - case 'eth_uninstallFilter': - self.sendAsync(payload, noop) - result = true - break - - case 'net_version': - const networkVersion = self.publicConfigStore.getState().networkVersion - result = networkVersion || null - break - - // throw not-supported Error - default: - var link = 'https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#dizzy-all-async---think-of-metamask-as-a-light-client' - var message = `The Nifty Wallet Web3 object does not support synchronous methods like ${payload.method} without a callback parameter. See ${link} for details.` - throw new Error(message) - - } - - // return the result - return { - id: payload.id, - jsonrpc: payload.jsonrpc, - result: result, - } -} - -MetamaskInpageProvider.prototype.isConnected = function () { - return true -} - -MetamaskInpageProvider.prototype.isMetaMask = true - -// util - -function logStreamDisconnectWarning (remoteLabel, err) { - let warningMsg = `MetamaskInpageProvider - lost connection to ${remoteLabel}` - if (err) warningMsg += '\n' + err.stack - console.warn(warningMsg) -} - -function noop () {} diff --git a/app/scripts/lib/ipfsContent.js b/app/scripts/lib/ipfsContent.js index 26255896d..38682b916 100644 --- a/app/scripts/lib/ipfsContent.js +++ b/app/scripts/lib/ipfsContent.js @@ -34,7 +34,7 @@ module.exports = function (provider) { return { cancel: true } } - extension.webRequest.onBeforeRequest.addListener(ipfsContent, {urls: ['*://*.eth/']}) + extension.webRequest.onErrorOccurred.addListener(ipfsContent, {urls: ['*://*.eth/']}) return { remove () { diff --git a/app/scripts/lib/message-manager.js b/app/scripts/lib/message-manager.js index 901367f04..47925b94b 100644 --- a/app/scripts/lib/message-manager.js +++ b/app/scripts/lib/message-manager.js @@ -69,10 +69,39 @@ module.exports = class MessageManager extends EventEmitter { * new Message to this.messages, and to save the unapproved Messages from that list to this.memStore. * * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object possibly containing the origin + * @returns {promise} after signature has been + * + */ + addUnapprovedMessageAsync (msgParams, req) { + return new Promise((resolve, reject) => { + const msgId = this.addUnapprovedMessage(msgParams, req) + // await finished + this.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return resolve(data.rawSig) + case 'rejected': + return reject(new Error('MetaMask Message Signature: User denied message signature.')) + default: + return reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + }) + } + + /** + * Creates a new Message with an 'unapproved' status using the passed msgParams. this.addMsg is called to add the + * new Message to this.messages, and to save the unapproved Messages from that list to this.memStore. + * + * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object where the origin may be specificied * @returns {number} The id of the newly created message. * */ - addUnapprovedMessage (msgParams) { + addUnapprovedMessage (msgParams, req) { + // add origin from request + if (req) msgParams.origin = req.origin msgParams.data = normalizeMsgData(msgParams.data) // create txData obj with parameters and meta data var time = (new Date()).getTime() diff --git a/app/scripts/lib/personal-message-manager.js b/app/scripts/lib/personal-message-manager.js index e96ced1f2..fc2cccdf1 100644 --- a/app/scripts/lib/personal-message-manager.js +++ b/app/scripts/lib/personal-message-manager.js @@ -73,11 +73,43 @@ module.exports = class PersonalMessageManager extends EventEmitter { * this.memStore. * * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object possibly containing the origin + * @returns {promise} When the message has been signed or rejected + * + */ + addUnapprovedMessageAsync (msgParams, req) { + return new Promise((resolve, reject) => { + if (!msgParams.from) { + reject(new Error('MetaMask Message Signature: from field is required.')) + } + const msgId = this.addUnapprovedMessage(msgParams, req) + this.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return resolve(data.rawSig) + case 'rejected': + return reject(new Error('MetaMask Message Signature: User denied message signature.')) + default: + return reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + }) + } + + /** + * Creates a new PersonalMessage with an 'unapproved' status using the passed msgParams. this.addMsg is called to add + * the new PersonalMessage to this.messages, and to save the unapproved PersonalMessages from that list to + * this.memStore. + * + * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object possibly containing the origin * @returns {number} The id of the newly created PersonalMessage. * */ - addUnapprovedMessage (msgParams) { + addUnapprovedMessage (msgParams, req) { log.debug(`PersonalMessageManager addUnapprovedMessage: ${JSON.stringify(msgParams)}`) + // add origin from request + if (req) msgParams.origin = req.origin msgParams.data = this.normalizeMsgData(msgParams.data) // create txData obj with parameters and meta data var time = (new Date()).getTime() @@ -257,4 +289,3 @@ module.exports = class PersonalMessageManager extends EventEmitter { } } - diff --git a/app/scripts/lib/port-stream.js b/app/scripts/lib/port-stream.js deleted file mode 100644 index fd65d94f3..000000000 --- a/app/scripts/lib/port-stream.js +++ /dev/null @@ -1,80 +0,0 @@ -const Duplex = require('readable-stream').Duplex -const inherits = require('util').inherits -const noop = function () {} - -module.exports = PortDuplexStream - -inherits(PortDuplexStream, Duplex) - -/** - * Creates a stream that's both readable and writable. - * The stream supports arbitrary objects. - * - * @class - * @param {Object} port Remote Port object - */ -function PortDuplexStream (port) { - Duplex.call(this, { - objectMode: true, - }) - this._port = port - port.onMessage.addListener(this._onMessage.bind(this)) - port.onDisconnect.addListener(this._onDisconnect.bind(this)) -} - -/** - * Callback triggered when a message is received from - * the remote Port associated with this Stream. - * - * @private - * @param {Object} msg - Payload from the onMessage listener of Port - */ -PortDuplexStream.prototype._onMessage = function (msg) { - if (Buffer.isBuffer(msg)) { - delete msg._isBuffer - var data = new Buffer(msg) - this.push(data) - } else { - this.push(msg) - } -} - -/** - * Callback triggered when the remote Port - * associated with this Stream disconnects. - * - * @private - */ -PortDuplexStream.prototype._onDisconnect = function () { - this.destroy() -} - -/** - * Explicitly sets read operations to a no-op - */ -PortDuplexStream.prototype._read = noop - - -/** - * Called internally when data should be written to - * this writable stream. - * - * @private - * @param {*} msg Arbitrary object to write - * @param {string} encoding Encoding to use when writing payload - * @param {Function} cb Called when writing is complete or an error occurs - */ -PortDuplexStream.prototype._write = function (msg, encoding, cb) { - try { - if (Buffer.isBuffer(msg)) { - var data = msg.toJSON() - data._isBuffer = true - this._port.postMessage(data) - } else { - this._port.postMessage(msg) - } - } catch (err) { - return cb(new Error('PortDuplexStream - disconnected')) - } - cb() -} diff --git a/app/scripts/lib/setupRaven.js b/app/scripts/lib/setupRaven.js index c74520665..058ce5541 100644 --- a/app/scripts/lib/setupRaven.js +++ b/app/scripts/lib/setupRaven.js @@ -70,11 +70,11 @@ function simplifyErrorMessages (report) { function rewriteErrorMessages (report, rewriteFn) { // rewrite top level message - if (report.message) report.message = rewriteFn(report.message) + if (typeof report.message === 'string') report.message = rewriteFn(report.message) // rewrite each exception message if (report.exception && report.exception.values) { report.exception.values.forEach(item => { - item.value = rewriteFn(item.value) + if (typeof item.value === 'string') item.value = rewriteFn(item.value) }) } } diff --git a/app/scripts/lib/typed-message-manager.js b/app/scripts/lib/typed-message-manager.js index c58921610..b10145f3b 100644 --- a/app/scripts/lib/typed-message-manager.js +++ b/app/scripts/lib/typed-message-manager.js @@ -4,6 +4,7 @@ const createId = require('./random-id') const assert = require('assert') const sigUtil = require('eth-sig-util') const log = require('loglevel') +const jsonschema = require('jsonschema') /** * Represents, and contains data about, an 'eth_signTypedData' type signature request. These are created when a @@ -17,7 +18,7 @@ const log = require('loglevel') * @property {Object} msgParams.from The address that is making the signature request. * @property {string} msgParams.data A hex string conversion of the raw buffer data of the signature request * @property {number} time The epoch time at which the this message was created - * @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed' or 'rejected' + * @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed', 'rejected', or 'errored' * @property {string} type The json-prc signing method for which a signature request has been made. A 'Message' will * always have a 'eth_signTypedData' type. * @@ -26,17 +27,10 @@ const log = require('loglevel') module.exports = class TypedMessageManager extends EventEmitter { /** * Controller in charge of managing - storing, adding, removing, updating - TypedMessage. - * - * @typedef {Object} TypedMessage - * @param {Object} opts @deprecated - * @property {Object} memStore The observable store where TypedMessage are saved. - * @property {Object} memStore.unapprovedTypedMessages A collection of all TypedMessages in the 'unapproved' state - * @property {number} memStore.unapprovedTypedMessagesCount The count of all TypedMessages in this.memStore.unapprobedMsgs - * @property {array} messages Holds all messages that have been created by this TypedMessage - * */ - constructor (opts) { + constructor ({ networkController }) { super() + this.networkController = networkController this.memStore = new ObservableStore({ unapprovedTypedMessages: {}, unapprovedTypedMessagesCount: 0, @@ -72,11 +66,43 @@ module.exports = class TypedMessageManager extends EventEmitter { * this.memStore. Before any of this is done, msgParams are validated * * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object possibly containing the origin + * @returns {promise} When the message has been signed or rejected + * + */ + addUnapprovedMessageAsync (msgParams, req, version) { + return new Promise((resolve, reject) => { + const msgId = this.addUnapprovedMessage(msgParams, req, version) + this.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return resolve(data.rawSig) + case 'rejected': + return reject(new Error('MetaMask Message Signature: User denied message signature.')) + case 'errored': + return reject(new Error(`MetaMask Message Signature: ${data.error}`)) + default: + return reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + }) + } + + /** + * Creates a new TypedMessage with an 'unapproved' status using the passed msgParams. this.addMsg is called to add + * the new TypedMessage to this.messages, and to save the unapproved TypedMessages from that list to + * this.memStore. Before any of this is done, msgParams are validated + * + * @param {Object} msgParams The params for the eth_sign call to be made after the message is approved. + * @param {Object} req (optional) The original request object possibly containing the origin * @returns {number} The id of the newly created TypedMessage. * */ - addUnapprovedMessage (msgParams) { + addUnapprovedMessage (msgParams, req, version) { + msgParams.version = version this.validateParams(msgParams) + // add origin from request + if (req) msgParams.origin = req.origin log.debug(`TypedMessageManager addUnapprovedMessage: ${JSON.stringify(msgParams)}`) // create txData obj with parameters and meta data @@ -103,14 +129,33 @@ module.exports = class TypedMessageManager extends EventEmitter { * */ validateParams (params) { - assert.equal(typeof params, 'object', 'Params should ben an object.') - assert.ok('data' in params, 'Params must include a data field.') - assert.ok('from' in params, 'Params must include a from field.') - assert.ok(Array.isArray(params.data), 'Data should be an array.') - assert.equal(typeof params.from, 'string', 'From field must be a string.') - assert.doesNotThrow(() => { - sigUtil.typedSignatureHash(params.data) - }, 'Expected EIP712 typed data') + switch (params.version) { + case 'V1': + assert.equal(typeof params, 'object', 'Params should ben an object.') + assert.ok('data' in params, 'Params must include a data field.') + assert.ok('from' in params, 'Params must include a from field.') + assert.ok(Array.isArray(params.data), 'Data should be an array.') + assert.equal(typeof params.from, 'string', 'From field must be a string.') + assert.doesNotThrow(() => { + sigUtil.typedSignatureHash(params.data) + }, 'Expected EIP712 typed data') + break + case 'V3': + let data + assert.equal(typeof params, 'object', 'Params should be an object.') + assert.ok('data' in params, 'Params must include a data field.') + assert.ok('from' in params, 'Params must include a from field.') + assert.equal(typeof params.from, 'string', 'From field must be a string.') + assert.equal(typeof params.data, 'string', 'Data must be passed as a valid JSON string.') + assert.doesNotThrow(() => { data = JSON.parse(params.data) }, 'Data must be passed as a valid JSON string.') + const validation = jsonschema.validate(data, sigUtil.TYPED_MESSAGE_SCHEMA) + assert.ok(data.primaryType in data.types, `Primary type of "${data.primaryType}" has no type definition.`) + assert.equal(validation.errors.length, 0, 'Data must conform to EIP-712 schema. See https://git.io/fNtcx.') + const chainId = data.domain.chainId + const activeChainId = parseInt(this.networkController.getNetworkState()) + chainId && assert.equal(chainId, activeChainId, `Provided chainId (${chainId}) must match the active chainId (${activeChainId})`) + break + } } /** @@ -185,6 +230,7 @@ module.exports = class TypedMessageManager extends EventEmitter { */ prepMsgForSigning (msgParams) { delete msgParams.metamaskId + delete msgParams.version return Promise.resolve(msgParams) } @@ -198,6 +244,19 @@ module.exports = class TypedMessageManager extends EventEmitter { this._setMsgStatus(msgId, 'rejected') } + /** + * Sets a TypedMessage status to 'errored' via a call to this._setMsgStatus. + * + * @param {number} msgId The id of the TypedMessage to error + * + */ + errorMessage (msgId, error) { + const msg = this.getMsg(msgId) + msg.error = error + this._updateMsg(msg) + this._setMsgStatus(msgId, 'errored') + } + // // PRIVATE METHODS // @@ -221,7 +280,7 @@ module.exports = class TypedMessageManager extends EventEmitter { msg.status = status this._updateMsg(msg) this.emit(`${msgId}:${status}`, msg) - if (status === 'rejected' || status === 'signed') { + if (status === 'rejected' || status === 'signed' || status === 'errored') { this.emit(`${msgId}:finished`, msg) } } diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js index d7423f2ad..ea13b26be 100644 --- a/app/scripts/lib/util.js +++ b/app/scripts/lib/util.js @@ -127,7 +127,21 @@ function BnMultiplyByFraction (targetBN, numerator, denominator) { return targetBN.mul(numBN).div(denomBN) } +function applyListeners (listeners, emitter) { + Object.keys(listeners).forEach((key) => { + emitter.on(key, listeners[key]) + }) +} + +function removeListeners (listeners, emitter) { + Object.keys(listeners).forEach((key) => { + emitter.removeListener(key, listeners[key]) + }) +} + module.exports = { + removeListeners, + applyListeners, getPlatform, getStack, getEnvironmentType, diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 02f2292b3..aaf60f914 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -36,7 +36,6 @@ const TransactionController = require('./controllers/transactions') const BalancesController = require('./controllers/computed-balances') const TokenRatesController = require('./controllers/token-rates') const DetectTokensController = require('./controllers/detect-tokens') -const ConfigManager = require('./lib/config-manager') const nodeify = require('./lib/nodeify') const accountImporter = require('./account-import-strategies') const getBuyEthUrl = require('./lib/buy-eth-url') @@ -46,10 +45,12 @@ const BN = require('ethereumjs-util').BN const GWEI_BN = new BN('1000000000') const percentile = require('percentile') const seedPhraseVerifier = require('./lib/seed-phrase-verifier') -const cleanErrorStack = require('./lib/cleanErrorStack') const log = require('loglevel') const TrezorKeyring = require('eth-trezor-keyring') const LedgerBridgeKeyring = require('eth-ledger-bridge-keyring') +const EthQuery = require('eth-query') +const ethUtil = require('ethereumjs-util') +const sigUtil = require('eth-sig-util') module.exports = class MetamaskController extends EventEmitter { @@ -67,6 +68,10 @@ module.exports = class MetamaskController extends EventEmitter { const initState = opts.initState || {} this.recordFirstTimeInfo(initState) + // this keeps track of how many "controllerStream" connections are open + // the only thing that uses controller connections are open metamask UI instances + this.activeControllerConnections = 0 + // platform-specific api this.platform = opts.platform @@ -79,15 +84,11 @@ module.exports = class MetamaskController extends EventEmitter { // network store this.networkController = new NetworkController(initState.NetworkController) - // config manager - this.configManager = new ConfigManager({ - store: this.store, - }) - // preferences controller this.preferencesController = new PreferencesController({ initState: initState.PreferencesController, initLangCode: opts.initLangCode, + showWatchAssetUi: opts.showWatchAssetUi, network: this.networkController, }) @@ -108,8 +109,9 @@ module.exports = class MetamaskController extends EventEmitter { this.blacklistController.scheduleUpdates() // rpc provider - this.provider = this.initializeProvider() - this.blockTracker = this.provider._blockTracker + this.initializeProvider() + this.provider = this.networkController.getProviderAndBlockTracker().provider + this.blockTracker = this.networkController.getProviderAndBlockTracker().blockTracker // token exchange rate tracker this.tokenRatesController = new TokenRatesController({ @@ -126,6 +128,14 @@ module.exports = class MetamaskController extends EventEmitter { provider: this.provider, blockTracker: this.blockTracker, }) + // start and stop polling for balances based on activeControllerConnections + this.on('controllerConnectionChanged', (activeControllerConnections) => { + if (activeControllerConnections > 0) { + this.accountTracker.start() + } else { + this.accountTracker.stop() + } + }) // key mgmt const additionalKeyrings = [TrezorKeyring, LedgerBridgeKeyring] @@ -136,19 +146,7 @@ module.exports = class MetamaskController extends EventEmitter { encryptor: opts.encryptor || undefined, }) - // If only one account exists, make sure it is selected. - this.keyringController.memStore.subscribe((state) => { - const addresses = state.keyrings.reduce((res, keyring) => { - return res.concat(keyring.accounts) - }, []) - if (addresses.length === 1) { - const address = addresses[0] - this.preferencesController.setSelectedAddress(address) - } - // ensure preferences + identities controller know about all addresses - this.preferencesController.addAddresses(addresses) - this.accountTracker.syncWithAddresses(addresses) - }) + this.keyringController.memStore.subscribe((s) => this._onKeyringControllerUpdate(s)) // detect tokens controller this.detectTokensController = new DetectTokensController({ @@ -175,7 +173,7 @@ module.exports = class MetamaskController extends EventEmitter { blockTracker: this.blockTracker, getGasPrice: this.getGasPrice.bind(this), }) - this.txController.on('newUnapprovedTx', opts.showUnapprovedTx.bind(opts)) + this.txController.on('newUnapprovedTx', () => opts.showUnapprovedTx()) this.txController.on(`tx:status-update`, (txId, status) => { if (status === 'confirmed' || status === 'failed') { @@ -209,7 +207,7 @@ module.exports = class MetamaskController extends EventEmitter { this.networkController.lookupNetwork() this.messageManager = new MessageManager() this.personalMessageManager = new PersonalMessageManager() - this.typedMessageManager = new TypedMessageManager() + this.typedMessageManager = new TypedMessageManager({ networkController: this.networkController }) this.publicConfigStore = this.initPublicConfigStore() this.store.updateStructure({ @@ -253,30 +251,23 @@ module.exports = class MetamaskController extends EventEmitter { static: { eth_syncing: false, web3_clientVersion: `MetaMask/v${version}`, - eth_sendTransaction: (payload, next, end) => { - const origin = payload.origin - const txParams = payload.params[0] - nodeify(this.txController.newUnapprovedTransaction, this.txController)(txParams, { origin }, end) - }, }, // account mgmt - getAccounts: (cb) => { + getAccounts: async () => { const isUnlocked = this.keyringController.memStore.getState().isUnlocked - const result = [] const selectedAddress = this.preferencesController.getSelectedAddress() - // only show address if account is unlocked if (isUnlocked && selectedAddress) { - result.push(selectedAddress) + return [selectedAddress] + } else { + return [] } - cb(null, result) }, // tx signing - // old style msg signing - processMessage: this.newUnsignedMessage.bind(this), - // personal_sign msg signing + processTransaction: this.newUnapprovedTransaction.bind(this), + // msg signing + processEthSignMessage: this.newUnsignedMessage.bind(this), processPersonalMessage: this.newUnsignedPersonalMessage.bind(this), - processTypedMessage: this.newUnsignedTypedMessage.bind(this), } const providerProxy = this.networkController.initializeProvider(providerOpts) return providerProxy @@ -318,18 +309,15 @@ module.exports = class MetamaskController extends EventEmitter { * @returns {Object} status */ getState () { - const wallet = this.configManager.getWallet() const vault = this.keyringController.store.getState().vault - const isInitialized = (!!wallet || !!vault) + const isInitialized = !!vault return { ...{ isInitialized }, ...this.memStore.getFilteredFlatState(), - ...this.configManager.getConfig(), ...{ - lostAccounts: this.configManager.getLostAccounts(), - seedWords: this.configManager.getSeedWords(), - forgottenPassword: this.configManager.getPasswordForgotten(), + // TODO: Remove usages of lost accounts + lostAccounts: [], }, } } @@ -394,6 +382,7 @@ module.exports = class MetamaskController extends EventEmitter { addToken: nodeify(preferencesController.addToken, preferencesController), removeToken: nodeify(preferencesController.removeToken, preferencesController), removeRpcUrl: nodeify(preferencesController.removeRpcUrl, preferencesController), + removeSuggestedTokens: nodeify(preferencesController.removeSuggestedTokens, preferencesController), setCurrentAccountTab: nodeify(preferencesController.setCurrentAccountTab, preferencesController), setAccountLabel: nodeify(preferencesController.setAccountLabel, preferencesController), setFeatureFlag: nodeify(preferencesController.setFeatureFlag, preferencesController), @@ -413,6 +402,7 @@ module.exports = class MetamaskController extends EventEmitter { updateTransaction: nodeify(txController.updateTransaction, txController), updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController), retryTransaction: nodeify(this.retryTransaction, this), + createCancelTransaction: nodeify(this.createCancelTransaction, this), getFilteredTxList: nodeify(txController.getFilteredTxList, txController), isNonceTaken: nodeify(txController.isNonceTaken, txController), estimateGas: nodeify(this.estimateGas, this), @@ -483,12 +473,32 @@ module.exports = class MetamaskController extends EventEmitter { async createNewVaultAndRestore (password, seed) { const releaseLock = await this.createVaultMutex.acquire() try { + let accounts, lastBalance + + const keyringController = this.keyringController + // clear known identities this.preferencesController.setAddresses([]) // create new vault - const vault = await this.keyringController.createNewVaultAndRestore(password, seed) + const vault = await keyringController.createNewVaultAndRestore(password, seed) + + const ethQuery = new EthQuery(this.provider) + accounts = await keyringController.getAccounts() + lastBalance = await this.getBalance(accounts[accounts.length - 1], ethQuery) + + const primaryKeyring = keyringController.getKeyringsByType('HD Key Tree')[0] + if (!primaryKeyring) { + throw new Error('MetamaskController - No HD Key Tree found') + } + + // seek out the first zero balance + while (lastBalance !== '0x0') { + await keyringController.addNewAccount(primaryKeyring) + accounts = await keyringController.getAccounts() + lastBalance = await this.getBalance(accounts[accounts.length - 1], ethQuery) + } + // set new identities - const accounts = await this.keyringController.getAccounts() this.preferencesController.setAddresses(accounts) this.selectFirstIdentity() releaseLock() @@ -499,6 +509,30 @@ module.exports = class MetamaskController extends EventEmitter { } } + /** + * Get an account balance from the AccountTracker or request it directly from the network. + * @param {string} address - The account address + * @param {EthQuery} ethQuery - The EthQuery instance to use when asking the network + */ + getBalance (address, ethQuery) { + return new Promise((resolve, reject) => { + const cached = this.accountTracker.store.getState().accounts[address] + + if (cached && cached.balance) { + resolve(cached.balance) + } else { + ethQuery.getBalance(address, (error, balance) => { + if (error) { + reject(error) + log.error(error) + } else { + resolve(balance || '0x0') + } + }) + } + }) + } + /* * Submits the user's password and attempts to unlock the vault. * Also synchronizes the preferencesController, to ensure its schema @@ -632,7 +666,9 @@ module.exports = class MetamaskController extends EventEmitter { this.preferencesController.setAddresses(newAccounts) newAccounts.forEach(address => { if (!oldAccounts.includes(address)) { - this.preferencesController.setAccountLabel(address, `${deviceName.toUpperCase()} ${parseInt(index, 10) + 1}`) + // Set the account label to Trezor 1 / Ledger 1, etc + this.preferencesController.setAccountLabel(address, `${deviceName[0].toUpperCase()}${deviceName.slice(1)} ${parseInt(index, 10) + 1}`) + // Select the account this.preferencesController.setSelectedAddress(address) } }) @@ -686,7 +722,7 @@ module.exports = class MetamaskController extends EventEmitter { this.verifySeedPhrase() .then((seedWords) => { - this.configManager.setSeedWords(seedWords) + this.preferencesController.setSeedWords(seedWords) return cb(null, seedWords) }) .catch((err) => { @@ -735,7 +771,7 @@ module.exports = class MetamaskController extends EventEmitter { * @param {function} cb Callback function called with the current address. */ clearSeedWordCache (cb) { - this.configManager.setSeedWords(null) + this.preferencesController.setSeedWords(null) cb(null, this.preferencesController.getSelectedAddress()) } @@ -768,7 +804,8 @@ module.exports = class MetamaskController extends EventEmitter { // Remove account from the preferences controller this.preferencesController.removeAddress(address) // Remove account from the account tracker controller - this.accountTracker.removeAccount(address) + this.accountTracker.removeAccount([address]) + // Remove account from the keyring await this.keyringController.removeAccount(address) return address @@ -798,6 +835,18 @@ module.exports = class MetamaskController extends EventEmitter { // --------------------------------------------------------------------------- // Identity Management (signature operations) + /** + * Called when a Dapp suggests a new tx to be signed. + * this wrapper needs to exist so we can provide a reference to + * "newUnapprovedTransaction" before "txController" is instantiated + * + * @param {Object} msgParams - The params passed to eth_sign. + * @param {Object} req - (optional) the original request, containing the origin + */ + async newUnapprovedTransaction (txParams, req) { + return await this.txController.newUnapprovedTransaction(txParams, req) + } + // eth_sign methods: /** @@ -809,20 +858,11 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Object} msgParams - The params passed to eth_sign. * @param {Function} cb = The callback function called with the signature. */ - newUnsignedMessage (msgParams, cb) { - const msgId = this.messageManager.addUnapprovedMessage(msgParams) + newUnsignedMessage (msgParams, req) { + const promise = this.messageManager.addUnapprovedMessageAsync(msgParams, req) this.sendUpdate() this.opts.showUnconfirmedMessage() - this.messageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(cleanErrorStack(new Error('Nifty Wallet Message Signature: User denied message signature.'))) - default: - return cb(cleanErrorStack(new Error(`Nifty Wallet Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) - } - }) + return promise } /** @@ -876,24 +916,11 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Function} cb - The callback function called with the signature. * Passed back to the requesting Dapp. */ - newUnsignedPersonalMessage (msgParams, cb) { - if (!msgParams.from) { - return cb(cleanErrorStack(new Error('Nifty Wallet Message Signature: from field is required.'))) - } - - const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams) + async newUnsignedPersonalMessage (msgParams, req) { + const promise = this.personalMessageManager.addUnapprovedMessageAsync(msgParams, req) this.sendUpdate() this.opts.showUnconfirmedMessage() - this.personalMessageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(cleanErrorStack(new Error('Nifty Wallet Message Signature: User denied message signature.'))) - default: - return cb(cleanErrorStack(new Error(`Nifty Wallet Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) - } - }) + return promise } /** @@ -942,26 +969,11 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Object} msgParams - The params passed to eth_signTypedData. * @param {Function} cb - The callback function, called with the signature. */ - newUnsignedTypedMessage (msgParams, cb) { - let msgId - try { - msgId = this.typedMessageManager.addUnapprovedMessage(msgParams) - this.sendUpdate() - this.opts.showUnconfirmedMessage() - } catch (e) { - return cb(e) - } - - this.typedMessageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(cleanErrorStack(new Error('Nifty Wallet Message Signature: User denied message signature.'))) - default: - return cb(cleanErrorStack(new Error(`Nifty Wallet Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) - } - }) + newUnsignedTypedMessage (msgParams, req) { + const promise = this.typedMessageManager.addUnapprovedMessageAsync(msgParams, req) + this.sendUpdate() + this.opts.showUnconfirmedMessage() + return promise } /** @@ -971,22 +983,31 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Object} msgParams - The params passed to eth_signTypedData. * @returns {Object} Full state update. */ - signTypedMessage (msgParams) { - log.info('MetaMaskController - signTypedMessage') + async signTypedMessage (msgParams) { + log.info('MetaMaskController - eth_signTypedData') const msgId = msgParams.metamaskId - // sets the status op the message to 'approved' - // and removes the metamaskId for signing - return this.typedMessageManager.approveMessage(msgParams) - .then((cleanMsgParams) => { - // signs the message - return this.keyringController.signTypedMessage(cleanMsgParams) - }) - .then((rawSig) => { - // tells the listener that the message has been signed - // and can be returned to the dapp - this.typedMessageManager.setMsgStatusSigned(msgId, rawSig) - return this.getState() - }) + const version = msgParams.version + try { + const cleanMsgParams = await this.typedMessageManager.approveMessage(msgParams) + const address = sigUtil.normalize(cleanMsgParams.from) + const keyring = await this.keyringController.getKeyringForAccount(address) + const wallet = keyring._getWalletForAccount(address) + const privKey = ethUtil.toBuffer(wallet.getPrivateKey()) + let signature + switch (version) { + case 'V1': + signature = sigUtil.signTypedDataLegacy(privKey, { data: cleanMsgParams.data }) + break + case 'V3': + signature = sigUtil.signTypedData(privKey, { data: JSON.parse(cleanMsgParams.data) }) + break + } + this.typedMessageManager.setMsgStatusSigned(msgId, signature) + return this.getState() + } catch (error) { + log.info('MetaMaskController - eth_signTypedData failed.', error) + this.typedMessageManager.errorMessage(msgId, error) + } } /** @@ -1024,35 +1045,16 @@ module.exports = class MetamaskController extends EventEmitter { /** * A legacy method used to record user confirmation that they understand * that some of their accounts have been recovered but should be backed up. + * This function no longer does anything and will be removed. * * @deprecated * @param {Function} cb - A callback function called with a full state update. */ markAccountsFound (cb) { - this.configManager.setLostAccounts([]) - this.sendUpdate() + // TODO Remove me cb(null, this.getState()) } - /** - * A legacy method (probably dead code) that was used when we swapped out our - * key management library that we depended on. - * - * Described in: - * https://medium.com/metamask/metamask-3-migration-guide-914b79533cdd - * - * @deprecated - * @param {} migratorOutput - */ - restoreOldLostAccounts (migratorOutput) { - const { lostAccounts } = migratorOutput - if (lostAccounts) { - this.configManager.setLostAccounts(lostAccounts.map(acct => acct.address)) - return this.importLostAccounts(migratorOutput) - } - return Promise.resolve(migratorOutput) - } - /** * An account object * @typedef Account @@ -1097,6 +1099,19 @@ module.exports = class MetamaskController extends EventEmitter { return state } + /** + * Allows a user to attempt to cancel a previously submitted transaction by creating a new + * transaction. + * @param {number} originalTxId - the id of the txMeta that you want to attempt to cancel + * @param {string=} customGasPrice - the hex value to use for the cancel transaction + * @returns {object} MetaMask state + */ + async createCancelTransaction (originalTxId, customGasPrice, cb) { + await this.txController.createCancelTransaction(originalTxId, customGasPrice) + const state = await this.getState() + return state + } + estimateGas (estimateGasParams) { return new Promise((resolve, reject) => { return this.txController.txGasUtil.query.estimateGas(estimateGasParams, (err, res) => { @@ -1118,7 +1133,7 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Function} cb - A callback function called when complete. */ markPasswordForgotten (cb) { - this.configManager.setPasswordForgotten(true) + this.preferencesController.setPasswordForgotten(true) this.sendUpdate() cb() } @@ -1128,7 +1143,7 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Function} cb - A callback function called when complete. */ unMarkPasswordForgotten (cb) { - this.configManager.setPasswordForgotten(false) + this.preferencesController.setPasswordForgotten(false) this.sendUpdate() cb() } @@ -1199,18 +1214,28 @@ module.exports = class MetamaskController extends EventEmitter { setupControllerConnection (outStream) { const api = this.getApi() const dnode = Dnode(api) + // report new active controller connection + this.activeControllerConnections++ + this.emit('controllerConnectionChanged', this.activeControllerConnections) + // connect dnode api to remote connection pump( outStream, dnode, outStream, (err) => { + // report new active controller connection + this.activeControllerConnections-- + this.emit('controllerConnectionChanged', this.activeControllerConnections) + // report any error if (err) log.error(err) } ) dnode.on('remote', (remote) => { // push updates to popup - const sendUpdate = remote.sendUpdate.bind(remote) + const sendUpdate = (update) => remote.sendUpdate(update) this.on('update', sendUpdate) + // remove update listener once the connection ends + dnode.on('end', () => this.removeListener('update', sendUpdate)) }) } @@ -1226,12 +1251,16 @@ module.exports = class MetamaskController extends EventEmitter { // create filter polyfill middleware const filterMiddleware = createFilterMiddleware({ provider: this.provider, - blockTracker: this.provider._blockTracker, + blockTracker: this.blockTracker, }) engine.push(createOriginMiddleware({ origin })) engine.push(createLoggerMiddleware({ origin })) engine.push(filterMiddleware) + engine.push(this.preferencesController.requestWatchAsset.bind(this.preferencesController)) + engine.push(this.createTypedDataMiddleware('eth_signTypedData', 'V1').bind(this)) + engine.push(this.createTypedDataMiddleware('eth_signTypedData_v1', 'V1').bind(this)) + engine.push(this.createTypedDataMiddleware('eth_signTypedData_v3', 'V3').bind(this)) engine.push(createProviderMiddleware({ provider: this.provider })) // setup connection @@ -1259,15 +1288,45 @@ module.exports = class MetamaskController extends EventEmitter { * @param {*} outStream - The stream to provide public config over. */ setupPublicConfig (outStream) { + const configStream = asStream(this.publicConfigStore) pump( - asStream(this.publicConfigStore), + configStream, outStream, (err) => { + configStream.destroy() if (err) log.error(err) } ) } + /** + * Handle a KeyringController update + * @param {object} state the KC state + * @return {Promise} + * @private + */ + async _onKeyringControllerUpdate (state) { + const {isUnlocked, keyrings} = state + const addresses = keyrings.reduce((acc, {accounts}) => acc.concat(accounts), []) + + if (!addresses.length) { + return + } + + // Ensure preferences + identities controller know about all addresses + this.preferencesController.addAddresses(addresses) + this.accountTracker.syncWithAddresses(addresses) + + const wasLocked = !isUnlocked + if (wasLocked) { + const oldSelectedAddress = this.preferencesController.getSelectedAddress() + if (!addresses.includes(oldSelectedAddress)) { + const address = addresses[0] + await this.preferencesController.setSelectedAddress(address) + } + } + } + /** * A method for emitting the full MetaMask state to all registered listeners. * @private @@ -1439,6 +1498,7 @@ module.exports = class MetamaskController extends EventEmitter { } } + // TODO: Replace isClientOpen methods with `controllerConnectionChanged` events. /** * A method for recording whether the MetaMask user interface is open or not. * @private @@ -1459,4 +1519,34 @@ module.exports = class MetamaskController extends EventEmitter { set isClientOpenAndUnlocked (active) { this.tokenRatesController.isActive = active } + + /** + * Creates RPC engine middleware for processing eth_signTypedData requests + * + * @param {Object} req - request object + * @param {Object} res - response object + * @param {Function} - next + * @param {Function} - end + */ + createTypedDataMiddleware (methodName, version) { + return async (req, res, next, end) => { + const { method, params } = req + if (method === methodName) { + const promise = this.typedMessageManager.addUnapprovedMessageAsync({ + data: params.length >= 1 && params[0], + from: params.length >= 2 && params[1], + }, req, version) + this.sendUpdate() + this.opts.showUnconfirmedMessage() + try { + res.result = await promise + end() + } catch (error) { + end(error) + } + } else { + next() + } + } + } } diff --git a/app/scripts/migrations/_multi-keyring.js b/app/scripts/migrations/_multi-keyring.js deleted file mode 100644 index 4cf27f343..000000000 --- a/app/scripts/migrations/_multi-keyring.js +++ /dev/null @@ -1,50 +0,0 @@ -const version = 5 - -/* - -This is an incomplete migration bc it requires post-decrypted data -which we dont have access to at the time of this writing. - -*/ - -const ObservableStore = require('obs-store') -const ConfigManager = require('../../app/scripts/lib/config-manager') -const IdentityStoreMigrator = require('../../app/scripts/lib/idStore-migrator') -const KeyringController = require('eth-keychain-controller') - -const password = 'obviously not correct' - -module.exports = { - version, - - migrate: function (versionedData) { - versionedData.meta.version = version - - const store = new ObservableStore(versionedData.data) - const configManager = new ConfigManager({ store }) - const idStoreMigrator = new IdentityStoreMigrator({ configManager }) - const keyringController = new KeyringController({ - configManager: configManager, - }) - - // attempt to migrate to multiVault - return idStoreMigrator.migratedVaultForPassword(password) - .then((result) => { - // skip if nothing to migrate - if (!result) return Promise.resolve(versionedData) - delete versionedData.data.wallet - // create new keyrings - const privKeys = result.lostAccounts.map(acct => acct.privateKey) - return Promise.all([ - keyringController.restoreKeyring(result.serialized), - keyringController.restoreKeyring({ type: 'Simple Key Pair', data: privKeys }), - ]).then(() => { - return keyringController.persistAllKeyrings(password) - }).then(() => { - // copy result on to state object - versionedData.data = store.get() - return Promise.resolve(versionedData) - }) - }) - }, -} diff --git a/app/scripts/notice-controller.js b/app/scripts/notice-controller.js index 2def4371e..ce686d9d1 100644 --- a/app/scripts/notice-controller.js +++ b/app/scripts/notice-controller.js @@ -7,7 +7,7 @@ const uniqBy = require('lodash.uniqby') module.exports = class NoticeController extends EventEmitter { - constructor (opts) { + constructor (opts = {}) { super() this.noticePoller = null this.firstVersion = opts.firstVersion diff --git a/app/scripts/ui.js b/app/scripts/ui.js index 4b7556b5f..eabc1d37f 100644 --- a/app/scripts/ui.js +++ b/app/scripts/ui.js @@ -2,7 +2,7 @@ const injectCss = require('inject-css') const OldMetaMaskUiCss = require('../../old-ui/css') const NewMetaMaskUiCss = require('../../ui/css') const startPopup = require('./popup-core') -const PortStream = require('./lib/port-stream.js') +const PortStream = require('extension-port-stream') const { getEnvironmentType } = require('./lib/util') const { ENVIRONMENT_TYPE_NOTIFICATION } = require('./lib/enums') const extension = require('extensionizer') diff --git a/development/states/add-token.json b/development/states/add-token.json index 80ed30e25..a01582cc0 100644 --- a/development/states/add-token.json +++ b/development/states/add-token.json @@ -124,6 +124,7 @@ "modalState": {}, "previousModalState": {} }, + "sidebar": {}, "transForward": true, "isLoading": false, "warning": null, diff --git a/development/states/confirm-new-ui.json b/development/states/confirm-new-ui.json index 6560f2da6..c362036c7 100644 --- a/development/states/confirm-new-ui.json +++ b/development/states/confirm-new-ui.json @@ -141,6 +141,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "modal": { "modalState": {}, "previousModalState": {} diff --git a/development/states/confirm-sig-requests.json b/development/states/confirm-sig-requests.json index edd4de685..5e3017592 100644 --- a/development/states/confirm-sig-requests.json +++ b/development/states/confirm-sig-requests.json @@ -162,6 +162,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "modal": { "modalState": {}, "previousModalState": {} diff --git a/development/states/currency-localization.json b/development/states/currency-localization.json index 634203b18..1db7fb839 100644 --- a/development/states/currency-localization.json +++ b/development/states/currency-localization.json @@ -120,6 +120,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "modal": { "modalState": {}, "previousModalState": {} diff --git a/development/states/first-time.json b/development/states/first-time.json index f44148973..a31b985a3 100644 --- a/development/states/first-time.json +++ b/development/states/first-time.json @@ -48,6 +48,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "transForward": true, "isLoading": false, "warning": null, diff --git a/development/states/send-edit.json b/development/states/send-edit.json index 8c0d5af2f..0ee8c72ee 100644 --- a/development/states/send-edit.json +++ b/development/states/send-edit.json @@ -22,6 +22,7 @@ "name": "Send Account 4" } }, + "assetImages": {}, "unapprovedTxs": {}, "currentCurrency": "USD", "conversionRate": 1200.88200327, @@ -141,6 +142,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "modal": { "modalState": {}, "previousModalState": {} diff --git a/development/states/send-new-ui.json b/development/states/send-new-ui.json index 6d8559902..ac77129d4 100644 --- a/development/states/send-new-ui.json +++ b/development/states/send-new-ui.json @@ -61,6 +61,7 @@ "name": "Address Book Account 1" } ], + "assetImages": {}, "tokens": [], "transactions": {}, "selectedAddressTxList": [], @@ -120,6 +121,7 @@ "accountDetail": { "subview": "transactions" }, + "sidebar": {}, "modal": { "modalState": {}, "previousModalState": {} diff --git a/development/states/send.json b/development/states/send.json index 73ac62f65..4c67f8ac6 100644 --- a/development/states/send.json +++ b/development/states/send.json @@ -21,6 +21,7 @@ "name": "Account 4" } }, + "assetImages": {}, "unapprovedTxs": {}, "currentCurrency": "USD", "conversionRate": 16.88200327, @@ -99,6 +100,7 @@ "accountExport": "none", "privateKey": "" }, + "sidebar": {}, "transForward": true, "isLoading": false, "warning": null, diff --git a/development/states/tx-list-items.json b/development/states/tx-list-items.json index a0248c89b..9541058ac 100644 --- a/development/states/tx-list-items.json +++ b/development/states/tx-list-items.json @@ -118,6 +118,7 @@ "modalState": {}, "previousModalState": {} }, + "sidebar": {}, "transForward": true, "isLoading": false, "warning": null, diff --git a/docs/adding-new-networks.md b/docs/adding-new-networks.md index ea1453c21..b74233fa6 100644 --- a/docs/adding-new-networks.md +++ b/docs/adding-new-networks.md @@ -5,7 +5,6 @@ To add another network to our dropdown menu, make sure the following files are a ``` app/scripts/config.js app/scripts/lib/buy-eth-url.js -app/scripts/lib/config-manager.js ui/app/app.js ui/app/components/buy-button-subview.js ui/app/components/drop-menu-item.js diff --git a/docs/developing-on-deps.md b/docs/developing-on-deps.md index 7de3f67a8..e2e07cb4e 100644 --- a/docs/developing-on-deps.md +++ b/docs/developing-on-deps.md @@ -1,10 +1,9 @@ ### Developing on Dependencies -To enjoy the live-reloading that `gulp dev` offers while working on the `web3-provider-engine` or other dependencies: +To enjoy the live-reloading that `gulp dev` offers while working on the dependencies: 1. Clone the dependency locally. 2. `npm install` in its folder. 3. Run `npm link` in its folder. 4. Run `npm link $DEP_NAME` in this project folder. 5. Next time you `npm start` it will watch the dependency for changes as well! - diff --git a/docs/porting_to_new_environment.md b/docs/porting_to_new_environment.md index 3b1e46052..983c81f3e 100644 --- a/docs/porting_to_new_environment.md +++ b/docs/porting_to_new_environment.md @@ -89,8 +89,6 @@ MetaMask has two kinds of [duplex stream APIs](https://github.com/substack/strea If you are making a MetaMask-powered browser for a new platform, one of the trickiest tasks will be injecting the Web3 API into websites that are visited. On WebExtensions, we actually have to pipe data through a total of three JS contexts just to let sites talk to our background process (site -> contentscript -> background). -To make this as easy as possible, we use one of our favorite internal tools, [web3-provider-engine](https://www.npmjs.com/package/web3-provider-engine) to construct a custom web3 provider object whose source of truth is a stream that we connect to remotely. - To see how we do that, you can refer to the [inpage script](https://github.com/MetaMask/metamask-extension/blob/master/app/scripts/inpage.js) that we inject into every website. There you can see it creates a multiplex stream to the background, and uses it to initialize what we call the [inpage-provider](https://github.com/MetaMask/metamask-extension/blob/master/app/scripts/lib/inpage-provider.js), which you can see stubs a few methods out, but mostly just passes calls to `sendAsync` through the stream it's passed! That's really all the magic that's needed to create a web3-like API in a remote context, once you have a stream to MetaMask available. In `inpage.js` you can see we create a `PortStream`, that's just a class we use to wrap WebExtension ports as streams, so we can reuse our favorite stream abstraction over the more irregular API surface of the WebExtension. In a new platform, you will probably need to construct this stream differently. The key is that you need to construct a stream that talks from the site context to the background. Once you have that set up, it works like magic! diff --git a/mascara/src/app/first-time/create-password-screen.js b/mascara/src/app/first-time/create-password-screen.js index d7d005753..9d0cfe530 100644 --- a/mascara/src/app/first-time/create-password-screen.js +++ b/mascara/src/app/first-time/create-password-screen.js @@ -62,7 +62,9 @@ class CreatePasswordScreen extends Component { return password === confirmPassword } - createAccount = () => { + createAccount = (event) => { + event.preventDefault() + if (!this.isValid()) { return } @@ -121,7 +123,7 @@ class CreatePasswordScreen extends Component { It allows you to hold ether & tokens, and interact with decentralized applications. } -
+
Create Password
@@ -182,7 +184,7 @@ class CreatePasswordScreen extends Component { { */ } -
+ ) diff --git a/old-ui/app/account-detail.js b/old-ui/app/account-detail.js index 59b6623d4..b581df38f 100644 --- a/old-ui/app/account-detail.js +++ b/old-ui/app/account-detail.js @@ -33,6 +33,7 @@ function mapStateToProps (state) { currentCurrency: state.metamask.currentCurrency, currentAccountTab: state.metamask.currentAccountTab, tokens: state.metamask.tokens, + suggestedTokens: state.metamask.suggestedTokens, computedBalances: state.metamask.computedBalances, } } @@ -50,6 +51,10 @@ AccountDetailScreen.prototype.render = function () { var account = props.accounts[selected] const { network, conversionRate, currentCurrency } = props + if (Object.keys(props.suggestedTokens).length > 0) { + this.props.dispatch(actions.showAddSuggestedTokenPage()) + } + return ( h('.account-detail-section.full-flex-height', [ diff --git a/old-ui/app/add-suggested-token.js b/old-ui/app/add-suggested-token.js new file mode 100644 index 000000000..ea534b7da --- /dev/null +++ b/old-ui/app/add-suggested-token.js @@ -0,0 +1,202 @@ +const inherits = require('util').inherits +const Component = require('react').Component +const h = require('react-hyperscript') +const connect = require('react-redux').connect +const actions = require('../../ui/app/actions') +const Tooltip = require('./components/tooltip.js') +const ethUtil = require('ethereumjs-util') +const Copyable = require('./components/copyable') +const addressSummary = require('./util').addressSummary + + +module.exports = connect(mapStateToProps)(AddSuggestedTokenScreen) + +function mapStateToProps (state) { + return { + identities: state.metamask.identities, + suggestedTokens: state.metamask.suggestedTokens, + } +} + +inherits(AddSuggestedTokenScreen, Component) +function AddSuggestedTokenScreen () { + this.state = { + warning: null, + } + Component.call(this) +} + +AddSuggestedTokenScreen.prototype.render = function () { + const state = this.state + const props = this.props + const { warning } = state + const key = Object.keys(props.suggestedTokens)[0] + const { address, symbol, decimals } = props.suggestedTokens[key] + + return ( + h('.flex-column.flex-grow', [ + + // subtitle and nav + h('.section-title.flex-row.flex-center', [ + h('h2.page-subtitle', 'Add Suggested Token'), + ]), + + h('.error', { + style: { + display: warning ? 'block' : 'none', + padding: '0 20px', + textAlign: 'center', + }, + }, warning), + + // conf view + h('.flex-column.flex-justify-center.flex-grow.select-none', [ + h('.flex-space-around', { + style: { + padding: '20px', + }, + }, [ + + h('div', [ + h(Tooltip, { + position: 'top', + title: 'The contract of the actual token contract. Click for more info.', + }, [ + h('a', { + style: { fontWeight: 'bold', paddingRight: '10px'}, + href: 'https://support.metamask.io/kb/article/24-what-is-a-token-contract-address', + target: '_blank', + }, [ + h('span', 'Token Contract Address '), + h('i.fa.fa-question-circle'), + ]), + ]), + ]), + + h('div', { + style: { display: 'flex' }, + }, [ + h(Copyable, { + value: ethUtil.toChecksumAddress(address), + }, [ + h('span#token-address', { + style: { + width: 'inherit', + flex: '1 0 auto', + height: '30px', + margin: '8px', + display: 'flex', + }, + }, addressSummary(address, 24, 4, false)), + ]), + ]), + + h('div', [ + h('span', { + style: { fontWeight: 'bold', paddingRight: '10px'}, + }, 'Token Symbol'), + ]), + + h('div', { style: {display: 'flex'} }, [ + h('p#token_symbol', { + style: { + width: 'inherit', + flex: '1 0 auto', + height: '30px', + margin: '8px', + }, + }, symbol), + ]), + + h('div', [ + h('span', { + style: { fontWeight: 'bold', paddingRight: '10px'}, + }, 'Decimals of Precision'), + ]), + + h('div', { style: {display: 'flex'} }, [ + h('p#token_decimals', { + type: 'number', + style: { + width: 'inherit', + flex: '1 0 auto', + height: '30px', + margin: '8px', + }, + }, decimals), + ]), + + h('button', { + style: { + alignSelf: 'center', + margin: '8px', + }, + onClick: (event) => { + this.props.dispatch(actions.removeSuggestedTokens()) + }, + }, 'Cancel'), + + h('button', { + style: { + alignSelf: 'center', + margin: '8px', + }, + onClick: (event) => { + const valid = this.validateInputs({ address, symbol, decimals }) + if (!valid) return + + this.props.dispatch(actions.addToken(address.trim(), symbol.trim(), decimals)) + .then(() => { + this.props.dispatch(actions.removeSuggestedTokens()) + }) + }, + }, 'Add'), + ]), + ]), + ]) + ) +} + +AddSuggestedTokenScreen.prototype.componentWillMount = function () { + if (typeof global.ethereumProvider === 'undefined') return +} + +AddSuggestedTokenScreen.prototype.validateInputs = function (opts) { + let msg = '' + const identitiesList = Object.keys(this.props.identities) + const { address, symbol, decimals } = opts + const standardAddress = ethUtil.addHexPrefix(address).toLowerCase() + + const validAddress = ethUtil.isValidAddress(address) + if (!validAddress) { + msg += 'Address is invalid.' + } + + const validDecimals = decimals >= 0 && decimals <= 36 + if (!validDecimals) { + msg += 'Decimals must be at least 0, and not over 36. ' + } + + const symbolLen = symbol.trim().length + const validSymbol = symbolLen > 0 && symbolLen < 10 + if (!validSymbol) { + msg += 'Symbol must be between 0 and 10 characters.' + } + + const ownAddress = identitiesList.includes(standardAddress) + if (ownAddress) { + msg = 'Personal address detected. Input the token contract address.' + } + + const isValid = validAddress && validDecimals && !ownAddress + + if (!isValid) { + this.setState({ + warning: msg, + }) + } else { + this.setState({ warning: null }) + } + + return isValid +} diff --git a/old-ui/app/app.js b/old-ui/app/app.js index 170a5c520..a3aa70fd9 100644 --- a/old-ui/app/app.js +++ b/old-ui/app/app.js @@ -26,6 +26,7 @@ const ConfigScreen = require('./config') const AddTokenScreen = require('./components/add-token') const ConfirmAddTokenScreen = require('./components/confirm-add-token') const RemoveTokenScreen = require('./remove-token') +const AddSuggestedTokenScreen = require('./add-suggested-token') const Import = require('./accounts/import') const InfoScreen = require('./info') const AppBar = require('./components/app-bar') @@ -80,6 +81,7 @@ function mapStateToProps (state) { lostAccounts: state.metamask.lostAccounts, frequentRpcList: state.metamask.frequentRpcList || [], featureFlags, + suggestedTokens: state.metamask.suggestedTokens, // state needed to get account dropdown temporarily rendering from app bar identities, @@ -248,6 +250,10 @@ App.prototype.renderPrimary = function () { log.debug('rendering remove-token screen from unlock screen.') return h(RemoveTokenScreen, {key: 'remove-token', ...props.currentView.context }) + case 'add-suggested-token': + log.debug('rendering add-suggested-token screen from unlock screen.') + return h(AddSuggestedTokenScreen, {key: 'add-suggested-token'}) + case 'config': log.debug('rendering config screen') return h(ConfigScreen, {key: 'config'}) diff --git a/old-ui/app/components/notice.js b/old-ui/app/components/notice.js index 79caa2c88..697b58681 100644 --- a/old-ui/app/components/notice.js +++ b/old-ui/app/components/notice.js @@ -124,6 +124,12 @@ Notice.prototype.render = function () { ) } +Notice.prototype.setInitialDisclaimerState = function () { + if (document.getElementsByClassName('notice-box')[0].clientHeight < 310) { + this.setState({disclaimerDisabled: false}) + } +} + Notice.prototype.componentDidMount = function () { // eslint-disable-next-line react/no-find-dom-node var node = findDOMNode(this) @@ -131,6 +137,16 @@ Notice.prototype.componentDidMount = function () { if (document.getElementsByClassName('notice-box')[0].clientHeight < 300) { this.setState({disclaimerDisabled: false}) } + this.setInitialDisclaimerState() +} + +Notice.prototype.componentDidUpdate = function (prevProps) { + const { notice: { id } = {} } = this.props + const { notice: { id: prevNoticeId } = {} } = prevProps + + if (id !== prevNoticeId) { + this.setInitialDisclaimerState() + } } Notice.prototype.componentWillUnmount = function () { diff --git a/old-ui/app/components/pending-typed-msg-details.js b/old-ui/app/components/pending-typed-msg-details.js index b5fd29f71..f95bf43a7 100644 --- a/old-ui/app/components/pending-typed-msg-details.js +++ b/old-ui/app/components/pending-typed-msg-details.js @@ -21,7 +21,7 @@ PendingMsgDetails.prototype.render = function () { var identity = state.identities[address] || { address: address } var account = state.accounts[address] || { address: address } - var { data } = msgParams + var { data, version } = msgParams return ( h('div', { @@ -48,6 +48,7 @@ PendingMsgDetails.prototype.render = function () { h('label.font-small', { style: { display: 'block' } }, 'YOU ARE SIGNING'), h(TypedMessageRenderer, { value: data, + version, style: { height: '215px', }, diff --git a/old-ui/app/components/typed-message-renderer.js b/old-ui/app/components/typed-message-renderer.js index 19e46f4fc..0dc673b8a 100644 --- a/old-ui/app/components/typed-message-renderer.js +++ b/old-ui/app/components/typed-message-renderer.js @@ -2,6 +2,7 @@ const Component = require('react').Component const h = require('react-hyperscript') const inherits = require('util').inherits const extend = require('xtend') +const { ObjectInspector } = require('react-inspector') module.exports = TypedMessageRenderer @@ -12,8 +13,16 @@ function TypedMessageRenderer () { TypedMessageRenderer.prototype.render = function () { const props = this.props - const { value, style } = props - const text = renderTypedData(value) + const { value, version, style } = props + let text + switch (version) { + case 'V1': + text = renderTypedData(value) + break + case 'V3': + text = renderTypedDataV3(value) + break + } const defaultStyle = extend({ width: '315px', @@ -44,3 +53,17 @@ function renderTypedData (values) { ]) }) } + +function renderTypedDataV3 (values) { + const { domain, message } = JSON.parse(values) + return [ + domain ? h('div', [ + h('h1', 'Domain'), + h(ObjectInspector, { data: domain, expandLevel: 1, name: 'domain' }), + ]) : '', + message ? h('div', [ + h('h1', 'Message'), + h(ObjectInspector, { data: message, expandLevel: 1, name: 'message' }), + ]) : '', + ] +} diff --git a/package-lock.json b/package-lock.json index dfcc89105..21af609db 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1672,9 +1672,9 @@ } }, "@zxing/library": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.7.0.tgz", - "integrity": "sha512-VJ1cJaCWVF8MspnuyaZKGKlrSQLqQ5usgSap8uuCAvWGQ6W6OwN1NeGvnjhT+9hmnwkHK8XjaflvzaDBC7nKnw==", + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.8.0.tgz", + "integrity": "sha512-D7oopukr7cJ0Va01Er2zXiSPXvmvc6D1PpOq/THRvd/57yEsBs+setRsiDo7tSRnYHcw7FrRZSZ7rwyzNSLJeA==", "requires": { "text-encoding": "^0.6.4", "ts-custom-error": "^2.2.1" @@ -3963,6 +3963,7 @@ "version": "2.5.0", "resolved": "https://registry.npmjs.org/backoff/-/backoff-2.5.0.tgz", "integrity": "sha1-9hbtqdPktmuMp/ynn2lXIsX44m8=", + "dev": true, "requires": { "precond": "0.2" } @@ -5188,7 +5189,7 @@ }, "chromedriver": { "version": "2.36.0", - "resolved": "http://registry.npmjs.org/chromedriver/-/chromedriver-2.36.0.tgz", + "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-2.36.0.tgz", "integrity": "sha512-Lq2HrigCJ4RVdIdCmchenv1rVrejNSJ7EUCQojycQo12ww3FedQx4nb+GgTdqMhjbOMTqq5+ziaiZlrEN2z1gQ==", "dev": true, "requires": { @@ -6115,6 +6116,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-2.1.0.tgz", "integrity": "sha512-FTIt2WK44RiafWQ62xIvd+oBoVd392abh1lF872trLlA74JCR1s4oTHlixwoIKy44ehn8WbQ0Ds2P16sw7ZQxg==", + "dev": true, "requires": { "node-fetch": "2.1.1", "whatwg-fetch": "2.0.3" @@ -6123,7 +6125,8 @@ "node-fetch": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.1.1.tgz", - "integrity": "sha1-NpynC4L1DIZJYQSmx3bSdPTkotQ=" + "integrity": "sha1-NpynC4L1DIZJYQSmx3bSdPTkotQ=", + "dev": true } } }, @@ -8297,88 +8300,62 @@ } }, "eth-block-tracker": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/eth-block-tracker/-/eth-block-tracker-2.3.0.tgz", - "integrity": "sha512-yrNyBIBKC7WfUjrXSG/CZVy0gW2aF8+MnjnrkOxkZOR+BAtL6JgYOnzVnrU8KE6mKJETlA/1dYMygvLXWyJGGw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/eth-block-tracker/-/eth-block-tracker-4.0.1.tgz", + "integrity": "sha512-ytJxddJ0TMcJHYxPlgGhMyr5EH6/Kyp3bg0WsjXgY9X0uYX3xVHTTeU5WVX6KX+9oJ37ZLUjh5PZ6VYnF1Fx/Q==", "requires": { - "async-eventemitter": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "eth-json-rpc-infura": "^3.1.0", "eth-query": "^2.1.0", - "ethereumjs-tx": "^1.3.3", - "ethereumjs-util": "^5.1.3", - "ethjs-util": "^0.1.3", - "json-rpc-engine": "^3.6.0", - "pify": "^2.3.0", - "tape": "^4.6.3" + "pify": "^3.0.0" }, "dependencies": { - "async-eventemitter": { - "version": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", - "from": "async-eventemitter@github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "cross-fetch": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-2.2.2.tgz", + "integrity": "sha1-pH/09/xxLauo9qaVoRyUhEDUVyM=", "requires": { - "async": "^2.4.0" + "node-fetch": "2.1.2", + "whatwg-fetch": "2.0.4" } }, - "babel-preset-env": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/babel-preset-env/-/babel-preset-env-1.6.1.tgz", - "integrity": "sha512-W6VIyA6Ch9ePMI7VptNn2wBM6dbG0eSz25HEiL40nQXCsXGTGZSTZu1Iap+cj3Q0S5a7T9+529l/5Bkvd+afNA==", + "eth-json-rpc-infura": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/eth-json-rpc-infura/-/eth-json-rpc-infura-3.1.2.tgz", + "integrity": "sha512-IuK5Iowfs6taluA/3Okmu6EfZcFMq6MQuyrUL1PrCoJstuuBr3TvVeSy3keDyxfbrjFB34nCo538I8G+qMtsbw==", "requires": { - "babel-plugin-check-es2015-constants": "^6.22.0", - "babel-plugin-syntax-trailing-function-commas": "^6.22.0", - "babel-plugin-transform-async-to-generator": "^6.22.0", - "babel-plugin-transform-es2015-arrow-functions": "^6.22.0", - "babel-plugin-transform-es2015-block-scoped-functions": "^6.22.0", - "babel-plugin-transform-es2015-block-scoping": "^6.23.0", - "babel-plugin-transform-es2015-classes": "^6.23.0", - "babel-plugin-transform-es2015-computed-properties": "^6.22.0", - "babel-plugin-transform-es2015-destructuring": "^6.23.0", - "babel-plugin-transform-es2015-duplicate-keys": "^6.22.0", - "babel-plugin-transform-es2015-for-of": "^6.23.0", - "babel-plugin-transform-es2015-function-name": "^6.22.0", - "babel-plugin-transform-es2015-literals": "^6.22.0", - "babel-plugin-transform-es2015-modules-amd": "^6.22.0", - "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0", - "babel-plugin-transform-es2015-modules-systemjs": "^6.23.0", - "babel-plugin-transform-es2015-modules-umd": "^6.23.0", - "babel-plugin-transform-es2015-object-super": "^6.22.0", - "babel-plugin-transform-es2015-parameters": "^6.23.0", - "babel-plugin-transform-es2015-shorthand-properties": "^6.22.0", - "babel-plugin-transform-es2015-spread": "^6.22.0", - "babel-plugin-transform-es2015-sticky-regex": "^6.22.0", - "babel-plugin-transform-es2015-template-literals": "^6.22.0", - "babel-plugin-transform-es2015-typeof-symbol": "^6.23.0", - "babel-plugin-transform-es2015-unicode-regex": "^6.22.0", - "babel-plugin-transform-exponentiation-operator": "^6.22.0", - "babel-plugin-transform-regenerator": "^6.22.0", - "browserslist": "^2.1.2", - "invariant": "^2.2.2", - "semver": "^5.3.0" + "cross-fetch": "^2.1.1", + "eth-json-rpc-middleware": "^1.5.0", + "json-rpc-engine": "^3.4.0", + "json-rpc-error": "^2.0.0", + "tape": "^4.8.0" } }, - "babelify": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/babelify/-/babelify-7.3.0.tgz", - "integrity": "sha1-qlau3nBn/XvVSWZu4W3ChQh+iOU=", + "eth-json-rpc-middleware": { + "version": "1.6.0", + "resolved": "http://registry.npmjs.org/eth-json-rpc-middleware/-/eth-json-rpc-middleware-1.6.0.tgz", + "integrity": "sha512-tDVCTlrUvdqHKqivYMjtFZsdD7TtpNLBCfKAcOpaVs7orBMS/A8HWro6dIzNtTZIR05FAbJ3bioFOnZpuCew9Q==", "requires": { - "babel-core": "^6.0.14", - "object-assign": "^4.0.0" - } - }, - "browserslist": { - "version": "2.11.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-2.11.3.tgz", - "integrity": "sha512-yWu5cXT7Av6mVwzWc8lMsJMHWn4xyjSuGYi4IozbVTLUOEYPSagUB8kiMDUHA1fS3zjr8nkxkn9jdvug4BBRmA==", - "requires": { - "caniuse-lite": "^1.0.30000792", - "electron-to-chromium": "^1.3.30" + "async": "^2.5.0", + "eth-query": "^2.1.2", + "eth-tx-summary": "^3.1.2", + "ethereumjs-block": "^1.6.0", + "ethereumjs-tx": "^1.3.3", + "ethereumjs-util": "^5.1.2", + "ethereumjs-vm": "^2.1.0", + "fetch-ponyfill": "^4.0.0", + "json-rpc-engine": "^3.6.0", + "json-rpc-error": "^2.0.0", + "json-stable-stringify": "^1.0.1", + "promise-to-callback": "^1.0.0", + "tape": "^4.6.3" } }, "ethereumjs-util": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.1.3.tgz", - "integrity": "sha512-U/wmHagElZVxnpo3bFsvk5beFADegUcEzqtA/NfQbitAPOs6JoYq8M4SY9NfH4HD8236i63UOkkXafd7bqBL9A==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", + "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", "requires": { - "bn.js": "^4.8.0", + "bn.js": "^4.11.0", "create-hash": "^1.1.2", "ethjs-util": "^0.1.3", "keccak": "^1.0.2", @@ -8387,22 +8364,15 @@ "secp256k1": "^3.0.1" } }, - "json-rpc-engine": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/json-rpc-engine/-/json-rpc-engine-3.6.0.tgz", - "integrity": "sha512-QGEIIPMaG4lQ8iKQgzKq7Ra6hscqSL+6S+xiUFbNAoVaZII8iyN1l6tJHmUWIdbnl2o0rbwCnOPFAhTn9AJObw==", - "requires": { - "async": "^2.0.1", - "babel-preset-env": "^1.3.2", - "babelify": "^7.3.0", - "json-rpc-error": "^2.0.0", - "promise-to-callback": "^1.0.0" - } + "node-fetch": { + "version": "2.1.2", + "resolved": "http://registry.npmjs.org/node-fetch/-/node-fetch-2.1.2.tgz", + "integrity": "sha1-q4hOjn5X44qUR1POxwb3iNF2i7U=" }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" + "whatwg-fetch": { + "version": "2.0.4", + "resolved": "http://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz", + "integrity": "sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng==" } } }, @@ -8529,6 +8499,24 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } + } + }, + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" } } } @@ -8598,32 +8586,92 @@ "json-rpc-engine": "^3.4.0", "json-rpc-error": "^2.0.0", "tape": "^4.8.0" + }, + "dependencies": { + "eth-json-rpc-middleware": { + "version": "1.6.0", + "resolved": "http://registry.npmjs.org/eth-json-rpc-middleware/-/eth-json-rpc-middleware-1.6.0.tgz", + "integrity": "sha512-tDVCTlrUvdqHKqivYMjtFZsdD7TtpNLBCfKAcOpaVs7orBMS/A8HWro6dIzNtTZIR05FAbJ3bioFOnZpuCew9Q==", + "requires": { + "async": "^2.5.0", + "eth-query": "^2.1.2", + "eth-tx-summary": "^3.1.2", + "ethereumjs-block": "^1.6.0", + "ethereumjs-tx": "^1.3.3", + "ethereumjs-util": "^5.1.2", + "ethereumjs-vm": "^2.1.0", + "fetch-ponyfill": "^4.0.0", + "json-rpc-engine": "^3.6.0", + "json-rpc-error": "^2.0.0", + "json-stable-stringify": "^1.0.1", + "promise-to-callback": "^1.0.0", + "tape": "^4.6.3" + } + }, + "ethereumjs-util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", + "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", + "requires": { + "bn.js": "^4.11.0", + "create-hash": "^1.1.2", + "ethjs-util": "^0.1.3", + "keccak": "^1.0.2", + "rlp": "^2.0.0", + "safe-buffer": "^5.1.1", + "secp256k1": "^3.0.1" + } + } } }, "eth-json-rpc-middleware": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/eth-json-rpc-middleware/-/eth-json-rpc-middleware-1.6.0.tgz", - "integrity": "sha512-tDVCTlrUvdqHKqivYMjtFZsdD7TtpNLBCfKAcOpaVs7orBMS/A8HWro6dIzNtTZIR05FAbJ3bioFOnZpuCew9Q==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/eth-json-rpc-middleware/-/eth-json-rpc-middleware-2.4.0.tgz", + "integrity": "sha512-KUxyz7pr6MZmFlsym8EObWwrFHVxRCLHGfl8H2V7D4ZjK0yhoPaA94jSXAumUbfx2AmyYEtG9j2xmU1P83m7OQ==", + "dev": true, "requires": { "async": "^2.5.0", + "clone": "^2.1.1", "eth-query": "^2.1.2", + "eth-sig-util": "^1.4.2", "eth-tx-summary": "^3.1.2", "ethereumjs-block": "^1.6.0", "ethereumjs-tx": "^1.3.3", "ethereumjs-util": "^5.1.2", "ethereumjs-vm": "^2.1.0", "fetch-ponyfill": "^4.0.0", - "json-rpc-engine": "^3.6.0", + "json-rpc-engine": "^3.6.3", "json-rpc-error": "^2.0.0", "json-stable-stringify": "^1.0.1", + "pify": "^3.0.0", "promise-to-callback": "^1.0.0", "tape": "^4.6.3" }, "dependencies": { + "eth-sig-util": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/eth-sig-util/-/eth-sig-util-1.4.2.tgz", + "integrity": "sha1-jZWCAsftuq6Dlwf7pvCf8ydgYhA=", + "dev": true, + "requires": { + "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "ethereumjs-util": "^5.1.1" + } + }, + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "dev": true, + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + }, "ethereumjs-util": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", + "dev": true, "requires": { "bn.js": "^4.11.0", "create-hash": "^1.1.2", @@ -8672,12 +8720,22 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "dev": true, + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } } }, "ethereumjs-abi": { "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", - "dev": true, "requires": { "bn.js": "^4.10.0", "ethereumjs-util": "^5.0.0" @@ -8687,7 +8745,6 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", - "dev": true, "requires": { "bn.js": "^4.11.0", "create-hash": "^1.1.2", @@ -8732,6 +8789,16 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } } }, "ethereum-common": { @@ -8934,13 +9001,13 @@ "resolved": "https://registry.npmjs.org/eth-sig-util/-/eth-sig-util-2.0.2.tgz", "integrity": "sha512-tB6E8jf/aZQ943bo3+iojl8xRe3Jzcl+9OT6v8K7kWis6PdIX19SB2vYvN849cB9G9m/XLjYFK381SgdbsnpTA==", "requires": { - "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "ethereumjs-abi": "0.6.5", "ethereumjs-util": "^5.1.1" }, "dependencies": { "ethereumjs-abi": { - "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", - "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "version": "0.6.5", + "resolved": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "requires": { "bn.js": "^4.10.0", "ethereumjs-util": "^5.0.0" @@ -9205,6 +9272,16 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } } }, "ethereum-common": { @@ -9336,6 +9413,11 @@ } } }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" + }, "web3-provider-engine": { "version": "13.8.0", "resolved": "https://registry.npmjs.org/web3-provider-engine/-/web3-provider-engine-13.8.0.tgz", @@ -9362,6 +9444,28 @@ "xtend": "^4.0.1" }, "dependencies": { + "async-eventemitter": { + "version": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "from": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "requires": { + "async": "^2.4.0" + } + }, + "eth-block-tracker": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/eth-block-tracker/-/eth-block-tracker-2.3.1.tgz", + "integrity": "sha512-NamWuMBIl8kmkJFVj8WzGatySTzQPQag4Xr677yFxdVtIxACFbL/dQowk0MzEqIKk93U1TwY3MjVU6mOcwZnKA==", + "requires": { + "async-eventemitter": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "eth-query": "^2.1.0", + "ethereumjs-tx": "^1.3.3", + "ethereumjs-util": "^5.1.3", + "ethjs-util": "^0.1.3", + "json-rpc-engine": "^3.6.0", + "pify": "^2.3.0", + "tape": "^4.6.3" + } + }, "eth-sig-util": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/eth-sig-util/-/eth-sig-util-1.4.2.tgz", @@ -9369,6 +9473,24 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } + } + }, + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" } }, "ethereumjs-util": { @@ -10196,6 +10318,52 @@ "extensionizer": "^1.0.0" } }, + "extension-port-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/extension-port-stream/-/extension-port-stream-1.0.0.tgz", + "integrity": "sha512-FsFr64yr6ituPdaGP6Io5recGFWVjJoDYt7asz2AvPkYqGN9c923nmEtyHH+413066bjGcQZaF8w5wn9HbNXiQ==", + "requires": { + "readable-stream": "^2.3.6", + "util": "^0.11.0" + }, + "dependencies": { + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "util": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/util/-/util-0.11.0.tgz", + "integrity": "sha512-5n12uMzKCjvB2HPFHnbQSjaqAa98L5iIXmHrZCLavuZVe0qe/SJGbDGWlpaHk5lnBkWRDO+dRu1/PgmUYKPPTw==", + "requires": { + "inherits": "2.0.3" + } + } + } + }, "extensionizer": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/extensionizer/-/extensionizer-1.0.1.tgz", @@ -12181,8 +12349,7 @@ "bn.js": { "version": "4.11.6", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.6.tgz", - "integrity": "sha1-UzRK2xRhehP26N0s4okF0cC6MhU=", - "dev": true + "integrity": "sha1-UzRK2xRhehP26N0s4okF0cC6MhU=" }, "chai": { "version": "3.5.0", @@ -12273,6 +12440,46 @@ "node-fetch": "2.1.2", "whatwg-fetch": "2.0.4" } + }, + "eth-json-rpc-middleware": { + "version": "1.6.0", + "resolved": "http://registry.npmjs.org/eth-json-rpc-middleware/-/eth-json-rpc-middleware-1.6.0.tgz", + "integrity": "sha512-tDVCTlrUvdqHKqivYMjtFZsdD7TtpNLBCfKAcOpaVs7orBMS/A8HWro6dIzNtTZIR05FAbJ3bioFOnZpuCew9Q==", + "dev": true, + "requires": { + "async": "^2.5.0", + "eth-query": "^2.1.2", + "eth-tx-summary": "^3.1.2", + "ethereumjs-block": "^1.6.0", + "ethereumjs-tx": "^1.3.3", + "ethereumjs-util": "^5.1.2", + "ethereumjs-vm": "^2.1.0", + "fetch-ponyfill": "^4.0.0", + "json-rpc-engine": "^3.6.0", + "json-rpc-error": "^2.0.0", + "json-stable-stringify": "^1.0.1", + "promise-to-callback": "^1.0.0", + "tape": "^4.6.3" + } + }, + "ethereum-common": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/ethereum-common/-/ethereum-common-0.2.0.tgz", + "integrity": "sha512-XOnAR/3rntJgbCdGhqdaLIxDLWKLmsZOGhHdBKadEr6gEnJLH52k93Ou+TUdFaPN3hJc3isBZBal3U/XZ15abA==", + "dev": true + }, + "ethereumjs-block": { + "version": "1.7.1", + "resolved": "http://registry.npmjs.org/ethereumjs-block/-/ethereumjs-block-1.7.1.tgz", + "integrity": "sha512-B+sSdtqm78fmKkBq78/QLKJbu/4Ts4P2KFISdgcuZUPDm9x+N7qgBPIIFUGbaakQh8bzuquiRVbdmvPKqbILRg==", + "dev": true, + "requires": { + "async": "^2.0.1", + "ethereum-common": "0.2.0", + "ethereumjs-tx": "^1.2.2", + "ethereumjs-util": "^5.0.0", + "merkle-patricia-tree": "^2.1.2" + } } } }, @@ -12285,7 +12492,6 @@ "ethereumjs-abi": { "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", - "dev": true, "requires": { "bn.js": "^4.10.0", "ethereumjs-util": "^5.0.0" @@ -12380,7 +12586,6 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", - "dev": true, "requires": { "bn.js": "^4.11.0", "create-hash": "^1.1.2", @@ -12559,6 +12764,17 @@ "requires": { "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", "ethereumjs-util": "^5.1.1" + }, + "dependencies": { + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", + "dev": true, + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + } } }, "ethereum-common": { @@ -12567,6 +12783,14 @@ "integrity": "sha1-L9w1dvIykDNYl26znaeDIT/5Uj8=", "dev": true }, + "ethereumjs-abi": { + "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", + "requires": { + "bn.js": "^4.10.0", + "ethereumjs-util": "^5.0.0" + } + }, "ethereumjs-tx": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/ethereumjs-tx/-/ethereumjs-tx-1.3.3.tgz", @@ -16087,8 +16311,7 @@ "is-dom": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/is-dom/-/is-dom-1.0.9.tgz", - "integrity": "sha1-SDgy1SlyBz3hK5/j9gMghw2oNw0=", - "dev": true + "integrity": "sha1-SDgy1SlyBz3hK5/j9gMghw2oNw0=" }, "is-dotfile": { "version": "1.0.3", @@ -17056,11 +17279,47 @@ "readable-stream": "^2.3.3" }, "dependencies": { + "async-eventemitter": { + "version": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "from": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "requires": { + "async": "^2.4.0" + } + }, "bn.js": { "version": "4.11.6", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.6.tgz", "integrity": "sha1-UzRK2xRhehP26N0s4okF0cC6MhU=" }, + "eth-block-tracker": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/eth-block-tracker/-/eth-block-tracker-2.3.1.tgz", + "integrity": "sha512-NamWuMBIl8kmkJFVj8WzGatySTzQPQag4Xr677yFxdVtIxACFbL/dQowk0MzEqIKk93U1TwY3MjVU6mOcwZnKA==", + "requires": { + "async-eventemitter": "github:ahultgren/async-eventemitter#fa06e39e56786ba541c180061dbf2c0a5bbf951c", + "eth-query": "^2.1.0", + "ethereumjs-tx": "^1.3.3", + "ethereumjs-util": "^5.1.3", + "ethjs-util": "^0.1.3", + "json-rpc-engine": "^3.6.0", + "pify": "^2.3.0", + "tape": "^4.6.3" + } + }, + "ethereumjs-util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.2.0.tgz", + "integrity": "sha512-CJAKdI0wgMbQFLlLRtZKGcy/L6pzVRgelIZqRqNbuVFM3K9VEnyfbcvz0ncWMRNCe4kaHWjwRYQcYMucmwsnWA==", + "requires": { + "bn.js": "^4.11.0", + "create-hash": "^1.1.2", + "ethjs-util": "^0.1.3", + "keccak": "^1.0.2", + "rlp": "^2.0.0", + "safe-buffer": "^5.1.1", + "secp256k1": "^3.0.1" + } + }, "ethjs-format": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/ethjs-format/-/ethjs-format-0.2.2.tgz", @@ -17096,6 +17355,11 @@ "is-hex-prefixed": "1.0.0", "strip-hex-prefix": "1.0.0" } + }, + "pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" } } }, @@ -17132,6 +17396,14 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, + "json2mq": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/json2mq/-/json2mq-0.2.0.tgz", + "integrity": "sha1-tje9O6nqvhIsg+lyBIOusQ0skEo=", + "requires": { + "string-convert": "^0.2.0" + } + }, "json3": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/json3/-/json3-3.3.2.tgz", @@ -17242,6 +17514,11 @@ "dev": true, "optional": true }, + "jsonschema": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.4.tgz", + "integrity": "sha512-lz1nOH69GbsVHeVgEdvyavc/33oymY1AZwtePMiMj4HZPMbP5OIKK3zT9INMWjwua/V4Z4yq7wSlBbSG+g4AEw==" + }, "jsprim": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", @@ -19931,6 +20208,26 @@ } } }, + "metamask-inpage-provider": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/metamask-inpage-provider/-/metamask-inpage-provider-1.0.0.tgz", + "integrity": "sha512-8ouTHzBuMb5DlsJstb3ikeA53zKk01ebcXEy3vHzg48MBO8sqHyFII37KYBkzkZ+ZkvouhmxMVCO+n8qo1oTmQ==", + "requires": { + "json-rpc-engine": "^3.7.3", + "json-rpc-middleware-stream": "^1.0.1", + "loglevel": "^1.6.1", + "obj-multiplex": "^1.0.0", + "obs-store": "^3.0.0", + "pump": "^3.0.0" + }, + "dependencies": { + "loglevel": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.6.1.tgz", + "integrity": "sha1-4PyVEztu8nbNyIh82vJKpvFW+Po=" + } + } + }, "methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", @@ -25221,7 +25518,8 @@ "precond": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/precond/-/precond-0.2.3.tgz", - "integrity": "sha1-qpWRvKokkj8eD0hJ0kD0fvwQdaw=" + "integrity": "sha1-qpWRvKokkj8eD0hJ0kD0fvwQdaw=", + "dev": true }, "prelude-ls": { "version": "1.1.2", @@ -26191,7 +26489,6 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/react-inspector/-/react-inspector-2.3.0.tgz", "integrity": "sha512-aIcbWb0fKFhEMB+RadoOYawlr1JoMMfrQ1oRgPUG/f/e4zERVJ6nYcIaQmrQmdHCZ63BOqe2cEkoeY0kyLBzNg==", - "dev": true, "requires": { "babel-runtime": "^6.26.0", "is-dom": "^1.0.9" @@ -26232,6 +26529,16 @@ "xtend": "^4.0.1" } }, + "react-media": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/react-media/-/react-media-1.8.0.tgz", + "integrity": "sha512-XcfqkDQj5/hmJod/kXUAZljJyMVkWrBWOkzwynAR8BXOGlbFLGBwezM0jQHtp2BrSymhf14/XrQrb3gGBnGK4g==", + "requires": { + "invariant": "^2.2.2", + "json2mq": "^0.2.0", + "prop-types": "^15.5.10" + } + }, "react-modal": { "version": "3.4.4", "resolved": "https://registry.npmjs.org/react-modal/-/react-modal-3.4.4.tgz", @@ -29121,6 +29428,11 @@ "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz", "integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM=" }, + "string-convert": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz", + "integrity": "sha1-aYLMMEn7tM2F+LJFaLnZvznu/5c=" + }, "string-length": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/string-length/-/string-length-1.0.1.tgz", @@ -29947,6 +30259,11 @@ } } }, + "swappable-obj-proxy": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/swappable-obj-proxy/-/swappable-obj-proxy-1.1.0.tgz", + "integrity": "sha512-bXbKO85b0YNbZi/61TjRAbNtY49ABKu7rQ4k2+RFXPL7TA2mphttfqAqCeJ+lrlKlkYc5pvm6erFk6vOWJSpdw==" + }, "swarm-js": { "version": "0.1.37", "resolved": "https://registry.npmjs.org/swarm-js/-/swarm-js-0.1.37.tgz", @@ -32269,124 +32586,6 @@ "web3-utils": "1.0.0-beta.34" } }, - "web3-provider-engine": { - "version": "14.0.5", - "resolved": "https://registry.npmjs.org/web3-provider-engine/-/web3-provider-engine-14.0.5.tgz", - "integrity": "sha512-1W/ue7VOwOMnmKgMY3HCpbixi6qhfl4r1dK8W597AwJLbrQ+twJKwWlFAedDpJjCc9MwRCCB3pyexW4HJVSiBg==", - "requires": { - "async": "^2.5.0", - "backoff": "^2.5.0", - "clone": "^2.0.0", - "cross-fetch": "^2.1.0", - "eth-block-tracker": "^3.0.0", - "eth-json-rpc-infura": "^3.1.0", - "eth-sig-util": "^1.4.2", - "ethereumjs-block": "^1.2.2", - "ethereumjs-tx": "^1.2.0", - "ethereumjs-util": "^5.1.5", - "ethereumjs-vm": "^2.3.4", - "json-rpc-error": "^2.0.0", - "json-stable-stringify": "^1.0.1", - "promise-to-callback": "^1.0.0", - "readable-stream": "^2.2.9", - "request": "^2.67.0", - "semaphore": "^1.0.3", - "tape": "^4.4.0", - "ws": "^5.1.1", - "xhr": "^2.2.0", - "xtend": "^4.0.1" - }, - "dependencies": { - "eth-block-tracker": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/eth-block-tracker/-/eth-block-tracker-3.0.0.tgz", - "integrity": "sha512-Lhhu/+1GOeekMRDRhUcM7VSJRmX279DByrwzEbmG0JL1tcT3xRo6GLNXnidyJ7ahHJm+0JFhw/RqtTeIxagQwA==", - "requires": { - "eth-query": "^2.1.0", - "ethereumjs-tx": "^1.3.3", - "ethereumjs-util": "^5.1.3", - "ethjs-util": "^0.1.3", - "json-rpc-engine": "^3.6.0", - "pify": "^2.3.0", - "tape": "^4.6.3" - } - }, - "eth-json-rpc-infura": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/eth-json-rpc-infura/-/eth-json-rpc-infura-3.1.0.tgz", - "integrity": "sha512-uMYkEP6fga8CyNo8TMoA/7cxi6bL3V8pTvjKQikOi9iYl6/AO5xlfgniyAMElSiq2mmXz3lYa/9VYDMzt/J5aA==", - "requires": { - "cross-fetch": "^2.1.0", - "eth-json-rpc-middleware": "^1.5.0", - "json-rpc-engine": "^3.4.0", - "json-rpc-error": "^2.0.0", - "tape": "^4.8.0" - } - }, - "eth-sig-util": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/eth-sig-util/-/eth-sig-util-1.4.2.tgz", - "integrity": "sha1-jZWCAsftuq6Dlwf7pvCf8ydgYhA=", - "requires": { - "ethereumjs-abi": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", - "ethereumjs-util": "^5.1.1" - } - }, - "ethereumjs-abi": { - "version": "git+https://github.com/ethereumjs/ethereumjs-abi.git#00ba8463a7f7a67fcad737ff9c2ebd95643427f7", - "from": "git+https://github.com/ethereumjs/ethereumjs-abi.git", - "requires": { - "bn.js": "^4.10.0", - "ethereumjs-util": "^5.0.0" - } - }, - "ethereumjs-util": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/ethereumjs-util/-/ethereumjs-util-5.1.5.tgz", - "integrity": "sha512-xPaSEATYJpMTCGowIt0oMZwFP4R1bxd6QsWgkcDvFL0JtXsr39p32WEcD14RscCjfP41YXZPCVWA4yAg0nrJmw==", - "requires": { - "bn.js": "^4.11.0", - "create-hash": "^1.1.2", - "ethjs-util": "^0.1.3", - "keccak": "^1.0.2", - "rlp": "^2.0.0", - "safe-buffer": "^5.1.1", - "secp256k1": "^3.0.1" - } - }, - "ethereumjs-vm": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/ethereumjs-vm/-/ethereumjs-vm-2.3.5.tgz", - "integrity": "sha512-AJ7x44+xqyE5+UO3Nns19WkTdZfyqFZ+sEjIEpvme7Ipbe3iBU1uwCcHEdiu/yY9bdhr3IfSa/NfIKNeXPaRVQ==", - "requires": { - "async": "^2.1.2", - "async-eventemitter": "^0.2.2", - "ethereum-common": "0.2.0", - "ethereumjs-account": "^2.0.3", - "ethereumjs-block": "~1.7.0", - "ethereumjs-util": "^5.1.3", - "fake-merkle-patricia-tree": "^1.0.1", - "functional-red-black-tree": "^1.0.1", - "merkle-patricia-tree": "^2.1.2", - "rustbn.js": "~0.1.1", - "safe-buffer": "^5.1.1" - } - }, - "pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=" - }, - "ws": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-5.1.1.tgz", - "integrity": "sha512-bOusvpCb09TOBLbpMKszd45WKC2KPtxiyiHanv+H2DE3Az+1db5a/L7sVJZVDPUC1Br8f0SKRr1KjLpD1U/IAw==", - "requires": { - "async-limiter": "~1.0.0" - } - } - } - }, "web3-providers-http": { "version": "1.0.0-beta.34", "resolved": "https://registry.npmjs.org/web3-providers-http/-/web3-providers-http-1.0.0-beta.34.tgz", diff --git a/package.json b/package.json index 03b6990e6..44572c492 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "mascara": "gulp dev:mascara & node ./mascara/example/server", "dist": "gulp dist", "doc": "jsdoc -c development/tools/.jsdoc.json", + "publish-docs": "gh-pages -d docs/jsdocs", "test": "npm run test:unit && npm run test:integration && npm run lint", "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", @@ -22,7 +23,7 @@ "test:e2e:run:firefox": "SELENIUM_BROWSER=firefox mocha test/e2e/metamask.spec --bail --recursive", "test:screens": "shell-parallel -s 'npm run ganache:start' -x 'sleep 3 && npm run test:screens:run'", "test:screens:run": "node test/screens/new-ui.js", - "test:coverage": "nyc npm run test:unit && npm run test:coveralls-upload", + "test:coverage": "nyc --reporter=text --reporter=html npm run test:unit && npm run test:coveralls-upload", "test:coveralls-upload": "if [ $COVERALLS_REPO_TOKEN ]; then nyc report --reporter=text-lcov | coveralls; fi", "test:flat": "npm run test:flat:build && karma start test/flat.conf.js", "test:flat:build": "npm run test:flat:build:ui && npm run test:flat:build:tests && npm run test:flat:build:locales", @@ -36,7 +37,7 @@ "test:mascara:build:locales": "mkdirp dist/chrome && cp -R app/_locales dist/chrome/_locales", "test:mascara:build:background": "browserify mascara/src/background.js -o dist/mascara/background.js", "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'", + "ganache:start": "ganache-cli --noVMErrorsOnRPCResponse -m 'phrase upgrade clock rough situate wedding elder clever doctor stamp excess tent'", "sentry:publish": "node ./development/sentry-publish.js", "lint": "eslint .", "lint:fix": "eslint . --fix", @@ -57,7 +58,11 @@ [ "env", { - "debug": true + "browsers": [ + ">0.25%", + "not ie 11", + "not op_mini all" + ] } ], "stage-0" @@ -75,7 +80,7 @@ }, "dependencies": { "@material-ui/core": "1.0.0", - "@zxing/library": "^0.7.0", + "@zxing/library": "^0.8.0", "abi-decoder": "^1.0.9", "asmcrypto.js": "0.22.0", "async": "^2.5.0", @@ -105,11 +110,13 @@ "ensnare": "^1.0.0", "eslint-plugin-react": "^7.4.0", "eth-bin-to-ops": "^1.0.1", + "eth-block-tracker": "^4.0.1", "eth-contract-metadata": "github:MetaMask/eth-contract-metadata#master", "eth-ens-namehash": "^2.0.8", "eth-hd-keyring": "^2.0.0", "eth-json-rpc-filters": "^3.0.1", "eth-json-rpc-infura": "^3.0.0", + "eth-keyring-controller": "^3.1.4", "eth-ledger-bridge-keyring": "^0.1.0", "eth-method-registry": "^1.0.0", "eth-net-props": "^1.0.7", @@ -128,6 +135,7 @@ "ethjs-query": "^0.3.4", "express": "^4.15.5", "extension-link-enabler": "^1.0.0", + "extension-port-stream": "^1.0.0", "extensionizer": "^1.0.1", "fast-json-patch": "^2.0.4", "fast-levenshtein": "^2.0.6", @@ -149,12 +157,14 @@ "inject-css": "^0.1.1", "json-rpc-engine": "^3.8.0", "json-rpc-middleware-stream": "^1.0.1", + "jsonschema": "^1.2.4", "lodash.debounce": "^4.0.8", "lodash.memoize": "^4.1.2", "lodash.shuffle": "^4.2.0", "lodash.uniqby": "^4.7.0", "loglevel": "^1.4.1", "metamascara": "^2.0.0", + "metamask-inpage-provider": "^1.0.0", "mkdirp": "^0.5.1", "multihashes": "^0.4.12", "multiplex": "^6.7.0", @@ -180,7 +190,9 @@ "react-addons-css-transition-group": "^15.6.0", "react-dom": "^15.6.2", "react-hyperscript": "^3.0.0", + "react-inspector": "^2.3.0", "react-markdown": "^3.0.0", + "react-media": "^1.8.0", "react-redux": "^5.0.5", "react-router-dom": "^4.2.2", "react-select": "^1.0.0", @@ -205,10 +217,10 @@ "shallow-copy": "0.0.1", "sw-controller": "^1.0.3", "sw-stream": "^2.0.2", + "swappable-obj-proxy": "^1.1.0", "valid-url": "^1.0.9", "vreme": "^3.0.2", "web3": "^0.20.1", - "web3-provider-engine": "^14.0.5", "web3-stream-provider": "^3.0.1", "webrtc-adapter": "^6.3.0", "xtend": "^4.0.1" @@ -248,9 +260,10 @@ "eslint-plugin-json": "^1.2.0", "eslint-plugin-mocha": "^5.0.0", "eslint-plugin-react": "^7.4.0", - "eth-json-rpc-middleware": "^1.6.0", + "eth-json-rpc-middleware": "^2.4.0", "eth-keychain-controller": "^5.0.0", "file-loader": "^1.1.11", + "fs-extra": "^6.0.1", "fs-promise": "^2.0.3", "ganache-cli": "^6.1.0", "ganache-core": "^2.1.5", @@ -295,6 +308,7 @@ "open": "0.0.5", "path": "^0.12.7", "png-file-stream": "^1.0.0", + "prepend-file": "^1.3.1", "prompt": "^1.0.0", "proxyquire": "2.0.1", "qs": "^6.2.0", diff --git a/test/e2e/beta/from-import-beta-ui.spec.js b/test/e2e/beta/from-import-beta-ui.spec.js index 1261b6f95..32aaa29a6 100644 --- a/test/e2e/beta/from-import-beta-ui.spec.js +++ b/test/e2e/beta/from-import-beta-ui.spec.js @@ -314,12 +314,12 @@ describe('Using MetaMask with an existing account', function () { }) it('finds the transaction in the transactions list', async function () { - const transactions = await findElements(driver, By.css('.tx-list-item')) + const transactions = await findElements(driver, By.css('.transaction-list-item')) assert.equal(transactions.length, 1) - const txValues = await findElements(driver, By.css('.tx-list-value')) + const txValues = await findElements(driver, By.css('.transaction-list-item__amount--primary')) assert.equal(txValues.length, 1) - assert.equal(await txValues[0].getText(), '1 ETH') + assert.equal(await txValues[0].getText(), '-1 ETH') }) }) diff --git a/test/e2e/beta/helpers.js b/test/e2e/beta/helpers.js index d90cd5d66..73289e526 100644 --- a/test/e2e/beta/helpers.js +++ b/test/e2e/beta/helpers.js @@ -2,8 +2,8 @@ const fs = require('fs') const mkdirp = require('mkdirp') const pify = require('pify') const assert = require('assert') -const {until} = require('selenium-webdriver') const { delay } = require('../func') +const { until } = require('selenium-webdriver') module.exports = { assertElementNotPresent, diff --git a/test/e2e/beta/metamask-beta-ui.spec.js b/test/e2e/beta/metamask-beta-ui.spec.js index 43300bda6..7370f1a92 100644 --- a/test/e2e/beta/metamask-beta-ui.spec.js +++ b/test/e2e/beta/metamask-beta-ui.spec.js @@ -225,19 +225,9 @@ describe('MetaMask', function () { await delay(regularDelayMs) } - await clickWordAndWait(words[0]) - await clickWordAndWait(words[1]) - await clickWordAndWait(words[2]) - await clickWordAndWait(words[3]) - await clickWordAndWait(words[4]) - await clickWordAndWait(words[5]) - await clickWordAndWait(words[6]) - await clickWordAndWait(words[7]) - await clickWordAndWait(words[8]) - await clickWordAndWait(words[9]) - await clickWordAndWait(words[10]) - await clickWordAndWait(words[11]) - + for (let i = 0; i < 12; i++) { + await clickWordAndWait(words[i]) + } } catch (e) { if (count > 2) { throw e @@ -414,12 +404,12 @@ describe('MetaMask', function () { }) it('finds the transaction in the transactions list', async function () { - const transactions = await findElements(driver, By.css('.tx-list-item')) + const transactions = await findElements(driver, By.css('.transaction-list-item')) assert.equal(transactions.length, 1) if (process.env.SELENIUM_BROWSER !== 'firefox') { - const txValues = await findElement(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txValues, /1\sETH/), 10000) + const txValues = await findElement(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues, /-1\sETH/), 10000) } }) }) @@ -457,16 +447,11 @@ describe('MetaMask', function () { }) it('finds the transaction in the transactions list', async function () { - const transactions = await findElements(driver, By.css('.tx-list-item')) + const transactions = await findElements(driver, By.css('.transaction-list-item')) assert.equal(transactions.length, 2) - await findElement(driver, By.xpath(`//span[contains(text(), 'Submitted')]`)) - - 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 txValues = await findElement(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues, /-3\sETH/), 10000) }) }) @@ -489,9 +474,9 @@ describe('MetaMask', function () { await driver.switchTo().window(extension) await delay(regularDelayMs) - const txListItem = await findElement(driver, By.xpath(`//span[contains(text(), 'Contract Deployment')]`)) + const txListItem = await findElement(driver, By.xpath(`//div[contains(text(), 'Contract Deployment')]`)) await txListItem.click() - await delay(regularDelayMs) + await delay(largeDelayMs) }) it('displays the contract creation data', async () => { @@ -513,15 +498,15 @@ describe('MetaMask', function () { it('confirms a deploy contract transaction', async () => { const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`)) await confirmButton.click() - await delay(regularDelayMs) + await delay(largeDelayMs) - await findElement(driver, By.xpath(`//span[contains(text(), 'Submitted')]`)) + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 3 + }, 10000) - 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') + const txAction = await findElements(driver, By.css('.transaction-list-item__action')) + await driver.wait(until.elementTextMatches(txAction[0], /Contract\sDeployment/), 10000) await delay(regularDelayMs) }) @@ -542,9 +527,9 @@ describe('MetaMask', function () { await driver.switchTo().window(extension) await delay(largeDelayMs) - await findElements(driver, By.css('.tx-list-pending-item-container')) - const [txListValue] = await findElements(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txListValue, /4\sETH/), 10000) + await findElements(driver, By.css('.transaction-list-item')) + const [txListValue] = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txListValue, /-4\sETH/), 10000) await txListValue.click() await delay(regularDelayMs) @@ -572,15 +557,17 @@ describe('MetaMask', function () { await confirmButton.click() await delay(regularDelayMs) - const txStatuses = await findElements(driver, By.css('.tx-list-status')) - await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/)) + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 4 + }, 10000) - const txValues = await findElement(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txValues, /4\sETH/), 10000) + const txValues = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues[0], /-4\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}$/)) + // 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('calls and confirms a contract method where ETH is received', async () => { @@ -594,7 +581,7 @@ describe('MetaMask', function () { await driver.switchTo().window(extension) await delay(regularDelayMs) - const txListItem = await findElement(driver, By.css('.tx-list-item')) + const txListItem = await findElement(driver, By.css('.transaction-list-item')) await txListItem.click() await delay(regularDelayMs) @@ -602,18 +589,20 @@ describe('MetaMask', function () { await confirmButton.click() await delay(regularDelayMs) - const txStatuses = await findElements(driver, By.css('.tx-list-status')) - await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/)) + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 5 + }, 10000) - const txValues = await findElement(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txValues, /0\sETH/), 10000) + const txValues = await findElement(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues, /-0\sETH/), 10000) await closeAllWindowHandlesExcept(driver, [extension, dapp]) 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')) + const balance = await findElement(driver, By.css('.transaction-view-balance__primary-balance')) await delay(regularDelayMs) if (process.env.SELENIUM_BROWSER !== 'firefox') { await driver.wait(until.elementTextMatches(balance, /^92.*ETH.*$/), 10000) @@ -626,20 +615,21 @@ describe('MetaMask', function () { describe('Add a custom token from a dapp', () => { it('creates a new token', async () => { - const windowHandles = await driver.getAllWindowHandles() + let windowHandles = await driver.getAllWindowHandles() const extension = windowHandles[0] const dapp = windowHandles[1] await delay(regularDelayMs * 2) await driver.switchTo().window(dapp) - await delay(regularDelayMs) + await delay(regularDelayMs * 2) const createToken = await findElement(driver, By.xpath(`//button[contains(text(), 'Create Token')]`)) await createToken.click() - await delay(regularDelayMs) + await delay(largeDelayMs) - await driver.switchTo().window(extension) - await loadExtension(driver, extensionId) + windowHandles = await driver.getAllWindowHandles() + const popup = windowHandles[2] + await driver.switchTo().window(popup) await delay(regularDelayMs) const confirmButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`)) @@ -657,18 +647,17 @@ describe('MetaMask', function () { await closeAllWindowHandlesExcept(driver, [extension, dapp]) await delay(regularDelayMs) await driver.switchTo().window(extension) - await delay(regularDelayMs) - + await delay(largeDelayMs) }) it('clicks on the Add Token button', async () => { - const addToken = await findElement(driver, By.xpath(`//button[contains(text(), 'Add Token')]`)) + const addToken = await driver.findElement(By.css('.wallet-view__add-token-button')) await addToken.click() await delay(regularDelayMs) }) it('picks the newly created Test token', async () => { - const addCustomToken = await findElement(driver, By.xpath("//div[contains(text(), 'Custom Token')]")) + const addCustomToken = await findElement(driver, By.xpath("//li[contains(text(), 'Custom Token')]")) await addCustomToken.click() await delay(regularDelayMs) @@ -686,7 +675,7 @@ describe('MetaMask', function () { }) it('renders the balance for the new token', async () => { - const balance = await findElement(driver, By.css('.tx-view .balance-display .token-amount')) + const balance = await findElement(driver, By.css('.transaction-view-balance .transaction-view-balance__token-balance')) await driver.wait(until.elementTextMatches(balance, /^100\s*TST\s*$/)) const tokenAmount = await balance.getText() assert.ok(/^100\s*TST\s*$/.test(tokenAmount)) @@ -755,21 +744,25 @@ describe('MetaMask', function () { }) it('finds the transaction in the transactions list', async function () { - const transactions = await findElements(driver, By.css('.tx-list-item')) + const transactions = await findElements(driver, By.css('.transaction-list-item')) assert.equal(transactions.length, 1) - const txValues = await findElements(driver, By.css('.tx-list-value')) + const txValues = await findElements(driver, By.css('.transaction-list-item__amount--primary')) 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) + 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') + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 1 + }, 10000) + const txStatuses = await findElements(driver, By.css('.transaction-list-item__action')) + const tx = await driver.wait(until.elementTextMatches(txStatuses[0], /Sent\sToken|Failed/), 10000) + assert.equal(await tx.getText(), 'Sent Tokens') }) }) @@ -792,9 +785,9 @@ describe('MetaMask', function () { await driver.switchTo().window(extension) await delay(largeDelayMs) - await findElements(driver, By.css('.tx-list-pending-item-container')) - const [txListValue] = await findElements(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txListValue, /7\sTST/), 10000) + await findElements(driver, By.css('.transaction-list__pending-transactions')) + const [txListValue] = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txListValue, /-7\sTST/), 10000) await txListValue.click() await delay(regularDelayMs) @@ -841,25 +834,28 @@ describe('MetaMask', function () { }) 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) + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 2 + }, 10000) - const txValues = await findElements(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txValues[0], /7\sTST/)) - const txStatuses = await findElements(driver, By.css('.tx-list-status')) - await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/)) + const txValues = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues[0], /-7\sTST/)) + const txStatuses = await findElements(driver, By.css('.transaction-list-item__action')) + await driver.wait(until.elementTextMatches(txStatuses[0], /Sent\sToken/)) 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() + await delay(regularDelayMs) // 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(), '43') + const tokenBalanceAmount = await findElement(driver, By.css('.transaction-view-balance__token-balance')) + assert.equal(await tokenBalanceAmount.getText(), '43 TST') } }) }) @@ -883,9 +879,14 @@ describe('MetaMask', function () { await driver.switchTo().window(extension) await delay(regularDelayMs) - const [txListItem] = await findElements(driver, By.css('.tx-list-item')) - const [txListValue] = await findElements(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txListValue, /0\sETH/)) + driver.wait(async () => { + const pendingTxes = await findElements(driver, By.css('.transaction-list__pending-transactions .transaction-list-item')) + return pendingTxes.length === 1 + }, 10000) + + const [txListItem] = await findElements(driver, By.css('.transaction-list-item')) + const [txListValue] = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txListValue, /-7\sTST/)) await txListItem.click() await delay(regularDelayMs) }) @@ -956,10 +957,15 @@ describe('MetaMask', function () { }) it('finds the transaction in the transactions list', async function () { - const txValues = await findElements(driver, By.css('.tx-list-value')) - await driver.wait(until.elementTextMatches(txValues[0], /0\sETH/)) - const txStatuses = await findElements(driver, By.css('.tx-list-status')) - await driver.wait(until.elementTextMatches(txStatuses[0], /Confirmed/)) + driver.wait(async () => { + const confirmedTxes = await findElements(driver, By.css('.transaction-list__completed-transactions .transaction-list-item')) + return confirmedTxes.length === 3 + }, 10000) + + const txValues = await findElements(driver, By.css('.transaction-list-item__amount--primary')) + await driver.wait(until.elementTextMatches(txValues[0], /-7\sTST/)) + const txStatuses = await findElements(driver, By.css('.transaction-list-item__action')) + await driver.wait(until.elementTextMatches(txStatuses[0], /Approve/)) }) }) @@ -1009,9 +1015,69 @@ describe('MetaMask', function () { }) it('renders the balance for the chosen token', async () => { - const balance = await findElement(driver, By.css('.tx-view .balance-display .token-amount')) + const balance = await findElement(driver, By.css('.transaction-view-balance__token-balance')) await driver.wait(until.elementTextMatches(balance, /0\sBAT/)) await delay(regularDelayMs) }) }) + + describe('Stores custom RPC history', () => { + const customRpcUrls = [ + 'https://mainnet.infura.io/1', + 'https://mainnet.infura.io/2', + 'https://mainnet.infura.io/3', + 'https://mainnet.infura.io/4', + ] + + customRpcUrls.forEach(customRpcUrl => { + it('creates custom RPC: ' + customRpcUrl, async () => { + const networkDropdown = await findElement(driver, By.css('.network-name')) + await networkDropdown.click() + await delay(regularDelayMs) + + const customRpcButton = await findElement(driver, By.xpath(`//span[contains(text(), 'Custom RPC')]`)) + await customRpcButton.click() + await delay(regularDelayMs) + + const customRpcInput = await findElement(driver, By.css('input[placeholder="New RPC URL"]')) + await customRpcInput.clear() + await customRpcInput.sendKeys(customRpcUrl) + + const customRpcSave = await findElement(driver, By.css('.settings-tab__rpc-save-button')) + await customRpcSave.click() + await delay(largeDelayMs * 2) + }) + }) + + it('selects another provider', async () => { + const networkDropdown = await findElement(driver, By.css('.network-name')) + await networkDropdown.click() + await delay(regularDelayMs) + + const customRpcButton = await findElement(driver, By.xpath(`//span[contains(text(), 'Main Ethereum Network')]`)) + await customRpcButton.click() + await delay(largeDelayMs * 2) + }) + + it('finds 3 recent RPCs in history', async () => { + const networkDropdown = await findElement(driver, By.css('.network-name')) + await networkDropdown.click() + await delay(regularDelayMs) + + // oldest selected RPC is not found + await assertElementNotPresent(webdriver, driver, By.xpath(`//span[contains(text(), '${customRpcUrls[0]}')]`)) + + // only recent 3 are found and in correct order (most recent at the top) + const customRpcs = await findElements(driver, By.xpath(`//span[contains(text(), 'https://mainnet.infura.io/')]`)) + + assert.equal(customRpcs.length, 3) + + for (let i = 0; i < customRpcs.length; i++) { + const linkText = await customRpcs[i].getText() + const rpcUrl = customRpcUrls[customRpcUrls.length - i - 1] + + assert.notEqual(linkText.indexOf(rpcUrl), -1) + } + }) + }) }) diff --git a/test/e2e/beta/run-all.sh b/test/e2e/beta/run-all.sh index 7da61e504..cde46a2d3 100755 --- a/test/e2e/beta/run-all.sh +++ b/test/e2e/beta/run-all.sh @@ -6,5 +6,5 @@ set -o pipefail export PATH="$PATH:./node_modules/.bin" -shell-parallel -s 'npm run ganache:start' -x 'sleep 5 && static-server test/e2e/beta/contract-test/ --port 8080' -x 'sleep 5 && mocha test/e2e/beta/metamask-beta-ui.spec' -shell-parallel -s 'npm run ganache:start -- -d' -x 'sleep 5 && static-server test/e2e/beta/contract-test/ --port 8080' -x 'sleep 5 && mocha test/e2e/beta/from-import-beta-ui.spec' +shell-parallel -s 'npm run ganache:start -- -b 2' -x 'sleep 5 && static-server test/e2e/beta/contract-test/ --port 8080' -x 'sleep 5 && mocha test/e2e/beta/metamask-beta-ui.spec' +shell-parallel -s 'npm run ganache:start -- -d -b 2' -x 'sleep 5 && static-server test/e2e/beta/contract-test/ --port 8080' -x 'sleep 5 && mocha test/e2e/beta/from-import-beta-ui.spec' diff --git a/test/e2e/func.js b/test/e2e/func.js index 709357578..0d91da857 100644 --- a/test/e2e/func.js +++ b/test/e2e/func.js @@ -1,8 +1,10 @@ require('chromedriver') require('geckodriver') -const fs = require('fs') +const fs = require('fs-extra') const os = require('os') const path = require('path') +const pify = require('pify') +const prependFile = pify(require('prepend-file')) const webdriver = require('selenium-webdriver') const Command = require('selenium-webdriver/lib/command').Command @@ -10,6 +12,9 @@ const { By } = webdriver module.exports = { delay, + createModifiedTestBuild, + setupBrowserAndExtension, + verboseReportOnFailure, buildChromeWebDriver, buildFirefoxWebdriver, installWebExt, @@ -21,6 +26,37 @@ function delay (time) { return new Promise(resolve => setTimeout(resolve, time)) } +async function createModifiedTestBuild ({ browser, srcPath }) { + // copy build to test-builds directory + const extPath = path.resolve(`test-builds/${browser}`) + await fs.ensureDir(extPath) + await fs.copy(srcPath, extPath) + // inject METAMASK_TEST_CONFIG setting default test network + const config = { NetworkController: { provider: { type: 'localhost' } } } + await prependFile(`${extPath}/background.js`, `window.METAMASK_TEST_CONFIG=${JSON.stringify(config)};\n`) + return { extPath } +} + +async function setupBrowserAndExtension ({ browser, extPath }) { + let driver, extensionId, extensionUri + + if (browser === 'chrome') { + driver = buildChromeWebDriver(extPath) + extensionId = await getExtensionIdChrome(driver) + extensionUri = `chrome-extension://${extensionId}/home.html` + } else if (browser === 'firefox') { + driver = buildFirefoxWebdriver() + await installWebExt(driver, extPath) + await delay(700) + extensionId = await getExtensionIdFirefox(driver) + extensionUri = `moz-extension://${extensionId}/home.html` + } else { + throw new Error(`Unknown Browser "${browser}"`) + } + + return { driver, extensionId, extensionUri } +} + function buildChromeWebDriver (extPath) { const tmpProfile = fs.mkdtempSync(path.join(os.tmpdir(), 'mm-chrome-profile')) return new webdriver.Builder() @@ -62,3 +98,13 @@ async function installWebExt (driver, extension) { return await driver.execute(cmd, 'installWebExt(' + extension + ')') } + +async function verboseReportOnFailure ({ browser, driver, title }) { + const artifactDir = `./test-artifacts/${browser}/${title}` + const filepathBase = `${artifactDir}/test-failure` + await fs.ensureDir(artifactDir) + const screenshot = await driver.takeScreenshot() + await fs.writeFile(`${filepathBase}-screenshot.png`, screenshot, { encoding: 'base64' }) + const htmlSource = await driver.getPageSource() + await fs.writeFile(`${filepathBase}-dom.html`, htmlSource) +} diff --git a/test/helper.js b/test/helper.js index a3abbebf2..51f28de17 100644 --- a/test/helper.js +++ b/test/helper.js @@ -1,10 +1,21 @@ +const Ganache = require('ganache-core') +const nock = require('nock') import Enzyme from 'enzyme' import Adapter from 'enzyme-adapter-react-15' +nock.disableNetConnect() +nock.enableNetConnect('localhost') + Enzyme.configure({ adapter: new Adapter() }) // disallow promises from swallowing errors enableFailureOnUnhandledPromiseRejection() +// ganache server +const server = Ganache.server() +server.listen(8545, () => { + console.log('Ganache Testrpc is running on "http://localhost:8545"') +}) + // logging util var log = require('loglevel') log.setDefaultLevel(5) @@ -14,6 +25,9 @@ global.log = log // polyfills // +// fetch +global.fetch = require('isomorphic-fetch') + // dom require('jsdom-global')() diff --git a/test/integration/lib/send-new-ui.js b/test/integration/lib/send-new-ui.js index a9ccc97d2..540bf84c8 100644 --- a/test/integration/lib/send-new-ui.js +++ b/test/integration/lib/send-new-ui.js @@ -58,7 +58,7 @@ async function runSendFlowTest (assert, done) { selectState.val('send new ui') reactTriggerChange(selectState[0]) - const sendScreenButton = await queryAsync($, 'button.btn-primary.hero-balance-button') + const sendScreenButton = await queryAsync($, 'button.btn-primary.transaction-view-balance__button') assert.ok(sendScreenButton[1], 'send screen button present') sendScreenButton[1].click() @@ -124,10 +124,10 @@ async function runSendFlowTest (assert, done) { selectState.val('send edit') reactTriggerChange(selectState[0]) - const confirmFromName = (await queryAsync($, '.sender-to-recipient__sender-name')).first() + const confirmFromName = (await queryAsync($, '.sender-to-recipient__name')).first() assert.equal(confirmFromName[0].textContent, 'Send Account 4', 'confirm screen should show correct from name') - const confirmToName = (await queryAsync($, '.sender-to-recipient__recipient-name')).last() + const confirmToName = (await queryAsync($, '.sender-to-recipient__name')).last() assert.equal(confirmToName[0].textContent, 'Send Account 3', 'confirm screen should show correct to name') const confirmScreenRowFiats = await queryAsync($, '.confirm-detail-row__fiat') diff --git a/test/integration/lib/tx-list-items.js b/test/integration/lib/tx-list-items.js index c156b16ca..e53a52b67 100644 --- a/test/integration/lib/tx-list-items.js +++ b/test/integration/lib/tx-list-items.js @@ -29,26 +29,25 @@ async function runTxListItemsTest (assert, done) { assert.ok(metamaskLogo[0], 'metamask logo present') metamaskLogo[0].click() - const txListItems = await queryAsync($, '.tx-list-item') + const txListItems = await queryAsync($, '.transaction-list-item') assert.equal(txListItems.length, 8, 'all tx list items are rendered') - const unapprovedTx = txListItems[0] - assert.equal($(unapprovedTx).hasClass('tx-list-pending-item-container'), true, 'unapprovedTx has the correct class') - - const retryTx = txListItems[1] - const retryTxLink = await findAsync($(retryTx), '.tx-list-item-retry-container span') - assert.equal(retryTxLink[0].textContent, 'Taking too long? Increase the gas price on your transaction', 'retryTx has expected link') + const retryTxGrid = await findAsync($(txListItems[1]), '.transaction-list-item__grid') + retryTxGrid[0].click() + const retryTxDetails = await findAsync($(txListItems[1]), '.transaction-list-item-details') + const headerButtons = await findAsync($(retryTxDetails[0]), '.transaction-list-item-details__header-button') + assert.equal(headerButtons[0].textContent, 'speed up') const approvedTx = txListItems[2] - const approvedTxRenderedStatus = await findAsync($(approvedTx), '.tx-list-status') - assert.equal(approvedTxRenderedStatus[0].textContent, 'Approved', 'approvedTx has correct label') + const approvedTxRenderedStatus = await findAsync($(approvedTx), '.transaction-list-item__status') + assert.equal(approvedTxRenderedStatus[0].textContent, 'pending', 'approvedTx has correct label') const unapprovedMsg = txListItems[3] - const unapprovedMsgDescription = await findAsync($(unapprovedMsg), '.tx-list-account') + const unapprovedMsgDescription = await findAsync($(unapprovedMsg), '.transaction-list-item__action') assert.equal(unapprovedMsgDescription[0].textContent, 'Signature Request', 'unapprovedMsg has correct description') const failedTx = txListItems[4] - const failedTxRenderedStatus = await findAsync($(failedTx), '.tx-list-status') + const failedTxRenderedStatus = await findAsync($(failedTx), '.transaction-list-item__status') assert.equal(failedTxRenderedStatus[0].textContent, 'Failed', 'failedTx has correct label') const shapeShiftTx = txListItems[5] @@ -56,10 +55,10 @@ async function runTxListItemsTest (assert, done) { assert.equal(shapeShiftTxStatus[0].textContent, 'No deposits received', 'shapeShiftTx has correct status') const confirmedTokenTx = txListItems[6] - const confirmedTokenTxAddress = await findAsync($(confirmedTokenTx), '.tx-list-account') - assert.equal(confirmedTokenTxAddress[0].textContent, '0xE7884118...81a9', 'confirmedTokenTx has correct address') + const confirmedTokenTxAddress = await findAsync($(confirmedTokenTx), '.transaction-list-item__status') + assert.equal(confirmedTokenTxAddress[0].textContent, 'Confirmed', 'confirmedTokenTx has correct address') const rejectedTx = txListItems[7] - const rejectedTxRenderedStatus = await findAsync($(rejectedTx), '.tx-list-status') + const rejectedTxRenderedStatus = await findAsync($(rejectedTx), '.transaction-list-item__status') assert.equal(rejectedTxRenderedStatus[0].textContent, 'Rejected', 'rejectedTx has correct label') } diff --git a/test/lib/createTxMeta.js b/test/lib/createTxMeta.js new file mode 100644 index 000000000..0e88e3cfb --- /dev/null +++ b/test/lib/createTxMeta.js @@ -0,0 +1,16 @@ +const txStateHistoryHelper = require('../../app/scripts/controllers/transactions/lib/tx-state-history-helper') + +module.exports = createTxMeta + +function createTxMeta (partialMeta) { + const txMeta = Object.assign({ + status: 'unapproved', + txParams: {}, + }, partialMeta) + // initialize history + txMeta.history = [] + // capture initial snapshot of txMeta for history + const snapshot = txStateHistoryHelper.snapshotFromTxMeta(txMeta) + txMeta.history.push(snapshot) + return txMeta +} diff --git a/test/lib/mock-config-manager.js b/test/lib/mock-config-manager.js deleted file mode 100644 index 0cc6953bb..000000000 --- a/test/lib/mock-config-manager.js +++ /dev/null @@ -1,9 +0,0 @@ -const ObservableStore = require('obs-store') -const clone = require('clone') -const ConfigManager = require('../../app/scripts/lib/config-manager') -const firstTimeState = require('../../app/scripts/first-time-state') - -module.exports = function () { - const store = new ObservableStore(clone(firstTimeState)) - return new ConfigManager({ store }) -} diff --git a/test/unit/app/controllers/currency-controller-test.js b/test/unit/app/controllers/currency-controller-test.js index 1941d1c43..7c4644d9f 100644 --- a/test/unit/app/controllers/currency-controller-test.js +++ b/test/unit/app/controllers/currency-controller-test.js @@ -1,6 +1,3 @@ -// polyfill fetch -global.fetch = global.fetch || require('isomorphic-fetch') - const assert = require('assert') const nock = require('nock') const CurrencyController = require('../../../../app/scripts/controllers/currency') diff --git a/test/unit/app/controllers/detect-tokens-test.js b/test/unit/app/controllers/detect-tokens-test.js index 2e3890ebb..e2140d801 100644 --- a/test/unit/app/controllers/detect-tokens-test.js +++ b/test/unit/app/controllers/detect-tokens-test.js @@ -1,4 +1,5 @@ const assert = require('assert') +const nock = require('nock') const sinon = require('sinon') const ObservableStore = require('obs-store') const DetectTokensController = require('../../../../app/scripts/controllers/detect-tokens') @@ -6,15 +7,34 @@ const NetworkController = require('../../../../app/scripts/controllers/network/n const PreferencesController = require('../../../../app/scripts/controllers/preferences') describe('DetectTokensController', () => { - const sandbox = sinon.createSandbox() - let clock, keyringMemStore, network, preferences - beforeEach(async () => { - keyringMemStore = new ObservableStore({ isUnlocked: false}) - network = new NetworkController({ provider: { type: 'mainnet' }}) - preferences = new PreferencesController({ network }) - }) - after(() => { - sandbox.restore() + const sandbox = sinon.createSandbox() + let clock, keyringMemStore, network, preferences, controller + + const noop = () => {} + + const networkControllerProviderConfig = { + getAccounts: noop, + } + + beforeEach(async () => { + + + nock('https://api.infura.io') + .get(/.*/) + .reply(200) + + keyringMemStore = new ObservableStore({ isUnlocked: false}) + network = new NetworkController() + preferences = new PreferencesController({ network }) + controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) + + network.initializeProvider(networkControllerProviderConfig) + + }) + + after(() => { + sandbox.restore() + nock.cleanAll() }) it('should poll on correct interval', async () => { @@ -26,7 +46,10 @@ describe('DetectTokensController', () => { it('should be called on every polling period', async () => { clock = sandbox.useFakeTimers() + const network = new NetworkController() + network.initializeProvider(networkControllerProviderConfig) network.setProviderType('mainnet') + const preferences = new PreferencesController({ network }) const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.isUnlocked = true @@ -44,8 +67,6 @@ describe('DetectTokensController', () => { }) it('should not check tokens while in test network', async () => { - network.setProviderType('rinkeby') - const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.isUnlocked = true @@ -58,7 +79,6 @@ describe('DetectTokensController', () => { }) it('should only check and add tokens while in main network', async () => { - network.setProviderType('mainnet') const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.isUnlocked = true @@ -95,8 +115,6 @@ describe('DetectTokensController', () => { // }) it('should trigger detect new tokens when change address', async () => { - network.setProviderType('mainnet') - const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.isUnlocked = true var stub = sandbox.stub(controller, 'detectNewTokens') @@ -105,8 +123,6 @@ describe('DetectTokensController', () => { }) it('should trigger detect new tokens when submit password', async () => { - network.setProviderType('mainnet') - const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.selectedAddress = '0x0' var stub = sandbox.stub(controller, 'detectNewTokens') @@ -115,8 +131,6 @@ describe('DetectTokensController', () => { }) it('should not trigger detect new tokens when not open or not unlocked', async () => { - network.setProviderType('mainnet') - const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore }) controller.isOpen = true controller.isUnlocked = false var stub = sandbox.stub(controller, 'detectTokenBalance') diff --git a/test/unit/app/controllers/metamask-controller-test.js b/test/unit/app/controllers/metamask-controller-test.js index 467066437..5273d2d4a 100644 --- a/test/unit/app/controllers/metamask-controller-test.js +++ b/test/unit/app/controllers/metamask-controller-test.js @@ -3,16 +3,22 @@ const sinon = require('sinon') const clone = require('clone') const nock = require('nock') const createThoughStream = require('through2').obj -const MetaMaskController = require('../../../../app/scripts/metamask-controller') const blacklistJSON = require('eth-phishing-detect/src/config') -const firstTimeState = require('../../../../app/scripts/first-time-state') +const MetaMaskController = require('../../../../app/scripts/metamask-controller') +const firstTimeState = require('../../../unit/localhostState') +const createTxMeta = require('../../../lib/createTxMeta') +const EthQuery = require('eth-query') const currentNetworkId = 42 const DEFAULT_LABEL = 'Account 1' +const DEFAULT_LABEL_2 = 'Account 2' const TEST_SEED = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium' const TEST_ADDRESS = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' +const TEST_ADDRESS_2 = '0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b' +const TEST_ADDRESS_3 = '0xeb9e64b93097bc15f01f13eae97015c57ab64823' const TEST_SEED_ALT = 'setup olympic issue mobile velvet surge alcohol burger horse view reopen gentle' const TEST_ADDRESS_ALT = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' +const CUSTOM_RPC_URL = 'http://localhost:8545' describe('MetaMaskController', function () { let metamaskController @@ -134,6 +140,9 @@ describe('MetaMaskController', function () { describe('#createNewVaultAndRestore', function () { it('should be able to call newVaultAndRestore despite a mistake.', async function () { const password = 'what-what-what' + sandbox.stub(metamaskController, 'getBalance') + metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + await metamaskController.createNewVaultAndRestore(password, TEST_SEED.slice(0, -1)).catch((e) => null) await metamaskController.createNewVaultAndRestore(password, TEST_SEED) @@ -141,6 +150,9 @@ describe('MetaMaskController', function () { }) it('should clear previous identities after vault restoration', async () => { + sandbox.stub(metamaskController, 'getBalance') + metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED) assert.deepEqual(metamaskController.getState().identities, { [TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL }, @@ -156,6 +168,54 @@ describe('MetaMaskController', function () { [TEST_ADDRESS_ALT]: { address: TEST_ADDRESS_ALT, name: DEFAULT_LABEL }, }) }) + + it('should restore any consecutive accounts with balances', async () => { + sandbox.stub(metamaskController, 'getBalance') + metamaskController.getBalance.withArgs(TEST_ADDRESS).callsFake(() => { + return Promise.resolve('0x14ced5122ce0a000') + }) + metamaskController.getBalance.withArgs(TEST_ADDRESS_2).callsFake(() => { + return Promise.resolve('0x0') + }) + metamaskController.getBalance.withArgs(TEST_ADDRESS_3).callsFake(() => { + return Promise.resolve('0x14ced5122ce0a000') + }) + + await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED) + assert.deepEqual(metamaskController.getState().identities, { + [TEST_ADDRESS]: { address: TEST_ADDRESS, name: DEFAULT_LABEL }, + [TEST_ADDRESS_2]: { address: TEST_ADDRESS_2, name: DEFAULT_LABEL_2 }, + }) + }) + }) + + describe('#getBalance', () => { + it('should return the balance known by accountTracker', async () => { + const accounts = {} + const balance = '0x14ced5122ce0a000' + accounts[TEST_ADDRESS] = { balance: balance } + + metamaskController.accountTracker.store.putState({ accounts: accounts }) + + const gotten = await metamaskController.getBalance(TEST_ADDRESS) + + assert.equal(balance, gotten) + }) + + it('should ask the network for a balance when not known by accountTracker', async () => { + const accounts = {} + const balance = '0x14ced5122ce0a000' + const ethQuery = new EthQuery() + sinon.stub(ethQuery, 'getBalance').callsFake((account, callback) => { + callback(undefined, balance) + }) + + metamaskController.accountTracker.store.putState({ accounts: accounts }) + + const gotten = await metamaskController.getBalance(TEST_ADDRESS, ethQuery) + + assert.equal(balance, gotten) + }) }) describe('#getApi', function () { @@ -360,29 +420,19 @@ describe('MetaMaskController', function () { }) describe('#setCustomRpc', function () { - const customRPC = 'https://custom.rpc/' let rpcTarget beforeEach(function () { - - nock('https://custom.rpc') - .post('/') - .reply(200) - - rpcTarget = metamaskController.setCustomRpc(customRPC) - }) - - afterEach(function () { - nock.cleanAll() + rpcTarget = metamaskController.setCustomRpc(CUSTOM_RPC_URL) }) it('returns custom RPC that when called', async function () { - assert.equal(await rpcTarget, customRPC) + assert.equal(await rpcTarget, CUSTOM_RPC_URL) }) it('changes the network controller rpc', function () { const networkControllerState = metamaskController.networkController.store.getState() - assert.equal(networkControllerState.provider.rpcTarget, customRPC) + assert.equal(networkControllerState.provider.rpcTarget, CUSTOM_RPC_URL) }) }) @@ -487,9 +537,10 @@ describe('MetaMaskController', function () { getNetworkstub.returns(42) metamaskController.txController.txStateManager._saveTxList([ - { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'} }, - { id: 2, status: 'rejected', metamaskNetworkId: 32, txParams: {} }, - { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4'} }, + createTxMeta({ id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'} }), + createTxMeta({ id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'} }), + createTxMeta({ id: 2, status: 'rejected', metamaskNetworkId: 32 }), + createTxMeta({ id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4'} }), ]) }) @@ -522,7 +573,7 @@ describe('MetaMaskController', function () { assert(metamaskController.preferencesController.removeAddress.calledWith(addressToRemove)) }) it('should call accountTracker.removeAccount', async function () { - assert(metamaskController.accountTracker.removeAccount.calledWith(addressToRemove)) + assert(metamaskController.accountTracker.removeAccount.calledWith([addressToRemove])) }) it('should call keyringController.removeAccount', async function () { assert(metamaskController.keyringController.removeAccount.calledWith(addressToRemove)) @@ -533,22 +584,18 @@ describe('MetaMaskController', function () { }) describe('#clearSeedWordCache', function () { + it('should set seed words to null', function (done) { + sandbox.stub(metamaskController.preferencesController, 'setSeedWords') + metamaskController.clearSeedWordCache((err) => { + if (err) { + done(err) + } - it('should have set seed words', function () { - metamaskController.configManager.setSeedWords('test words') - const getConfigSeed = metamaskController.configManager.getSeedWords() - assert.equal(getConfigSeed, 'test words') - }) - - it('should clear config seed phrase', function () { - metamaskController.configManager.setSeedWords('test words') - metamaskController.clearSeedWordCache((err, result) => { - if (err) console.log(err) + assert.ok(metamaskController.preferencesController.setSeedWords.calledOnce) + assert.deepEqual(metamaskController.preferencesController.setSeedWords.args, [[null]]) + done() }) - const getConfigSeed = metamaskController.configManager.getSeedWords() - assert.equal(getConfigSeed, null) }) - }) describe('#setCurrentLocale', function () { @@ -566,14 +613,16 @@ describe('MetaMaskController', function () { }) - describe('#newUnsignedMessage', function () { + describe('#newUnsignedMessage', () => { let msgParams, metamaskMsgs, messages, msgId const address = '0xc42edfcc21ed14dda456aa0756c153f7985d8813' const data = '0x43727970746f6b697474696573' - beforeEach(async function () { + beforeEach(async () => { + sandbox.stub(metamaskController, 'getBalance') + metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) @@ -582,7 +631,10 @@ describe('MetaMaskController', function () { 'data': data, } - metamaskController.newUnsignedMessage(msgParams, noop) + const promise = metamaskController.newUnsignedMessage(msgParams) + // handle the promise so it doesn't throw an unhandledRejection + promise.then(noop).catch(noop) + metamaskMsgs = metamaskController.messageManager.getUnapprovedMsgs() messages = metamaskController.messageManager.messages msgId = Object.keys(metamaskMsgs)[0] @@ -622,13 +674,17 @@ describe('MetaMaskController', function () { describe('#newUnsignedPersonalMessage', function () { - it('errors with no from in msgParams', function () { + it('errors with no from in msgParams', async () => { const msgParams = { 'data': data, } - metamaskController.newUnsignedPersonalMessage(msgParams, function (error) { + + try { + await metamaskController.newUnsignedPersonalMessage(msgParams) + assert.fail('should have thrown') + } catch (error) { assert.equal(error.message, 'Nifty Wallet Message Signature: from field is required.') - }) + } }) let msgParams, metamaskPersonalMsgs, personalMessages, msgId @@ -637,6 +693,8 @@ describe('MetaMaskController', function () { const data = '0x43727970746f6b697474696573' beforeEach(async function () { + sandbox.stub(metamaskController, 'getBalance') + metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) @@ -645,7 +703,10 @@ describe('MetaMaskController', function () { 'data': data, } - metamaskController.newUnsignedPersonalMessage(msgParams, noop) + const promise = metamaskController.newUnsignedPersonalMessage(msgParams) + // handle the promise so it doesn't throw an unhandledRejection + promise.then(noop).catch(noop) + metamaskPersonalMsgs = metamaskController.personalMessageManager.getUnapprovedMsgs() personalMessages = metamaskController.personalMessageManager.messages msgId = Object.keys(metamaskPersonalMsgs)[0] @@ -684,22 +745,27 @@ describe('MetaMaskController', function () { describe('#setupUntrustedCommunication', function () { let streamTest - const phishingUrl = 'decentral.market' + const phishingUrl = 'myethereumwalletntw.com' afterEach(function () { streamTest.end() }) - it('sets up phishing stream for untrusted communication ', async function () { + it('sets up phishing stream for untrusted communication ', async () => { await metamaskController.blacklistController.updatePhishingList() + console.log(blacklistJSON.blacklist.includes(phishingUrl)) + + const { promise, resolve } = deferredPromise() streamTest = createThoughStream((chunk, enc, cb) => { - assert.equal(chunk.name, 'phishing') + if (chunk.name !== 'phishing') return cb() assert.equal(chunk.data.hostname, phishingUrl) - cb() - }) - // console.log(streamTest) - metamaskController.setupUntrustedCommunication(streamTest, phishingUrl) + resolve() + cb() + }) + metamaskController.setupUntrustedCommunication(streamTest, phishingUrl) + + await promise }) }) @@ -724,25 +790,102 @@ describe('MetaMaskController', function () { describe('#markAccountsFound', function () { it('adds lost accounts to config manager data', function () { metamaskController.markAccountsFound(noop) - const configManagerData = metamaskController.configManager.getData() - assert.deepEqual(configManagerData.lostAccounts, []) + const state = metamaskController.getState() + assert.deepEqual(state.lostAccounts, []) }) }) describe('#markPasswordForgotten', function () { it('adds and sets forgottenPassword to config data to true', function () { metamaskController.markPasswordForgotten(noop) - const configManagerData = metamaskController.configManager.getData() - assert.equal(configManagerData.forgottenPassword, true) + const state = metamaskController.getState() + assert.equal(state.forgottenPassword, true) }) }) describe('#unMarkPasswordForgotten', function () { it('adds and sets forgottenPassword to config data to false', function () { metamaskController.unMarkPasswordForgotten(noop) - const configManagerData = metamaskController.configManager.getData() - assert.equal(configManagerData.forgottenPassword, false) + const state = metamaskController.getState() + assert.equal(state.forgottenPassword, false) + }) + }) + + describe('#_onKeyringControllerUpdate', function () { + it('should do nothing if there are no keyrings in state', async function () { + const addAddresses = sinon.fake() + const syncWithAddresses = sinon.fake() + sandbox.replace(metamaskController, 'preferencesController', { + addAddresses, + }) + sandbox.replace(metamaskController, 'accountTracker', { + syncWithAddresses, + }) + + const oldState = metamaskController.getState() + await metamaskController._onKeyringControllerUpdate({keyrings: []}) + + assert.ok(addAddresses.notCalled) + assert.ok(syncWithAddresses.notCalled) + assert.deepEqual(metamaskController.getState(), oldState) + }) + + it('should update selected address if keyrings was locked', async function () { + const addAddresses = sinon.fake() + const getSelectedAddress = sinon.fake.returns('0x42') + const setSelectedAddress = sinon.fake() + const syncWithAddresses = sinon.fake() + sandbox.replace(metamaskController, 'preferencesController', { + addAddresses, + getSelectedAddress, + setSelectedAddress, + }) + sandbox.replace(metamaskController, 'accountTracker', { + syncWithAddresses, + }) + + const oldState = metamaskController.getState() + await metamaskController._onKeyringControllerUpdate({ + isUnlocked: false, + keyrings: [{ + accounts: ['0x1', '0x2'], + }], + }) + + assert.deepEqual(addAddresses.args, [[['0x1', '0x2']]]) + assert.deepEqual(syncWithAddresses.args, [[['0x1', '0x2']]]) + assert.deepEqual(setSelectedAddress.args, [['0x1']]) + assert.deepEqual(metamaskController.getState(), oldState) + }) + + it('should NOT update selected address if already unlocked', async function () { + const addAddresses = sinon.fake() + const syncWithAddresses = sinon.fake() + sandbox.replace(metamaskController, 'preferencesController', { + addAddresses, + }) + sandbox.replace(metamaskController, 'accountTracker', { + syncWithAddresses, + }) + + const oldState = metamaskController.getState() + await metamaskController._onKeyringControllerUpdate({ + isUnlocked: true, + keyrings: [{ + accounts: ['0x1', '0x2'], + }], + }) + + assert.deepEqual(addAddresses.args, [[['0x1', '0x2']]]) + assert.deepEqual(syncWithAddresses.args, [[['0x1', '0x2']]]) + assert.deepEqual(metamaskController.getState(), oldState) }) }) }) + +function deferredPromise () { + let resolve + const promise = new Promise(_resolve => { resolve = _resolve }) + return { promise, resolve } +} diff --git a/test/unit/app/controllers/network-contoller-test.js b/test/unit/app/controllers/network-contoller-test.js index 8a3d555f2..746b0d07a 100644 --- a/test/unit/app/controllers/network-contoller-test.js +++ b/test/unit/app/controllers/network-contoller-test.js @@ -32,9 +32,10 @@ describe('# Network Controller', function () { describe('#provider', function () { it('provider should be updatable without reassignment', function () { networkController.initializeProvider(networkControllerProviderConfig) - const proxy = networkController._proxy - proxy.setTarget({ test: true, on: () => {} }) - assert.ok(proxy.test) + const providerProxy = networkController.getProviderAndBlockTracker().provider + assert.equal(providerProxy.test, undefined) + providerProxy.setTarget({ test: true }) + assert.equal(providerProxy.test, true) }) }) describe('#getNetworkState', function () { diff --git a/test/unit/app/controllers/notice-controller-test.js b/test/unit/app/controllers/notice-controller-test.js index b3ae75080..834c88f7b 100644 --- a/test/unit/app/controllers/notice-controller-test.js +++ b/test/unit/app/controllers/notice-controller-test.js @@ -1,16 +1,11 @@ const assert = require('assert') -const configManagerGen = require('../../../lib/mock-config-manager') const NoticeController = require('../../../../app/scripts/notice-controller') describe('notice-controller', function () { var noticeController beforeEach(function () { - // simple localStorage polyfill - const configManager = configManagerGen() - noticeController = new NoticeController({ - configManager: configManager, - }) + noticeController = new NoticeController() }) describe('notices', function () { diff --git a/test/unit/app/controllers/preferences-controller-test.js b/test/unit/app/controllers/preferences-controller-test.js index 1d83d8452..f6fd2faeb 100644 --- a/test/unit/app/controllers/preferences-controller-test.js +++ b/test/unit/app/controllers/preferences-controller-test.js @@ -1,6 +1,7 @@ const assert = require('assert') const ObservableStore = require('obs-store') const PreferencesController = require('../../../../app/scripts/controllers/preferences') +const sinon = require('sinon') describe('preferences controller', function () { let preferencesController @@ -368,5 +369,144 @@ describe('preferences controller', function () { assert.deepEqual(tokensSecond, initialTokensSecond, 'tokens equal for same network') }) }) + + describe('on watchAsset', function () { + var stubNext, stubEnd, stubHandleWatchAssetERC20, asy, req, res + const sandbox = sinon.createSandbox() + + beforeEach(() => { + req = {params: {}} + res = {} + asy = {next: () => {}, end: () => {}} + stubNext = sandbox.stub(asy, 'next') + stubEnd = sandbox.stub(asy, 'end').returns(0) + stubHandleWatchAssetERC20 = sandbox.stub(preferencesController, '_handleWatchAssetERC20') + }) + after(() => { + sandbox.restore() + }) + + it('shouldn not do anything if method not corresponds', async function () { + const asy = {next: () => {}, end: () => {}} + var stubNext = sandbox.stub(asy, 'next') + var stubEnd = sandbox.stub(asy, 'end').returns(0) + req.method = 'metamask' + await preferencesController.requestWatchAsset(req, res, asy.next, asy.end) + sandbox.assert.notCalled(stubEnd) + sandbox.assert.called(stubNext) + }) + it('should do something if method is supported', async function () { + const asy = {next: () => {}, end: () => {}} + var stubNext = sandbox.stub(asy, 'next') + var stubEnd = sandbox.stub(asy, 'end').returns(0) + req.method = 'metamask_watchAsset' + req.params.type = 'someasset' + await preferencesController.requestWatchAsset(req, res, asy.next, asy.end) + sandbox.assert.called(stubEnd) + sandbox.assert.notCalled(stubNext) + }) + it('should through error if method is supported but asset type is not', async function () { + req.method = 'metamask_watchAsset' + req.params.type = 'someasset' + await preferencesController.requestWatchAsset(req, res, asy.next, asy.end) + sandbox.assert.called(stubEnd) + sandbox.assert.notCalled(stubHandleWatchAssetERC20) + sandbox.assert.notCalled(stubNext) + assert.deepEqual(res, {}) + }) + it('should trigger handle add asset if type supported', async function () { + const asy = {next: () => {}, end: () => {}} + req.method = 'metamask_watchAsset' + req.params.type = 'ERC20' + await preferencesController.requestWatchAsset(req, res, asy.next, asy.end) + sandbox.assert.called(stubHandleWatchAssetERC20) + }) + }) + + describe('on watchAsset of type ERC20', function () { + var req + + const sandbox = sinon.createSandbox() + beforeEach(() => { + req = {params: {type: 'ERC20'}} + }) + after(() => { + sandbox.restore() + }) + + it('should add suggested token', async function () { + const address = '0xabcdef1234567' + const symbol = 'ABBR' + const decimals = 5 + const image = 'someimage' + req.params.options = { address, symbol, decimals, image } + + sandbox.stub(preferencesController, '_validateERC20AssetParams').returns(true) + preferencesController.showWatchAssetUi = async () => {} + + await preferencesController._handleWatchAssetERC20(req.params.options) + const suggested = preferencesController.getSuggestedTokens() + assert.equal(Object.keys(suggested).length, 1, `one token added ${Object.keys(suggested)}`) + + assert.equal(suggested[address].address, address, 'set address correctly') + assert.equal(suggested[address].symbol, symbol, 'set symbol correctly') + assert.equal(suggested[address].decimals, decimals, 'set decimals correctly') + assert.equal(suggested[address].image, image, 'set image correctly') + }) + + it('should add token correctly if user confirms', async function () { + const address = '0xabcdef1234567' + const symbol = 'ABBR' + const decimals = 5 + const image = 'someimage' + req.params.options = { address, symbol, decimals, image } + + sandbox.stub(preferencesController, '_validateERC20AssetParams').returns(true) + preferencesController.showWatchAssetUi = async () => { + await preferencesController.addToken(address, symbol, decimals, image) + } + + await preferencesController._handleWatchAssetERC20(req.params.options) + const tokens = preferencesController.getTokens() + assert.equal(tokens.length, 1, `one token added`) + const added = tokens[0] + assert.equal(added.address, address, 'set address correctly') + assert.equal(added.symbol, symbol, 'set symbol correctly') + assert.equal(added.decimals, decimals, 'set decimals correctly') + + const assetImages = preferencesController.getAssetImages() + assert.ok(assetImages[address], `set image correctly`) + }) + }) + + describe('setPasswordForgotten', function () { + it('should default to false', function () { + const state = preferencesController.store.getState() + assert.equal(state.forgottenPassword, false) + }) + + it('should set the forgottenPassword property in state', function () { + assert.equal(preferencesController.store.getState().forgottenPassword, false) + + preferencesController.setPasswordForgotten(true) + + assert.equal(preferencesController.store.getState().forgottenPassword, true) + }) + }) + + describe('setSeedWords', function () { + it('should default to null', function () { + const state = preferencesController.store.getState() + assert.equal(state.seedWords, null) + }) + + it('should set the seedWords property in state', function () { + assert.equal(preferencesController.store.getState().seedWords, null) + + preferencesController.setSeedWords('foo bar baz') + + assert.equal(preferencesController.store.getState().seedWords, 'foo bar baz') + }) + }) }) diff --git a/test/unit/app/controllers/transactions/nonce-tracker-test.js b/test/unit/app/controllers/transactions/nonce-tracker-test.js index 6c0ac759f..51ac390e9 100644 --- a/test/unit/app/controllers/transactions/nonce-tracker-test.js +++ b/test/unit/app/controllers/transactions/nonce-tracker-test.js @@ -224,14 +224,15 @@ function generateNonceTrackerWith (pending, confirmed, providerStub = '0x0') { providerResultStub.result = providerStub const provider = { sendAsync: (_, cb) => { cb(undefined, providerResultStub) }, - _blockTracker: { - getCurrentBlock: () => '0x11b568', - }, + } + const blockTracker = { + getCurrentBlock: () => '0x11b568', + getLatestBlock: async () => '0x11b568', } return new NonceTracker({ provider, + blockTracker, getPendingTransactions, getConfirmedTransactions, }) } - diff --git a/test/unit/app/controllers/transactions/pending-tx-test.js b/test/unit/app/controllers/transactions/pending-tx-test.js index 8bf2da6f8..ba15f1953 100644 --- a/test/unit/app/controllers/transactions/pending-tx-test.js +++ b/test/unit/app/controllers/transactions/pending-tx-test.js @@ -9,6 +9,7 @@ describe('PendingTransactionTracker', function () { let pendingTxTracker, txMeta, txMetaNoHash, providerResultStub, provider, txMeta3, txList, knownErrors this.timeout(10000) + beforeEach(function () { txMeta = { id: 1, @@ -40,7 +41,10 @@ describe('PendingTransactionTracker', function () { getPendingTransactions: () => { return [] }, getCompletedTransactions: () => { return [] }, publishTransaction: () => {}, + confirmTransaction: () => {}, }) + + pendingTxTracker._getBlock = (blockNumber) => { return {number: blockNumber, transactions: []} } }) describe('_checkPendingTx state management', function () { @@ -92,58 +96,6 @@ describe('PendingTransactionTracker', function () { }) }) - describe('#checkForTxInBlock', function () { - it('should return if no pending transactions', function () { - // throw a type error if it trys to do anything on the block - // thus failing the test - const block = Proxy.revocable({}, {}).revoke() - pendingTxTracker.checkForTxInBlock(block) - }) - it('should emit \'tx:failed\' if the txMeta does not have a hash', function (done) { - const block = Proxy.revocable({}, {}).revoke() - pendingTxTracker.getPendingTransactions = () => [txMetaNoHash] - pendingTxTracker.once('tx:failed', (txId, err) => { - assert(txId, txMetaNoHash.id, 'should pass txId') - done() - }) - pendingTxTracker.checkForTxInBlock(block) - }) - it('should emit \'txConfirmed\' if the tx is in the block', function (done) { - const block = { transactions: [txMeta]} - pendingTxTracker.getPendingTransactions = () => [txMeta] - pendingTxTracker.once('tx:confirmed', (txId) => { - assert(txId, txMeta.id, 'should pass txId') - done() - }) - pendingTxTracker.once('tx:failed', (_, err) => { done(err) }) - pendingTxTracker.checkForTxInBlock(block) - }) - }) - describe('#queryPendingTxs', function () { - it('should call #_checkPendingTxs if their is no oldBlock', function (done) { - let oldBlock - const newBlock = { number: '0x01' } - pendingTxTracker._checkPendingTxs = done - pendingTxTracker.queryPendingTxs({ oldBlock, newBlock }) - }) - it('should call #_checkPendingTxs if oldBlock and the newBlock have a diff of greater then 1', function (done) { - const oldBlock = { number: '0x01' } - const newBlock = { number: '0x03' } - pendingTxTracker._checkPendingTxs = done - pendingTxTracker.queryPendingTxs({ oldBlock, newBlock }) - }) - it('should not call #_checkPendingTxs if oldBlock and the newBlock have a diff of 1 or less', function (done) { - const oldBlock = { number: '0x1' } - const newBlock = { number: '0x2' } - pendingTxTracker._checkPendingTxs = () => { - const err = new Error('should not call #_checkPendingTxs if oldBlock and the newBlock have a diff of 1 or less') - done(err) - } - pendingTxTracker.queryPendingTxs({ oldBlock, newBlock }) - done() - }) - }) - describe('#_checkPendingTx', function () { it('should emit \'tx:failed\' if the txMeta does not have a hash', function (done) { pendingTxTracker.once('tx:failed', (txId, err) => { @@ -157,16 +109,6 @@ describe('PendingTransactionTracker', function () { providerResultStub.eth_getTransactionByHash = null pendingTxTracker._checkPendingTx(txMeta) }) - - it('should emit \'txConfirmed\'', function (done) { - providerResultStub.eth_getTransactionByHash = {blockNumber: '0x01'} - pendingTxTracker.once('tx:confirmed', (txId) => { - assert(txId, txMeta.id, 'should pass txId') - done() - }) - pendingTxTracker.once('tx:failed', (_, err) => { done(err) }) - pendingTxTracker._checkPendingTx(txMeta) - }) }) describe('#_checkPendingTxs', function () { @@ -180,19 +122,19 @@ describe('PendingTransactionTracker', function () { }) }) - it('should warp all txMeta\'s in #_checkPendingTx', function (done) { + it('should warp all txMeta\'s in #updatePendingTxs', function (done) { pendingTxTracker.getPendingTransactions = () => txList pendingTxTracker._checkPendingTx = (tx) => { tx.resolve(tx) } Promise.all(txList.map((tx) => tx.processed)) .then((txCompletedList) => done()) .catch(done) - pendingTxTracker._checkPendingTxs() + pendingTxTracker.updatePendingTxs() }) }) describe('#resubmitPendingTxs', function () { - const blockStub = { number: '0x0' } + const blockNumberStub = '0x0' beforeEach(function () { const txMeta2 = txMeta3 = txMeta txList = [txMeta, txMeta2, txMeta3].map((tx) => { @@ -210,7 +152,7 @@ describe('PendingTransactionTracker', function () { Promise.all(txList.map((tx) => tx.processed)) .then((txCompletedList) => done()) .catch(done) - pendingTxTracker.resubmitPendingTxs(blockStub) + pendingTxTracker.resubmitPendingTxs(blockNumberStub) }) it('should not emit \'tx:failed\' if the txMeta throws a known txError', function (done) { knownErrors = [ @@ -237,7 +179,7 @@ describe('PendingTransactionTracker', function () { .then((txCompletedList) => done()) .catch(done) - pendingTxTracker.resubmitPendingTxs(blockStub) + pendingTxTracker.resubmitPendingTxs(blockNumberStub) }) it('should emit \'tx:warning\' if it encountered a real error', function (done) { pendingTxTracker.once('tx:warning', (txMeta, err) => { @@ -255,7 +197,7 @@ describe('PendingTransactionTracker', function () { .then((txCompletedList) => done()) .catch(done) - pendingTxTracker.resubmitPendingTxs(blockStub) + pendingTxTracker.resubmitPendingTxs(blockNumberStub) }) }) describe('#_resubmitTx', function () { diff --git a/test/unit/app/controllers/transactions/tx-controller-test.js b/test/unit/app/controllers/transactions/tx-controller-test.js index 3e94e2562..45260aa83 100644 --- a/test/unit/app/controllers/transactions/tx-controller-test.js +++ b/test/unit/app/controllers/transactions/tx-controller-test.js @@ -1,4 +1,5 @@ const assert = require('assert') +const EventEmitter = require('events') const ethUtil = require('ethereumjs-util') const EthTx = require('ethereumjs-tx') const ObservableStore = require('obs-store') @@ -22,12 +23,14 @@ describe('Transaction Controller', function () { } provider = createTestProviderTools({ scaffold: providerResultStub }).provider fromAccount = getTestAccounts()[0] - + const blockTrackerStub = new EventEmitter() + blockTrackerStub.getCurrentBlock = noop + blockTrackerStub.getLatestBlock = noop txController = new TransactionController({ provider, networkStore: new ObservableStore(currentNetworkId), txHistoryLimit: 10, - blockTracker: { getCurrentBlock: noop, on: noop, once: noop }, + blockTracker: blockTrackerStub, signTransaction: (ethTx) => new Promise((resolve) => { ethTx.sign(fromAccount.key) resolve() @@ -49,9 +52,9 @@ describe('Transaction Controller', function () { describe('#getUnapprovedTxCount', function () { it('should return the number of unapproved txs', function () { txController.txStateManager._saveTxList([ - { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, - { id: 2, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, - { id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, + { id: 2, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, + { id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, ]) const unapprovedTxCount = txController.getUnapprovedTxCount() assert.equal(unapprovedTxCount, 3, 'should be 3') @@ -61,9 +64,9 @@ describe('Transaction Controller', function () { describe('#getPendingTxCount', function () { it('should return the number of pending txs', function () { txController.txStateManager._saveTxList([ - { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, - { id: 2, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, - { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, + { id: 2, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, + { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {}, history: [] }, ]) const pendingTxCount = txController.getPendingTxCount() assert.equal(pendingTxCount, 3, 'should be 3') @@ -79,15 +82,15 @@ describe('Transaction Controller', function () { 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', } txController.txStateManager._saveTxList([ - {id: 0, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, - {id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, - {id: 2, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, - {id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams}, - {id: 4, status: 'rejected', metamaskNetworkId: currentNetworkId, txParams}, - {id: 5, status: 'approved', metamaskNetworkId: currentNetworkId, txParams}, - {id: 6, status: 'signed', metamaskNetworkId: currentNetworkId, txParams}, - {id: 7, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams}, - {id: 8, status: 'failed', metamaskNetworkId: currentNetworkId, txParams}, + {id: 0, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 2, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 4, status: 'rejected', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 5, status: 'approved', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 6, status: 'signed', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 7, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams, history: [] }, + {id: 8, status: 'failed', metamaskNetworkId: currentNetworkId, txParams, history: [] }, ]) }) @@ -201,24 +204,22 @@ describe('Transaction Controller', function () { }) describe('#addTxGasDefaults', function () { - it('should add the tx defaults if their are none', function (done) { + it('should add the tx defaults if their are none', async () => { const txMeta = { - 'txParams': { - 'from': '0xc684832530fcbddae4b4230a47e991ddcec2831d', - 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', + txParams: { + from: '0xc684832530fcbddae4b4230a47e991ddcec2831d', + to: '0xc684832530fcbddae4b4230a47e991ddcec2831d', }, + history: [], } - providerResultStub.eth_gasPrice = '4a817c800' - providerResultStub.eth_getBlockByNumber = { gasLimit: '47b784' } - providerResultStub.eth_estimateGas = '5209' - txController.addTxGasDefaults(txMeta) - .then((txMetaWithDefaults) => { - assert(txMetaWithDefaults.txParams.value, '0x0', 'should have added 0x0 as the value') - assert(txMetaWithDefaults.txParams.gasPrice, 'should have added the gas price') - assert(txMetaWithDefaults.txParams.gas, 'should have added the gas field') - done() - }) - .catch(done) + providerResultStub.eth_gasPrice = '4a817c800' + providerResultStub.eth_getBlockByNumber = { gasLimit: '47b784' } + providerResultStub.eth_estimateGas = '5209' + + const txMetaWithDefaults = await txController.addTxGasDefaults(txMeta) + assert(txMetaWithDefaults.txParams.value, '0x0', 'should have added 0x0 as the value') + assert(txMetaWithDefaults.txParams.gasPrice, 'should have added the gas price') + assert(txMetaWithDefaults.txParams.gas, 'should have added the gas field') }) }) @@ -381,8 +382,9 @@ describe('Transaction Controller', function () { }) it('should publish a tx, updates the rawTx when provided a one', async function () { + const rawTx = '0x477b2e6553c917af0db0388ae3da62965ff1a184558f61b749d1266b2e6d024c' txController.txStateManager.addTx(txMeta) - await txController.publishTransaction(txMeta.id) + await txController.publishTransaction(txMeta.id, rawTx) const publishedTx = txController.txStateManager.getTx(1) assert.equal(publishedTx.hash, hash) assert.equal(publishedTx.status, 'submitted') @@ -398,7 +400,7 @@ describe('Transaction Controller', function () { data: '0x0', } txController.txStateManager._saveTxList([ - { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams }, + { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams, history: [] }, ]) txController.retryTransaction(1) .then((txMeta) => { diff --git a/test/unit/config-manager-test.js b/test/unit/config-manager-test.js deleted file mode 100644 index 2dbaad01a..000000000 --- a/test/unit/config-manager-test.js +++ /dev/null @@ -1,100 +0,0 @@ -// polyfill fetch -global.fetch = global.fetch || require('isomorphic-fetch') - -const assert = require('assert') -const configManagerGen = require('../lib/mock-config-manager') - -describe('config-manager', function () { - var configManager - - beforeEach(function () { - configManager = configManagerGen() - }) - - describe('#setConfig', function () { - it('should set the config key', function () { - var testConfig = { - provider: { - type: 'rpc', - rpcTarget: 'foobar', - }, - } - configManager.setConfig(testConfig) - var result = configManager.getData() - - assert.equal(result.config.provider.type, testConfig.provider.type) - assert.equal(result.config.provider.rpcTarget, testConfig.provider.rpcTarget) - }) - - it('setting wallet should not overwrite config', function () { - var testConfig = { - provider: { - type: 'rpc', - rpcTarget: 'foobar', - }, - } - configManager.setConfig(testConfig) - - var testWallet = { - name: 'this is my fake wallet', - } - configManager.setWallet(testWallet) - - var result = configManager.getData() - assert.equal(result.wallet.name, testWallet.name, 'wallet name is set') - assert.equal(result.config.provider.rpcTarget, testConfig.provider.rpcTarget) - - testConfig.provider.type = 'something else!' - configManager.setConfig(testConfig) - - result = configManager.getData() - assert.equal(result.wallet.name, testWallet.name, 'wallet name is set') - assert.equal(result.config.provider.rpcTarget, testConfig.provider.rpcTarget) - assert.equal(result.config.provider.type, testConfig.provider.type) - }) - }) - - describe('wallet nicknames', function () { - it('should return null when no nicknames are saved', function () { - var nick = configManager.nicknameForWallet('0x0') - assert.equal(nick, null, 'no nickname returned') - }) - - it('should persist nicknames', function () { - var account = '0x0' - var nick1 = 'foo' - var nick2 = 'bar' - configManager.setNicknameForWallet(account, nick1) - - var result1 = configManager.nicknameForWallet(account) - assert.equal(result1, nick1) - - configManager.setNicknameForWallet(account, nick2) - var result2 = configManager.nicknameForWallet(account) - assert.equal(result2, nick2) - }) - }) - - describe('transactions', function () { - beforeEach(function () { - configManager.setTxList([]) - }) - - describe('#getTxList', function () { - it('when new should return empty array', function () { - var result = configManager.getTxList() - assert.ok(Array.isArray(result)) - assert.equal(result.length, 0) - }) - }) - - describe('#setTxList', function () { - it('saves the submitted data to the tx list', function () { - var target = [{ foo: 'bar' }] - configManager.setTxList(target) - var result = configManager.getTxList() - assert.equal(result[0].foo, 'bar') - }) - }) - }) -}) diff --git a/test/unit/localhostState.js b/test/unit/localhostState.js new file mode 100644 index 000000000..f9fa157d7 --- /dev/null +++ b/test/unit/localhostState.js @@ -0,0 +1,21 @@ + +/** + * @typedef {Object} FirstTimeState + * @property {Object} config Initial configuration parameters + * @property {Object} NetworkController Network controller state + */ + +/** + * @type {FirstTimeState} + */ +const initialState = { + config: {}, + NetworkController: { + provider: { + type: 'rpc', + rpcTarget: 'http://localhost:8545', + }, + }, +} + +module.exports = initialState diff --git a/ui/app/account-and-transaction-details.js b/ui/app/account-and-transaction-details.js deleted file mode 100644 index 03101d37a..000000000 --- a/ui/app/account-and-transaction-details.js +++ /dev/null @@ -1,33 +0,0 @@ -const Component = require('react').Component -const h = require('react-hyperscript') -const inherits = require('util').inherits -// Main Views -const TxView = require('./components/tx-view') -const WalletView = require('./components/wallet-view') - -module.exports = AccountAndTransactionDetails - -inherits(AccountAndTransactionDetails, Component) -function AccountAndTransactionDetails () { - Component.call(this) -} - -AccountAndTransactionDetails.prototype.render = function () { - return h('div.account-and-transaction-details', [ - // wallet - h(WalletView, { - style: { - }, - responsiveDisplayClassname: '.lap-visible', - }, [ - ]), - - // transaction - h(TxView, { - style: { - }, - }, [ - ]), - ]) -} - diff --git a/ui/app/actions.js b/ui/app/actions.js index 6a4423c62..ad1135489 100644 --- a/ui/app/actions.js +++ b/ui/app/actions.js @@ -10,6 +10,7 @@ const { const ethUtil = require('ethereumjs-util') const { fetchLocale } = require('../i18n-helper') const log = require('loglevel') +const { ENVIRONMENT_TYPE_NOTIFICATION } = require('../../app/scripts/lib/enums') const { hasUnconfirmedTransactions } = require('./helpers/confirm-transaction/util') const WebcamUtils = require('../lib/webcam-utils') @@ -232,10 +233,13 @@ var actions = { showAddTokenPage, showConfirmAddTokensPage, showRemoveTokenPage, + SHOW_ADD_SUGGESTED_TOKEN_PAGE: 'SHOW_ADD_SUGGESTED_TOKEN_PAGE', + showAddSuggestedTokenPage, addToken, addTokens, removeToken, updateTokens, + removeSuggestedTokens, UPDATE_TOKENS: 'UPDATE_TOKENS', setRpcTarget: setRpcTarget, setProviderType: setProviderType, @@ -323,6 +327,8 @@ var actions = { showDeleteImportedAccount, CONFIRM_CHANGE_PASSWORD: 'CONFIRM_CHANGE_PASSWORD', confirmChangePassword, + + createCancelTransaction, } module.exports = actions @@ -425,12 +431,18 @@ function createNewVaultAndRestore (password, seed) { log.debug(`background.createNewVaultAndRestore`) return new Promise((resolve, reject) => { - background.createNewVaultAndRestore(password, seed, err => { + background.clearSeedWordCache((err) => { if (err) { return reject(err) } - resolve() + background.createNewVaultAndRestore(password, seed, (err) => { + if (err) { + return reject(err) + } + + resolve() + }) }) }) .then(() => dispatch(actions.unMarkPasswordForgotten())) @@ -1181,6 +1193,10 @@ function updateAndApproveTx (txData) { return txData }) + .catch((err) => { + dispatch(actions.hideLoadingIndication()) + return Promise.reject(err) + }) } } @@ -1630,6 +1646,13 @@ function showConfirmAddTokensPage (transitionForward = true) { } } +function showAddSuggestedTokenPage (transitionForward = true) { + return { + type: actions.SHOW_ADD_SUGGESTED_TOKEN_PAGE, + value: transitionForward, + } +} + function showRemoveTokenPage (token, transitionForward = true) { return { type: actions.SHOW_REMOVE_TOKEN_PAGE, @@ -1638,11 +1661,11 @@ function showRemoveTokenPage (token, transitionForward = true) { } } -function addToken (address, symbol, decimals, network) { +function addToken (address, symbol, decimals, image, network) { return (dispatch) => { dispatch(actions.showLoadingIndication()) return new Promise((resolve, reject) => { - background.addToken(address, symbol, decimals, network, (err, tokens) => { + background.addToken(address, symbol, decimals, image, network, (err, tokens) => { dispatch(actions.hideLoadingIndication()) if (err) { dispatch(actions.displayWarning(err.message)) @@ -1692,6 +1715,27 @@ function addTokens (tokens) { } } +function removeSuggestedTokens () { + return (dispatch) => { + dispatch(actions.showLoadingIndication()) + return new Promise((resolve, reject) => { + background.removeSuggestedTokens((err, suggestedTokens) => { + dispatch(actions.hideLoadingIndication()) + if (err) { + dispatch(actions.displayWarning(err.message)) + } + dispatch(actions.clearPendingTokens()) + if (global.METAMASK_UI_TYPE === ENVIRONMENT_TYPE_NOTIFICATION) { + return global.platform.closeCurrentWindow() + } + resolve(suggestedTokens) + }) + }) + .then(() => updateMetamaskStateFromBackground()) + .then(suggestedTokens => dispatch(actions.updateMetamaskState({...suggestedTokens}))) + } +} + function updateTokens (newTokens) { return { type: actions.UPDATE_TOKENS, @@ -1699,6 +1743,12 @@ function updateTokens (newTokens) { } } +function clearPendingTokens () { + return { + type: actions.CLEAR_PENDING_TOKENS, + } +} + function goBackToInitView () { return { type: actions.BACK_TO_INIT_MENU, @@ -1774,6 +1824,29 @@ function retryTransaction (txId) { } } +function createCancelTransaction (txId, customGasPrice) { + log.debug('background.cancelTransaction') + let newTxId + + return dispatch => { + return new Promise((resolve, reject) => { + background.createCancelTransaction(txId, customGasPrice, (err, newState) => { + if (err) { + dispatch(actions.displayWarning(err.message)) + reject(err) + } + + const { selectedAddressTxList } = newState + const { id } = selectedAddressTxList[selectedAddressTxList.length - 1] + newTxId = id + resolve(newState) + }) + }) + .then(newState => dispatch(actions.updateMetamaskState(newState))) + .then(() => newTxId) + } +} + // // config // @@ -1878,9 +1951,13 @@ function hideModal (payload) { } } -function showSidebar () { +function showSidebar ({ transitionName, type }) { return { type: actions.SIDEBAR_OPEN, + value: { + transitionName, + type, + }, } } @@ -2382,12 +2459,6 @@ function setPendingTokens (pendingTokens) { } } -function clearPendingTokens () { - return { - type: actions.CLEAR_PENDING_TOKENS, - } -} - function showDeleteRPC (RPC_URL, transitionForward = true) { return { type: actions.SHOW_DELETE_RPC, diff --git a/ui/app/app.js b/ui/app/app.js index aa848ddb0..f816dfb1c 100644 --- a/ui/app/app.js +++ b/ui/app/app.js @@ -15,22 +15,22 @@ const SendTransactionScreen = require('./components/send/send.container') const ConfirmTransaction = require('./components/pages/confirm-transaction') // slideout menu -const WalletView = require('./components/wallet-view') +const Sidebar = require('./components/sidebars').default // other views -const Home = require('./components/pages/home') +import Home from './components/pages/home' +import Settings from './components/pages/settings' const Authenticated = require('./components/pages/authenticated') const Initialized = require('./components/pages/initialized') -const Settings = require('./components/pages/settings') const RestoreVaultPage = require('./components/pages/keychains/restore-vault').default const RevealSeedConfirmation = require('./components/pages/keychains/reveal-seed') const AddTokenPage = require('./components/pages/add-token') const ConfirmAddTokenPage = require('./components/pages/confirm-add-token') +const ConfirmAddSuggestedTokenPage = require('./components/pages/confirm-add-suggested-token') const CreateAccountPage = require('./components/pages/create-account') const NoticeScreen = require('./components/pages/notice') const Loading = require('./components/loading-screen') -const ReactCSSTransitionGroup = require('react-addons-css-transition-group') const NetworkDropdown = require('./components/dropdowns/network-dropdown') const AccountMenu = require('./components/account-menu') @@ -39,8 +39,7 @@ const Modal = require('./components/modals/index').Modal // Global Alert const Alert = require('./components/alert') -const AppHeader = require('./components/app-header') - +import AppHeader from './components/app-header' import UnlockPage from './components/pages/unlock-page' // Routes @@ -52,6 +51,7 @@ const { RESTORE_VAULT_ROUTE, ADD_TOKEN_ROUTE, CONFIRM_ADD_TOKEN_ROUTE, + CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE, NEW_ACCOUNT_ROUTE, SEND_ROUTE, CONFIRM_TRANSACTION_ROUTE, @@ -86,6 +86,7 @@ class App extends Component { h(Authenticated, { path: SEND_ROUTE, exact, component: SendTransactionScreen }), h(Authenticated, { path: ADD_TOKEN_ROUTE, exact, component: AddTokenPage }), h(Authenticated, { path: CONFIRM_ADD_TOKEN_ROUTE, exact, component: ConfirmAddTokenPage }), + h(Authenticated, { path: CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE, exact, component: ConfirmAddSuggestedTokenPage }), h(Authenticated, { path: NEW_ACCOUNT_ROUTE, component: CreateAccountPage }), h(Authenticated, { path: DEFAULT_ROUTE, exact, component: Home }), ]) @@ -103,6 +104,7 @@ class App extends Component { frequentRpcList, currentView, setMouseUserState, + sidebar, } = this.props const isLoadingNetwork = network === 'loading' && currentView.name !== 'config' const loadMessage = loadingMessage || isLoadingNetwork ? @@ -135,7 +137,12 @@ class App extends Component { h(AppHeader), // sidebar - this.renderSidebar(), + h(Sidebar, { + sidebarOpen: sidebar.isOpen, + hideSidebar: this.props.hideSidebar, + transitionName: sidebar.transitionName, + type: sidebar.type, + }), // network dropdown h(NetworkDropdown, { @@ -145,61 +152,18 @@ class App extends Component { h(AccountMenu), - (isLoading || isLoadingNetwork) && h(Loading, { - loadingMessage: loadMessage, - }), + h('div.main-container-wrapper', [ + (isLoading || isLoadingNetwork) && h(Loading, { + loadingMessage: loadMessage, + }), - // content - this.renderRoutes(), + // content + this.renderRoutes(), + ]), ]) ) } - renderSidebar () { - return h('div', [ - h('style', ` - .sidebar-enter { - transition: transform 300ms ease-in-out; - transform: translateX(-100%); - } - .sidebar-enter.sidebar-enter-active { - transition: transform 300ms ease-in-out; - transform: translateX(0%); - } - .sidebar-leave { - transition: transform 200ms ease-out; - transform: translateX(0%); - } - .sidebar-leave.sidebar-leave-active { - transition: transform 200ms ease-out; - transform: translateX(-100%); - } - `), - - h(ReactCSSTransitionGroup, { - transitionName: 'sidebar', - transitionEnterTimeout: 300, - transitionLeaveTimeout: 200, - }, [ - // A second instance of Walletview is used for non-mobile viewports - this.props.sidebarOpen ? h(WalletView, { - responsiveDisplayClassname: '.sidebar', - style: {}, - }) : undefined, - - ]), - - // overlay - // TODO: add onClick for overlay to close sidebar - this.props.sidebarOpen ? h('div.sidebar-overlay', { - style: {}, - onClick: () => { - this.props.hideSidebar() - }, - }, []) : undefined, - ]) - } - toggleMetamaskActive () { if (!this.props.isUnlocked) { // currently inactive: redirect to password box @@ -226,7 +190,7 @@ class App extends Component { } else if (providerName === 'ropsten') { name = this.context.t('connectingToRopsten') } else if (providerName === 'kovan') { - name = this.context.t('connectingToRopsten') + name = this.context.t('connectingToKovan') } else if (providerName === 'rinkeby') { name = this.context.t('connectingToRinkeby') } else if (providerName === 'poa') { @@ -272,7 +236,7 @@ App.propTypes = { provider: PropTypes.object, frequentRpcList: PropTypes.array, currentView: PropTypes.object, - sidebarOpen: PropTypes.bool, + sidebar: PropTypes.object, alertOpen: PropTypes.bool, hideSidebar: PropTypes.func, isMascara: PropTypes.bool, @@ -308,7 +272,7 @@ function mapStateToProps (state) { const { appState, metamask } = state const { networkDropdownOpen, - sidebarOpen, + sidebar, alertOpen, alertMessage, isLoading, @@ -335,7 +299,7 @@ function mapStateToProps (state) { return { // state from plugin networkDropdownOpen, - sidebarOpen, + sidebar, alertOpen, alertMessage, isLoading, diff --git a/ui/app/components/app-header/app-header.component.js b/ui/app/components/app-header/app-header.component.js index 07ca6cf84..b8b002dcc 100644 --- a/ui/app/components/app-header/app-header.component.js +++ b/ui/app/components/app-header/app-header.component.js @@ -1,4 +1,4 @@ -import React, { Component } from 'react' +import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' import { matchPath } from 'react-router-dom' @@ -11,7 +11,7 @@ const { DEFAULT_ROUTE, INITIALIZE_ROUTE, CONFIRM_TRANSACTION_ROUTE } = require(' const Identicon = require('../identicon') const NetworkIndicator = require('../network') -class AppHeader extends Component { +export default class AppHeader extends PureComponent { static propTypes = { history: PropTypes.object, location: PropTypes.object, @@ -107,20 +107,19 @@ class AppHeader extends Component { onClick={() => history.push(DEFAULT_ROUTE)} > + -
-

{ this.context.t('appName') }

-
- { this.context.t('beta') } -
-
-
+
currency.code === upperCaseFiatSuffix) - ? currencyFormatter.format(Number(fiatDisplayNumber), { - code: upperCaseFiatSuffix, - }) - : `${fiatPrefix}${fiatDisplayNumber} ${upperCaseFiatSuffix}` - - return h('div.fiat-amount', { - style: {}, - }, display) -} - BalanceComponent.prototype.getTokenBalance = function (formattedBalance, shorten) { const balanceObj = generateBalanceObject(formattedBalance, shorten ? 1 : 3) diff --git a/ui/app/components/button/button.component.js b/ui/app/components/button/button.component.js index 1e0ef1b64..4a06333e7 100644 --- a/ui/app/components/button/button.component.js +++ b/ui/app/components/button/button.component.js @@ -6,6 +6,7 @@ const CLASSNAME_DEFAULT = 'btn-default' const CLASSNAME_PRIMARY = 'btn-primary' const CLASSNAME_SECONDARY = 'btn-secondary' const CLASSNAME_CONFIRM = 'btn-confirm' +const CLASSNAME_RAISED = 'btn-raised' const CLASSNAME_LARGE = 'btn--large' const typeHash = { @@ -13,6 +14,7 @@ const typeHash = { primary: CLASSNAME_PRIMARY, secondary: CLASSNAME_SECONDARY, confirm: CLASSNAME_CONFIRM, + raised: CLASSNAME_RAISED, } export default class Button extends Component { @@ -20,7 +22,7 @@ export default class Button extends Component { type: PropTypes.string, large: PropTypes.bool, className: PropTypes.string, - children: PropTypes.string, + children: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), } render () { @@ -29,6 +31,7 @@ export default class Button extends Component { return (
) } diff --git a/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-error/index.scss b/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-error/index.scss index e99b0f631..89ff25578 100644 --- a/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-error/index.scss +++ b/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-error/index.scss @@ -1,5 +1,5 @@ .confirm-page-container-error { - height: 32px; + min-height: 32px; border: 1px solid $monzo; color: $monzo; background: lighten($monzo, 56%); @@ -8,10 +8,14 @@ display: flex; justify-content: flex-start; align-items: center; - padding-left: 16px; + padding: 8px 16px; &__icon { margin-right: 8px; flex: 0 0 auto; } + + &__text { + overflow: auto; + } } diff --git a/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js b/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js index 3b1ee62c5..38b158fd3 100644 --- a/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js +++ b/ui/app/components/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js @@ -4,7 +4,7 @@ import classnames from 'classnames' import Identicon from '../../../identicon' const ConfirmPageContainerSummary = props => { - const { action, title, subtitle, hideSubtitle, className, identiconAddress, nonce } = props + const { action, title, subtitle, hideSubtitle, className, identiconAddress, nonce, assetImage } = props return (
@@ -27,6 +27,7 @@ const ConfirmPageContainerSummary = props => { className="confirm-page-container-summary__identicon" diameter={36} address={identiconAddress} + image={assetImage} /> ) } @@ -51,6 +52,7 @@ ConfirmPageContainerSummary.propTypes = { className: PropTypes.string, identiconAddress: PropTypes.string, nonce: PropTypes.string, + assetImage: PropTypes.string, } export default ConfirmPageContainerSummary diff --git a/ui/app/components/confirm-page-container/confirm-page-container.component.js b/ui/app/components/confirm-page-container/confirm-page-container.component.js index 24ff05353..b1582051e 100644 --- a/ui/app/components/confirm-page-container/confirm-page-container.component.js +++ b/ui/app/components/confirm-page-container/confirm-page-container.component.js @@ -38,6 +38,7 @@ export default class ConfirmPageContainer extends Component { detailsComponent: PropTypes.node, identiconAddress: PropTypes.string, nonce: PropTypes.string, + assetImage: PropTypes.string, summaryComponent: PropTypes.node, warning: PropTypes.string, // Footer @@ -70,8 +71,10 @@ export default class ConfirmPageContainer extends Component { onSubmit, identiconAddress, nonce, + assetImage, warning, } = this.props + const renderAssetImage = contentComponent || (!contentComponent && !identiconAddress) return (
@@ -84,6 +87,7 @@ export default class ConfirmPageContainer extends Component { senderAddress={fromAddress} recipientName={toName} recipientAddress={toAddress} + assetImage={renderAssetImage ? assetImage : undefined} /> { @@ -101,6 +105,7 @@ export default class ConfirmPageContainer extends Component { errorKey={errorKey} identiconAddress={identiconAddress} nonce={nonce} + assetImage={assetImage} warning={warning} /> ) diff --git a/ui/app/components/currency-display/currency-display.component.js b/ui/app/components/currency-display/currency-display.component.js new file mode 100644 index 000000000..e4eb58a2a --- /dev/null +++ b/ui/app/components/currency-display/currency-display.component.js @@ -0,0 +1,31 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import { ETH, GWEI } from '../../constants/common' + +export default class CurrencyDisplay extends PureComponent { + static propTypes = { + className: PropTypes.string, + displayValue: PropTypes.string, + prefix: PropTypes.string, + // Used in container + currency: PropTypes.oneOf([ETH]), + denomination: PropTypes.oneOf([GWEI]), + value: PropTypes.string, + numberOfDecimals: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), + hideLabel: PropTypes.bool, + } + + render () { + const { className, displayValue, prefix } = this.props + const text = `${prefix || ''}${displayValue}` + + return ( +
+ { text } +
+ ) + } +} diff --git a/ui/app/components/currency-display/currency-display.container.js b/ui/app/components/currency-display/currency-display.container.js new file mode 100644 index 000000000..6644a1099 --- /dev/null +++ b/ui/app/components/currency-display/currency-display.container.js @@ -0,0 +1,21 @@ +import { connect } from 'react-redux' +import CurrencyDisplay from './currency-display.component' +import { getValueFromWeiHex, formatCurrency } from '../../helpers/confirm-transaction/util' + +const mapStateToProps = (state, ownProps) => { + const { value, numberOfDecimals = 2, currency, denomination, hideLabel } = ownProps + const { metamask: { currentCurrency, conversionRate } } = state + + const toCurrency = currency || currentCurrency + const convertedValue = getValueFromWeiHex({ + value, toCurrency, conversionRate, numberOfDecimals, toDenomination: denomination, + }) + const formattedValue = formatCurrency(convertedValue, toCurrency) + const displayValue = hideLabel ? formattedValue : `${formattedValue} ${toCurrency.toUpperCase()}` + + return { + displayValue, + } +} + +export default connect(mapStateToProps)(CurrencyDisplay) diff --git a/ui/app/components/currency-display/index.js b/ui/app/components/currency-display/index.js new file mode 100644 index 000000000..38f08765f --- /dev/null +++ b/ui/app/components/currency-display/index.js @@ -0,0 +1 @@ +export { default } from './currency-display.container' diff --git a/ui/app/components/currency-display/tests/currency-display.component.test.js b/ui/app/components/currency-display/tests/currency-display.component.test.js new file mode 100644 index 000000000..d9ef052f1 --- /dev/null +++ b/ui/app/components/currency-display/tests/currency-display.component.test.js @@ -0,0 +1,27 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import CurrencyDisplay from '../currency-display.component' + +describe('CurrencyDisplay Component', () => { + it('should render text with a className', () => { + const wrapper = shallow() + + assert.ok(wrapper.hasClass('currency-display')) + assert.equal(wrapper.text(), '$123.45') + }) + + it('should render text with a prefix', () => { + const wrapper = shallow() + + assert.ok(wrapper.hasClass('currency-display')) + assert.equal(wrapper.text(), '-$123.45') + }) +}) diff --git a/ui/app/components/currency-display/tests/currency-display.container.test.js b/ui/app/components/currency-display/tests/currency-display.container.test.js new file mode 100644 index 000000000..5265bbb04 --- /dev/null +++ b/ui/app/components/currency-display/tests/currency-display.container.test.js @@ -0,0 +1,105 @@ +import assert from 'assert' +import proxyquire from 'proxyquire' + +let mapStateToProps + +proxyquire('../currency-display.container.js', { + 'react-redux': { + connect: ms => { + mapStateToProps = ms + return () => ({}) + }, + }, +}) + +describe('CurrencyDisplay container', () => { + describe('mapStateToProps()', () => { + it('should return the correct props', () => { + const mockState = { + metamask: { + conversionRate: 280.45, + currentCurrency: 'usd', + }, + } + + const tests = [ + { + props: { + value: '0x2386f26fc10000', + numberOfDecimals: 2, + currency: 'usd', + }, + result: { + displayValue: '$2.80 USD', + }, + }, + { + props: { + value: '0x2386f26fc10000', + }, + result: { + displayValue: '$2.80 USD', + }, + }, + { + props: { + value: '0x1193461d01595930', + currency: 'ETH', + numberOfDecimals: 3, + }, + result: { + displayValue: '1.266 ETH', + }, + }, + { + props: { + value: '0x1193461d01595930', + currency: 'ETH', + numberOfDecimals: 3, + hideLabel: true, + }, + result: { + displayValue: '1.266', + }, + }, + { + props: { + value: '0x3b9aca00', + currency: 'ETH', + denomination: 'GWEI', + hideLabel: true, + }, + result: { + displayValue: '1', + }, + }, + { + props: { + value: '0x3b9aca00', + currency: 'ETH', + denomination: 'WEI', + hideLabel: true, + }, + result: { + displayValue: '1000000000', + }, + }, + { + props: { + value: '0x3b9aca00', + currency: 'ETH', + numberOfDecimals: 100, + hideLabel: true, + }, + result: { + displayValue: '1e-9', + }, + }, + ] + + tests.forEach(({ props, result }) => { + assert.deepEqual(mapStateToProps(mockState, props), result) + }) + }) + }) +}) diff --git a/ui/app/components/custom-radio-list.js b/ui/app/components/custom-radio-list.js deleted file mode 100644 index a4c525396..000000000 --- a/ui/app/components/custom-radio-list.js +++ /dev/null @@ -1,60 +0,0 @@ -const Component = require('react').Component -const h = require('react-hyperscript') -const inherits = require('util').inherits - -module.exports = RadioList - -inherits(RadioList, Component) -function RadioList () { - Component.call(this) -} - -RadioList.prototype.render = function () { - const props = this.props - const activeClass = '.custom-radio-selected' - const inactiveClass = '.custom-radio-inactive' - const { - labels, - defaultFocus, - } = props - - - return ( - h('.flex-row', { - style: { - fontSize: '12px', - }, - }, [ - h('.flex-column.custom-radios', { - style: { - marginRight: '5px', - }, - }, - labels.map((lable, i) => { - let isSelcted = (this.state !== null) - isSelcted = isSelcted ? (this.state.selected === lable) : (defaultFocus === lable) - return h(isSelcted ? activeClass : inactiveClass, { - title: lable, - onClick: (event) => { - this.setState({selected: event.target.title}) - props.onClick(event) - }, - }) - }) - ), - h('.text', {}, - labels.map((lable) => { - if (props.subtext) { - return h('.flex-row', {}, [ - h('.radio-titles', lable), - h('.radio-titles-subtext', `- ${props.subtext[lable]}`), - ]) - } else { - return h('.radio-titles', lable) - } - }) - ), - ]) - ) -} - diff --git a/ui/app/components/customize-gas-modal/index.js b/ui/app/components/customize-gas-modal/index.js index c255fd64d..e67fbe45b 100644 --- a/ui/app/components/customize-gas-modal/index.js +++ b/ui/app/components/customize-gas-modal/index.js @@ -5,6 +5,7 @@ const inherits = require('util').inherits const connect = require('react-redux').connect const actions = require('../../actions') const GasModalCard = require('./gas-modal-card') +import Button from '../button' const ethUtil = require('ethereumjs-util') @@ -353,16 +354,16 @@ CustomizeGasModal.prototype.render = function () { }, [this.context.t('revert')]), h('div.send-v2__customize-gas__buttons', [ - h('button.btn-default.send-v2__customize-gas__cancel', { + h(Button, { + type: 'default', + className: 'send-v2__customize-gas__cancel', onClick: this.props.hideModal, - style: { - marginRight: '10px', - }, }, [this.context.t('cancel')]), - - h('button.btn-primary.send-v2__customize-gas__save', { + h(Button, { + type: 'primary', + className: 'send-v2__customize-gas__save', onClick: () => !error && this.save(newGasPrice, gasLimit, gasTotal), - className: error && 'btn-primary--disabled', + disabled: error, }, [this.context.t('save')]), ]), diff --git a/ui/app/components/dropdowns/components/account-dropdowns.js b/ui/app/components/dropdowns/components/account-dropdowns.js index e9c7ce936..3e53a1f79 100644 --- a/ui/app/components/dropdowns/components/account-dropdowns.js +++ b/ui/app/components/dropdowns/components/account-dropdowns.js @@ -459,7 +459,7 @@ const mapDispatchToProps = (dispatch) => { function mapStateToProps (state) { return { keyrings: state.metamask.keyrings, - sidebarOpen: state.appState.sidebarOpen, + sidebarOpen: state.appState.sidebar.isOpen, } } diff --git a/ui/app/components/dropdowns/network-dropdown.js b/ui/app/components/dropdowns/network-dropdown.js index 8020061d8..ea4606615 100644 --- a/ui/app/components/dropdowns/network-dropdown.js +++ b/ui/app/components/dropdowns/network-dropdown.js @@ -296,10 +296,12 @@ NetworkDropdown.prototype.getNetworkName = function () { NetworkDropdown.prototype.renderCommonRpc = function (rpcList, provider) { const props = this.props - const rpcTarget = provider.rpcTarget + const reversedRpcList = rpcList.slice().reverse() - return rpcList.map((rpc) => { - if ((rpc === 'http://localhost:8545') || (rpc === rpcTarget)) { + return reversedRpcList.map((rpc) => { + const currentRpcTarget = provider.type === 'rpc' && rpc === provider.rpcTarget + + if ((rpc === 'http://localhost:8545') || currentRpcTarget) { return null } else { return h( @@ -315,11 +317,11 @@ NetworkDropdown.prototype.renderCommonRpc = function (rpcList, provider) { }, }, [ - rpcTarget === rpc ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'), + currentRpcTarget ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'), h('i.fa.fa-question-circle.fa-med.menu-icon-circle'), h('span.network-name-item', { style: { - color: rpcTarget === rpc ? '#ffffff' : '#9b9b9b', + color: currentRpcTarget ? '#ffffff' : '#9b9b9b', }, }, rpc), ] diff --git a/ui/app/components/hex-as-decimal-input.js b/ui/app/components/hex-as-decimal-input.js deleted file mode 100644 index 75303a34a..000000000 --- a/ui/app/components/hex-as-decimal-input.js +++ /dev/null @@ -1,161 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const h = require('react-hyperscript') -const inherits = require('util').inherits -const ethUtil = require('ethereumjs-util') -const BN = ethUtil.BN -const extend = require('xtend') -const connect = require('react-redux').connect - -HexAsDecimalInput.contextTypes = { - t: PropTypes.func, -} - -module.exports = connect()(HexAsDecimalInput) - - -inherits(HexAsDecimalInput, Component) -function HexAsDecimalInput () { - this.state = { invalid: null } - Component.call(this) -} - -/* Hex as Decimal Input - * - * A component for allowing easy, decimal editing - * of a passed in hex string value. - * - * On change, calls back its `onChange` function parameter - * and passes it an updated hex string. - */ - -HexAsDecimalInput.prototype.render = function () { - const props = this.props - const state = this.state - - const { value, onChange, min, max } = props - - const toEth = props.toEth - const suffix = props.suffix - const decimalValue = decimalize(value, toEth) - const style = props.style - - return ( - h('.flex-column', [ - h('.flex-row', { - style: { - alignItems: 'flex-end', - lineHeight: '13px', - fontFamily: 'Montserrat Light', - textRendering: 'geometricPrecision', - }, - }, [ - h('input.hex-input', { - type: 'number', - required: true, - min: min, - max: max, - style: extend({ - display: 'block', - textAlign: 'right', - backgroundColor: 'transparent', - border: '1px solid #bdbdbd', - - }, style), - value: parseInt(decimalValue), - onBlur: (event) => { - this.updateValidity(event) - }, - onChange: (event) => { - this.updateValidity(event) - const hexString = (event.target.value === '') ? '' : hexify(event.target.value) - onChange(hexString) - }, - onInvalid: (event) => { - const msg = this.constructWarning() - if (msg === state.invalid) { - return - } - this.setState({ invalid: msg }) - event.preventDefault() - return false - }, - }), - h('div', { - style: { - color: ' #AEAEAE', - fontSize: '12px', - marginLeft: '5px', - marginRight: '6px', - width: '20px', - }, - }, suffix), - ]), - - state.invalid ? h('span.error', { - style: { - position: 'absolute', - right: '0px', - textAlign: 'right', - transform: 'translateY(26px)', - padding: '3px', - background: 'rgba(255,255,255,0.85)', - zIndex: '1', - textTransform: 'capitalize', - border: '2px solid #E20202', - }, - }, state.invalid) : null, - ]) - ) -} - -HexAsDecimalInput.prototype.setValid = function (message) { - this.setState({ invalid: null }) -} - -HexAsDecimalInput.prototype.updateValidity = function (event) { - const target = event.target - const value = this.props.value - const newValue = target.value - - if (value === newValue) { - return - } - - const valid = target.checkValidity() - if (valid) { - this.setState({ invalid: null }) - } -} - -HexAsDecimalInput.prototype.constructWarning = function () { - const { name, min, max } = this.props - let message = name ? name + ' ' : '' - - if (min && max) { - message += this.context.t('betweenMinAndMax', [min, max]) - } else if (min) { - message += this.context.t('greaterThanMin', [min]) - } else if (max) { - message += this.context.t('lessThanMax', [max]) - } else { - message += this.context.t('invalidInput') - } - - return message -} - -function hexify (decimalString) { - const hexBN = new BN(parseInt(decimalString), 10) - return '0x' + hexBN.toString('hex') -} - -function decimalize (input, toEth) { - if (input === '') { - return '' - } else { - const strippedInput = ethUtil.stripHexPrefix(input) - const inputBN = new BN(strippedInput, 'hex') - return inputBN.toString(10) - } -} diff --git a/ui/app/components/hex-to-decimal/hex-to-decimal.component.js b/ui/app/components/hex-to-decimal/hex-to-decimal.component.js new file mode 100644 index 000000000..6847a6919 --- /dev/null +++ b/ui/app/components/hex-to-decimal/hex-to-decimal.component.js @@ -0,0 +1,21 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import { hexToDecimal } from '../../helpers/conversions.util' + +export default class HexToDecimal extends PureComponent { + static propTypes = { + className: PropTypes.string, + value: PropTypes.string, + } + + render () { + const { className, value } = this.props + const decimalValue = hexToDecimal(value) + + return ( +
+ { decimalValue } +
+ ) + } +} diff --git a/ui/app/components/hex-to-decimal/index.js b/ui/app/components/hex-to-decimal/index.js new file mode 100644 index 000000000..6e8567ca9 --- /dev/null +++ b/ui/app/components/hex-to-decimal/index.js @@ -0,0 +1 @@ +export { default } from './hex-to-decimal.component' diff --git a/ui/app/components/hex-to-decimal/tests/hex-to-decimal.component.test.js b/ui/app/components/hex-to-decimal/tests/hex-to-decimal.component.test.js new file mode 100644 index 000000000..c98da9ad4 --- /dev/null +++ b/ui/app/components/hex-to-decimal/tests/hex-to-decimal.component.test.js @@ -0,0 +1,26 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import HexToDecimal from '../hex-to-decimal.component' + +describe('HexToDecimal Component', () => { + it('should render a prefixed hex as a decimal with a className', () => { + const wrapper = shallow() + + assert.ok(wrapper.hasClass('hex-to-decimal')) + assert.equal(wrapper.text(), '12345') + }) + + it('should render an unprefixed hex as a decimal with a className', () => { + const wrapper = shallow() + + assert.ok(wrapper.hasClass('hex-to-decimal')) + assert.equal(wrapper.text(), '6789') + }) +}) diff --git a/ui/app/components/identicon.js b/ui/app/components/identicon.js index 8774d66a8..e76068aa4 100644 --- a/ui/app/components/identicon.js +++ b/ui/app/components/identicon.js @@ -26,36 +26,43 @@ function mapStateToProps (state) { IdenticonComponent.prototype.render = function () { var props = this.props - const { className = '', address } = props + const { className = '', address, image } = props var diameter = props.diameter || this.defaultDiameter - - return address - ? ( - h('div', { - className: `${className} identicon`, - key: 'identicon-' + address, - style: { - display: 'flex', - flexShrink: 0, - alignItems: 'center', - justifyContent: 'center', - height: diameter, - width: diameter, - borderRadius: diameter / 2, - overflow: 'hidden', - }, - }) - ) - : ( - h('img.balance-icon', { - src: './images/eth_logo.svg', - style: { - height: diameter, - width: diameter, - borderRadius: diameter / 2, - }, - }) - ) + const style = { + height: diameter, + width: diameter, + borderRadius: diameter / 2, + } + if (image) { + return h('img', { + className: `${className} identicon`, + src: image, + style: { + ...style, + }, + }) + } else if (address) { + return h('div', { + className: `${className} identicon`, + key: 'identicon-' + address, + style: { + display: 'flex', + flexShrink: 0, + alignItems: 'center', + justifyContent: 'center', + ...style, + overflow: 'hidden', + }, + }) + } else { + return h('img.balance-icon', { + className, + src: './images/eth_logo.svg', + style: { + ...style, + }, + }) + } } IdenticonComponent.prototype.componentDidMount = function () { diff --git a/ui/app/components/index.scss b/ui/app/components/index.scss index b3e14ce23..983d6b98a 100644 --- a/ui/app/components/index.scss +++ b/ui/app/components/index.scss @@ -1,21 +1,47 @@ +@import './app-header/index'; + @import './button-group/index'; +@import './card/index'; + +@import './confirm-page-container/index'; + @import './export-text-container/index'; -@import './selected-account/index'; - @import './info-box/index'; -@import './network-display/index'; +@import './menu-bar/index'; -@import './confirm-page-container/index'; +@import './modals/index'; + +@import './network-display/index'; @import './page-container/index'; @import './pages/index'; -@import './modals/index'; +@import './selected-account/index'; @import './sender-to-recipient/index'; @import './tabs/index'; + +@import './transaction-activity-log/index'; + +@import './transaction-breakdown/index'; + +@import './transaction-view/index'; + +@import './transaction-view-balance/index'; + +@import './transaction-list/index'; + +@import './transaction-list-item/index'; + +@import './transaction-list-item-details/index'; + +@import './transaction-status/index'; + +@import './app-header/index'; + +@import './sidebars/index'; diff --git a/ui/app/components/input-number.js b/ui/app/components/input-number.js index 59c6842ef..eec5e3740 100644 --- a/ui/app/components/input-number.js +++ b/ui/app/components/input-number.js @@ -66,13 +66,16 @@ InputNumber.prototype.render = function () { }), h('span.gas-tooltip-input-detail', {}, [unitLabel]), h('div.gas-tooltip-input-arrows', {}, [ - h('i.fa.fa-angle-up', { + h('div.gas-tooltip-input-arrow-wrapper', { onClick: () => this.setValue(addCurrencies(value, step, { toNumericBase: 'dec' })), - }), - h('i.fa.fa-angle-down', { - style: { cursor: 'pointer' }, + }, [ + h('i.fa.fa-angle-up'), + ]), + h('div.gas-tooltip-input-arrow-wrapper', { onClick: () => this.setValue(subtractCurrencies(value, step, { toNumericBase: 'dec' })), - }), + }, [ + h('i.fa.fa-angle-down'), + ]), ]), ]) } diff --git a/ui/app/components/menu-bar/index.js b/ui/app/components/menu-bar/index.js new file mode 100644 index 000000000..c5760847f --- /dev/null +++ b/ui/app/components/menu-bar/index.js @@ -0,0 +1 @@ +export { default } from './menu-bar.container' diff --git a/ui/app/components/menu-bar/index.scss b/ui/app/components/menu-bar/index.scss new file mode 100644 index 000000000..f699f4090 --- /dev/null +++ b/ui/app/components/menu-bar/index.scss @@ -0,0 +1,23 @@ +.menu-bar { + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + flex: 0 0 auto; + margin-bottom: 16px; + padding: 5px; + border-bottom: 1px solid #e5e5e5; + + &__sidebar-button { + font-size: 1.25rem; + cursor: pointer; + padding: 10px; + } + + &__open-in-browser { + cursor: pointer; + display: flex; + justify-content: center; + padding: 10px; + } +} diff --git a/ui/app/components/menu-bar/menu-bar.component.js b/ui/app/components/menu-bar/menu-bar.component.js new file mode 100644 index 000000000..eee9feebb --- /dev/null +++ b/ui/app/components/menu-bar/menu-bar.component.js @@ -0,0 +1,52 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import Tooltip from '../tooltip' +import SelectedAccount from '../selected-account' + +export default class MenuBar extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + hideSidebar: PropTypes.func, + isMascara: PropTypes.bool, + sidebarOpen: PropTypes.bool, + showSidebar: PropTypes.func, + } + + render () { + const { t } = this.context + const { isMascara, sidebarOpen, hideSidebar, showSidebar } = this.props + + return ( +
+ +
sidebarOpen ? hideSidebar() : showSidebar()} + /> + + + { + !isMascara && ( + +
global.platform.openExtensionInBrowser()} + > + +
+
+ ) + } +
+ ) + } +} diff --git a/ui/app/components/menu-bar/menu-bar.container.js b/ui/app/components/menu-bar/menu-bar.container.js new file mode 100644 index 000000000..ae32882ae --- /dev/null +++ b/ui/app/components/menu-bar/menu-bar.container.js @@ -0,0 +1,26 @@ +import { connect } from 'react-redux' +import MenuBar from './menu-bar.component' +import { showSidebar, hideSidebar } from '../../actions' + +const mapStateToProps = state => { + const { appState: { sidebar: { isOpen }, isMascara } } = state + + return { + sidebarOpen: isOpen, + isMascara, + } +} + +const mapDispatchToProps = dispatch => { + return { + showSidebar: () => { + dispatch(showSidebar({ + transitionName: 'sidebar-right', + type: 'wallet-view', + })) + }, + hideSidebar: () => dispatch(hideSidebar()), + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(MenuBar) diff --git a/ui/app/components/modals/account-details-modal.js b/ui/app/components/modals/account-details-modal.js index 15a187723..2a28b56d7 100644 --- a/ui/app/components/modals/account-details-modal.js +++ b/ui/app/components/modals/account-details-modal.js @@ -10,6 +10,8 @@ const ethNetProps = require('eth-net-props') const QrView = require('../qr-code') const EditableLabel = require('../editable-label') +import Button from '../button' + function mapStateToProps (state) { return { network: state.metamask.network, @@ -61,7 +63,7 @@ AccountDetailsModal.prototype.render = function () { let exportPrivateKeyFeatureEnabled = true // This feature is disabled for hardware wallets - if (keyring.type.search('Hardware') !== -1) { + if (keyring && keyring.type.search('Hardware') !== -1) { exportPrivateKeyFeatureEnabled = false } @@ -80,12 +82,17 @@ AccountDetailsModal.prototype.render = function () { h('div.account-modal-divider'), - h('button.btn-primary.account-modal__button', { + h(Button, { + type: 'primary', + className: 'account-modal__button', onClick: () => global.platform.openWindow({ url: ethNetProps.explorerLinks.getExplorerAccountLinkFor(address, network) }), }, this.context.t('etherscanView')), // Holding on redesign for Export Private Key functionality - exportPrivateKeyFeatureEnabled ? h('button.btn-primary.account-modal__button', { + + exportPrivateKeyFeatureEnabled ? h(Button, { + type: 'primary', + className: 'account-modal__button', onClick: () => showExportPrivateKeyModal(), }, this.context.t('exportPrivateKey')) : null, diff --git a/ui/app/components/modals/account-modal-container.js b/ui/app/components/modals/account-modal-container.js index a9856b20f..aa0593df8 100644 --- a/ui/app/components/modals/account-modal-container.js +++ b/ui/app/components/modals/account-modal-container.js @@ -7,9 +7,9 @@ const actions = require('../../actions') const { getSelectedIdentity } = require('../../selectors') const Identicon = require('../identicon') -function mapStateToProps (state) { +function mapStateToProps (state, ownProps) { return { - selectedIdentity: getSelectedIdentity(state), + selectedIdentity: ownProps.selectedIdentity || getSelectedIdentity(state), } } diff --git a/ui/app/components/modals/customize-gas/customize-gas.component.js b/ui/app/components/modals/customize-gas/customize-gas.component.js index 0337c5413..3f526bd43 100644 --- a/ui/app/components/modals/customize-gas/customize-gas.component.js +++ b/ui/app/components/modals/customize-gas/customize-gas.component.js @@ -2,6 +2,7 @@ import React, { Component } from 'react' import PropTypes from 'prop-types' import GasModalCard from '../../customize-gas-modal/gas-modal-card' import { MIN_GAS_PRICE_GWEI } from '../../send/send.constants' +import Button from '../../button' import { getDecimalGasLimit, @@ -116,21 +117,23 @@ export default class CustomizeGas extends Component { { t('revert') }
- - +
diff --git a/ui/app/components/modals/deposit-ether-modal.js b/ui/app/components/modals/deposit-ether-modal.js index 2daa7fa1d..09137d39a 100644 --- a/ui/app/components/modals/deposit-ether-modal.js +++ b/ui/app/components/modals/deposit-ether-modal.js @@ -7,6 +7,8 @@ const actions = require('../../actions') const { getNetworkDisplayName } = require('../../../../app/scripts/controllers/network/util') const ShapeshiftForm = require('../shapeshift-form') +import Button from '../button' + let DIRECT_DEPOSIT_ROW_TITLE let DIRECT_DEPOSIT_ROW_TEXT let COINBASE_ROW_TITLE @@ -109,7 +111,10 @@ DepositEtherModal.prototype.renderRow = function ({ ]), !hideButton && h('div.deposit-ether-modal__buy-row__button', [ - h('button.btn-primary.btn--large.deposit-ether-modal__deposit-button', { + h(Button, { + type: 'primary', + className: 'deposit-ether-modal__deposit-button', + large: true, onClick: onButtonClick, }, [buttonLabel]), ]), diff --git a/ui/app/components/modals/export-private-key-modal.js b/ui/app/components/modals/export-private-key-modal.js index 80ece425f..d3e3c9a56 100644 --- a/ui/app/components/modals/export-private-key-modal.js +++ b/ui/app/components/modals/export-private-key-modal.js @@ -1,3 +1,4 @@ +const log = require('loglevel') const Component = require('react').Component const PropTypes = require('prop-types') const h = require('react-hyperscript') @@ -10,20 +11,35 @@ const { getSelectedIdentity } = require('../../selectors') const ReadOnlyInput = require('../readonly-input') const copyToClipboard = require('copy-to-clipboard') const { checksumAddress } = require('../../util') +import Button from '../button' -function mapStateToProps (state) { - return { - warning: state.appState.warning, - privateKey: state.appState.accountDetail.privateKey, - network: state.metamask.network, - selectedIdentity: getSelectedIdentity(state), - previousModalState: state.appState.modal.previousModalState.name, +function mapStateToPropsFactory () { + let selectedIdentity = null + return function mapStateToProps (state) { + // We should **not** change the identity displayed here even if it changes from underneath us. + // If we do, we will be showing the user one private key and a **different** address and name. + // Note that the selected identity **will** change from underneath us when we unlock the keyring + // which is the expected behavior that we are side-stepping. + selectedIdentity = selectedIdentity || getSelectedIdentity(state) + return { + warning: state.appState.warning, + privateKey: state.appState.accountDetail.privateKey, + network: state.metamask.network, + selectedIdentity, + previousModalState: state.appState.modal.previousModalState.name, + } } } function mapDispatchToProps (dispatch) { return { - exportAccount: (password, address) => dispatch(actions.exportAccount(password, address)), + exportAccount: (password, address) => { + return dispatch(actions.exportAccount(password, address)) + .then((res) => { + dispatch(actions.hideWarning()) + return res + }) + }, showAccountDetailModal: () => dispatch(actions.showModal({ name: 'ACCOUNT_DETAILS' })), hideModal: () => dispatch(actions.hideModal()), } @@ -36,6 +52,7 @@ function ExportPrivateKeyModal () { this.state = { password: '', privateKey: null, + showWarning: true, } } @@ -43,14 +60,18 @@ ExportPrivateKeyModal.contextTypes = { t: PropTypes.func, } -module.exports = connect(mapStateToProps, mapDispatchToProps)(ExportPrivateKeyModal) +module.exports = connect(mapStateToPropsFactory, mapDispatchToProps)(ExportPrivateKeyModal) ExportPrivateKeyModal.prototype.exportAccountAndGetPrivateKey = function (password, address) { const { exportAccount } = this.props exportAccount(password, address) - .then(privateKey => this.setState({ privateKey })) + .then(privateKey => this.setState({ + privateKey, + showWarning: false, + })) + .catch((e) => log.error(e)) } ExportPrivateKeyModal.prototype.renderPasswordLabel = function (privateKey) { @@ -77,24 +98,31 @@ ExportPrivateKeyModal.prototype.renderPasswordInput = function (privateKey) { }) } -ExportPrivateKeyModal.prototype.renderButton = function (className, onClick, label) { - return h('button', { - className, - onClick, - }, label) -} - ExportPrivateKeyModal.prototype.renderButtons = function (privateKey, password, address, hideModal) { return h('div.export-private-key-buttons', {}, [ - !privateKey && this.renderButton( - 'btn-default btn--large export-private-key__button export-private-key__button--cancel', - () => hideModal(), - 'Cancel' - ), + !privateKey && h(Button, { + type: 'default', + large: true, + className: 'export-private-key__button export-private-key__button--cancel', + onClick: () => hideModal(), + }, this.context.t('cancel')), (privateKey - ? this.renderButton('btn-primary btn--large export-private-key__button', () => hideModal(), this.context.t('done')) - : this.renderButton('btn-primary btn--large export-private-key__button', () => this.exportAccountAndGetPrivateKey(this.state.password, address), this.context.t('confirm')) + ? ( + h(Button, { + type: 'primary', + large: true, + className: 'export-private-key__button', + onClick: () => hideModal(), + }, this.context.t('done')) + ) : ( + h(Button, { + type: 'primary', + large: true, + className: 'export-private-key__button', + onClick: () => this.exportAccountAndGetPrivateKey(this.state.password, address), + }, this.context.t('confirm')) + ) ), ]) @@ -110,9 +138,13 @@ ExportPrivateKeyModal.prototype.render = function () { } = this.props const { name, address } = selectedIdentity - const { privateKey } = this.state + const { + privateKey, + showWarning, + } = this.state return h(AccountModalContainer, { + selectedIdentity, showBackButton: previousModalState === 'ACCOUNT_DETAILS', backButtonAction: () => showAccountDetailModal(), }, [ @@ -134,7 +166,7 @@ ExportPrivateKeyModal.prototype.render = function () { this.renderPasswordInput(privateKey), - !warning ? null : h('span.private-key-password-error', warning), + showWarning && warning ? h('span.private-key-password-error', warning) : null, ]), h('div.private-key-password-warning', this.context.t('privateKeyWarning')), diff --git a/ui/app/components/modals/hide-token-confirmation-modal.js b/ui/app/components/modals/hide-token-confirmation-modal.js index 1518fa9a0..fb38516d3 100644 --- a/ui/app/components/modals/hide-token-confirmation-modal.js +++ b/ui/app/components/modals/hide-token-confirmation-modal.js @@ -10,6 +10,7 @@ function mapStateToProps (state) { return { network: state.metamask.network, token: state.appState.modal.modalState.props.token, + assetImages: state.metamask.assetImages, } } @@ -40,8 +41,9 @@ module.exports = connect(mapStateToProps, mapDispatchToProps)(HideTokenConfirmat HideTokenConfirmationModal.prototype.render = function () { - const { token, network, hideToken, hideModal } = this.props + const { token, network, hideToken, hideModal, assetImages } = this.props const { symbol, address } = token + const image = assetImages[address] return h('div.hide-token-confirmation', {}, [ h('div.hide-token-confirmation__container', { @@ -55,6 +57,7 @@ HideTokenConfirmationModal.prototype.render = function () { diameter: 45, address, network, + image, }), h('div.hide-token-confirmation__symbol', {}, symbol), diff --git a/ui/app/components/page-container/index.scss b/ui/app/components/page-container/index.scss index 06c3ef709..61434cbcf 100644 --- a/ui/app/components/page-container/index.scss +++ b/ui/app/components/page-container/index.scss @@ -109,7 +109,7 @@ &--selected { color: $curious-blue; - border-bottom: 3px solid $curious-blue; + border-bottom: 2px solid $curious-blue; } } @@ -182,5 +182,7 @@ max-height: 82vh; min-height: 570px; flex: 0 0 auto; + margin-right: auto; + margin-left: auto; } } diff --git a/ui/app/components/page-container/page-container-header/page-container-header.component.js b/ui/app/components/page-container/page-container-header/page-container-header.component.js index 5a5de1e5a..a8458604e 100644 --- a/ui/app/components/page-container/page-container-header/page-container-header.component.js +++ b/ui/app/components/page-container/page-container-header/page-container-header.component.js @@ -1,8 +1,8 @@ import React, { Component } from 'react' import PropTypes from 'prop-types' +import classnames from 'classnames' export default class PageContainerHeader extends Component { - static propTypes = { title: PropTypes.string, subtitle: PropTypes.string, @@ -11,8 +11,18 @@ export default class PageContainerHeader extends Component { onBackButtonClick: PropTypes.func, backButtonStyles: PropTypes.object, backButtonString: PropTypes.string, - children: PropTypes.node, - }; + tabs: PropTypes.node, + } + + renderTabs () { + const { tabs } = this.props + + return tabs && ( +
    + { tabs } +
+ ) + } renderHeaderRow () { const { showBackButton, onBackButtonClick, backButtonStyles, backButtonString } = this.props @@ -31,15 +41,18 @@ export default class PageContainerHeader extends Component { } render () { - const { title, subtitle, onClose, children } = this.props + const { title, subtitle, onClose, tabs } = this.props return ( -
+
{ this.renderHeaderRow() } - { children } - { title &&
{ title } @@ -59,6 +72,7 @@ export default class PageContainerHeader extends Component { /> } + { this.renderTabs() }
) } diff --git a/ui/app/components/page-container/page-container.component.js b/ui/app/components/page-container/page-container.component.js index 9bfb99ade..3a2274a29 100644 --- a/ui/app/components/page-container/page-container.component.js +++ b/ui/app/components/page-container/page-container.component.js @@ -1,30 +1,82 @@ -import React, { Component } from 'react' +import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import PageContainerHeader from './page-container-header' import PageContainerFooter from './page-container-footer' -export default class PageContainer extends Component { - +export default class PageContainer extends PureComponent { static propTypes = { // PageContainerHeader props - title: PropTypes.string.isRequired, - subtitle: PropTypes.string, + backButtonString: PropTypes.string, + backButtonStyles: PropTypes.object, + onBackButtonClick: PropTypes.func, onClose: PropTypes.func, showBackButton: PropTypes.bool, - onBackButtonClick: PropTypes.func, - backButtonStyles: PropTypes.object, - backButtonString: PropTypes.string, + subtitle: PropTypes.string, + title: PropTypes.string.isRequired, + // Tabs-related props + defaultActiveTabIndex: PropTypes.number, + tabsComponent: PropTypes.node, // Content props - ContentComponent: PropTypes.func, - contentComponentProps: PropTypes.object, + contentComponent: PropTypes.node, // PageContainerFooter props - onCancel: PropTypes.func, cancelText: PropTypes.string, + disabled: PropTypes.bool, + onCancel: PropTypes.func, onSubmit: PropTypes.func, submitText: PropTypes.string, - disabled: PropTypes.bool, - }; + } + + state = { + activeTabIndex: this.props.defaultActiveTabIndex || 0, + } + + handleTabClick (activeTabIndex) { + this.setState({ activeTabIndex }) + } + + renderTabs () { + const { tabsComponent } = this.props + + if (!tabsComponent) { + return + } + + const numberOfTabs = React.Children.count(tabsComponent.props.children) + + return React.Children.map(tabsComponent.props.children, (child, tabIndex) => { + return child && React.cloneElement(child, { + onClick: index => this.handleTabClick(index), + tabIndex, + isActive: numberOfTabs > 1 && tabIndex === this.state.activeTabIndex, + key: tabIndex, + className: 'page-container__tab', + activeClassName: 'page-container__tab--selected', + }) + }) + } + + renderActiveTabContent () { + const { tabsComponent } = this.props + const { children } = tabsComponent.props + const { activeTabIndex } = this.state + + return children[activeTabIndex] + ? children[activeTabIndex].props.children + : children.props.children + } + + renderContent () { + const { contentComponent, tabsComponent } = this.props + + if (contentComponent) { + return contentComponent + } else if (tabsComponent) { + return this.renderActiveTabContent() + } else { + return null + } + } render () { const { @@ -35,8 +87,6 @@ export default class PageContainer extends Component { onBackButtonClick, backButtonStyles, backButtonString, - ContentComponent, - contentComponentProps, onCancel, cancelText, onSubmit, @@ -54,9 +104,10 @@ export default class PageContainer extends Component { onBackButtonClick={onBackButtonClick} backButtonStyles={backButtonStyles} backButtonString={backButtonString} + tabs={this.renderTabs()} />
- + { this.renderContent() }
) } - } diff --git a/ui/app/components/pages/add-token/add-token.component.js b/ui/app/components/pages/add-token/add-token.component.js index bcb93d401..3612e676c 100644 --- a/ui/app/components/pages/add-token/add-token.component.js +++ b/ui/app/components/pages/add-token/add-token.component.js @@ -1,14 +1,14 @@ import React, { Component } from 'react' -import classnames from 'classnames' import PropTypes from 'prop-types' import ethUtil from 'ethereumjs-util' import { checkExistingAddresses } from './util' import { tokenInfoGetter } from '../../../token-util' import { DEFAULT_ROUTE, CONFIRM_ADD_TOKEN_ROUTE } from '../../../routes' -import Button from '../../button' import TextField from '../../text-field' import TokenList from './token-list' import TokenSearch from './token-search' +import PageContainer from '../../page-container' +import { Tabs, Tab } from '../../tabs' const emptyAddr = '0x0000000000000000000000000000000000000000' const SEARCH_TAB = 'SEARCH' @@ -206,7 +206,7 @@ class AddToken extends Component { const validDecimals = customDecimals !== null && customDecimals !== '' && customDecimals >= 0 && - customDecimals < 36 + customDecimals <= 36 let customDecimalsError = null if (!validDecimals) { @@ -285,65 +285,33 @@ class AddToken extends Component { ) } + renderTabs () { + return ( + + + { this.renderSearchToken() } + + + { this.renderCustomTokenForm() } + + + ) + } + render () { - const { displayedTab } = this.state const { history, clearPendingTokens } = this.props return ( -
-
-
- { this.context.t('addTokens') } -
-
-
this.setState({ displayedTab: SEARCH_TAB })} - > - { this.context.t('search') } -
-
this.setState({ displayedTab: CUSTOM_TOKEN_TAB })} - > - { this.context.t('customToken') } -
-
-
-
- { - displayedTab === CUSTOM_TOKEN_TAB - ? this.renderCustomTokenForm() - : this.renderSearchToken() - } -
-
- - -
-
+ this.handleNext()} + disabled={this.hasError() || !this.hasSelected()} + onCancel={() => { + clearPendingTokens() + history.push(DEFAULT_ROUTE) + }} + /> ) } } diff --git a/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js b/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js new file mode 100644 index 000000000..c24e1e0ea --- /dev/null +++ b/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js @@ -0,0 +1,126 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import { DEFAULT_ROUTE } from '../../../routes' +import Button from '../../button' +import Identicon from '../../../components/identicon' +import TokenBalance from '../../token-balance' + +export default class ConfirmAddSuggestedToken extends Component { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + history: PropTypes.object, + clearPendingTokens: PropTypes.func, + addToken: PropTypes.func, + pendingTokens: PropTypes.object, + removeSuggestedTokens: PropTypes.func, + } + + componentDidMount () { + const { pendingTokens = {}, history } = this.props + + if (Object.keys(pendingTokens).length === 0) { + history.push(DEFAULT_ROUTE) + } + } + + getTokenName (name, symbol) { + return typeof name === 'undefined' + ? symbol + : `${name} (${symbol})` + } + + render () { + const { addToken, pendingTokens, removeSuggestedTokens, history } = this.props + const pendingTokenKey = Object.keys(pendingTokens)[0] + const pendingToken = pendingTokens[pendingTokenKey] + + return ( +
+
+
+ { this.context.t('addSuggestedTokens') } +
+
+ { this.context.t('likeToAddTokens') } +
+
+
+
+
+
+ { this.context.t('token') } +
+
+ { this.context.t('balance') } +
+
+
+ { + Object.entries(pendingTokens) + .map(([ address, token ]) => { + const { name, symbol, image } = token + + return ( +
+
+ +
+ { this.getTokenName(name, symbol) } +
+
+
+ +
+
+ ) + }) + } +
+
+
+
+ + +
+
+ ) + } +} diff --git a/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.container.js b/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.container.js new file mode 100644 index 000000000..1f2737e52 --- /dev/null +++ b/ui/app/components/pages/confirm-add-suggested-token/confirm-add-suggested-token.container.js @@ -0,0 +1,29 @@ +import { connect } from 'react-redux' +import { compose } from 'recompose' +import ConfirmAddSuggestedToken from './confirm-add-suggested-token.component' +import { withRouter } from 'react-router-dom' + +const extend = require('xtend') + +const { addToken, removeSuggestedTokens } = require('../../../actions') + +const mapStateToProps = ({ metamask }) => { + const { pendingTokens, suggestedTokens } = metamask + const params = extend(pendingTokens, suggestedTokens) + + return { + pendingTokens: params, + } +} + +const mapDispatchToProps = dispatch => { + return { + addToken: ({address, symbol, decimals, image}) => dispatch(addToken(address, symbol, decimals, image)), + removeSuggestedTokens: () => dispatch(removeSuggestedTokens()), + } +} + +export default compose( + withRouter, + connect(mapStateToProps, mapDispatchToProps) +)(ConfirmAddSuggestedToken) diff --git a/ui/app/components/pages/confirm-add-suggested-token/index.js b/ui/app/components/pages/confirm-add-suggested-token/index.js new file mode 100644 index 000000000..2ca56b43c --- /dev/null +++ b/ui/app/components/pages/confirm-add-suggested-token/index.js @@ -0,0 +1,2 @@ +import ConfirmAddSuggestedToken from './confirm-add-suggested-token.container' +module.exports = ConfirmAddSuggestedToken diff --git a/ui/app/components/pages/confirm-add-token/confirm-add-token.component.js b/ui/app/components/pages/confirm-add-token/confirm-add-token.component.js index 65d654b92..3dcc8cda9 100644 --- a/ui/app/components/pages/confirm-add-token/confirm-add-token.component.js +++ b/ui/app/components/pages/confirm-add-token/confirm-add-token.component.js @@ -2,8 +2,8 @@ import React, { Component } from 'react' import PropTypes from 'prop-types' import { DEFAULT_ROUTE, ADD_TOKEN_ROUTE } from '../../../routes' import Button from '../../button' -import Identicon from '../../../components/identicon' -import TokenBalance from './token-balance' +import Identicon from '../../identicon' +import TokenBalance from '../../token-balance' export default class ConfirmAddToken extends Component { static contextTypes = { diff --git a/ui/app/components/pages/confirm-add-token/token-balance/index.js b/ui/app/components/pages/confirm-add-token/token-balance/index.js deleted file mode 100644 index 6fb5c8223..000000000 --- a/ui/app/components/pages/confirm-add-token/token-balance/index.js +++ /dev/null @@ -1,2 +0,0 @@ -import TokenBalance from './token-balance.container' -module.exports = TokenBalance diff --git a/ui/app/components/pages/confirm-add-token/token-balance/token-balance.component.js b/ui/app/components/pages/confirm-add-token/token-balance/token-balance.component.js deleted file mode 100644 index 976788d4c..000000000 --- a/ui/app/components/pages/confirm-add-token/token-balance/token-balance.component.js +++ /dev/null @@ -1,16 +0,0 @@ -import React, { Component } from 'react' -import PropTypes from 'prop-types' - -export default class TokenBalance extends Component { - static propTypes = { - string: PropTypes.string, - symbol: PropTypes.string, - error: PropTypes.string, - } - - render () { - return ( -
{ this.props.string }
- ) - } -} diff --git a/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.component.js b/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.component.js index 961aa304e..56cfbccc8 100644 --- a/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.component.js +++ b/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.component.js @@ -38,6 +38,7 @@ export default class ConfirmTransactionBase extends Component { isTxReprice: PropTypes.bool, methodData: PropTypes.object, nonce: PropTypes.string, + assetImage: PropTypes.string, sendTransaction: PropTypes.func, showCustomizeGasModal: PropTypes.func, showTransactionConfirmedModal: PropTypes.func, @@ -73,6 +74,7 @@ export default class ConfirmTransactionBase extends Component { state = { submitting: false, + submitError: null, } componentDidUpdate () { @@ -268,7 +270,7 @@ export default class ConfirmTransactionBase extends Component { return } - this.setState({ submitting: true }) + this.setState({ submitting: true, submitError: null }) if (onSubmit) { Promise.resolve(onSubmit(txData)) @@ -280,7 +282,9 @@ export default class ConfirmTransactionBase extends Component { this.setState({ submitting: false }) history.push(DEFAULT_ROUTE) }) - .catch(() => this.setState({ submitting: false })) + .catch(error => { + this.setState({ submitting: false, submitError: error.message }) + }) } } @@ -307,9 +311,10 @@ export default class ConfirmTransactionBase extends Component { contentComponent, onEdit, nonce, + assetImage, warning, } = this.props - const { submitting } = this.state + const { submitting, submitError } = this.state const { name } = methodData const fiatConvertedAmount = formatCurrency(fiatTransactionAmount, currentCurrency) @@ -331,8 +336,9 @@ export default class ConfirmTransactionBase extends Component { dataComponent={this.renderData()} contentComponent={contentComponent} nonce={nonce} + assetImage={assetImage} identiconAddress={identiconAddress} - errorMessage={errorMessage} + errorMessage={errorMessage || submitError} errorKey={propsErrorKey || errorKey} warning={warning} disabled={!propsValid || !valid || submitting} diff --git a/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.container.js b/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.container.js index 0c0deff18..8f54c8040 100644 --- a/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.container.js +++ b/ui/app/components/pages/confirm-transaction-base/confirm-transaction-base.container.js @@ -52,8 +52,9 @@ const mapStateToProps = (state, props) => { accounts, selectedAddress, selectedAddressTxList, + assetImages, } = metamask - + const assetImage = assetImages[txParamsToAddress] const { balance } = accounts[selectedAddress] const { name: fromName } = identities[selectedAddress] const toAddress = propsToAddress || txParamsToAddress @@ -88,6 +89,7 @@ const mapStateToProps = (state, props) => { conversionRate, transactionStatus, nonce, + assetImage, } } diff --git a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.component.js b/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.component.js index 0280f73c6..2c44b6094 100644 --- a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.component.js +++ b/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.component.js @@ -12,25 +12,27 @@ import { CONFIRM_TOKEN_METHOD_PATH, SIGNATURE_REQUEST_PATH, } from '../../../routes' -import { isConfirmDeployContract } from './confirm-transaction-switch.util' +import { isConfirmDeployContract } from '../../../helpers/transactions.util' import { TOKEN_METHOD_TRANSFER, TOKEN_METHOD_APPROVE, TOKEN_METHOD_TRANSFER_FROM, -} from './confirm-transaction-switch.constants' +} from '../../../constants/transactions' export default class ConfirmTransactionSwitch extends Component { static propTypes = { txData: PropTypes.object, methodData: PropTypes.object, - fetchingMethodData: PropTypes.bool, + fetchingData: PropTypes.bool, + isEtherTransaction: PropTypes.bool, } redirectToTransaction () { const { txData, methodData: { name }, - fetchingMethodData, + fetchingData, + isEtherTransaction, } = this.props const { id, txParams: { data } = {} } = txData @@ -39,10 +41,15 @@ export default class ConfirmTransactionSwitch extends Component { return } - if (fetchingMethodData) { + if (fetchingData) { return } + if (isEtherTransaction) { + const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_SEND_ETHER_PATH}` + return + } + if (data) { const methodName = name && name.toLowerCase() diff --git a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.constants.js b/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.constants.js deleted file mode 100644 index 9db4a2f96..000000000 --- a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.constants.js +++ /dev/null @@ -1,3 +0,0 @@ -export const TOKEN_METHOD_TRANSFER = 'transfer' -export const TOKEN_METHOD_APPROVE = 'approve' -export const TOKEN_METHOD_TRANSFER_FROM = 'transferfrom' diff --git a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.container.js b/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.container.js index 3d7fc78cc..7f2c36af2 100644 --- a/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.container.js +++ b/ui/app/components/pages/confirm-transaction-switch/confirm-transaction-switch.container.js @@ -6,14 +6,16 @@ const mapStateToProps = state => { confirmTransaction: { txData, methodData, - fetchingMethodData, + fetchingData, + toSmartContract, }, } = state return { txData, methodData, - fetchingMethodData, + fetchingData, + isEtherTransaction: !toSmartContract, } } diff --git a/ui/app/components/pages/create-account/connect-hardware/account-list.js b/ui/app/components/pages/create-account/connect-hardware/account-list.js index c5c1cee61..25018b627 100644 --- a/ui/app/components/pages/create-account/connect-hardware/account-list.js +++ b/ui/app/components/pages/create-account/connect-hardware/account-list.js @@ -3,6 +3,7 @@ const PropTypes = require('prop-types') const h = require('react-hyperscript') const ethNetProps = require('eth-net-props') const Select = require('react-select').default +import Button from '../../../button' class AccountList extends Component { constructor (props, context) { @@ -143,22 +144,20 @@ class AccountList extends Component { } return h('div.new-account-connect-form__buttons', {}, [ - h( - 'button.btn-default.btn--large.new-account-connect-form__button', - { - onClick: this.props.onCancel.bind(this), - }, - [this.context.t('cancel')] - ), + h(Button, { + type: 'default', + large: true, + className: 'new-account-connect-form__button', + onClick: this.props.onCancel.bind(this), + }, [this.context.t('cancel')]), - h( - `button.btn-primary.btn--large.new-account-connect-form__button.unlock ${disabled ? '.btn-primary--disabled' : ''}`, - { - onClick: this.props.onUnlockAccount.bind(this, this.props.device), - ...buttonProps, - }, - [this.context.t('unlock')] - ), + h(Button, { + type: 'primary', + large: true, + className: 'new-account-connect-form__button unlock', + disabled, + onClick: this.props.onUnlockAccount.bind(this, this.props.device), + }, [this.context.t('unlock')]), ]) } diff --git a/ui/app/components/pages/create-account/connect-hardware/connect-screen.js b/ui/app/components/pages/create-account/connect-hardware/connect-screen.js index b3dfa4ee2..d3abf3119 100644 --- a/ui/app/components/pages/create-account/connect-hardware/connect-screen.js +++ b/ui/app/components/pages/create-account/connect-hardware/connect-screen.js @@ -1,6 +1,7 @@ const { Component } = require('react') const PropTypes = require('prop-types') const h = require('react-hyperscript') +import Button from '../../../button' class ConnectScreen extends Component { constructor (props, context) { @@ -60,13 +61,13 @@ class ConnectScreen extends Component { h('h3.hw-connect__title', {}, this.context.t('browserNotSupported')), h('p.hw-connect__msg', {}, this.context.t('chromeRequiredForHardwareWallets')), ]), - h( - 'button.btn-primary.btn--large', - { - onClick: () => global.platform.openWindow({ - url: 'https://google.com/chrome', - }), - }, + h(Button, { + type: 'primary', + large: true, + onClick: () => global.platform.openWindow({ + url: 'https://google.com/chrome', + }), + }, this.context.t('downloadGoogleChrome') ), ]) diff --git a/ui/app/components/pages/create-account/import-account/json.js b/ui/app/components/pages/create-account/import-account/json.js index dd57256a3..90279bbbd 100644 --- a/ui/app/components/pages/create-account/import-account/json.js +++ b/ui/app/components/pages/create-account/import-account/json.js @@ -8,6 +8,7 @@ const actions = require('../../../../actions') const FileInput = require('react-simple-file-input').default const { DEFAULT_ROUTE } = require('../../../../routes') const HELP_LINK = 'https://support.metamask.io/kb/article/7-importing-accounts' +import Button from '../../../button' class JsonImportSubview extends Component { constructor (props) { @@ -51,17 +52,19 @@ class JsonImportSubview extends Component { h('div.new-account-create-form__buttons', {}, [ - h('button.btn-default.new-account-create-form__button', { + h(Button, { + type: 'default', + large: true, + className: 'new-account-create-form__button', onClick: () => this.props.history.push(DEFAULT_ROUTE), - }, [ - this.context.t('cancel'), - ]), + }, [this.context.t('cancel')]), - h('button.btn-primary.new-account-create-form__button', { + h(Button, { + type: 'primary', + large: true, + className: 'new-account-create-form__button', onClick: () => this.createNewKeychain(), - }, [ - this.context.t('import'), - ]), + }, [this.context.t('import')]), ]), @@ -82,7 +85,7 @@ class JsonImportSubview extends Component { } createNewKeychain () { - const { firstAddress, displayWarning, importNewJsonAccount, setSelectedAddress } = this.props + const { firstAddress, displayWarning, importNewJsonAccount, setSelectedAddress, history } = this.props const state = this.state if (!state) { diff --git a/ui/app/components/pages/create-account/import-account/private-key.js b/ui/app/components/pages/create-account/import-account/private-key.js index 1db999f2f..8db1bfbdd 100644 --- a/ui/app/components/pages/create-account/import-account/private-key.js +++ b/ui/app/components/pages/create-account/import-account/private-key.js @@ -7,6 +7,7 @@ const PropTypes = require('prop-types') const connect = require('react-redux').connect const actions = require('../../../../actions') const { DEFAULT_ROUTE } = require('../../../../routes') +import Button from '../../../button' PrivateKeyImportView.contextTypes = { t: PropTypes.func, @@ -61,20 +62,22 @@ PrivateKeyImportView.prototype.render = function () { h('div.new-account-import-form__buttons', {}, [ - h('button.btn-default.btn--large.new-account-create-form__button', { + h(Button, { + type: 'default', + large: true, + className: 'new-account-create-form__button', onClick: () => { displayWarning(null) this.props.history.push(DEFAULT_ROUTE) }, - }, [ - this.context.t('cancel'), - ]), + }, [this.context.t('cancel')]), - h('button.btn-primary.btn--large.new-account-create-form__button', { + h(Button, { + type: 'primary', + large: true, + className: 'new-account-create-form__button', onClick: () => this.createNewKeychain(), - }, [ - this.context.t('import'), - ]), + }, [this.context.t('import')]), ]), diff --git a/ui/app/components/pages/create-account/new-account.js b/ui/app/components/pages/create-account/new-account.js index 402b8f03b..94a5fa487 100644 --- a/ui/app/components/pages/create-account/new-account.js +++ b/ui/app/components/pages/create-account/new-account.js @@ -4,6 +4,7 @@ const h = require('react-hyperscript') const connect = require('react-redux').connect const actions = require('../../../actions') const { DEFAULT_ROUTE } = require('../../../routes') +import Button from '../../button' class NewAccountCreateForm extends Component { constructor (props, context) { @@ -38,20 +39,22 @@ class NewAccountCreateForm extends Component { h('div.new-account-create-form__buttons', {}, [ - h('button.btn-default.btn--large.new-account-create-form__button', { + h(Button, { + type: 'default', + large: true, + className: 'new-account-create-form__button', onClick: () => history.push(DEFAULT_ROUTE), - }, [ - this.context.t('cancel'), - ]), + }, [this.context.t('cancel')]), - h('button.btn-primary.btn--large.new-account-create-form__button', { + h(Button, { + type: 'primary', + large: true, + className: 'new-account-create-form__button', onClick: () => { createAccount(newAccountName || defaultAccountName) .then(() => history.push(DEFAULT_ROUTE)) }, - }, [ - this.context.t('create'), - ]), + }, [this.context.t('create')]), ]), diff --git a/ui/app/components/pages/home.js b/ui/app/components/pages/home.js deleted file mode 100644 index 5e3fdc9af..000000000 --- a/ui/app/components/pages/home.js +++ /dev/null @@ -1,239 +0,0 @@ -const { Component } = require('react') -const { connect } = require('react-redux') -const PropTypes = require('prop-types') -const { Redirect, withRouter } = require('react-router-dom') -const { compose } = require('recompose') -const h = require('react-hyperscript') -const actions = require('../../actions') -const log = require('loglevel') - -// init -const NewKeyChainScreen = require('../../new-keychain') -// mascara -const MascaraBuyEtherScreen = require('../../../../mascara/src/app/first-time/buy-ether-screen').default - -// accounts -const MainContainer = require('../../main-container') - -// other views -const BuyView = require('../../components/buy-button-subview') -const QrView = require('../../components/qr-code') - -// Routes -const { - INITIALIZE_BACKUP_PHRASE_ROUTE, - RESTORE_VAULT_ROUTE, - CONFIRM_TRANSACTION_ROUTE, - NOTICE_ROUTE, -} = require('../../routes') - -const { unconfirmedTransactionsCountSelector } = require('../../selectors/confirm-transaction') - -class Home extends Component { - componentDidMount () { - const { - history, - unconfirmedTransactionsCount = 0, - } = this.props - - // unapprovedTxs and unapproved messages - if (unconfirmedTransactionsCount > 0) { - history.push(CONFIRM_TRANSACTION_ROUTE) - } - } - - render () { - log.debug('rendering primary') - const { - noActiveNotices, - lostAccounts, - forgottenPassword, - currentView, - activeAddress, - seedWords, - } = this.props - - // notices - if (!noActiveNotices || (lostAccounts && lostAccounts.length > 0)) { - return h(Redirect, { - to: { - pathname: NOTICE_ROUTE, - }, - }) - } - - // seed words - if (seedWords) { - log.debug('rendering seed words') - return h(Redirect, { - to: { - pathname: INITIALIZE_BACKUP_PHRASE_ROUTE, - }, - }) - } - - if (forgottenPassword) { - log.debug('rendering restore vault screen') - return h(Redirect, { - to: { - pathname: RESTORE_VAULT_ROUTE, - }, - }) - } - - // show current view - switch (currentView.name) { - - case 'accountDetail': - log.debug('rendering main container') - return h(MainContainer, {key: 'account-detail'}) - - case 'newKeychain': - log.debug('rendering new keychain screen') - return h(NewKeyChainScreen, {key: 'new-keychain'}) - - case 'buyEth': - log.debug('rendering buy ether screen') - return h(BuyView, {key: 'buyEthView'}) - - case 'onboardingBuyEth': - log.debug('rendering onboarding buy ether screen') - return h(MascaraBuyEtherScreen, {key: 'buyEthView'}) - - case 'qr': - log.debug('rendering show qr screen') - return h('div', { - style: { - position: 'absolute', - height: '100%', - top: '0px', - left: '0px', - }, - }, [ - h('i.fa.fa-arrow-left.fa-lg.cursor-pointer.color-orange', { - onClick: () => this.props.dispatch(actions.backToAccountDetail(activeAddress)), - style: { - marginLeft: '10px', - marginTop: '50px', - }, - }), - h('div', { - style: { - position: 'absolute', - left: '44px', - width: '285px', - }, - }, [ - h(QrView, {key: 'qr'}), - ]), - ]) - - default: - log.debug('rendering default, account detail screen') - return h(MainContainer, {key: 'account-detail'}) - } - } -} - -Home.propTypes = { - currentCurrency: PropTypes.string, - isLoading: PropTypes.bool, - loadingMessage: PropTypes.string, - network: PropTypes.string, - provider: PropTypes.object, - frequentRpcList: PropTypes.array, - currentView: PropTypes.object, - sidebarOpen: PropTypes.bool, - isMascara: PropTypes.bool, - isOnboarding: PropTypes.bool, - isUnlocked: PropTypes.bool, - networkDropdownOpen: PropTypes.bool, - history: PropTypes.object, - dispatch: PropTypes.func, - selectedAddress: PropTypes.string, - noActiveNotices: PropTypes.bool, - lostAccounts: PropTypes.array, - isInitialized: PropTypes.bool, - forgottenPassword: PropTypes.bool, - activeAddress: PropTypes.string, - unapprovedTxs: PropTypes.object, - seedWords: PropTypes.string, - unapprovedMsgCount: PropTypes.number, - unapprovedPersonalMsgCount: PropTypes.number, - unapprovedTypedMessagesCount: PropTypes.number, - welcomeScreenSeen: PropTypes.bool, - isPopup: PropTypes.bool, - isMouseUser: PropTypes.bool, - t: PropTypes.func, - unconfirmedTransactionsCount: PropTypes.number, -} - -function mapStateToProps (state) { - const { appState, metamask } = state - const { - networkDropdownOpen, - sidebarOpen, - isLoading, - loadingMessage, - } = appState - - const { - accounts, - address, - isInitialized, - noActiveNotices, - seedWords, - unapprovedTxs, - nextUnreadNotice, - lostAccounts, - unapprovedMsgCount, - unapprovedPersonalMsgCount, - unapprovedTypedMessagesCount, - } = metamask - const selected = address || Object.keys(accounts)[0] - - return { - // state from plugin - networkDropdownOpen, - sidebarOpen, - isLoading, - loadingMessage, - noActiveNotices, - isInitialized, - isUnlocked: state.metamask.isUnlocked, - selectedAddress: state.metamask.selectedAddress, - currentView: state.appState.currentView, - activeAddress: state.appState.activeAddress, - transForward: state.appState.transForward, - isMascara: state.metamask.isMascara, - isOnboarding: Boolean(!noActiveNotices || seedWords || !isInitialized), - isPopup: state.metamask.isPopup, - seedWords: state.metamask.seedWords, - unapprovedTxs, - unapprovedMsgs: state.metamask.unapprovedMsgs, - unapprovedMsgCount, - unapprovedPersonalMsgCount, - unapprovedTypedMessagesCount, - menuOpen: state.appState.menuOpen, - network: state.metamask.network, - provider: state.metamask.provider, - forgottenPassword: state.appState.forgottenPassword, - nextUnreadNotice, - lostAccounts, - frequentRpcList: state.metamask.frequentRpcList || [], - currentCurrency: state.metamask.currentCurrency, - isMouseUser: state.appState.isMouseUser, - isRevealingSeedWords: state.metamask.isRevealingSeedWords, - Qr: state.appState.Qr, - welcomeScreenSeen: state.metamask.welcomeScreenSeen, - - // state needed to get account dropdown temporarily rendering from app bar - selected, - unconfirmedTransactionsCount: unconfirmedTransactionsCountSelector(state), - } -} - -module.exports = compose( - withRouter, - connect(mapStateToProps) -)(Home) diff --git a/ui/app/components/pages/home/home.component.js b/ui/app/components/pages/home/home.component.js new file mode 100644 index 000000000..d3c71c4f6 --- /dev/null +++ b/ui/app/components/pages/home/home.component.js @@ -0,0 +1,77 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import Media from 'react-media' +import { Redirect } from 'react-router-dom' +import WalletView from '../../wallet-view' +import TransactionView from '../../transaction-view' +import { + INITIALIZE_BACKUP_PHRASE_ROUTE, + RESTORE_VAULT_ROUTE, + CONFIRM_TRANSACTION_ROUTE, + NOTICE_ROUTE, + CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE, +} from '../../../routes' + +export default class Home extends PureComponent { + static propTypes = { + history: PropTypes.object, + noActiveNotices: PropTypes.bool, + lostAccounts: PropTypes.array, + forgottenPassword: PropTypes.bool, + seedWords: PropTypes.string, + suggestedTokens: PropTypes.object, + unconfirmedTransactionsCount: PropTypes.number, + } + + componentDidMount () { + const { + history, + suggestedTokens = {}, + unconfirmedTransactionsCount = 0, + } = this.props + + // suggested new tokens + if (Object.keys(suggestedTokens).length > 0) { + history.push(CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE) + } + + if (unconfirmedTransactionsCount > 0) { + history.push(CONFIRM_TRANSACTION_ROUTE) + } + } + + render () { + const { + noActiveNotices, + lostAccounts, + forgottenPassword, + seedWords, + } = this.props + + // notices + if (!noActiveNotices || (lostAccounts && lostAccounts.length > 0)) { + return + } + + // seed words + if (seedWords) { + return + } + + if (forgottenPassword) { + return + } + + return ( +
+
+ } + /> + +
+
+ ) + } +} diff --git a/ui/app/components/pages/home/home.container.js b/ui/app/components/pages/home/home.container.js new file mode 100644 index 000000000..58001df6b --- /dev/null +++ b/ui/app/components/pages/home/home.container.js @@ -0,0 +1,30 @@ +import Home from './home.component' +import { compose } from 'recompose' +import { connect } from 'react-redux' +import { withRouter } from 'react-router-dom' +import { unconfirmedTransactionsCountSelector } from '../../../selectors/confirm-transaction' + +const mapStateToProps = state => { + const { metamask, appState } = state + const { + noActiveNotices, + lostAccounts, + seedWords, + suggestedTokens, + } = metamask + const { forgottenPassword } = appState + + return { + noActiveNotices, + lostAccounts, + forgottenPassword, + seedWords, + suggestedTokens, + unconfirmedTransactionsCount: unconfirmedTransactionsCountSelector(state), + } +} + +export default compose( + withRouter, + connect(mapStateToProps) +)(Home) diff --git a/ui/app/components/pages/home/index.js b/ui/app/components/pages/home/index.js new file mode 100644 index 000000000..4474ba5b8 --- /dev/null +++ b/ui/app/components/pages/home/index.js @@ -0,0 +1 @@ +export { default } from './home.container' diff --git a/ui/app/components/pages/index.scss b/ui/app/components/pages/index.scss index b15c59863..6551278f5 100644 --- a/ui/app/components/pages/index.scss +++ b/ui/app/components/pages/index.scss @@ -3,3 +3,5 @@ @import './add-token/index'; @import './confirm-add-token/index'; + +@import './settings/index'; diff --git a/ui/app/components/pages/keychains/reveal-seed.js b/ui/app/components/pages/keychains/reveal-seed.js index 7d7d3f462..7782b541c 100644 --- a/ui/app/components/pages/keychains/reveal-seed.js +++ b/ui/app/components/pages/keychains/reveal-seed.js @@ -8,6 +8,8 @@ const { requestRevealSeedWords } = require('../../../actions') const { DEFAULT_ROUTE } = require('../../../routes') const ExportTextContainer = require('../../export-text-container') +import Button from '../../button' + const PASSWORD_PROMPT_SCREEN = 'PASSWORD_PROMPT_SCREEN' const REVEAL_SEED_SCREEN = 'REVEAL_SEED_SCREEN' @@ -106,10 +108,16 @@ class RevealSeedPage extends Component { renderPasswordPromptFooter () { return ( h('.page-container__footer', [ - h('button.btn-default.btn--large.page-container__footer-button', { + h(Button, { + type: 'default', + large: true, + className: 'page-container__footer-button', onClick: () => this.props.history.push(DEFAULT_ROUTE), }, this.context.t('cancel')), - h('button.btn-primary.btn--large.page-container__footer-button', { + h(Button, { + type: 'primary', + large: true, + className: 'page-container__footer-button', onClick: event => this.handleSubmit(event), disabled: this.state.password === '', }, this.context.t('next')), @@ -120,7 +128,10 @@ class RevealSeedPage extends Component { renderRevealSeedFooter () { return ( h('.page-container__footer', [ - h('button.btn-default.btn--large.page-container__footer-button', { + h(Button, { + type: 'default', + large: true, + className: 'page-container__footer-button', onClick: () => this.props.history.push(DEFAULT_ROUTE), }, this.context.t('close')), ]) diff --git a/ui/app/components/pages/settings/index.js b/ui/app/components/pages/settings/index.js index aee17e0e8..44a9ffa63 100644 --- a/ui/app/components/pages/settings/index.js +++ b/ui/app/components/pages/settings/index.js @@ -1,64 +1 @@ -const { Component } = require('react') -const { Switch, Route, matchPath } = require('react-router-dom') -const PropTypes = require('prop-types') -const h = require('react-hyperscript') -const TabBar = require('../../tab-bar') -const Settings = require('./settings') -const Info = require('./info') -const { DEFAULT_ROUTE, SETTINGS_ROUTE, INFO_ROUTE } = require('../../../routes') - -class Config extends Component { - renderTabs () { - const { history, location } = this.props - - return h('div.settings__tabs', [ - h(TabBar, { - tabs: [ - { content: this.context.t('settings'), key: SETTINGS_ROUTE }, - { content: this.context.t('info'), key: INFO_ROUTE }, - ], - isActive: key => matchPath(location.pathname, { path: key, exact: true }), - onSelect: key => history.push(key), - }), - ]) - } - - render () { - const { history } = this.props - - return ( - h('.main-container.settings', {}, [ - h('.settings__header', [ - h('div.settings__close-button', { - onClick: () => history.push(DEFAULT_ROUTE), - }), - this.renderTabs(), - ]), - h(Switch, [ - h(Route, { - exact: true, - path: INFO_ROUTE, - component: Info, - }), - h(Route, { - exact: true, - path: SETTINGS_ROUTE, - component: Settings, - }), - ]), - ]) - ) - } -} - -Config.propTypes = { - location: PropTypes.object, - history: PropTypes.object, - t: PropTypes.func, -} - -Config.contextTypes = { - t: PropTypes.func, -} - -module.exports = Config +export { default } from './settings.component' diff --git a/ui/app/components/pages/settings/index.scss b/ui/app/components/pages/settings/index.scss new file mode 100644 index 000000000..138ebcfc5 --- /dev/null +++ b/ui/app/components/pages/settings/index.scss @@ -0,0 +1,80 @@ +@import './info-tab/index'; + +@import './settings-tab/index'; + +.settings-page { + position: relative; + background: $white; + display: flex; + flex-flow: column nowrap; + + &__header { + padding: 25px 25px 0; + } + + &__close-button::after { + content: '\00D7'; + font-size: 40px; + color: $dusty-gray; + position: absolute; + top: 25px; + right: 30px; + cursor: pointer; + } + + &__content { + padding: 25px; + height: auto; + overflow: auto; + } + + &__content-row { + display: flex; + flex-direction: row; + padding: 10px 0 20px; + + @media screen and (max-width: 575px) { + flex-direction: column; + padding: 10px 0; + } + } + + &__content-item { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + padding: 0 5px; + min-height: 71px; + + @media screen and (max-width: 575px) { + height: initial; + padding: 5px 0; + } + + &--without-height { + height: initial; + } + } + + &__content-label { + text-transform: capitalize; + } + + &__content-description { + font-size: 14px; + color: $dusty-gray; + padding-top: 5px; + } + + &__content-item-col { + max-width: 300px; + display: flex; + flex-direction: column; + + @media screen and (max-width: 575px) { + max-width: 100%; + width: 100%; + } + } +} diff --git a/ui/app/components/pages/settings/info-tab/index.js b/ui/app/components/pages/settings/info-tab/index.js new file mode 100644 index 000000000..7556a258d --- /dev/null +++ b/ui/app/components/pages/settings/info-tab/index.js @@ -0,0 +1 @@ +export { default } from './info-tab.component' diff --git a/ui/app/components/pages/settings/info-tab/index.scss b/ui/app/components/pages/settings/info-tab/index.scss new file mode 100644 index 000000000..43ad6f652 --- /dev/null +++ b/ui/app/components/pages/settings/info-tab/index.scss @@ -0,0 +1,56 @@ +.info-tab { + &__logo-wrapper { + height: 80px; + margin-bottom: 20px; + } + + &__logo { + max-height: 100%; + max-width: 100%; + } + + &__item { + padding: 10px 0; + } + + &__link-header { + padding-bottom: 15px; + + @media screen and (max-width: 575px) { + padding-bottom: 5px; + } + } + + &__link-item { + padding: 15px 0; + + @media screen and (max-width: 575px) { + padding: 5px 0; + } + } + + &__link-text { + color: $curious-blue; + } + + &__version-number { + padding-top: 5px; + font-size: 13px; + color: $dusty-gray; + } + + &__separator { + margin: 15px 0; + width: 80px; + border-color: $alto; + border: none; + height: 1px; + background-color: $alto; + color: $alto; + } + + &__about { + color: $dusty-gray; + margin-bottom: 15px; + } +} diff --git a/ui/app/components/pages/settings/info-tab/info-tab.component.js b/ui/app/components/pages/settings/info-tab/info-tab.component.js new file mode 100644 index 000000000..72f7d835e --- /dev/null +++ b/ui/app/components/pages/settings/info-tab/info-tab.component.js @@ -0,0 +1,136 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' + +export default class InfoTab extends PureComponent { + state = { + version: global.platform.getVersion(), + } + + static propTypes = { + tab: PropTypes.string, + metamask: PropTypes.object, + setCurrentCurrency: PropTypes.func, + setRpcTarget: PropTypes.func, + displayWarning: PropTypes.func, + revealSeedConfirmation: PropTypes.func, + warning: PropTypes.string, + location: PropTypes.object, + history: PropTypes.object, + } + + static contextTypes = { + t: PropTypes.func, + } + + renderInfoLinks () { + const { t } = this.context + + return ( + + ) + } + + render () { + const { t } = this.context + + return ( +
+
+
+
+ +
+
+
+ { t('metamaskVersion') } +
+
+ { this.state.version } +
+
+
+
+ { t('builtInCalifornia') } +
+
+
+ { this.renderInfoLinks() } +
+
+ ) + } +} diff --git a/ui/app/components/pages/settings/info.js b/ui/app/components/pages/settings/info.js deleted file mode 100644 index a0f994ac2..000000000 --- a/ui/app/components/pages/settings/info.js +++ /dev/null @@ -1,96 +0,0 @@ -const { Component } = require('react') -const PropTypes = require('prop-types') -const h = require('react-hyperscript') - -class Info extends Component { - constructor (props) { - super(props) - - this.state = { - version: global.platform.getVersion(), - } - } - - renderLogo () { - return ( - h('div.settings__info-logo-wrapper', [ - h('img.settings__info-logo', { src: 'images/info-logo.png' }), - ]) - ) - } - - renderInfoLinks () { - return ( - h('div.settings__content-item.settings__content-item--without-height', [ - h('div.settings__info-link-header', this.context.t('links')), - h('div.settings__info-link-item', [ - h('a', { - href: 'https://metamask.io/privacy.html', - target: '_blank', - }, [ - h('span.settings__info-link', this.context.t('privacyMsg')), - ]), - ]), - h('div.settings__info-link-item', [ - h('a', { - href: 'https://metamask.io/terms.html', - target: '_blank', - }, [ - h('span.settings__info-link', this.context.t('terms')), - ]), - ]), - h('div.settings__info-link-item', [ - h('a', { - href: 'https://metamask.io/attributions.html', - target: '_blank', - }, [ - h('span.settings__info-link', this.context.t('attributions')), - ]), - ]), - // h('hr.settings__info-separator'), - ]) - ) - } - - render () { - return ( - h('div.settings__content', [ - h('div.settings__content-row', [ - h('div.settings__content-item.settings__content-item--without-height', [ - this.renderLogo(), - h('div.settings__info-item', [ - h('div.settings__info-version-header', 'Nifty Wallet Version'), - h('div.settings__info-version-number', this.state.version), - ]), - h('div.settings__info-item', [ - h( - 'div.settings__info-about', - this.context.t('builtInCalifornia') - ), - ]), - ]), - this.renderInfoLinks(), - ]), - ]) - ) - } -} - -Info.propTypes = { - tab: PropTypes.string, - metamask: PropTypes.object, - setCurrentCurrency: PropTypes.func, - setRpcTarget: PropTypes.func, - displayWarning: PropTypes.func, - revealSeedConfirmation: PropTypes.func, - warning: PropTypes.string, - location: PropTypes.object, - history: PropTypes.object, - t: PropTypes.func, -} - -Info.contextTypes = { - t: PropTypes.func, -} - -module.exports = Info diff --git a/ui/app/components/pages/settings/settings-tab/index.js b/ui/app/components/pages/settings/settings-tab/index.js new file mode 100644 index 000000000..9fdaafd3f --- /dev/null +++ b/ui/app/components/pages/settings/settings-tab/index.js @@ -0,0 +1 @@ +export { default } from './settings-tab.container' diff --git a/ui/app/components/pages/settings/settings-tab/index.scss b/ui/app/components/pages/settings/settings-tab/index.scss new file mode 100644 index 000000000..76a0cec6f --- /dev/null +++ b/ui/app/components/pages/settings/settings-tab/index.scss @@ -0,0 +1,51 @@ +.settings-tab { + &__error { + padding-bottom: 20px; + text-align: center; + color: $crimson; + } + + &__rpc-save-button { + align-self: flex-end; + padding: 5px; + text-transform: uppercase; + color: $dusty-gray; + cursor: pointer; + } + + &__rpc-save-button { + align-self: flex-end; + padding: 5px; + text-transform: uppercase; + color: $dusty-gray; + cursor: pointer; + } + + &__button--red { + border-color: lighten($monzo, 10%); + color: $monzo; + + &:active { + background: lighten($monzo, 55%); + border-color: $monzo; + } + + &:hover { + border-color: $monzo; + } + } + + &__button--orange { + border-color: lighten($ecstasy, 20%); + color: $ecstasy; + + &:active { + background: lighten($ecstasy, 40%); + border-color: $ecstasy; + } + + &:hover { + border-color: $ecstasy; + } + } +} diff --git a/ui/app/components/pages/settings/settings-tab/settings-tab.component.js b/ui/app/components/pages/settings/settings-tab/settings-tab.component.js new file mode 100644 index 000000000..53c4f16e0 --- /dev/null +++ b/ui/app/components/pages/settings/settings-tab/settings-tab.component.js @@ -0,0 +1,359 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import infuraCurrencies from '../../../../infura-conversion.json' +import validUrl from 'valid-url' +import { exportAsFile } from '../../../../util' +import SimpleDropdown from '../../../dropdowns/simple-dropdown' +import ToggleButton from 'react-toggle-button' +import { REVEAL_SEED_ROUTE } from '../../../../routes' +import locales from '../../../../../../app/_locales/index.json' +import TextField from '../../../text-field' +import Button from '../../../button' + +const sortedCurrencies = infuraCurrencies.objects.sort((a, b) => { + return a.quote.name.toLocaleLowerCase().localeCompare(b.quote.name.toLocaleLowerCase()) +}) + +const infuraCurrencyOptions = sortedCurrencies.map(({ quote: { code, name } }) => { + return { + displayValue: `${code.toUpperCase()} - ${name}`, + key: code, + value: code, + } +}) + +const localeOptions = locales.map(locale => { + return { + displayValue: `${locale.name}`, + key: locale.code, + value: locale.code, + } +}) + +export default class SettingsTab extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + metamask: PropTypes.object, + setUseBlockie: PropTypes.func, + setHexDataFeatureFlag: PropTypes.func, + setCurrentCurrency: PropTypes.func, + setRpcTarget: PropTypes.func, + displayWarning: PropTypes.func, + revealSeedConfirmation: PropTypes.func, + setFeatureFlagToBeta: PropTypes.func, + showResetAccountConfirmationModal: PropTypes.func, + warning: PropTypes.string, + history: PropTypes.object, + isMascara: PropTypes.bool, + updateCurrentLocale: PropTypes.func, + currentLocale: PropTypes.string, + useBlockie: PropTypes.bool, + sendHexData: PropTypes.bool, + currentCurrency: PropTypes.string, + conversionDate: PropTypes.number, + } + + state = { + newRpc: '', + } + + renderCurrentConversion () { + const { t } = this.context + const { currentCurrency, conversionDate, setCurrentCurrency } = this.props + + return ( +
+
+ { t('currentConversion') } + + { t('updatedWithDate', [Date(conversionDate)]) } + +
+
+
+ setCurrentCurrency(newCurrency)} + /> +
+
+
+ ) + } + + renderCurrentLocale () { + const { t } = this.context + const { updateCurrentLocale, currentLocale } = this.props + const currentLocaleMeta = locales.find(locale => locale.code === currentLocale) + const currentLocaleName = currentLocaleMeta ? currentLocaleMeta.name : '' + + return ( +
+
+ + { t('currentLanguage') } + + + { currentLocaleName } + +
+
+
+ updateCurrentLocale(newLocale)} + /> +
+
+
+ ) + } + + renderNewRpcUrl () { + const { t } = this.context + const { newRpc } = this.state + + return ( +
+
+ { t('newRPC') } +
+
+
+ this.setState({ newRpc: e.target.value })} + onKeyPress={e => { + if (e.key === 'Enter') { + this.validateRpc(newRpc) + } + }} + fullWidth + margin="none" + /> +
{ + e.preventDefault() + this.validateRpc(newRpc) + }} + > + { t('save') } +
+
+
+
+ ) + } + + validateRpc (newRpc) { + const { setRpcTarget, displayWarning } = this.props + + if (validUrl.isWebUri(newRpc)) { + setRpcTarget(newRpc) + } else { + const appendedRpc = `http://${newRpc}` + + if (validUrl.isWebUri(appendedRpc)) { + displayWarning(this.context.t('uriErrorMsg')) + } else { + displayWarning(this.context.t('invalidRPC')) + } + } + } + + renderStateLogs () { + const { t } = this.context + const { displayWarning } = this.props + + return ( +
+
+ { t('stateLogs') } + + { t('stateLogsDescription') } + +
+
+
+ +
+
+
+ ) + } + + renderSeedWords () { + const { t } = this.context + const { history } = this.props + + return ( +
+
+ { t('revealSeedWords') } +
+
+
+ +
+
+
+ ) + } + + renderOldUI () { + const { t } = this.context + const { setFeatureFlagToBeta } = this.props + + return ( +
+
+ { t('useOldUI') } +
+
+
+ +
+
+
+ ) + } + + renderResetAccount () { + const { t } = this.context + const { showResetAccountConfirmationModal } = this.props + + return ( +
+
+ { t('resetAccount') } +
+
+
+ +
+
+
+ ) + } + + renderBlockieOptIn () { + const { useBlockie, setUseBlockie } = this.props + + return ( +
+
+ { this.context.t('blockiesIdenticon') } +
+
+
+ setUseBlockie(!value)} + activeLabel="" + inactiveLabel="" + /> +
+
+
+ ) + } + + renderHexDataOptIn () { + const { t } = this.context + const { sendHexData, setHexDataFeatureFlag } = this.props + + return ( +
+
+ { t('showHexData') } +
+ { t('showHexDataDescription') } +
+
+
+
+ setHexDataFeatureFlag(!value)} + activeLabel="" + inactiveLabel="" + /> +
+
+
+ ) + } + + render () { + const { warning, isMascara } = this.props + + return ( +
+ { warning &&
{ warning }
} + { this.renderCurrentConversion() } + { this.renderCurrentLocale() } + { this.renderNewRpcUrl() } + { this.renderStateLogs() } + { this.renderSeedWords() } + { !isMascara && this.renderOldUI() } + { this.renderResetAccount() } + { this.renderBlockieOptIn() } + { this.renderHexDataOptIn() } +
+ ) + } +} diff --git a/ui/app/components/pages/settings/settings-tab/settings-tab.container.js b/ui/app/components/pages/settings/settings-tab/settings-tab.container.js new file mode 100644 index 000000000..665b56f5c --- /dev/null +++ b/ui/app/components/pages/settings/settings-tab/settings-tab.container.js @@ -0,0 +1,59 @@ +import SettingsTab from './settings-tab.component' +import { compose } from 'recompose' +import { connect } from 'react-redux' +import { withRouter } from 'react-router-dom' +import { + setCurrentCurrency, + setRpcTarget, + displayWarning, + revealSeedConfirmation, + setUseBlockie, + updateCurrentLocale, + setFeatureFlag, + showModal, +} from '../../../../actions' + +const mapStateToProps = state => { + const { appState: { warning }, metamask } = state + const { + currentCurrency, + conversionDate, + useBlockie, + featureFlags: { sendHexData } = {}, + provider = {}, + isMascara, + currentLocale, + } = metamask + + return { + warning, + isMascara, + currentLocale, + currentCurrency, + conversionDate, + useBlockie, + sendHexData, + provider, + } +} + +const mapDispatchToProps = dispatch => { + return { + setCurrentCurrency: currency => dispatch(setCurrentCurrency(currency)), + setRpcTarget: newRpc => dispatch(setRpcTarget(newRpc)), + displayWarning: warning => dispatch(displayWarning(warning)), + revealSeedConfirmation: () => dispatch(revealSeedConfirmation()), + setUseBlockie: value => dispatch(setUseBlockie(value)), + updateCurrentLocale: key => dispatch(updateCurrentLocale(key)), + setFeatureFlagToBeta: () => { + return dispatch(setFeatureFlag('betaUI', false, 'OLD_UI_NOTIFICATION_MODAL')) + }, + setHexDataFeatureFlag: shouldShow => dispatch(setFeatureFlag('sendHexData', shouldShow)), + showResetAccountConfirmationModal: () => dispatch(showModal({ name: 'CONFIRM_RESET_ACCOUNT' })), + } +} + +export default compose( + withRouter, + connect(mapStateToProps, mapDispatchToProps) +)(SettingsTab) diff --git a/ui/app/components/pages/settings/settings.component.js b/ui/app/components/pages/settings/settings.component.js new file mode 100644 index 000000000..94a97bba1 --- /dev/null +++ b/ui/app/components/pages/settings/settings.component.js @@ -0,0 +1,54 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import { Switch, Route, matchPath } from 'react-router-dom' +import TabBar from '../../tab-bar' +import SettingsTab from './settings-tab' +import InfoTab from './info-tab' +import { DEFAULT_ROUTE, SETTINGS_ROUTE, INFO_ROUTE } from '../../../routes' + +export default class SettingsPage extends PureComponent { + static propTypes = { + location: PropTypes.object, + history: PropTypes.object, + t: PropTypes.func, + } + + static contextTypes = { + t: PropTypes.func, + } + + render () { + const { history, location } = this.props + + return ( +
+
+
history.push(DEFAULT_ROUTE)} + /> + matchPath(location.pathname, { path: key, exact: true })} + onSelect={key => history.push(key)} + /> +
+ + + + +
+ ) + } +} diff --git a/ui/app/components/pages/settings/settings.js b/ui/app/components/pages/settings/settings.js deleted file mode 100644 index a8945f22b..000000000 --- a/ui/app/components/pages/settings/settings.js +++ /dev/null @@ -1,371 +0,0 @@ -const { Component } = require('react') -const { withRouter } = require('react-router-dom') -const { compose } = require('recompose') -const PropTypes = require('prop-types') -const h = require('react-hyperscript') -const connect = require('react-redux').connect -const actions = require('../../../actions') -const infuraCurrencies = require('../../../infura-conversion.json') -const validUrl = require('valid-url') -const { exportAsFile } = require('../../../util') -const SimpleDropdown = require('../../dropdowns/simple-dropdown') -const ToggleButton = require('react-toggle-button') -const { REVEAL_SEED_ROUTE } = require('../../../routes') -const locales = require('../../../../../app/_locales/index.json') - -const getInfuraCurrencyOptions = () => { - const sortedCurrencies = infuraCurrencies.objects.sort((a, b) => { - return a.quote.name.toLocaleLowerCase().localeCompare(b.quote.name.toLocaleLowerCase()) - }) - - return sortedCurrencies.map(({ quote: { code, name } }) => { - return { - displayValue: `${code.toUpperCase()} - ${name}`, - key: code, - value: code, - } - }) -} - -const getLocaleOptions = () => { - return locales.map((locale) => { - return { - displayValue: `${locale.name}`, - key: locale.code, - value: locale.code, - } - }) -} - -class Settings extends Component { - constructor (props) { - super(props) - - this.state = { - newRpc: '', - } - } - - renderBlockieOptIn () { - const { metamask: { useBlockie }, setUseBlockie } = this.props - - return h('div.settings__content-row', [ - h('div.settings__content-item', [ - h('span', this.context.t('blockiesIdenticon')), - ]), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h(ToggleButton, { - value: useBlockie, - onToggle: (value) => setUseBlockie(!value), - activeLabel: '', - inactiveLabel: '', - }), - ]), - ]), - ]) - } - - renderCurrentConversion () { - const { metamask: { currentCurrency, conversionDate }, setCurrentCurrency } = this.props - - return h('div.settings__content-row', [ - h('div.settings__content-item', [ - h('span', this.context.t('currentConversion')), - h('span.settings__content-description', `Updated ${Date(conversionDate)}`), - ]), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h(SimpleDropdown, { - placeholder: this.context.t('selectCurrency'), - options: getInfuraCurrencyOptions(), - selectedOption: currentCurrency, - onSelect: newCurrency => setCurrentCurrency(newCurrency), - }), - ]), - ]), - ]) - } - - renderCurrentLocale () { - const { updateCurrentLocale, currentLocale } = this.props - const currentLocaleMeta = locales.find(locale => locale.code === currentLocale) - const currentLocaleName = currentLocaleMeta ? currentLocaleMeta.name : '' - - return h('div.settings__content-row', [ - h('div.settings__content-item', [ - h('span', 'Current Language'), - h('span.settings__content-description', `${currentLocaleName}`), - ]), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h(SimpleDropdown, { - placeholder: 'Select Locale', - options: getLocaleOptions(), - selectedOption: currentLocale, - onSelect: async (newLocale) => { - updateCurrentLocale(newLocale) - }, - }), - ]), - ]), - ]) - } - - renderCurrentProvider () { - const { metamask: { provider = {} } } = this.props - let title, value, color - - switch (provider.type) { - - case 'mainnet': - title = this.context.t('currentNetwork') - value = this.context.t('mainnet') - color = '#038789' - break - - case 'ropsten': - title = this.context.t('currentNetwork') - value = this.context.t('ropsten') - color = '#e91550' - break - - case 'kovan': - title = this.context.t('currentNetwork') - value = this.context.t('kovan') - color = '#690496' - break - - case 'rinkeby': - title = this.context.t('currentNetwork') - value = this.context.t('rinkeby') - color = '#ebb33f' - break - - case 'poa': - title = this.context.t('currentNetwork') - value = this.context.t('poa') - color = '#5c34a2' - break - - default: - title = this.context.t('currentRpc') - value = provider.rpcTarget - } - - return h('div.settings__content-row', [ - h('div.settings__content-item', title), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('div.settings__provider-wrapper', [ - h('div.settings__provider-icon', { style: { background: color } }), - h('div', value), - ]), - ]), - ]), - ]) - } - - renderNewRpcUrl () { - return ( - h('div.settings__content-row', [ - h('div.settings__content-item', [ - h('span', this.context.t('newRPC')), - ]), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('input.settings__input', { - placeholder: this.context.t('newRPC'), - onChange: event => this.setState({ newRpc: event.target.value }), - onKeyPress: event => { - if (event.key === 'Enter') { - this.validateRpc(this.state.newRpc) - } - }, - }), - h('div.settings__rpc-save-button', { - onClick: event => { - event.preventDefault() - this.validateRpc(this.state.newRpc) - }, - }, this.context.t('save')), - ]), - ]), - ]) - ) - } - - validateRpc (newRpc) { - const { setRpcTarget, displayWarning } = this.props - - if (validUrl.isWebUri(newRpc)) { - setRpcTarget(newRpc) - } else { - const appendedRpc = `http://${newRpc}` - - if (validUrl.isWebUri(appendedRpc)) { - displayWarning(this.context.t('uriErrorMsg')) - } else { - displayWarning(this.context.t('invalidRPC')) - } - } - } - - renderStateLogs () { - return ( - h('div.settings__content-row', [ - h('div.settings__content-item', [ - h('div', this.context.t('stateLogs')), - h( - 'div.settings__content-description', - this.context.t('stateLogsDescription') - ), - ]), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('button.btn-primary.btn--large.settings__button', { - onClick (event) { - window.logStateString((err, result) => { - if (err) { - this.state.dispatch(actions.displayWarning(this.context.t('stateLogError'))) - } else { - exportAsFile('Nifty Wallet State Logs.json', result) - } - }) - }, - }, this.context.t('downloadStateLogs')), - ]), - ]), - ]) - ) - } - - renderSeedWords () { - const { history } = this.props - - return ( - h('div.settings__content-row', [ - h('div.settings__content-item', this.context.t('revealSeedWords')), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('button.btn-primary.btn--large.settings__button--red', { - onClick: event => { - event.preventDefault() - history.push(REVEAL_SEED_ROUTE) - }, - }, this.context.t('revealSeedWords')), - ]), - ]), - ]) - ) - } - - renderOldUI () { - const { setFeatureFlagToBeta } = this.props - - return ( - h('div.settings__content-row', [ - h('div.settings__content-item', this.context.t('useOldUI')), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('button.btn-primary.btn--large.settings__button--orange', { - onClick (event) { - event.preventDefault() - setFeatureFlagToBeta() - }, - }, this.context.t('useOldUI')), - ]), - ]), - ]) - ) - } - - renderResetAccount () { - const { showResetAccountConfirmationModal } = this.props - - return h('div.settings__content-row', [ - h('div.settings__content-item', this.context.t('resetAccount')), - h('div.settings__content-item', [ - h('div.settings__content-item-col', [ - h('button.btn-primary.btn--large.settings__button--orange', { - onClick (event) { - event.preventDefault() - showResetAccountConfirmationModal() - }, - }, this.context.t('resetAccount')), - ]), - ]), - ]) - } - - render () { - const { warning, isMascara } = this.props - - return ( - h('div.settings__content', [ - warning && h('div.settings__error', warning), - this.renderCurrentConversion(), - this.renderCurrentLocale(), - // this.renderCurrentProvider(), - this.renderNewRpcUrl(), - this.renderStateLogs(), - this.renderSeedWords(), - !isMascara && this.renderOldUI(), - this.renderResetAccount(), - this.renderBlockieOptIn(), - ]) - ) - } -} - -Settings.propTypes = { - metamask: PropTypes.object, - setUseBlockie: PropTypes.func, - setCurrentCurrency: PropTypes.func, - setRpcTarget: PropTypes.func, - displayWarning: PropTypes.func, - revealSeedConfirmation: PropTypes.func, - setFeatureFlagToBeta: PropTypes.func, - showResetAccountConfirmationModal: PropTypes.func, - warning: PropTypes.string, - history: PropTypes.object, - isMascara: PropTypes.bool, - updateCurrentLocale: PropTypes.func, - currentLocale: PropTypes.string, - t: PropTypes.func, -} - -const mapStateToProps = state => { - return { - metamask: state.metamask, - warning: state.appState.warning, - isMascara: state.metamask.isMascara, - currentLocale: state.metamask.currentLocale, - } -} - -const mapDispatchToProps = dispatch => { - return { - setCurrentCurrency: currency => dispatch(actions.setCurrentCurrency(currency)), - setRpcTarget: newRpc => dispatch(actions.setRpcTarget(newRpc)), - displayWarning: warning => dispatch(actions.displayWarning(warning)), - revealSeedConfirmation: () => dispatch(actions.revealSeedConfirmation()), - setUseBlockie: value => dispatch(actions.setUseBlockie(value)), - updateCurrentLocale: key => dispatch(actions.updateCurrentLocale(key)), - setFeatureFlagToBeta: () => { - return dispatch(actions.setFeatureFlag('betaUI', false, 'OLD_UI_NOTIFICATION_MODAL')) - }, - showResetAccountConfirmationModal: () => { - return dispatch(actions.showModal({ name: 'CONFIRM_RESET_ACCOUNT' })) - }, - } -} - -Settings.contextTypes = { - t: PropTypes.func, -} - -module.exports = compose( - withRouter, - connect(mapStateToProps, mapDispatchToProps) -)(Settings) diff --git a/ui/app/components/pages/unlock-page/index.scss b/ui/app/components/pages/unlock-page/index.scss index 8b0764145..58e54a89d 100644 --- a/ui/app/components/pages/unlock-page/index.scss +++ b/ui/app/components/pages/unlock-page/index.scss @@ -14,6 +14,7 @@ align-self: stretch; justify-content: center; flex: 1 0 auto; + height: 100vh; } &__title { diff --git a/ui/app/components/pending-msg-details.js b/ui/app/components/pending-msg-details.js deleted file mode 100644 index f16fcb1c7..000000000 --- a/ui/app/components/pending-msg-details.js +++ /dev/null @@ -1,56 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const h = require('react-hyperscript') -const inherits = require('util').inherits -const connect = require('react-redux').connect - -const AccountPanel = require('./account-panel') - -PendingMsgDetails.contextTypes = { - t: PropTypes.func, -} - -module.exports = connect()(PendingMsgDetails) - - -inherits(PendingMsgDetails, Component) -function PendingMsgDetails () { - Component.call(this) -} - -PendingMsgDetails.prototype.render = function () { - var state = this.props - var msgData = state.txData - - var msgParams = msgData.msgParams || {} - var address = msgParams.from || state.selectedAddress - var identity = state.identities[address] || { address: address } - var account = state.accounts[address] || { address: address } - - return ( - h('div', { - key: msgData.id, - style: { - margin: '10px 20px', - }, - }, [ - - // account that will sign - h(AccountPanel, { - showFullAddress: true, - identity: identity, - account: account, - imageifyIdenticons: state.imageifyIdenticons, - }), - - // message data - h('.tx-data.flex-column.flex-justify-center.flex-grow.select-none', [ - h('.flex-column.flex-space-between', [ - h('label.font-small.allcaps', this.context.t('message')), - h('span.font-small', msgParams.data), - ]), - ]), - - ]) - ) -} diff --git a/ui/app/components/pending-msg.js b/ui/app/components/pending-msg.js deleted file mode 100644 index 21a7864e4..000000000 --- a/ui/app/components/pending-msg.js +++ /dev/null @@ -1,73 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const h = require('react-hyperscript') -const inherits = require('util').inherits -const PendingTxDetails = require('./pending-msg-details') -const connect = require('react-redux').connect - -PendingMsg.contextTypes = { - t: PropTypes.func, -} - -module.exports = connect()(PendingMsg) - - -inherits(PendingMsg, Component) -function PendingMsg () { - Component.call(this) -} - -PendingMsg.prototype.render = function () { - var state = this.props - var msgData = state.txData - - return ( - - h('div', { - key: msgData.id, - style: { - maxWidth: '350px', - }, - }, [ - - // header - h('h3', { - style: { - fontWeight: 'bold', - textAlign: 'center', - }, - }, this.context.t('signMessage')), - - h('.error', { - style: { - margin: '10px', - }, - }, [ - this.context.t('signNotice'), - h('a', { - href: 'https://medium.com/metamask/the-new-secure-way-to-sign-data-in-your-browser-6af9dd2a1527', - style: { color: 'rgb(247, 134, 28)' }, - onClick: (event) => { - event.preventDefault() - const url = 'https://medium.com/metamask/the-new-secure-way-to-sign-data-in-your-browser-6af9dd2a1527' - global.platform.openWindow({ url }) - }, - }, this.context.t('readMore')), - ]), - - // message details - h(PendingTxDetails, state), - - // sign + cancel - h('.flex-row.flex-space-around', [ - h('button', { - onClick: state.cancelMessage, - }, this.context.t('cancel')), - h('button', { - onClick: state.signMessage, - }, this.context.t('sign')), - ]), - ]) - - ) -} diff --git a/ui/app/components/selected-account/selected-account.component.js b/ui/app/components/selected-account/selected-account.component.js index 6c202141e..4f98df9b6 100644 --- a/ui/app/components/selected-account/selected-account.component.js +++ b/ui/app/components/selected-account/selected-account.component.js @@ -1,9 +1,9 @@ import React, { Component } from 'react' import PropTypes from 'prop-types' import copyToClipboard from 'copy-to-clipboard' -import { addressSlicer } from '../../util' +import { addressSlicer, checksumAddress } from '../../util' -const Tooltip = require('../tooltip-v2.js') +const Tooltip = require('../tooltip-v2.js').default class SelectedAccount extends Component { state = { @@ -22,6 +22,7 @@ class SelectedAccount extends Component { render () { const { t } = this.context const { selectedAddress, selectedIdentity } = this.props + const checksummedAddress = checksumAddress(selectedAddress) return (
@@ -34,14 +35,14 @@ class SelectedAccount extends Component { onClick={() => { this.setState({ copied: true }) setTimeout(() => this.setState({ copied: false }), 3000) - copyToClipboard(selectedAddress) + copyToClipboard(checksummedAddress) }} >
{ selectedIdentity.name }
- { addressSlicer(selectedAddress) } + { addressSlicer(checksummedAddress) }
diff --git a/ui/app/components/selected-account/tests/selected-account-component.test.js b/ui/app/components/selected-account/tests/selected-account-component.test.js new file mode 100644 index 000000000..78a94d1c8 --- /dev/null +++ b/ui/app/components/selected-account/tests/selected-account-component.test.js @@ -0,0 +1,16 @@ +import React from 'react' +import assert from 'assert' +import { render } from 'enzyme' +import SelectedAccount from '../selected-account.component' + +describe('SelectedAccount Component', () => { + it('should render checksummed address', () => { + const wrapper = render(, { context: { t: () => {}}}) + // Checksummed version of address is displayed + assert.equal(wrapper.find('.selected-account__address').text(), '0x1B82...5C9D') + assert.equal(wrapper.find('.selected-account__name').text(), 'testName') + }) +}) diff --git a/ui/app/components/send/send-content/send-content.component.js b/ui/app/components/send/send-content/send-content.component.js index df7bcb7cc..9e0ce9c23 100644 --- a/ui/app/components/send/send-content/send-content.component.js +++ b/ui/app/components/send/send-content/send-content.component.js @@ -12,6 +12,7 @@ export default class SendContent extends Component { static propTypes = { updateGas: PropTypes.func, scanQrCode: PropTypes.func, + showHexData: PropTypes.bool, }; render () { @@ -25,7 +26,7 @@ export default class SendContent extends Component { /> this.props.updateGas(updateData)} /> - + { this.props.showHexData ? : null }
) diff --git a/ui/app/components/send/send-content/send-to-row/send-to-row.component.js b/ui/app/components/send/send-content/send-to-row/send-to-row.component.js index 1163dcffc..434db81e5 100644 --- a/ui/app/components/send/send-content/send-to-row/send-to-row.component.js +++ b/ui/app/components/send/send-content/send-to-row/send-to-row.component.js @@ -48,7 +48,7 @@ export default class SendToRow extends Component { return ( { - wrapper = shallow() + wrapper = shallow() }) describe('render', () => { @@ -33,6 +34,17 @@ describe('SendContent Component', function () { assert(PageContainerContentChild.childAt(1).is(SendToRow)) assert(PageContainerContentChild.childAt(2).is(SendAmountRow)) assert(PageContainerContentChild.childAt(3).is(SendGasRow)) + assert(PageContainerContentChild.childAt(4).is(SendHexDataRow)) + }) + + it('should not render the SendHexDataRow if props.showHexData is false', () => { + wrapper.setProps({ showHexData: false }) + const PageContainerContentChild = wrapper.find(PageContainerContent).children() + assert(PageContainerContentChild.childAt(0).is(SendFromRow)) + assert(PageContainerContentChild.childAt(1).is(SendToRow)) + assert(PageContainerContentChild.childAt(2).is(SendAmountRow)) + assert(PageContainerContentChild.childAt(3).is(SendGasRow)) + assert.equal(PageContainerContentChild.childAt(4).exists(), false) }) }) }) diff --git a/ui/app/components/send/send.component.js b/ui/app/components/send/send.component.js index 0d8ffd179..0dc973632 100644 --- a/ui/app/components/send/send.component.js +++ b/ui/app/components/send/send.component.js @@ -193,7 +193,7 @@ export default class SendTransactionScreen extends PersistentForm { } render () { - const { history } = this.props + const { history, showHexData } = this.props return (
@@ -201,6 +201,7 @@ export default class SendTransactionScreen extends PersistentForm { this.updateGas(updateData)} scanQrCode={_ => this.props.scanQrCode()} + showHexData={showHexData} />
diff --git a/ui/app/components/send/send.container.js b/ui/app/components/send/send.container.js index 41735de64..6ee8de9aa 100644 --- a/ui/app/components/send/send.container.js +++ b/ui/app/components/send/send.container.js @@ -18,6 +18,7 @@ import { getSelectedTokenToFiatRate, getSendAmount, getSendEditingTransactionId, + getSendHexDataFeatureFlagState, getSendFromObject, getSendTo, getTokenBalance, @@ -64,6 +65,7 @@ function mapStateToProps (state) { recentBlocks: getRecentBlocks(state), selectedAddress: getSelectedAddress(state), selectedToken: getSelectedToken(state), + showHexData: getSendHexDataFeatureFlagState(state), to: getSendTo(state), tokenBalance: getTokenBalance(state), tokenContract: getSelectedTokenContract(state), diff --git a/ui/app/components/send/send.selectors.js b/ui/app/components/send/send.selectors.js index ab3f6d34b..22e379693 100644 --- a/ui/app/components/send/send.selectors.js +++ b/ui/app/components/send/send.selectors.js @@ -34,6 +34,7 @@ const selectors = { getSelectedTokenToFiatRate, getSendAmount, getSendHexData, + getSendHexDataFeatureFlagState, getSendEditingTransactionId, getSendErrors, getSendFrom, @@ -216,6 +217,10 @@ function getSendHexData (state) { return state.metamask.send.data } +function getSendHexDataFeatureFlagState (state) { + return state.metamask.featureFlags.sendHexData +} + function getSendEditingTransactionId (state) { return state.metamask.send.editingTransactionId } diff --git a/ui/app/components/send/tests/send-component.test.js b/ui/app/components/send/tests/send-component.test.js index 6194ec508..d2c2ee926 100644 --- a/ui/app/components/send/tests/send-component.test.js +++ b/ui/app/components/send/tests/send-component.test.js @@ -47,6 +47,7 @@ describe('Send Component', function () { recentBlocks={['mockBlock']} selectedAddress={'mockSelectedAddress'} selectedToken={'mockSelectedToken'} + showHexData={true} tokenBalance={'mockTokenBalance'} tokenContract={'mockTokenContract'} updateAndSetGasTotal={propsMethodSpies.updateAndSetGasTotal} @@ -328,5 +329,9 @@ describe('Send Component', function () { } ) }) + + it('should pass showHexData to SendContent', () => { + assert.equal(wrapper.find(SendContent).props().showHexData, true) + }) }) }) diff --git a/ui/app/components/send/tests/send-container.test.js b/ui/app/components/send/tests/send-container.test.js index 57e332780..85eec6a53 100644 --- a/ui/app/components/send/tests/send-container.test.js +++ b/ui/app/components/send/tests/send-container.test.js @@ -39,6 +39,7 @@ proxyquire('../send.container.js', { getSelectedToken: (s) => `mockSelectedToken:${s}`, getSelectedTokenContract: (s) => `mockTokenContract:${s}`, getSelectedTokenToFiatRate: (s) => `mockTokenToFiatRate:${s}`, + getSendHexDataFeatureFlagState: (s) => `mockSendHexDataFeatureFlagState:${s}`, getSendAmount: (s) => `mockAmount:${s}`, getSendTo: (s) => `mockTo:${s}`, getSendEditingTransactionId: (s) => `mockEditingTransactionId:${s}`, @@ -73,6 +74,7 @@ describe('send container', () => { recentBlocks: 'mockRecentBlocks:mockState', selectedAddress: 'mockSelectedAddress:mockState', selectedToken: 'mockSelectedToken:mockState', + showHexData: 'mockSendHexDataFeatureFlagState:mockState', to: 'mockTo:mockState', tokenBalance: 'mockTokenBalance:mockState', tokenContract: 'mockTokenContract:mockState', diff --git a/ui/app/components/send/tests/send-selectors-test-data.js b/ui/app/components/send/tests/send-selectors-test-data.js index 8f9c19314..8b939dadb 100644 --- a/ui/app/components/send/tests/send-selectors-test-data.js +++ b/ui/app/components/send/tests/send-selectors-test-data.js @@ -2,7 +2,7 @@ module.exports = { 'metamask': { 'isInitialized': true, 'isUnlocked': true, - 'featureFlags': {'betaUI': true}, + 'featureFlags': {'betaUI': true, 'sendHexData': true}, 'rpcTarget': 'https://rawtestrpc.metamask.io/', 'identities': { '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825': { diff --git a/ui/app/components/send/tests/send-selectors.test.js b/ui/app/components/send/tests/send-selectors.test.js index 218da656b..1a47cd209 100644 --- a/ui/app/components/send/tests/send-selectors.test.js +++ b/ui/app/components/send/tests/send-selectors.test.js @@ -31,6 +31,7 @@ const { getSendFrom, getSendFromBalance, getSendFromObject, + getSendHexDataFeatureFlagState, getSendMaxModeState, getSendTo, getSendToAccounts, @@ -379,6 +380,15 @@ describe('send selectors', () => { }) }) + describe('getSendHexDataFeatureFlagState()', () => { + it('should return the sendHexData feature flag state', () => { + assert.deepEqual( + getSendHexDataFeatureFlagState(mockState), + true + ) + }) + }) + describe('getSendFrom()', () => { it('should return the send.from', () => { assert.deepEqual( diff --git a/ui/app/components/sender-to-recipient/index.scss b/ui/app/components/sender-to-recipient/index.scss index a97393b8f..0ab0413be 100644 --- a/ui/app/components/sender-to-recipient/index.scss +++ b/ui/app/components/sender-to-recipient/index.scss @@ -1,5 +1,5 @@ .sender-to-recipient { - &__container { + &--default { width: 100%; display: flex; flex-direction: row; @@ -8,67 +8,113 @@ position: relative; flex: 0 0 auto; height: 42px; - } - &__tooltip-wrapper { - min-width: 0; - } + .sender-to-recipient { + &__tooltip-wrapper { + min-width: 0; + } - &__tooltip-container { - max-width: 100%; - } + &__tooltip-container { + max-width: 100%; + } - &__sender, - &__recipient { - display: flex; - flex-direction: row; - align-items: center; - flex: 1; - padding: 0 16px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } + &__party { + display: flex; + flex-direction: row; + align-items: center; + flex: 1; + padding: 0 16px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; - &__sender { - padding-right: 30px; - cursor: pointer; - } + &--sender { + padding-right: 30px; + cursor: pointer; + } - &__recipient { - padding-left: 30px; - border-left: 1px solid $geyser; + &--recipient { + padding-left: 30px; + border-left: 1px solid $geyser; - &--with-address { - cursor: pointer; + &-with-address { + cursor: pointer; + } + } + } + + &__arrow-container { + position: absolute; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + } + + &__arrow-circle { + background: $white; + padding: 5px; + border: 1px solid $geyser; + border-radius: 20px; + height: 32px; + width: 32px; + display: flex; + justify-content: center; + align-items: center; + } + + &__name { + padding-left: 14px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: .875rem; + } } } - &__arrow-container { - position: absolute; - height: 100%; + &--cards { + width: 100%; display: flex; - align-items: center; + flex-direction: row; justify-content: center; - } + position: relative; + flex: 0 0 auto; - &__arrow-circle { - background: $white; - padding: 5px; - border: 1px solid $geyser; - border-radius: 20px; - height: 32px; - width: 32px; - display: flex; - justify-content: center; - align-items: center; - } + .sender-to-recipient { + &__party { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + flex: 1; + border-radius: 4px; + box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08); + padding: 6px; + background: $white; + cursor: pointer; + min-width: 0; + color: $dusty-gray; + } - &__name { - padding-left: 14px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-size: .875rem; + &__tooltip-wrapper { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + &__name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: .5rem; + } + + &__arrow-container { + display: flex; + justify-content: center; + align-items: center; + } + } } } diff --git a/ui/app/components/sender-to-recipient/sender-to-recipient.component.js b/ui/app/components/sender-to-recipient/sender-to-recipient.component.js index cae173b56..61f77224d 100644 --- a/ui/app/components/sender-to-recipient/sender-to-recipient.component.js +++ b/ui/app/components/sender-to-recipient/sender-to-recipient.component.js @@ -1,16 +1,30 @@ -import React, { Component } from 'react' +import React, { PureComponent } from 'react' import PropTypes from 'prop-types' +import classnames from 'classnames' import Identicon from '../identicon' import Tooltip from '../tooltip-v2' import copyToClipboard from 'copy-to-clipboard' +import { DEFAULT_VARIANT, CARDS_VARIANT } from './sender-to-recipient.constants' -export default class SenderToRecipient extends Component { +const variantHash = { + [DEFAULT_VARIANT]: 'sender-to-recipient--default', + [CARDS_VARIANT]: 'sender-to-recipient--cards', +} + +export default class SenderToRecipient extends PureComponent { static propTypes = { senderName: PropTypes.string, senderAddress: PropTypes.string, recipientName: PropTypes.string, recipientAddress: PropTypes.string, t: PropTypes.func, + variant: PropTypes.oneOf([DEFAULT_VARIANT, CARDS_VARIANT]), + addressOnly: PropTypes.bool, + assetImage: PropTypes.string, + } + + static defaultProps = { + variant: DEFAULT_VARIANT, } static contextTypes = { @@ -22,24 +36,63 @@ export default class SenderToRecipient extends Component { recipientAddressCopied: false, } + renderSenderIdenticon () { + return !this.props.addressOnly && ( +
+ +
+ ) + } + + renderSenderAddress () { + const { t } = this.context + const { senderName, senderAddress, addressOnly } = this.props + + return ( + this.setState({ senderAddressCopied: false })} + > +
+ { addressOnly ? `${t('from')}: ${senderAddress}` : senderName } +
+
+ ) + } + + renderRecipientIdenticon () { + const { recipientAddress, assetImage } = this.props + + return !this.props.addressOnly && ( +
+ +
+ ) + } + renderRecipientWithAddress () { const { t } = this.context - const { recipientName, recipientAddress } = this.props + const { recipientName, recipientAddress, addressOnly } = this.props return (
{ this.setState({ recipientAddressCopied: true }) copyToClipboard(recipientAddress) }} > -
- -
+ { this.renderRecipientIdenticon() } this.setState({ recipientAddressCopied: false })} > -
- { recipientName || this.context.t('newContract') } +
+ { + addressOnly + ? `${t('to')}: ${recipientAddress}` + : (recipientName || this.context.t('newContract')) + }
@@ -57,46 +114,25 @@ export default class SenderToRecipient extends Component { renderRecipientWithoutAddress () { return ( -
- -
+
+ { !this.props.addressOnly && } +
{ this.context.t('newContract') }
) } - render () { - const { t } = this.context - const { senderName, senderAddress, recipientAddress } = this.props - - return ( -
-
{ - this.setState({ senderAddressCopied: true }) - copyToClipboard(senderAddress) - }} - > -
- -
- this.setState({ senderAddressCopied: false })} - > -
- { senderName } -
-
+ renderArrow () { + return this.props.variant === CARDS_VARIANT + ? ( +
+
+ ) : (
+ ) + } + + render () { + const { senderAddress, recipientAddress, variant } = this.props + + return ( +
+
{ + this.setState({ senderAddressCopied: true }) + copyToClipboard(senderAddress) + }} + > + { this.renderSenderIdenticon() } + { this.renderSenderAddress() } +
+ { this.renderArrow() } { recipientAddress ? this.renderRecipientWithAddress() diff --git a/ui/app/components/sender-to-recipient/sender-to-recipient.constants.js b/ui/app/components/sender-to-recipient/sender-to-recipient.constants.js new file mode 100644 index 000000000..166228932 --- /dev/null +++ b/ui/app/components/sender-to-recipient/sender-to-recipient.constants.js @@ -0,0 +1,3 @@ +// Component design variants +export const DEFAULT_VARIANT = 'DEFAULT_VARIANT' +export const CARDS_VARIANT = 'CARDS_VARIANT' diff --git a/ui/app/components/shapeshift-form.js b/ui/app/components/shapeshift-form.js index 4ac54525d..13e1e28e2 100644 --- a/ui/app/components/shapeshift-form.js +++ b/ui/app/components/shapeshift-form.js @@ -9,6 +9,8 @@ const { shapeShiftSubview, pairUpdate, buyWithShapeShift } = require('../actions const { isValidAddress } = require('../util') const SimpleDropdown = require('./dropdowns/simple-dropdown') +import Button from './button' + function mapStateToProps (state) { const { coinOptions, @@ -242,8 +244,10 @@ ShapeshiftForm.prototype.render = function () { ]), - !depositAddress && h('button.btn-primary.btn--large.shapeshift-form__shapeshift-buy-btn', { - className: btnClass, + !depositAddress && h(Button, { + type: 'primary', + large: true, + className: `${btnClass} shapeshift-form__shapeshift-buy-btn`, disabled: !token, onClick: () => this.onBuyWithShapeShift(), }, [this.context.t('buy')]), diff --git a/ui/app/components/shift-list-item.js b/ui/app/components/shift-list-item.js index 395c1e217..7fecdf192 100644 --- a/ui/app/components/shift-list-item.js +++ b/ui/app/components/shift-list-item.js @@ -35,12 +35,13 @@ function ShiftListItem () { } ShiftListItem.prototype.render = function () { - return h('div.tx-list-item.tx-list-clickable', { + return h('div.transaction-list-item.tx-list-clickable', { style: { paddingTop: '20px', paddingBottom: '20px', justifyContent: 'space-around', alignItems: 'center', + flexDirection: 'row', }, }, [ h('div', { diff --git a/ui/app/components/sidebars/index.js b/ui/app/components/sidebars/index.js new file mode 100644 index 000000000..732925f69 --- /dev/null +++ b/ui/app/components/sidebars/index.js @@ -0,0 +1 @@ +export { default } from './sidebar.component' diff --git a/ui/app/components/sidebars/index.scss b/ui/app/components/sidebars/index.scss new file mode 100644 index 000000000..5ab0664df --- /dev/null +++ b/ui/app/components/sidebars/index.scss @@ -0,0 +1,74 @@ +.sidebar-right-enter { + transition: transform 300ms ease-in-out; + transform: translateX(-100%); +} + +.sidebar-right-enter.sidebar-right-enter-active { + transition: transform 300ms ease-in-out; + transform: translateX(0%); +} + +.sidebar-right-leave { + transition: transform 200ms ease-out; + transform: translateX(0%); +} + +.sidebar-right-leave.sidebar-right-leave-active { + transition: transform 200ms ease-out; + transform: translateX(-100%); +} + +.sidebar-left-enter { + transition: transform 300ms ease-in-out; + transform: translateX(100%); +} + +.sidebar-left-enter.sidebar-left-enter-active { + transition: transform 300ms ease-in-out; + transform: translateX(0%); +} + +.sidebar-left-leave { + transition: transform 200ms ease-out; + transform: translateX(0%); +} + +.sidebar-left-leave.sidebar-left-leave-active { + transition: transform 200ms ease-out; + transform: translateX(100%); +} + +.sidebar-left { + flex: 1 0 230px; + background: rgb(250, 250, 250); + z-index: $sidebar-z-index; + position: fixed; + left: 15%; + right: 0; + bottom: 0; + opacity: 1; + visibility: visible; + will-change: transform; + overflow-y: auto; + box-shadow: rgba(0, 0, 0, .15) 2px 2px 4px; + width: 85%; + height: 100%; + + @media screen and (min-width: 769px) { + width: 408px; + left: calc(100% - 408px); + } +} + +.sidebar-overlay { + z-index: $sidebar-overlay-z-index; + position: fixed; + height: 100%; + width: 100%; + left: 0; + right: 0; + bottom: 0; + opacity: 1; + visibility: visible; + background-color: rgba(0, 0, 0, .3); +} \ No newline at end of file diff --git a/ui/app/components/sidebars/sidebar.component.js b/ui/app/components/sidebars/sidebar.component.js new file mode 100644 index 000000000..57cdd7111 --- /dev/null +++ b/ui/app/components/sidebars/sidebar.component.js @@ -0,0 +1,49 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import ReactCSSTransitionGroup from 'react-addons-css-transition-group' +import WalletView from '../wallet-view' +import { WALLET_VIEW_SIDEBAR } from './sidebar.constants' + +export default class Sidebar extends Component { + + static propTypes = { + sidebarOpen: PropTypes.bool, + hideSidebar: PropTypes.func, + transitionName: PropTypes.string, + type: PropTypes.string, + }; + + renderOverlay () { + return
this.props.hideSidebar()} /> + } + + renderSidebarContent () { + const { type } = this.props + + switch (type) { + case WALLET_VIEW_SIDEBAR: + return + default: + return null + } + + } + + render () { + const { transitionName, sidebarOpen } = this.props + + return ( +
+ + { sidebarOpen ? this.renderSidebarContent() : null } + + { sidebarOpen ? this.renderOverlay() : null } +
+ ) + } + +} diff --git a/ui/app/components/sidebars/sidebar.constants.js b/ui/app/components/sidebars/sidebar.constants.js new file mode 100644 index 000000000..1613a8245 --- /dev/null +++ b/ui/app/components/sidebars/sidebar.constants.js @@ -0,0 +1 @@ +export const WALLET_VIEW_SIDEBAR = 'wallet-view' diff --git a/ui/app/components/sidebars/tests/sidebars-component.test.js b/ui/app/components/sidebars/tests/sidebars-component.test.js new file mode 100644 index 000000000..e2d77518a --- /dev/null +++ b/ui/app/components/sidebars/tests/sidebars-component.test.js @@ -0,0 +1,88 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import sinon from 'sinon' +import ReactCSSTransitionGroup from 'react-addons-css-transition-group' +import Sidebar from '../sidebar.component.js' + +import WalletView from '../../wallet-view' + +const propsMethodSpies = { + hideSidebar: sinon.spy(), +} + +describe('Sidebar Component', function () { + let wrapper + + beforeEach(() => { + wrapper = shallow() + }) + + afterEach(() => { + propsMethodSpies.hideSidebar.resetHistory() + }) + + describe('renderOverlay', () => { + let renderOverlay + + beforeEach(() => { + renderOverlay = shallow(wrapper.instance().renderOverlay()) + }) + + it('should render a overlay element', () => { + assert(renderOverlay.hasClass('sidebar-overlay')) + }) + + it('should pass the correct onClick function to the element', () => { + assert.equal(propsMethodSpies.hideSidebar.callCount, 0) + renderOverlay.props().onClick() + assert.equal(propsMethodSpies.hideSidebar.callCount, 1) + }) + }) + + describe('renderSidebarContent', () => { + let renderSidebarContent + + beforeEach(() => { + wrapper.setProps({ type: 'wallet-view' }) + renderSidebarContent = wrapper.instance().renderSidebarContent() + }) + + it('should render sidebar content with the correct props', () => { + wrapper.setProps({ type: 'wallet-view' }) + renderSidebarContent = wrapper.instance().renderSidebarContent() + assert.equal(renderSidebarContent.props.responsiveDisplayClassname, 'sidebar-right') + }) + + it('should not render with an unrecognized type', () => { + wrapper.setProps({ type: 'foobar' }) + renderSidebarContent = wrapper.instance().renderSidebarContent() + assert.equal(renderSidebarContent, undefined) + }) + }) + + describe('render', () => { + it('should render a div with one child', () => { + assert(wrapper.is('div')) + assert.equal(wrapper.children().length, 1) + }) + + it('should render the ReactCSSTransitionGroup without any children', () => { + assert(wrapper.children().at(0).is(ReactCSSTransitionGroup)) + assert.equal(wrapper.children().at(0).children().length, 0) + }) + + it('should render sidebar content and the overlay if sidebarOpen is true', () => { + wrapper.setProps({ sidebarOpen: true }) + assert.equal(wrapper.children().length, 2) + assert(wrapper.children().at(1).hasClass('sidebar-overlay')) + assert.equal(wrapper.children().at(0).children().length, 1) + assert(wrapper.children().at(0).children().at(0).is(WalletView)) + }) + }) +}) diff --git a/ui/app/components/signature-request.js b/ui/app/components/signature-request.js index 2e0102d1a..5b0c7684a 100644 --- a/ui/app/components/signature-request.js +++ b/ui/app/components/signature-request.js @@ -8,6 +8,7 @@ const ethUtil = require('ethereumjs-util') const classnames = require('classnames') const { compose } = require('recompose') const { withRouter } = require('react-router-dom') +const { ObjectInspector } = require('react-inspector') const AccountDropdownMini = require('./dropdowns/account-dropdown-mini') @@ -23,6 +24,7 @@ const { } = require('../selectors.js') import { clearConfirmTransaction } from '../ducks/confirm-transaction.duck' +import Button from './button' const { DEFAULT_ROUTE } = require('../routes') @@ -168,12 +170,29 @@ SignatureRequest.prototype.msgHexToText = function (hex) { } } +// eslint-disable-next-line react/display-name +SignatureRequest.prototype.renderTypedDataV3 = function (data) { + const { domain, message } = JSON.parse(data) + return [ + h('div.request-signature__typed-container', [ + domain ? h('div', [ + h('h1', 'Domain'), + h(ObjectInspector, { data: domain, expandLevel: 1, name: 'domain' }), + ]) : '', + message ? h('div', [ + h('h1', 'Message'), + h(ObjectInspector, { data: message, expandLevel: 1, name: 'message' }), + ]) : '', + ]), + ] +} + SignatureRequest.prototype.renderBody = function () { let rows let notice = this.context.t('youSign') + ':' const { txData } = this.props - const { type, msgParams: { data } } = txData + const { type, msgParams: { data, version } } = txData if (type === 'personal_sign') { rows = [{ name: this.context.t('message'), value: this.msgHexToText(data) }] @@ -204,9 +223,9 @@ SignatureRequest.prototype.renderBody = function () { }), }, [notice]), - h('div.request-signature__rows', [ - - ...rows.map(({ name, value }) => { + h('div.request-signature__rows', type === 'eth_signTypedData' && version === 'V3' ? + this.renderTypedDataV3(data) : + rows.map(({ name, value }) => { if (typeof value === 'boolean') { value = value.toString() } @@ -215,9 +234,7 @@ SignatureRequest.prototype.renderBody = function () { h('div.request-signature__row-value', value), ]) }), - - ]), - + ), ]) } @@ -248,7 +265,10 @@ SignatureRequest.prototype.renderFooter = function () { } return h('div.request-signature__footer', [ - h('button.btn-default.btn--large.request-signature__footer__cancel-button', { + h(Button, { + type: 'default', + large: true, + className: 'request-signature__footer__cancel-button', onClick: event => { cancel(event).then(() => { this.props.clearConfirmTransaction() @@ -256,7 +276,9 @@ SignatureRequest.prototype.renderFooter = function () { }) }, }, this.context.t('cancel')), - h('button.btn-primary.btn--large', { + h(Button, { + type: 'primary', + large: true, onClick: event => { sign(event).then(() => { this.props.clearConfirmTransaction() diff --git a/ui/app/components/tabs/tab/tab.component.js b/ui/app/components/tabs/tab/tab.component.js index a59da8904..9e590391c 100644 --- a/ui/app/components/tabs/tab/tab.component.js +++ b/ui/app/components/tabs/tab/tab.component.js @@ -3,13 +3,13 @@ import PropTypes from 'prop-types' import classnames from 'classnames' const Tab = props => { - const { name, onClick, isActive, tabIndex } = props + const { name, onClick, isActive, tabIndex, className, activeClassName } = props return (
  • { event.preventDefault() @@ -26,6 +26,13 @@ Tab.propTypes = { onClick: PropTypes.func, isActive: PropTypes.bool, tabIndex: PropTypes.number, + className: PropTypes.string, + activeClassName: PropTypes.string, +} + +Tab.defaultProps = { + className: 'tab', + activeClassName: 'tab--active', } export default Tab diff --git a/ui/app/components/token-balance.js b/ui/app/components/token-balance.js deleted file mode 100644 index 7498f403c..000000000 --- a/ui/app/components/token-balance.js +++ /dev/null @@ -1,120 +0,0 @@ -const Component = require('react').Component -const h = require('react-hyperscript') -const inherits = require('util').inherits -const TokenTracker = require('eth-token-watcher') -const connect = require('react-redux').connect -const selectors = require('../selectors') -const log = require('loglevel') - -function mapStateToProps (state) { - return { - userAddress: selectors.getSelectedAddress(state), - } -} - -module.exports = connect(mapStateToProps)(TokenBalance) - - -inherits(TokenBalance, Component) -function TokenBalance () { - this.state = { - string: '', - symbol: '', - isLoading: true, - error: null, - } - Component.call(this) -} - -TokenBalance.prototype.render = function () { - const state = this.state - const { symbol, string, isLoading } = state - const { balanceOnly } = this.props - - return isLoading - ? h('span', '') - : h('span.token-balance', [ - h('span.hide-text-overflow.token-balance__amount', string), - !balanceOnly && h('span.token-balance__symbol', symbol), - ]) -} - -TokenBalance.prototype.componentDidMount = function () { - this.createFreshTokenTracker() -} - -TokenBalance.prototype.createFreshTokenTracker = function () { - if (this.tracker) { - // Clean up old trackers when refreshing: - this.tracker.stop() - this.tracker.removeListener('update', this.balanceUpdater) - this.tracker.removeListener('error', this.showError) - } - - if (!global.ethereumProvider) return - const { userAddress, token } = this.props - - this.tracker = new TokenTracker({ - userAddress, - provider: global.ethereumProvider, - tokens: [token], - pollingInterval: 8000, - }) - - - // Set up listener instances for cleaning up - this.balanceUpdater = this.updateBalance.bind(this) - this.showError = error => { - this.setState({ error, isLoading: false }) - } - this.tracker.on('update', this.balanceUpdater) - this.tracker.on('error', this.showError) - - this.tracker.updateBalances() - .then(() => { - this.updateBalance(this.tracker.serialize()) - }) - .catch((reason) => { - log.error(`Problem updating balances`, reason) - this.setState({ isLoading: false }) - }) -} - -TokenBalance.prototype.componentDidUpdate = function (nextProps) { - const { - userAddress: oldAddress, - token: { address: oldTokenAddress }, - } = this.props - const { - userAddress: newAddress, - token: { address: newTokenAddress }, - } = nextProps - - if ((!oldAddress || !newAddress) && (!oldTokenAddress || !newTokenAddress)) return - if ((oldAddress === newAddress) && (oldTokenAddress === newTokenAddress)) return - - this.setState({ isLoading: true }) - this.createFreshTokenTracker() -} - -TokenBalance.prototype.updateBalance = function (tokens = []) { - if (!this.tracker.running) { - return - } - - const [{ string, symbol }] = tokens - - this.setState({ - string, - symbol, - isLoading: false, - }) -} - -TokenBalance.prototype.componentWillUnmount = function () { - if (!this.tracker) return - this.tracker.stop() - this.tracker.removeListener('update', this.balanceUpdater) - this.tracker.removeListener('error', this.showError) -} - diff --git a/ui/app/components/token-balance/index.js b/ui/app/components/token-balance/index.js new file mode 100644 index 000000000..f7da15cf8 --- /dev/null +++ b/ui/app/components/token-balance/index.js @@ -0,0 +1 @@ +export { default } from './token-balance.container' diff --git a/ui/app/components/token-balance/token-balance.component.js b/ui/app/components/token-balance/token-balance.component.js new file mode 100644 index 000000000..2b4f73980 --- /dev/null +++ b/ui/app/components/token-balance/token-balance.component.js @@ -0,0 +1,23 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import classnames from 'classnames' + +export default class TokenBalance extends PureComponent { + static propTypes = { + string: PropTypes.string, + symbol: PropTypes.string, + error: PropTypes.string, + className: PropTypes.string, + withSymbol: PropTypes.bool, + } + + render () { + const { className, string, withSymbol, symbol } = this.props + + return ( +
    + { string + (withSymbol ? ` ${symbol}` : '') } +
    + ) + } +} diff --git a/ui/app/components/pages/confirm-add-token/token-balance/token-balance.container.js b/ui/app/components/token-balance/token-balance.container.js similarity index 72% rename from ui/app/components/pages/confirm-add-token/token-balance/token-balance.container.js rename to ui/app/components/token-balance/token-balance.container.js index bc1289ce1..adc001f83 100644 --- a/ui/app/components/pages/confirm-add-token/token-balance/token-balance.container.js +++ b/ui/app/components/token-balance/token-balance.container.js @@ -1,8 +1,8 @@ import { connect } from 'react-redux' import { compose } from 'recompose' -import withTokenTracker from '../../../../helpers/with-token-tracker' +import withTokenTracker from '../../higher-order-components/with-token-tracker' import TokenBalance from './token-balance.component' -import selectors from '../../../../selectors' +import selectors from '../../selectors' const mapStateToProps = state => { return { diff --git a/ui/app/components/token-cell.js b/ui/app/components/token-cell.js index f42af7868..edf8b2661 100644 --- a/ui/app/components/token-cell.js +++ b/ui/app/components/token-cell.js @@ -18,7 +18,7 @@ function mapStateToProps (state) { userAddress: selectors.getSelectedAddress(state), contractExchangeRates: state.metamask.contractExchangeRates, conversionRate: state.metamask.conversionRate, - sidebarOpen: state.appState.sidebarOpen, + sidebarOpen: state.appState.sidebar.isOpen, } } @@ -56,8 +56,8 @@ TokenCell.prototype.render = function () { sidebarOpen, currentCurrency, // userAddress, + image, } = props - let currentTokenToFiatRate let currentTokenInFiat let formattedFiat = '' @@ -97,6 +97,7 @@ TokenCell.prototype.render = function () { diameter: 50, address, network, + image, }), h('div.token-list-item__balance-ellipsis', null, [ diff --git a/ui/app/components/token-currency-display/index.js b/ui/app/components/token-currency-display/index.js new file mode 100644 index 000000000..6065cae1f --- /dev/null +++ b/ui/app/components/token-currency-display/index.js @@ -0,0 +1 @@ +export { default } from './token-currency-display.component' diff --git a/ui/app/components/token-currency-display/token-currency-display.component.js b/ui/app/components/token-currency-display/token-currency-display.component.js new file mode 100644 index 000000000..957aec376 --- /dev/null +++ b/ui/app/components/token-currency-display/token-currency-display.component.js @@ -0,0 +1,54 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import CurrencyDisplay from '../currency-display/currency-display.component' +import { getTokenData } from '../../helpers/transactions.util' +import { calcTokenAmount } from '../../token-util' + +export default class TokenCurrencyDisplay extends PureComponent { + static propTypes = { + transactionData: PropTypes.string, + token: PropTypes.object, + } + + state = { + displayValue: '', + } + + componentDidMount () { + this.setDisplayValue() + } + + componentDidUpdate (prevProps) { + const { transactionData } = this.props + const { transactionData: prevTransactionData } = prevProps + + if (transactionData !== prevTransactionData) { + this.setDisplayValue() + } + } + + setDisplayValue () { + const { transactionData: data, token } = this.props + const { decimals = '', symbol = '' } = token + const tokenData = getTokenData(data) + + let displayValue + + if (tokenData.params && tokenData.params.length === 2) { + const tokenValue = tokenData.params[1].value + const tokenAmount = calcTokenAmount(tokenValue, decimals) + displayValue = `${tokenAmount} ${symbol}` + } + + this.setState({ displayValue }) + } + + render () { + return ( + + ) + } +} diff --git a/ui/app/components/token-list.js b/ui/app/components/token-list.js index 522fbeaf2..5b5976e27 100644 --- a/ui/app/components/token-list.js +++ b/ui/app/components/token-list.js @@ -13,6 +13,7 @@ function mapStateToProps (state) { network: state.metamask.network, tokens: state.metamask.tokens, userAddress: selectors.getSelectedAddress(state), + assetImages: state.metamask.assetImages, } } @@ -44,10 +45,9 @@ function TokenList () { } TokenList.prototype.render = function () { - const { userAddress } = this.props + const { userAddress, assetImages } = this.props const state = this.state const { tokens, isLoading, error } = state - if (isLoading) { return this.message(this.context.t('loadingTokens')) } @@ -74,7 +74,10 @@ TokenList.prototype.render = function () { ]) } - return h('div', tokens.map((tokenData) => h(TokenCell, tokenData))) + return h('div', tokens.map((tokenData) => { + tokenData.image = assetImages[tokenData.address] + return h(TokenCell, tokenData) + })) } diff --git a/ui/app/components/tooltip-v2.js b/ui/app/components/tooltip-v2.js index 05a5efc80..054782203 100644 --- a/ui/app/components/tooltip-v2.js +++ b/ui/app/components/tooltip-v2.js @@ -1,33 +1,66 @@ -const Component = require('react').Component -const h = require('react-hyperscript') -const inherits = require('util').inherits -const ReactTippy = require('react-tippy').Tooltip +import PropTypes from 'prop-types' +import React, {PureComponent} from 'react' +import {Tooltip as ReactTippy} from 'react-tippy' -module.exports = Tooltip +export default class Tooltip extends PureComponent { + static defaultProps = { + arrow: true, + children: null, + containerClassName: '', + hideOnClick: false, + onHidden: null, + position: 'left', + size: 'small', + title: null, + trigger: 'mouseenter', + wrapperClassName: '', + } -inherits(Tooltip, Component) -function Tooltip () { - Component.call(this) -} - -Tooltip.prototype.render = function () { - const props = this.props - const { position, title, children, wrapperClassName, containerClassName, onHidden } = props - - return h('div', { - className: wrapperClassName, - }, [ - - h(ReactTippy, { - title, - position: position || 'left', - trigger: 'mouseenter', - hideOnClick: false, - size: 'small', - arrow: true, - className: containerClassName, - onHidden, - }, children), - - ]) + static propTypes = { + arrow: PropTypes.bool, + children: PropTypes.node, + containerClassName: PropTypes.string, + onHidden: PropTypes.func, + position: PropTypes.oneOf([ + 'top', + 'right', + 'bottom', + 'left', + ]), + size: PropTypes.oneOf([ + 'small', 'regular', 'big', + ]), + title: PropTypes.string, + trigger: PropTypes.any, + wrapperClassName: PropTypes.string, + } + + render () { + const {arrow, children, containerClassName, position, size, title, trigger, onHidden, wrapperClassName } = this.props + + if (!title) { + return ( +
    + {children} +
    + ) + } + + return ( +
    + + {children} + +
    + ) + } } diff --git a/ui/app/components/transaction-action/index.js b/ui/app/components/transaction-action/index.js new file mode 100644 index 000000000..a6e9097f1 --- /dev/null +++ b/ui/app/components/transaction-action/index.js @@ -0,0 +1 @@ +export { default } from './transaction-action.component' diff --git a/ui/app/components/transaction-action/tests/transaction-action.component.test.js b/ui/app/components/transaction-action/tests/transaction-action.component.test.js new file mode 100644 index 000000000..218792847 --- /dev/null +++ b/ui/app/components/transaction-action/tests/transaction-action.component.test.js @@ -0,0 +1,112 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import sinon from 'sinon' +import TransactionAction from '../transaction-action.component' + +describe('TransactionAction Component', () => { + const tOrDefault = key => key + global.eth = { + getCode: sinon.stub().callsFake(address => { + console.log('CALLED') + const code = address === 'approveAddress' ? 'contract' : '0x' + return Promise.resolve(code) + }), + } + + describe('Outgoing transaction', () => { + it('should render -- when methodData is still fetching', () => { + const methodData = { data: {}, done: false, error: null } + const transaction = { + id: 1, + status: 'confirmed', + submittedTime: 1534045442919, + time: 1534045440641, + txParams: { + from: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0x96', + to: '0x50a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow(, { context: { tOrDefault }}) + + assert.equal(wrapper.find('.transaction-action').length, 1) + assert.equal(wrapper.text(), '--') + }) + + it('should render Sent Ether', () => { + const methodData = { data: {}, done: true, error: null } + const transaction = { + id: 1, + status: 'confirmed', + submittedTime: 1534045442919, + time: 1534045440641, + txParams: { + from: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0x96', + to: 'sentEtherAddress', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow(, { context: { tOrDefault }}) + + assert.equal(wrapper.find('.transaction-action').length, 1) + wrapper.setState({ transactionAction: 'sentEther' }) + assert.equal(wrapper.text(), 'sentEther') + }) + + it('should render Approved', () => { + const methodData = { + data: { + name: 'Approve', + params: [ + { type: 'address' }, + { type: 'uint256' }, + ], + }, + done: true, + error: null, + } + const transaction = { + id: 1, + status: 'confirmed', + submittedTime: 1534045442919, + time: 1534045440641, + txParams: { + from: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0x96', + to: 'approveAddress', + value: '0x2386f26fc10000', + data: '0x095ea7b300000000000000000000000050a9d56c2b8ba9a5c7f2c08c3d26e0499f23a7060000000000000000000000000000000000000000000000000000000000000003', + }, + } + + const wrapper = shallow(, { context: { tOrDefault }}) + + assert.equal(wrapper.find('.transaction-action').length, 1) + wrapper.setState({ transactionAction: 'approve' }) + assert.equal(wrapper.text(), 'approve') + }) + }) +}) diff --git a/ui/app/components/transaction-action/transaction-action.component.js b/ui/app/components/transaction-action/transaction-action.component.js new file mode 100644 index 000000000..81a1e96d0 --- /dev/null +++ b/ui/app/components/transaction-action/transaction-action.component.js @@ -0,0 +1,52 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import { getTransactionActionKey } from '../../helpers/transactions.util' + +export default class TransactionAction extends PureComponent { + static contextTypes = { + tOrDefault: PropTypes.func, + } + + static propTypes = { + className: PropTypes.string, + transaction: PropTypes.object, + methodData: PropTypes.object, + } + + state = { + transactionAction: '', + } + + componentDidMount () { + this.getTransactionAction() + } + + componentDidUpdate () { + this.getTransactionAction() + } + + async getTransactionAction () { + const { transactionAction } = this.state + const { transaction, methodData } = this.props + const { data, done } = methodData + + if (!done || transactionAction) { + return + } + + const actionKey = await getTransactionActionKey(transaction, data) + const action = actionKey && this.context.tOrDefault(actionKey) + this.setState({ transactionAction: action }) + } + + render () { + const { className, methodData: { done } } = this.props + const { transactionAction } = this.state + + return ( +
    + { (done && transactionAction) || '--' } +
    + ) + } +} diff --git a/ui/app/components/transaction-activity-log/index.js b/ui/app/components/transaction-activity-log/index.js new file mode 100644 index 000000000..a33da15a3 --- /dev/null +++ b/ui/app/components/transaction-activity-log/index.js @@ -0,0 +1 @@ +export { default } from './transaction-activity-log.container' diff --git a/ui/app/components/transaction-activity-log/index.scss b/ui/app/components/transaction-activity-log/index.scss new file mode 100644 index 000000000..2324d44b1 --- /dev/null +++ b/ui/app/components/transaction-activity-log/index.scss @@ -0,0 +1,63 @@ +.transaction-activity-log { + &__card { + background: $white; + height: 100%; + } + + &__activities-container { + padding-top: 8px; + } + + &__activity { + padding: 4px 0; + display: flex; + flex-direction: row; + align-items: center; + position: relative; + + &::after { + content: ''; + position: absolute; + left: 0; + top: 0; + height: 100%; + width: 6px; + border-right: 1px solid $scorpion; + } + + &:first-child::after { + height: 50%; + top: 50%; + } + + &:last-child::after { + height: 50%; + } + } + + &__activity-icon { + width: 13px; + height: 13px; + margin-right: 6px; + border-radius: 50%; + background: $scorpion; + flex: 0 0 auto; + } + + &__activity-text { + color: $scorpion; + font-size: .75rem; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + &__value { + display: inline; + font-weight: 500; + } + + b { + font-weight: 500; + } +} diff --git a/ui/app/components/transaction-activity-log/tests/transaction-activity-log.component.test.js b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.component.test.js new file mode 100644 index 000000000..8687dbbc7 --- /dev/null +++ b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.component.test.js @@ -0,0 +1,35 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import TransactionActivityLog from '../transaction-activity-log.component' +import Card from '../../card' + +describe('TransactionActivityLog Component', () => { + it('should render properly', () => { + const transaction = { + history: [], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow( + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-activity-log')) + assert.ok(wrapper.hasClass('test-class')) + assert.equal(wrapper.find(Card).length, 1) + }) +}) diff --git a/ui/app/components/transaction-activity-log/tests/transaction-activity-log.container.test.js b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.container.test.js new file mode 100644 index 000000000..85d56a6a2 --- /dev/null +++ b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.container.test.js @@ -0,0 +1,27 @@ +import assert from 'assert' +import proxyquire from 'proxyquire' + +let mapStateToProps + +proxyquire('../transaction-activity-log.container.js', { + 'react-redux': { + connect: ms => { + mapStateToProps = ms + return () => ({}) + }, + }, +}) + +describe('TransactionActivityLog container', () => { + describe('mapStateToProps()', () => { + it('should return the correct props', () => { + const mockState = { + metamask: { + conversionRate: 280.45, + }, + } + + assert.deepEqual(mapStateToProps(mockState), { conversionRate: 280.45 }) + }) + }) +}) diff --git a/ui/app/components/transaction-activity-log/tests/transaction-activity-log.util.test.js b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.util.test.js new file mode 100644 index 000000000..586500408 --- /dev/null +++ b/ui/app/components/transaction-activity-log/tests/transaction-activity-log.util.test.js @@ -0,0 +1,208 @@ +import assert from 'assert' +import { getActivities } from '../transaction-activity-log.util' + +describe('getActivities', () => { + it('should return no activities for an empty history', () => { + const transaction = { + history: [], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + assert.deepEqual(getActivities(transaction), []) + }) + + it('should return activities for a transaction\'s history', () => { + const transaction = { + history: [ + { + id: 5559712943815343, + loadingDefaults: true, + metamaskNetworkId: '3', + status: 'unapproved', + time: 1535507561452, + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + }, + [ + { + op: 'replace', + path: '/loadingDefaults', + timestamp: 1535507561515, + value: false, + }, + { + op: 'add', + path: '/gasPriceSpecified', + value: true, + }, + { + op: 'add', + path: '/gasLimitSpecified', + value: true, + }, + { + op: 'add', + path: '/estimatedGas', + value: '0x5208', + }, + ], + [ + { + note: '#newUnapprovedTransaction - adding the origin', + op: 'add', + path: '/origin', + timestamp: 1535507561516, + value: 'MetaMask', + }, + [], + ], + [ + { + note: 'confTx: user approved transaction', + op: 'replace', + path: '/txParams/gasPrice', + timestamp: 1535664571504, + value: '0x77359400', + }, + ], + [ + { + note: 'txStateManager: setting status to approved', + op: 'replace', + path: '/status', + timestamp: 1535507564302, + value: 'approved', + }, + ], + [ + { + note: 'transactions#approveTransaction', + op: 'add', + path: '/txParams/nonce', + timestamp: 1535507564439, + value: '0xa4', + }, + { + op: 'add', + path: '/nonceDetails', + value: { + local: {}, + network: {}, + params: {}, + }, + }, + ], + [ + { + note: 'transactions#publishTransaction', + op: 'replace', + path: '/status', + timestamp: 1535507564518, + value: 'signed', + }, + { + op: 'add', + path: '/rawTx', + value: '0xf86b81a4843b9aca008252089450a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706872386f26fc10000802aa007b30119fc4fc5954fad727895b7e3ba80a78d197e95703cc603bcf017879151a01c50beda40ffaee541da9c05b9616247074f25f392800e0ad6c7a835d5366edf', + }, + ], + [], + [ + { + note: 'transactions#setTxHash', + op: 'add', + path: '/hash', + timestamp: 1535507564658, + value: '0x7acc4987b5c0dfa8d423798a8c561138259de1f98a62e3d52e7e83c0e0dd9fb7', + }, + ], + [ + { + note: 'txStateManager - add submitted time stamp', + op: 'add', + path: '/submittedTime', + timestamp: 1535507564660, + value: 1535507564660, + }, + ], + [ + { + note: 'txStateManager: setting status to submitted', + op: 'replace', + path: '/status', + timestamp: 1535507564665, + value: 'submitted', + }, + ], + [ + { + note: 'transactions/pending-tx-tracker#event: tx:block-update', + op: 'add', + path: '/firstRetryBlockNumber', + timestamp: 1535507575476, + value: '0x3bf624', + }, + ], + [ + { + note: 'txStateManager: setting status to confirmed', + op: 'replace', + path: '/status', + timestamp: 1535507615993, + value: 'confirmed', + }, + ], + ], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + const expectedResult = [ + { + 'eventKey': 'transactionCreated', + 'timestamp': 1535507561452, + 'value': '0x2386f26fc10000', + }, + { + 'eventKey': 'transactionUpdatedGas', + 'timestamp': 1535664571504, + 'value': '0x77359400', + }, + { + 'eventKey': 'transactionSubmitted', + 'timestamp': 1535507564665, + 'value': undefined, + }, + { + 'eventKey': 'transactionConfirmed', + 'timestamp': 1535507615993, + 'value': undefined, + }, + ] + + assert.deepEqual(getActivities(transaction), expectedResult) + }) +}) diff --git a/ui/app/components/transaction-activity-log/transaction-activity-log.component.js b/ui/app/components/transaction-activity-log/transaction-activity-log.component.js new file mode 100644 index 000000000..c4cf57d14 --- /dev/null +++ b/ui/app/components/transaction-activity-log/transaction-activity-log.component.js @@ -0,0 +1,91 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import classnames from 'classnames' +import { getActivities } from './transaction-activity-log.util' +import Card from '../card' +import { getEthConversionFromWeiHex, getValueFromWeiHex } from '../../helpers/conversions.util' +import { ETH } from '../../constants/common' +import { formatDate } from '../../util' + +export default class TransactionActivityLog extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + transaction: PropTypes.object, + className: PropTypes.string, + conversionRate: PropTypes.number, + } + + state = { + activities: [], + } + + componentDidMount () { + this.setActivites() + } + + componentDidUpdate (prevProps) { + const { transaction: { history: prevHistory = [] } = {} } = prevProps + const { transaction: { history = [] } = {} } = this.props + + if (prevHistory.length !== history.length) { + this.setActivites() + } + } + + setActivites () { + const activities = getActivities(this.props.transaction) + this.setState({ activities }) + } + + renderActivity (activity, index) { + const { conversionRate } = this.props + const { eventKey, value, timestamp } = activity + const ethValue = index === 0 + ? `${getValueFromWeiHex({ + value, + toCurrency: ETH, + conversionRate, + numberOfDecimals: 6, + })} ${ETH}` + : getEthConversionFromWeiHex({ value, toCurrency: ETH, conversionRate }) + const formattedTimestamp = formatDate(timestamp) + const activityText = this.context.t(eventKey, [ethValue, formattedTimestamp]) + + return ( +
    +
    +
    + { activityText } +
    +
    + ) + } + + render () { + const { t } = this.context + const { className } = this.props + const { activities } = this.state + + return ( +
    + +
    + { activities.map((activity, index) => this.renderActivity(activity, index)) } +
    +
    +
    + ) + } +} diff --git a/ui/app/components/transaction-activity-log/transaction-activity-log.container.js b/ui/app/components/transaction-activity-log/transaction-activity-log.container.js new file mode 100644 index 000000000..4c8b6d971 --- /dev/null +++ b/ui/app/components/transaction-activity-log/transaction-activity-log.container.js @@ -0,0 +1,11 @@ +import { connect } from 'react-redux' +import TransactionActivityLog from './transaction-activity-log.component' +import { conversionRateSelector } from '../../selectors' + +const mapStateToProps = state => { + return { + conversionRate: conversionRateSelector(state), + } +} + +export default connect(mapStateToProps)(TransactionActivityLog) diff --git a/ui/app/components/transaction-activity-log/transaction-activity-log.util.js b/ui/app/components/transaction-activity-log/transaction-activity-log.util.js new file mode 100644 index 000000000..32834ff47 --- /dev/null +++ b/ui/app/components/transaction-activity-log/transaction-activity-log.util.js @@ -0,0 +1,82 @@ +// path constants +const STATUS_PATH = '/status' +const GAS_PRICE_PATH = '/txParams/gasPrice' + +// status constants +const UNAPPROVED_STATUS = 'unapproved' +const SUBMITTED_STATUS = 'submitted' +const CONFIRMED_STATUS = 'confirmed' +const DROPPED_STATUS = 'dropped' + +// op constants +const REPLACE_OP = 'replace' + +// event constants +const TRANSACTION_CREATED_EVENT = 'transactionCreated' +const TRANSACTION_UPDATED_GAS_EVENT = 'transactionUpdatedGas' +const TRANSACTION_SUBMITTED_EVENT = 'transactionSubmitted' +const TRANSACTION_CONFIRMED_EVENT = 'transactionConfirmed' +const TRANSACTION_DROPPED_EVENT = 'transactionDropped' +const TRANSACTION_UPDATED_EVENT = 'transactionUpdated' + +const eventPathsHash = { + [STATUS_PATH]: true, + [GAS_PRICE_PATH]: true, +} + +const statusHash = { + [SUBMITTED_STATUS]: TRANSACTION_SUBMITTED_EVENT, + [CONFIRMED_STATUS]: TRANSACTION_CONFIRMED_EVENT, + [DROPPED_STATUS]: TRANSACTION_DROPPED_EVENT, +} + +function eventCreator (eventKey, timestamp, value) { + return { + eventKey, + timestamp, + value, + } +} + +export function getActivities (transaction) { + const { history = [] } = transaction + + return history.reduce((acc, base) => { + // First history item should be transaction creation + if (!Array.isArray(base) && base.status === UNAPPROVED_STATUS && base.txParams) { + const { time, txParams: { value } = {} } = base + return acc.concat(eventCreator(TRANSACTION_CREATED_EVENT, time, value)) + } else if (Array.isArray(base)) { + const events = [] + + base.forEach(entry => { + const { op, path, value, timestamp } = entry + + if (path in eventPathsHash && op === REPLACE_OP) { + switch (path) { + case STATUS_PATH: { + if (value in statusHash) { + events.push(eventCreator(statusHash[value], timestamp)) + } + + break + } + + case GAS_PRICE_PATH: { + events.push(eventCreator(TRANSACTION_UPDATED_GAS_EVENT, timestamp, value)) + break + } + + default: { + events.push(eventCreator(TRANSACTION_UPDATED_EVENT, timestamp)) + } + } + } + }) + + return acc.concat(events) + } + + return acc + }, []) +} diff --git a/ui/app/components/transaction-breakdown/index.js b/ui/app/components/transaction-breakdown/index.js new file mode 100644 index 000000000..c887f504f --- /dev/null +++ b/ui/app/components/transaction-breakdown/index.js @@ -0,0 +1 @@ +export { default } from './transaction-breakdown.component' diff --git a/ui/app/components/transaction-breakdown/index.scss b/ui/app/components/transaction-breakdown/index.scss new file mode 100644 index 000000000..1bb108943 --- /dev/null +++ b/ui/app/components/transaction-breakdown/index.scss @@ -0,0 +1,23 @@ +@import './transaction-breakdown-row/index'; + +.transaction-breakdown { + &__card { + background: $white; + height: 100%; + } + + &__row-title { + text-transform: capitalize; + } + + &__value { + text-align: end; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + &--eth-total { + font-weight: 500; + } + } +} diff --git a/ui/app/components/transaction-breakdown/tests/transaction-breakdown.component.test.js b/ui/app/components/transaction-breakdown/tests/transaction-breakdown.component.test.js new file mode 100644 index 000000000..d18cd420c --- /dev/null +++ b/ui/app/components/transaction-breakdown/tests/transaction-breakdown.component.test.js @@ -0,0 +1,37 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import TransactionBreakdown from '../transaction-breakdown.component' +import TransactionBreakdownRow from '../transaction-breakdown-row' +import Card from '../../card' + +describe('TransactionBreakdown Component', () => { + it('should render properly', () => { + const transaction = { + history: [], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow( + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-breakdown')) + assert.ok(wrapper.hasClass('test-class')) + assert.equal(wrapper.find(Card).length, 1) + assert.equal(wrapper.find(Card).find(TransactionBreakdownRow).length, 4) + }) +}) diff --git a/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.js b/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.js new file mode 100644 index 000000000..557bf75fb --- /dev/null +++ b/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.js @@ -0,0 +1 @@ +export { default } from './transaction-breakdown-row.component' diff --git a/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.scss b/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.scss new file mode 100644 index 000000000..8c73be1a6 --- /dev/null +++ b/ui/app/components/transaction-breakdown/transaction-breakdown-row/index.scss @@ -0,0 +1,19 @@ +.transaction-breakdown-row { + font-size: .75rem; + color: $scorpion; + display: flex; + justify-content: space-between; + padding: 8px 0; + + &:not(:last-child) { + border-bottom: 1px solid #d8d8d8; + } + + &__title { + padding-right: 8px; + } + + &__value { + min-width: 0; + } +} diff --git a/ui/app/components/transaction-breakdown/transaction-breakdown-row/tests/transaction-breakdown-row.component.test.js b/ui/app/components/transaction-breakdown/transaction-breakdown-row/tests/transaction-breakdown-row.component.test.js new file mode 100644 index 000000000..c19399dbb --- /dev/null +++ b/ui/app/components/transaction-breakdown/transaction-breakdown-row/tests/transaction-breakdown-row.component.test.js @@ -0,0 +1,39 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import TransactionBreakdownRow from '../transaction-breakdown-row.component' +import Button from '../../../button' + +describe('TransactionBreakdownRow Component', () => { + it('should render text properly', () => { + const wrapper = shallow( + + Test + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-breakdown-row')) + assert.equal(wrapper.find('.transaction-breakdown-row__title').text(), 'test') + assert.equal(wrapper.find('.transaction-breakdown-row__value').text(), 'Test') + }) + + it('should render components properly', () => { + const wrapper = shallow( + + + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-breakdown-row')) + assert.equal(wrapper.find('.transaction-breakdown-row__title').text(), 'test') + assert.ok(wrapper.find('.transaction-breakdown-row__value').find(Button)) + }) +}) diff --git a/ui/app/components/transaction-breakdown/transaction-breakdown-row/transaction-breakdown-row.component.js b/ui/app/components/transaction-breakdown/transaction-breakdown-row/transaction-breakdown-row.component.js new file mode 100644 index 000000000..c11ff8efa --- /dev/null +++ b/ui/app/components/transaction-breakdown/transaction-breakdown-row/transaction-breakdown-row.component.js @@ -0,0 +1,26 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import classnames from 'classnames' + +export default class TransactionBreakdownRow extends PureComponent { + static propTypes = { + title: PropTypes.string, + children: PropTypes.node, + className: PropTypes.string, + } + + render () { + const { title, children, className } = this.props + + return ( +
    +
    + { title } +
    +
    + { children } +
    +
    + ) + } +} diff --git a/ui/app/components/transaction-breakdown/transaction-breakdown.component.js b/ui/app/components/transaction-breakdown/transaction-breakdown.component.js new file mode 100644 index 000000000..bb6075e9f --- /dev/null +++ b/ui/app/components/transaction-breakdown/transaction-breakdown.component.js @@ -0,0 +1,82 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import classnames from 'classnames' +import TransactionBreakdownRow from './transaction-breakdown-row' +import Card from '../card' +import CurrencyDisplay from '../currency-display' +import HexToDecimal from '../hex-to-decimal' +import { ETH, GWEI } from '../../constants/common' +import { getHexGasTotal } from '../../helpers/confirm-transaction/util' +import { sumHexes } from '../../helpers/transactions.util' + +export default class TransactionBreakdown extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + transaction: PropTypes.object, + className: PropTypes.string, + } + + static defaultProps = { + transaction: {}, + } + + render () { + const { t } = this.context + const { transaction, className } = this.props + const { txParams: { gas, gasPrice, value } = {} } = transaction + const hexGasTotal = getHexGasTotal({ gasLimit: gas, gasPrice }) + const totalInHex = sumHexes(hexGasTotal, value) + + return ( +
    + + + + + + + + + + + +
    + + +
    +
    +
    +
    + ) + } +} diff --git a/ui/app/components/transaction-list-item-details/index.js b/ui/app/components/transaction-list-item-details/index.js new file mode 100644 index 000000000..0e878d032 --- /dev/null +++ b/ui/app/components/transaction-list-item-details/index.js @@ -0,0 +1 @@ +export { default } from './transaction-list-item-details.component' diff --git a/ui/app/components/transaction-list-item-details/index.scss b/ui/app/components/transaction-list-item-details/index.scss new file mode 100644 index 000000000..54cf834cc --- /dev/null +++ b/ui/app/components/transaction-list-item-details/index.scss @@ -0,0 +1,49 @@ +.transaction-list-item-details { + &__header { + margin-bottom: 8px; + display: flex; + justify-content: space-between; + align-items: center; + } + + &__header-buttons { + display: flex; + flex-direction: row; + } + + &__header-button { + font-size: .625rem; + + &:not(:last-child) { + margin-right: 8px; + } + } + + &__sender-to-recipient-container { + margin-bottom: 8px; + } + + &__cards-container { + display: flex; + flex-direction: row; + + @media screen and (max-width: $break-small) { + flex-direction: column; + } + } + + &__transaction-breakdown { + flex: 1; + margin-right: 8px; + min-width: 0; + + @media screen and (max-width: $break-small) { + margin: 0 0 8px 0; + } + } + + &__transaction-activity-log { + flex: 2; + min-width: 0; + } +} diff --git a/ui/app/components/transaction-list-item-details/tests/transaction-list-item-details.component.test.js b/ui/app/components/transaction-list-item-details/tests/transaction-list-item-details.component.test.js new file mode 100644 index 000000000..f2bbe8789 --- /dev/null +++ b/ui/app/components/transaction-list-item-details/tests/transaction-list-item-details.component.test.js @@ -0,0 +1,66 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import TransactionListItemDetails from '../transaction-list-item-details.component' +import Button from '../../button' +import SenderToRecipient from '../../sender-to-recipient' +import TransactionBreakdown from '../../transaction-breakdown' +import TransactionActivityLog from '../../transaction-activity-log' + +describe('TransactionListItemDetails Component', () => { + it('should render properly', () => { + const transaction = { + history: [], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow( + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-list-item-details')) + assert.equal(wrapper.find(Button).length, 1) + assert.equal(wrapper.find(SenderToRecipient).length, 1) + assert.equal(wrapper.find(TransactionBreakdown).length, 1) + assert.equal(wrapper.find(TransactionActivityLog).length, 1) + }) + + it('should render a retry button', () => { + const transaction = { + history: [], + id: 1, + status: 'confirmed', + txParams: { + from: '0x1', + gas: '0x5208', + gasPrice: '0x3b9aca00', + nonce: '0xa4', + to: '0x2', + value: '0x2386f26fc10000', + }, + } + + const wrapper = shallow( + , + { context: { t: (str1, str2) => str2 ? str1 + str2 : str1 } } + ) + + assert.ok(wrapper.hasClass('transaction-list-item-details')) + assert.equal(wrapper.find(Button).length, 2) + }) +}) diff --git a/ui/app/components/transaction-list-item-details/transaction-list-item-details.component.js b/ui/app/components/transaction-list-item-details/transaction-list-item-details.component.js new file mode 100644 index 000000000..4f6290cf1 --- /dev/null +++ b/ui/app/components/transaction-list-item-details/transaction-list-item-details.component.js @@ -0,0 +1,87 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import SenderToRecipient from '../sender-to-recipient' +import { CARDS_VARIANT } from '../sender-to-recipient/sender-to-recipient.constants' +import TransactionActivityLog from '../transaction-activity-log' +import TransactionBreakdown from '../transaction-breakdown' +import Button from '../button' + +export default class TransactionListItemDetails extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + onRetry: PropTypes.func, + showRetry: PropTypes.bool, + transaction: PropTypes.object, + } + + handleEtherscanClick = () => { + const { hash } = this.props.transaction + + const prefix = '' + const etherscanUrl = `https://${prefix}etherscan.io/tx/${hash}` + global.platform.openWindow({ url: etherscanUrl }) + this.setState({ showTransactionDetails: true }) + } + + handleRetry = event => { + const { onRetry } = this.props + + event.stopPropagation() + onRetry() + } + + render () { + const { t } = this.context + const { transaction, showRetry } = this.props + const { txParams: { to, from } = {} } = transaction + + return ( +
    +
    +
    Details
    +
    + { + showRetry && ( + + ) + } + +
    +
    +
    + +
    +
    + + +
    +
    + ) + } +} diff --git a/ui/app/components/transaction-list-item/index.js b/ui/app/components/transaction-list-item/index.js new file mode 100644 index 000000000..697cc55e9 --- /dev/null +++ b/ui/app/components/transaction-list-item/index.js @@ -0,0 +1 @@ +export { default } from './transaction-list-item.container' diff --git a/ui/app/components/transaction-list-item/index.scss b/ui/app/components/transaction-list-item/index.scss new file mode 100644 index 000000000..427686c29 --- /dev/null +++ b/ui/app/components/transaction-list-item/index.scss @@ -0,0 +1,120 @@ +.transaction-list-item { + box-sizing: border-box; + min-height: 74px; + border-bottom: 1px solid $geyser; + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; + + &__grid { + cursor: pointer; + width: 100%; + padding: 16px 20px; + display: grid; + grid-template-columns: 45px 1fr 1fr 1fr; + grid-template-areas: + "identicon action status primary-amount" + "identicon nonce status secondary-amount"; + + @media screen and (max-width: $break-small) { + padding: 8px 20px 12px; + grid-template-columns: 45px 5fr 3fr; + grid-template-areas: + "nonce nonce nonce" + "identicon action primary-amount" + "identicon status secondary-amount"; + } + + &:hover { + background: rgba($alto, .2); + } + } + + &__identicon { + grid-area: identicon; + grid-row: 1 / span 2; + align-self: center; + + @media screen and (max-width: $break-small) { + grid-row: 2 / span 2; + } + } + + &__action { + text-transform: capitalize; + padding: 0 8px 2px 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + grid-area: action; + align-self: end; + } + + &__status { + grid-area: status; + grid-row: 1 / span 2; + align-self: center; + + @media screen and (max-width: $break-small) { + grid-row: 3; + } + } + + &__nonce { + font-size: .75rem; + color: #5e6064; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + grid-area: nonce; + align-self: start; + + @media screen and (max-width: $break-small) { + padding-bottom: 4px; + } + } + + &__amount { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + &--primary { + text-align: end; + grid-area: primary-amount; + align-self: end; + + @media screen and (max-width: $break-small) { + padding-bottom: 2px; + } + } + + &--secondary { + text-align: end; + font-size: .75rem; + color: #5e6064; + grid-area: secondary-amount; + align-self: start; + } + } + + &__retry { + background: #d1edff; + border-radius: 12px; + font-size: .75rem; + padding: 4px 12px; + cursor: pointer; + margin-top: 8px; + + @media screen and (max-width: $break-small) { + font-size: .5rem; + } + } + + &__details-container { + padding: 8px 16px 16px; + background: #f3f4f7; + width: 100%; + } +} diff --git a/ui/app/components/transaction-list-item/transaction-list-item.component.js b/ui/app/components/transaction-list-item/transaction-list-item.component.js new file mode 100644 index 000000000..e590e96e0 --- /dev/null +++ b/ui/app/components/transaction-list-item/transaction-list-item.component.js @@ -0,0 +1,165 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import Identicon from '../identicon' +import TransactionStatus from '../transaction-status' +import TransactionAction from '../transaction-action' +import CurrencyDisplay from '../currency-display' +import TokenCurrencyDisplay from '../token-currency-display' +import TransactionListItemDetails from '../transaction-list-item-details' +import { CONFIRM_TRANSACTION_ROUTE } from '../../routes' +import { UNAPPROVED_STATUS, TOKEN_METHOD_TRANSFER } from '../../constants/transactions' +import { ETH } from '../../constants/common' + +export default class TransactionListItem extends PureComponent { + static propTypes = { + history: PropTypes.object, + transaction: PropTypes.object, + value: PropTypes.string, + methodData: PropTypes.object, + showRetry: PropTypes.bool, + retryTransaction: PropTypes.func, + setSelectedToken: PropTypes.func, + nonceAndDate: PropTypes.string, + token: PropTypes.object, + assetImages: PropTypes.object, + tokenData: PropTypes.object, + } + + state = { + showTransactionDetails: false, + } + + handleClick = () => { + const { transaction, history } = this.props + const { id, status } = transaction + const { showTransactionDetails } = this.state + + if (status === UNAPPROVED_STATUS) { + history.push(`${CONFIRM_TRANSACTION_ROUTE}/${id}`) + return + } + + this.setState({ showTransactionDetails: !showTransactionDetails }) + } + + handleRetry = () => { + const { + transaction: { txParams: { to } = {} }, + methodData: { name } = {}, + setSelectedToken, + } = this.props + + if (name === TOKEN_METHOD_TRANSFER) { + setSelectedToken(to) + } + + this.resubmit() + } + + resubmit () { + const { transaction: { id }, retryTransaction, history } = this.props + retryTransaction(id) + .then(id => history.push(`${CONFIRM_TRANSACTION_ROUTE}/${id}`)) + } + + renderPrimaryCurrency () { + const { token, transaction: { txParams: { data } = {} } = {}, value } = this.props + + return token + ? ( + + ) : ( + + ) + } + + renderSecondaryCurrency () { + const { token, value } = this.props + + return token + ? null + : ( + + ) + } + + render () { + const { + transaction, + methodData, + showRetry, + nonceAndDate, + assetImages, + tokenData, + } = this.props + const { txParams = {} } = transaction + const { showTransactionDetails } = this.state + const toAddress = tokenData + ? tokenData.params && tokenData.params[0] && tokenData.params[0].value || txParams.to + : txParams.to + + return ( +
    +
    + + +
    + { nonceAndDate } +
    + + { this.renderPrimaryCurrency() } + { this.renderSecondaryCurrency() } +
    + { + showTransactionDetails && ( +
    + +
    + ) + } +
    + ) + } +} diff --git a/ui/app/components/transaction-list-item/transaction-list-item.container.js b/ui/app/components/transaction-list-item/transaction-list-item.container.js new file mode 100644 index 000000000..3db9d40ec --- /dev/null +++ b/ui/app/components/transaction-list-item/transaction-list-item.container.js @@ -0,0 +1,35 @@ +import { connect } from 'react-redux' +import { withRouter } from 'react-router-dom' +import { compose } from 'recompose' +import withMethodData from '../../higher-order-components/with-method-data' +import TransactionListItem from './transaction-list-item.component' +import { setSelectedToken, retryTransaction } from '../../actions' +import { hexToDecimal } from '../../helpers/conversions.util' +import { getTokenData } from '../../helpers/transactions.util' +import { formatDate } from '../../util' + +const mapStateToProps = (state, ownProps) => { + const { transaction: { txParams: { value, nonce, data } = {}, time } = {} } = ownProps + + const tokenData = data && getTokenData(data) + const nonceAndDate = nonce ? `#${hexToDecimal(nonce)} - ${formatDate(time)}` : formatDate(time) + + return { + value, + nonceAndDate, + tokenData, + } +} + +const mapDispatchToProps = dispatch => { + return { + setSelectedToken: tokenAddress => dispatch(setSelectedToken(tokenAddress)), + retryTransaction: transactionId => dispatch(retryTransaction(transactionId)), + } +} + +export default compose( + withRouter, + connect(mapStateToProps, mapDispatchToProps), + withMethodData, +)(TransactionListItem) diff --git a/ui/app/components/transaction-list/index.js b/ui/app/components/transaction-list/index.js new file mode 100644 index 000000000..688994367 --- /dev/null +++ b/ui/app/components/transaction-list/index.js @@ -0,0 +1 @@ +export { default } from './transaction-list.container' diff --git a/ui/app/components/transaction-list/index.scss b/ui/app/components/transaction-list/index.scss new file mode 100644 index 000000000..d944ef20e --- /dev/null +++ b/ui/app/components/transaction-list/index.scss @@ -0,0 +1,47 @@ +.transaction-list { + display: flex; + flex-direction: column; + flex: 1; + overflow-y: hidden; + + &__completed-transactions { + display: flex; + flex-direction: column; + flex: 1; + } + + &__header { + flex: 0 0 auto; + font-size: .875rem; + color: $dusty-gray; + border-bottom: 1px solid $geyser; + padding: 16px 0 8px 20px; + + @media screen and (max-width: $break-small) { + padding: 8px 0 8px 16px; + } + } + + &__transactions { + flex: 1; + overflow-y: auto; + } + + &__pending-transactions { + margin-bottom: 16px; + } + + &__empty { + flex: 1; + display: grid; + grid-template-rows: 35% 1fr; + padding-top: 8px; + } + + &__empty-text { + grid-row-start: 2; + display: flex; + justify-content: center; + color: $silver; + } +} diff --git a/ui/app/components/transaction-list/transaction-list.component.js b/ui/app/components/transaction-list/transaction-list.component.js new file mode 100644 index 000000000..c864fea3b --- /dev/null +++ b/ui/app/components/transaction-list/transaction-list.component.js @@ -0,0 +1,118 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import TransactionListItem from '../transaction-list-item' +import ShapeShiftTransactionListItem from '../shift-list-item' +import { TRANSACTION_TYPE_SHAPESHIFT } from '../../constants/transactions' + +export default class TransactionList extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static defaultProps = { + pendingTransactions: [], + completedTransactions: [], + transactionToRetry: {}, + } + + static propTypes = { + pendingTransactions: PropTypes.array, + completedTransactions: PropTypes.array, + transactionToRetry: PropTypes.object, + selectedToken: PropTypes.object, + updateNetworkNonce: PropTypes.func, + assetImages: PropTypes.object, + } + + componentDidMount () { + this.props.updateNetworkNonce() + } + + componentDidUpdate (prevProps) { + const { pendingTransactions: prevPendingTransactions = [] } = prevProps + const { pendingTransactions = [], updateNetworkNonce } = this.props + + if (pendingTransactions.length > prevPendingTransactions.length) { + updateNetworkNonce() + } + } + + shouldShowRetry = transaction => { + const { transactionToRetry } = this.props + const { id, submittedTime } = transaction + return id === transactionToRetry.id && Date.now() - submittedTime > 30000 + } + + renderTransactions () { + const { t } = this.context + const { pendingTransactions = [], completedTransactions = [] } = this.props + return ( +
    + { + pendingTransactions.length > 0 && ( +
    +
    + { `${t('queue')} (${pendingTransactions.length})` } +
    + { + pendingTransactions.map((transaction, index) => ( + this.renderTransaction(transaction, index) + )) + } +
    + ) + } +
    +
    + { t('history') } +
    + { + completedTransactions.length > 0 + ? completedTransactions.map((transaction, index) => ( + this.renderTransaction(transaction, index) + )) + : this.renderEmpty() + } +
    +
    + ) + } + + renderTransaction (transaction, index) { + const { selectedToken, assetImages } = this.props + + return transaction.key === TRANSACTION_TYPE_SHAPESHIFT + ? ( + + ) : ( + + ) + } + + renderEmpty () { + return ( +
    +
    + { this.context.t('noTransactions') } +
    +
    + ) + } + + render () { + return ( +
    + { this.renderTransactions() } +
    + ) + } +} diff --git a/ui/app/components/transaction-list/transaction-list.container.js b/ui/app/components/transaction-list/transaction-list.container.js new file mode 100644 index 000000000..2e946c67d --- /dev/null +++ b/ui/app/components/transaction-list/transaction-list.container.js @@ -0,0 +1,51 @@ +import { connect } from 'react-redux' +import { withRouter } from 'react-router-dom' +import { compose } from 'recompose' +import TransactionList from './transaction-list.component' +import { + pendingTransactionsSelector, + submittedPendingTransactionsSelector, + completedTransactionsSelector, +} from '../../selectors/transactions' +import { getSelectedAddress, getAssetImages } from '../../selectors' +import { selectedTokenSelector } from '../../selectors/tokens' +import { getLatestSubmittedTxWithNonce } from '../../helpers/transactions.util' +import { updateNetworkNonce } from '../../actions' + +const mapStateToProps = state => { + const pendingTransactions = pendingTransactionsSelector(state) + const submittedPendingTransactions = submittedPendingTransactionsSelector(state) + const networkNonce = state.appState.networkNonce + + return { + completedTransactions: completedTransactionsSelector(state), + pendingTransactions, + transactionToRetry: getLatestSubmittedTxWithNonce(submittedPendingTransactions, networkNonce), + selectedToken: selectedTokenSelector(state), + selectedAddress: getSelectedAddress(state), + assetImages: getAssetImages(state), + } +} + +const mapDispatchToProps = dispatch => { + return { + updateNetworkNonce: address => dispatch(updateNetworkNonce(address)), + } +} + +const mergeProps = (stateProps, dispatchProps, ownProps) => { + const { selectedAddress, ...restStateProps } = stateProps + const { updateNetworkNonce, ...restDispatchProps } = dispatchProps + + return { + ...restStateProps, + ...restDispatchProps, + ...ownProps, + updateNetworkNonce: () => updateNetworkNonce(selectedAddress), + } +} + +export default compose( + withRouter, + connect(mapStateToProps, mapDispatchToProps, mergeProps) +)(TransactionList) diff --git a/ui/app/components/transaction-status/index.js b/ui/app/components/transaction-status/index.js new file mode 100644 index 000000000..dece41e9c --- /dev/null +++ b/ui/app/components/transaction-status/index.js @@ -0,0 +1 @@ +export { default } from './transaction-status.component' diff --git a/ui/app/components/transaction-status/index.scss b/ui/app/components/transaction-status/index.scss new file mode 100644 index 000000000..35be550f7 --- /dev/null +++ b/ui/app/components/transaction-status/index.scss @@ -0,0 +1,28 @@ +.transaction-status { + height: 26px; + width: 81px; + border-radius: 4px; + background-color: #f0f0f0; + color: #5e6064; + font-size: .625rem; + text-transform: uppercase; + display: flex; + justify-content: center; + align-items: center; + + @media screen and (max-width: $break-small) { + height: 16px; + width: 70px; + font-size: .5rem; + } + + &--confirmed { + background-color: #eafad7; + color: #609a1c; + } + + &--approved, &--submitted { + background-color: #FFF2DB; + color: #CA810A; + } +} \ No newline at end of file diff --git a/ui/app/components/transaction-status/transaction-status.component.js b/ui/app/components/transaction-status/transaction-status.component.js new file mode 100644 index 000000000..c22baf18a --- /dev/null +++ b/ui/app/components/transaction-status/transaction-status.component.js @@ -0,0 +1,59 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import classnames from 'classnames' +import Tooltip from '../tooltip-v2' +import { + UNAPPROVED_STATUS, + REJECTED_STATUS, + APPROVED_STATUS, + SIGNED_STATUS, + SUBMITTED_STATUS, + CONFIRMED_STATUS, + FAILED_STATUS, + DROPPED_STATUS, +} from '../../constants/transactions' + +const statusToClassNameHash = { + [UNAPPROVED_STATUS]: 'transaction-status--unapproved', + [REJECTED_STATUS]: 'transaction-status--rejected', + [APPROVED_STATUS]: 'transaction-status--approved', + [SIGNED_STATUS]: 'transaction-status--signed', + [SUBMITTED_STATUS]: 'transaction-status--submitted', + [CONFIRMED_STATUS]: 'transaction-status--confirmed', + [FAILED_STATUS]: 'transaction-status--failed', + [DROPPED_STATUS]: 'transaction-status--dropped', +} + +const statusToTextHash = { + [APPROVED_STATUS]: 'pending', + [SUBMITTED_STATUS]: 'pending', +} + +export default class TransactionStatus extends PureComponent { + static defaultProps = { + title: null, + } + + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + statusKey: PropTypes.string, + className: PropTypes.string, + title: PropTypes.string, + } + + render () { + const { className, statusKey, title } = this.props + const statusText = this.context.t(statusToTextHash[statusKey] || statusKey) + + return ( +
    + + { statusText } + +
    + ) + } +} diff --git a/ui/app/components/transaction-view-balance/index.js b/ui/app/components/transaction-view-balance/index.js new file mode 100644 index 000000000..8824737f7 --- /dev/null +++ b/ui/app/components/transaction-view-balance/index.js @@ -0,0 +1 @@ +export { default } from './transaction-view-balance.container' diff --git a/ui/app/components/transaction-view-balance/index.scss b/ui/app/components/transaction-view-balance/index.scss new file mode 100644 index 000000000..12045ab6d --- /dev/null +++ b/ui/app/components/transaction-view-balance/index.scss @@ -0,0 +1,76 @@ +.transaction-view-balance { + display: flex; + justify-content: space-between; + align-items: center; + flex: 1; + height: 54px; + + &__balance { + margin-left: 12px; + display: flex; + flex-direction: column; + + @media screen and (max-width: $break-small) { + align-items: center; + margin: 16px 0; + } + } + + &__token-balance { + margin-left: 12px; + font-size: 1.5rem; + + @media screen and (max-width: $break-small) { + margin-bottom: 12px; + font-size: 1.75rem; + } + } + + &__primary-balance { + font-size: 1.5rem; + + @media screen and (max-width: $break-small) { + margin-bottom: 12px; + font-size: 1.75rem; + } + } + + &__secondary-balance { + font-size: 1.15rem; + color: #a0a0a0; + } + + &__balance-container { + flex: 1; + display: flex; + flex-direction: row; + align-items: center; + + @media screen and (max-width: $break-small) { + flex-direction: column; + } + } + + &__buttons { + display: flex; + flex-direction: row; + + @media screen and (max-width: $break-small) { + margin-bottom: 16px; + } + } + + &__button { + min-width: initial; + width: 100px; + + &:not(:last-child) { + margin-right: 12px; + } + } + + @media screen and (max-width: $break-small) { + flex-direction: column; + height: initial + } +} diff --git a/ui/app/components/transaction-view-balance/tests/token-view-balance.component.test.js b/ui/app/components/transaction-view-balance/tests/token-view-balance.component.test.js new file mode 100644 index 000000000..bb95cb27e --- /dev/null +++ b/ui/app/components/transaction-view-balance/tests/token-view-balance.component.test.js @@ -0,0 +1,71 @@ +import React from 'react' +import assert from 'assert' +import { shallow } from 'enzyme' +import sinon from 'sinon' +import TokenBalance from '../../token-balance' +import CurrencyDisplay from '../../currency-display' +import { SEND_ROUTE } from '../../../routes' +import TransactionViewBalance from '../transaction-view-balance.component' + +const propsMethodSpies = { + showDepositModal: sinon.spy(), +} + +const historySpies = { + push: sinon.spy(), +} + +const t = (str1, str2) => str2 ? str1 + str2 : str1 + +describe('TransactionViewBalance Component', () => { + afterEach(() => { + propsMethodSpies.showDepositModal.resetHistory() + historySpies.push.resetHistory() + }) + + it('should render ETH balance properly', () => { + const wrapper = shallow(, { context: { t } }) + + assert.equal(wrapper.find('.transaction-view-balance').length, 1) + assert.equal(wrapper.find('.transaction-view-balance__button').length, 2) + assert.equal(wrapper.find(CurrencyDisplay).length, 2) + + const buttons = wrapper.find('.transaction-view-balance__buttons') + assert.equal(propsMethodSpies.showDepositModal.callCount, 0) + buttons.childAt(0).simulate('click') + assert.equal(propsMethodSpies.showDepositModal.callCount, 1) + assert.equal(historySpies.push.callCount, 0) + buttons.childAt(1).simulate('click') + assert.equal(historySpies.push.callCount, 1) + assert.equal(historySpies.push.getCall(0).args[0], SEND_ROUTE) + }) + + it('should render token balance properly', () => { + const token = { + address: '0x35865238f0bec9d5ce6abff0fdaebe7b853dfcc5', + decimals: '2', + symbol: 'ABC', + } + + const wrapper = shallow(, { context: { t } }) + + assert.equal(wrapper.find('.transaction-view-balance').length, 1) + assert.equal(wrapper.find('.transaction-view-balance__button').length, 1) + assert.equal(wrapper.find(TokenBalance).length, 1) + }) +}) diff --git a/ui/app/components/transaction-view-balance/transaction-view-balance.component.js b/ui/app/components/transaction-view-balance/transaction-view-balance.component.js new file mode 100644 index 000000000..1b7a29c87 --- /dev/null +++ b/ui/app/components/transaction-view-balance/transaction-view-balance.component.js @@ -0,0 +1,96 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import Button from '../button' +import Identicon from '../identicon' +import TokenBalance from '../token-balance' +import CurrencyDisplay from '../currency-display' +import { SEND_ROUTE } from '../../routes' +import { ETH } from '../../constants/common' + +export default class TransactionViewBalance extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + static propTypes = { + showDepositModal: PropTypes.func, + selectedToken: PropTypes.object, + history: PropTypes.object, + network: PropTypes.string, + balance: PropTypes.string, + assetImage: PropTypes.string, + } + + renderBalance () { + const { selectedToken, balance } = this.props + + return selectedToken + ? ( + + ) : ( +
    + + +
    + ) + } + + renderButtons () { + const { t } = this.context + const { selectedToken, showDepositModal, history } = this.props + + return ( +
    + { + !selectedToken && ( + + ) + } + +
    + ) + } + + render () { + const { network, selectedToken, assetImage } = this.props + + return ( +
    +
    + + { this.renderBalance() } +
    + { this.renderButtons() } +
    + ) + } +} diff --git a/ui/app/components/transaction-view-balance/transaction-view-balance.container.js b/ui/app/components/transaction-view-balance/transaction-view-balance.container.js new file mode 100644 index 000000000..30c5cab16 --- /dev/null +++ b/ui/app/components/transaction-view-balance/transaction-view-balance.container.js @@ -0,0 +1,31 @@ +import { connect } from 'react-redux' +import { withRouter } from 'react-router-dom' +import { compose } from 'recompose' +import TransactionViewBalance from './transaction-view-balance.component' +import { getSelectedToken, getSelectedAddress, getSelectedTokenAssetImage } from '../../selectors' +import { showModal } from '../../actions' + +const mapStateToProps = state => { + const selectedAddress = getSelectedAddress(state) + const { metamask: { network, accounts } } = state + const account = accounts[selectedAddress] + const { balance } = account + + return { + selectedToken: getSelectedToken(state), + network, + balance, + assetImage: getSelectedTokenAssetImage(state), + } +} + +const mapDispatchToProps = dispatch => { + return { + showDepositModal: () => dispatch(showModal({ name: 'DEPOSIT_ETHER' })), + } +} + +export default compose( + withRouter, + connect(mapStateToProps, mapDispatchToProps) +)(TransactionViewBalance) diff --git a/ui/app/components/transaction-view/index.js b/ui/app/components/transaction-view/index.js new file mode 100644 index 000000000..9eb0c3c83 --- /dev/null +++ b/ui/app/components/transaction-view/index.js @@ -0,0 +1 @@ +export { default } from './transaction-view.component' diff --git a/ui/app/components/transaction-view/index.scss b/ui/app/components/transaction-view/index.scss new file mode 100644 index 000000000..af9771ce0 --- /dev/null +++ b/ui/app/components/transaction-view/index.scss @@ -0,0 +1,27 @@ +.transaction-view { + flex: 1 1 66.5%; + background: $white; + min-width: 0; + display: flex; + flex-direction: column; + + &__balance-wrapper { + @media screen and (max-width: $break-small) { + display: flex; + flex-direction: column; + justify-content: flex-start; + align-items: center; + flex: 0 0 auto; + padding-top: 16px; + } + + @media screen and (min-width: $break-large) { + display: flex; + flex-direction: row; + justify-content: flex-start; + align-items: center; + margin: 2.3em 2.37em .8em; + flex: 0 0 auto; + } + } +} diff --git a/ui/app/components/transaction-view/transaction-view.component.js b/ui/app/components/transaction-view/transaction-view.component.js new file mode 100644 index 000000000..7014ca173 --- /dev/null +++ b/ui/app/components/transaction-view/transaction-view.component.js @@ -0,0 +1,27 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import Media from 'react-media' +import MenuBar from '../menu-bar' +import TransactionViewBalance from '../transaction-view-balance' +import TransactionList from '../transaction-list' + +export default class TransactionView extends PureComponent { + static contextTypes = { + t: PropTypes.func, + } + + render () { + return ( +
    + } + /> +
    + +
    + +
    + ) + } +} diff --git a/ui/app/components/tx-list-item.js b/ui/app/components/tx-list-item.js deleted file mode 100644 index 474d62638..000000000 --- a/ui/app/components/tx-list-item.js +++ /dev/null @@ -1,356 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const { compose } = require('recompose') -const { withRouter } = require('react-router-dom') -const h = require('react-hyperscript') -const connect = require('react-redux').connect -const inherits = require('util').inherits -const classnames = require('classnames') -const abi = require('human-standard-token-abi') -const abiDecoder = require('abi-decoder') -abiDecoder.addABI(abi) -const Identicon = require('./identicon') -const contractMap = require('eth-contract-metadata') -const { checksumAddress } = require('../util') - -const actions = require('../actions') -const { conversionUtil, multiplyCurrencies } = require('../conversion-util') -const { calcTokenAmount } = require('../token-util') - -const { getCurrentCurrency } = require('../selectors') -const { CONFIRM_TRANSACTION_ROUTE } = require('../routes') - -TxListItem.contextTypes = { - t: PropTypes.func, -} - -module.exports = compose( - withRouter, - connect(mapStateToProps, mapDispatchToProps) -)(TxListItem) - -function mapStateToProps (state) { - return { - tokens: state.metamask.tokens, - currentCurrency: getCurrentCurrency(state), - contractExchangeRates: state.metamask.contractExchangeRates, - selectedAddressTxList: state.metamask.selectedAddressTxList, - networkNonce: state.appState.networkNonce, - } -} - -function mapDispatchToProps (dispatch) { - return { - setSelectedToken: tokenAddress => dispatch(actions.setSelectedToken(tokenAddress)), - retryTransaction: transactionId => dispatch(actions.retryTransaction(transactionId)), - } -} - -inherits(TxListItem, Component) -function TxListItem () { - Component.call(this) - - this.state = { - total: null, - fiatTotal: null, - isTokenTx: null, - } - - this.unmounted = false -} - -TxListItem.prototype.componentDidMount = async function () { - const { txParams = {} } = this.props - - const decodedData = txParams.data && abiDecoder.decodeMethod(txParams.data) - const { name: txDataName } = decodedData || {} - const isTokenTx = txDataName === 'transfer' - - const { total, fiatTotal } = isTokenTx - ? await this.getSendTokenTotal() - : this.getSendEtherTotal() - - if (this.unmounted) { - return - } - this.setState({ total, fiatTotal, isTokenTx }) -} - -TxListItem.prototype.componentWillUnmount = function () { - this.unmounted = true -} - -TxListItem.prototype.getAddressText = function () { - const { - address, - txParams = {}, - isMsg, - } = this.props - - const decodedData = txParams.data && abiDecoder.decodeMethod(txParams.data) - const { name: txDataName, params = [] } = decodedData || {} - const { value } = params[0] || {} - const checksummedAddress = checksumAddress(address) - const checksummedValue = checksumAddress(value) - - let addressText - if (txDataName === 'transfer' || address) { - const addressToRender = txDataName === 'transfer' ? checksummedValue : checksummedAddress - addressText = `${addressToRender.slice(0, 10)}...${addressToRender.slice(-4)}` - } else if (isMsg) { - addressText = this.context.t('sigRequest') - } else { - addressText = this.context.t('contractDeployment') - } - - return addressText -} - -TxListItem.prototype.getSendEtherTotal = function () { - const { - transactionAmount, - conversionRate, - address, - currentCurrency, - } = this.props - - if (!address) { - return {} - } - - const totalInFiat = conversionUtil(transactionAmount, { - fromNumericBase: 'hex', - toNumericBase: 'dec', - fromCurrency: 'ETH', - toCurrency: currentCurrency, - fromDenomination: 'WEI', - numberOfDecimals: 2, - conversionRate, - }) - const totalInETH = conversionUtil(transactionAmount, { - fromNumericBase: 'hex', - toNumericBase: 'dec', - fromCurrency: 'ETH', - toCurrency: 'ETH', - fromDenomination: 'WEI', - conversionRate, - numberOfDecimals: 6, - }) - - return { - total: `${totalInETH} ETH`, - fiatTotal: `${totalInFiat} ${currentCurrency.toUpperCase()}`, - } -} - -TxListItem.prototype.getTokenInfo = async function () { - const { txParams = {}, tokenInfoGetter, tokens } = this.props - const toAddress = txParams.to - - let decimals - let symbol - - ({ decimals, symbol } = tokens.filter(({ address }) => address === toAddress)[0] || {}) - - if (!decimals && !symbol) { - ({ decimals, symbol } = contractMap[toAddress] || {}) - } - - if (!decimals && !symbol) { - ({ decimals, symbol } = await tokenInfoGetter(toAddress)) - } - - return { decimals, symbol, address: toAddress } -} - -TxListItem.prototype.getSendTokenTotal = async function () { - const { - txParams = {}, - conversionRate, - contractExchangeRates, - currentCurrency, - } = this.props - - const decodedData = txParams.data && abiDecoder.decodeMethod(txParams.data) - const { params = [] } = decodedData || {} - const { value } = params[1] || {} - const { decimals, symbol, address } = await this.getTokenInfo() - const total = calcTokenAmount(value, decimals) - - let tokenToFiatRate - let totalInFiat - - if (contractExchangeRates[address]) { - tokenToFiatRate = multiplyCurrencies( - contractExchangeRates[address], - conversionRate - ) - - totalInFiat = conversionUtil(total, { - fromNumericBase: 'dec', - toNumericBase: 'dec', - fromCurrency: symbol, - toCurrency: currentCurrency, - numberOfDecimals: 2, - conversionRate: tokenToFiatRate, - }) - } - - const showFiat = Boolean(totalInFiat) && currentCurrency.toUpperCase() !== symbol - - return { - total: `${total} ${symbol}`, - fiatTotal: showFiat && `${totalInFiat} ${currentCurrency.toUpperCase()}`, - } -} - -TxListItem.prototype.showRetryButton = function () { - const { - transactionSubmittedTime, - selectedAddressTxList, - transactionId, - txParams, - networkNonce, - } = this.props - if (!txParams) { - return false - } - let currentTxSharesEarliestNonce = false - const currentNonce = txParams.nonce - const currentNonceTxs = selectedAddressTxList.filter(tx => tx.txParams.nonce === currentNonce) - const currentNonceSubmittedTxs = currentNonceTxs.filter(tx => tx.status === 'submitted') - const currentSubmittedTxs = selectedAddressTxList.filter(tx => tx.status === 'submitted') - const lastSubmittedTxWithCurrentNonce = currentNonceSubmittedTxs[currentNonceSubmittedTxs.length - 1] - const currentTxIsLatestWithNonce = lastSubmittedTxWithCurrentNonce && - lastSubmittedTxWithCurrentNonce.id === transactionId - if (currentSubmittedTxs.length > 0) { - currentTxSharesEarliestNonce = currentNonce === networkNonce - } - - return currentTxSharesEarliestNonce && currentTxIsLatestWithNonce && Date.now() - transactionSubmittedTime > 30000 -} - -TxListItem.prototype.setSelectedToken = function (tokenAddress) { - this.props.setSelectedToken(tokenAddress) -} - -TxListItem.prototype.resubmit = function () { - const { transactionId } = this.props - this.props.retryTransaction(transactionId) - .then(id => this.props.history.push(`${CONFIRM_TRANSACTION_ROUTE}/${id}`)) -} - -TxListItem.prototype.render = function () { - const { - transactionStatus, - onClick, - transactionId, - dateString, - address, - className, - txParams, - } = this.props - const { total, fiatTotal, isTokenTx } = this.state - - return h(`div${className || ''}`, { - key: transactionId, - onClick: () => onClick && onClick(transactionId), - }, [ - h(`div.flex-column.tx-list-item-wrapper`, {}, [ - - h('div.tx-list-date-wrapper', { - style: {}, - }, [ - h('span.tx-list-date', {}, [ - dateString, - ]), - ]), - - h('div.flex-row.tx-list-content-wrapper', { - style: {}, - }, [ - - h('div.tx-list-identicon-wrapper', { - style: {}, - }, [ - h(Identicon, { - address, - diameter: 28, - }), - ]), - - h('div.tx-list-account-and-status-wrapper', {}, [ - h('div.tx-list-account-wrapper', { - style: {}, - }, [ - h('span.tx-list-account', {}, [ - this.getAddressText(address), - ]), - ]), - - h('div.tx-list-status-wrapper', { - style: {}, - }, [ - h('span', { - className: classnames('tx-list-status', { - 'tx-list-status--rejected': transactionStatus === 'rejected', - 'tx-list-status--failed': transactionStatus === 'failed', - 'tx-list-status--dropped': transactionStatus === 'dropped', - }), - }, - this.txStatusIndicator(), - ), - ]), - ]), - - h('div.flex-column.tx-list-details-wrapper', { - style: {}, - }, [ - - h('span.tx-list-value', total), - - fiatTotal && h('span.tx-list-fiat-value', fiatTotal), - - ]), - ]), - - this.showRetryButton() && h('.tx-list-item-retry-container', { - onClick: (event) => { - event.stopPropagation() - if (isTokenTx) { - this.setSelectedToken(txParams.to) - } - this.resubmit() - }, - }, [ - h('span', 'Taking too long? Increase the gas price on your transaction'), - ]), - - ]), // holding on icon from design - ]) -} - -TxListItem.prototype.txStatusIndicator = function () { - const { transactionStatus } = this.props - - let name - - if (transactionStatus === 'unapproved') { - name = this.context.t('unapproved') - } else if (transactionStatus === 'rejected') { - name = this.context.t('rejected') - } else if (transactionStatus === 'approved') { - name = this.context.t('approved') - } else if (transactionStatus === 'signed') { - name = this.context.t('signed') - } else if (transactionStatus === 'submitted') { - name = this.context.t('submitted') - } else if (transactionStatus === 'confirmed') { - name = this.context.t('confirmed') - } else if (transactionStatus === 'failed') { - name = this.context.t('failed') - } else if (transactionStatus === 'dropped') { - name = this.context.t('dropped') - } - return name -} diff --git a/ui/app/components/tx-list.js b/ui/app/components/tx-list.js deleted file mode 100644 index ad28f2c1a..000000000 --- a/ui/app/components/tx-list.js +++ /dev/null @@ -1,166 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const connect = require('react-redux').connect -const h = require('react-hyperscript') -const inherits = require('util').inherits -const ethNetProps = require('eth-net-props') -const selectors = require('../selectors') -const TxListItem = require('./tx-list-item') -const ShiftListItem = require('./shift-list-item') -const { formatDate } = require('../util') -const { showConfTxPage, updateNetworkNonce } = require('../actions') -const classnames = require('classnames') -const { tokenInfoGetter } = require('../token-util') -const { withRouter } = require('react-router-dom') -const { compose } = require('recompose') -const { CONFIRM_TRANSACTION_ROUTE } = require('../routes') - -module.exports = compose( - withRouter, - connect(mapStateToProps, mapDispatchToProps) -)(TxList) - -TxList.contextTypes = { - t: PropTypes.func, -} - -function mapStateToProps (state) { - return { - txsToRender: selectors.transactionsSelector(state), - conversionRate: selectors.conversionRateSelector(state), - selectedAddress: selectors.getSelectedAddress(state), - } -} - -function mapDispatchToProps (dispatch) { - return { - showConfTxPage: ({ id }) => dispatch(showConfTxPage({ id })), - updateNetworkNonce: (address) => dispatch(updateNetworkNonce(address)), - } -} - -inherits(TxList, Component) -function TxList () { - Component.call(this) -} - -TxList.prototype.componentWillMount = function () { - this.tokenInfoGetter = tokenInfoGetter() - this.props.updateNetworkNonce(this.props.selectedAddress) -} - -TxList.prototype.componentDidUpdate = function (prevProps) { - const oldTxsToRender = prevProps.txsToRender - const { - txsToRender: newTxsToRender, - selectedAddress, - updateNetworkNonce, - } = this.props - - if (newTxsToRender.length > oldTxsToRender.length) { - updateNetworkNonce(selectedAddress) - } -} - -TxList.prototype.render = function () { - return h('div.flex-column', [ - h('div.flex-row.tx-list-header-wrapper', [ - h('div.flex-row.tx-list-header', [ - h('div', this.context.t('transactions')), - ]), - ]), - h('div.flex-column.tx-list-container', {}, [ - this.renderTransaction(), - ]), - ]) -} - -TxList.prototype.renderTransaction = function () { - const { txsToRender, conversionRate } = this.props - - return txsToRender.length - ? txsToRender.map((transaction, i) => this.renderTransactionListItem(transaction, conversionRate, i)) - : [h( - 'div.tx-list-item.tx-list-item--empty', - { key: 'tx-list-none' }, - [ this.context.t('noTransactions') ], - )] -} - -// TODO: Consider moving TxListItem into a separate component -TxList.prototype.renderTransactionListItem = function (transaction, conversionRate, index) { - // console.log({transaction}) - // refer to transaction-list.js:line 58 - - if (transaction.key === 'shapeshift') { - return h(ShiftListItem, { ...transaction, key: `shapeshift${index}` }) - } - - const props = { - dateString: formatDate(transaction.time), - address: transaction.txParams && transaction.txParams.to, - transactionStatus: transaction.status, - transactionAmount: transaction.txParams && transaction.txParams.value, - transactionId: transaction.id, - transactionHash: transaction.hash, - transactionNetworkId: transaction.metamaskNetworkId, - transactionSubmittedTime: transaction.submittedTime, - } - - const { - address, - transactionStatus, - transactionAmount, - dateString, - transactionId, - transactionHash, - transactionNetworkId, - transactionSubmittedTime, - } = props - const { history } = this.props - - const opts = { - key: transactionId || transactionHash, - txParams: transaction.txParams, - isMsg: Boolean(transaction.msgParams), - transactionStatus, - transactionId, - dateString, - address, - transactionAmount, - transactionHash, - conversionRate, - tokenInfoGetter: this.tokenInfoGetter, - transactionSubmittedTime, - } - - const isUnapproved = transactionStatus === 'unapproved' - - if (isUnapproved) { - opts.onClick = () => { - this.props.showConfTxPage({ id: transactionId}) - history.push(CONFIRM_TRANSACTION_ROUTE) - } - opts.transactionStatus = this.context.t('notStarted') - } else if (transactionHash) { - opts.onClick = () => this.view(transactionHash, transactionNetworkId) - } - - opts.className = classnames('.tx-list-item', { - '.tx-list-pending-item-container': isUnapproved, - '.tx-list-clickable': Boolean(transactionHash) || isUnapproved, - }) - - return h(TxListItem, opts) -} - -TxList.prototype.view = function (txHash, network) { - const url = ethNetProps.explorerLinks.getExplorerTxLinkFor(txHash, network) - if (url) { - navigateTo(url) - } -} - -function navigateTo (url) { - global.platform.openWindow({ url }) -} diff --git a/ui/app/components/tx-view.js b/ui/app/components/tx-view.js deleted file mode 100644 index 654090da6..000000000 --- a/ui/app/components/tx-view.js +++ /dev/null @@ -1,156 +0,0 @@ -const Component = require('react').Component -const PropTypes = require('prop-types') -const connect = require('react-redux').connect -const h = require('react-hyperscript') -const inherits = require('util').inherits -const { withRouter } = require('react-router-dom') -const { compose } = require('recompose') -const actions = require('../actions') -const selectors = require('../selectors') -const { SEND_ROUTE } = require('../routes') -const { checksumAddress: toChecksumAddress } = require('../util') - -const BalanceComponent = require('./balance-component') -const Tooltip = require('./tooltip') -const TxList = require('./tx-list') -const SelectedAccount = require('./selected-account') - -module.exports = compose( - withRouter, - connect(mapStateToProps, mapDispatchToProps) -)(TxView) - -TxView.contextTypes = { - t: PropTypes.func, -} - -function mapStateToProps (state) { - const sidebarOpen = state.appState.sidebarOpen - const isMascara = state.appState.isMascara - - const identities = state.metamask.identities - const accounts = state.metamask.accounts - const network = state.metamask.network - const selectedTokenAddress = state.metamask.selectedTokenAddress - const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0] - const checksumAddress = toChecksumAddress(selectedAddress) - const identity = identities[selectedAddress] - - return { - sidebarOpen, - selectedAddress, - checksumAddress, - selectedTokenAddress, - selectedToken: selectors.getSelectedToken(state), - identity, - network, - isMascara, - } -} - -function mapDispatchToProps (dispatch) { - return { - showSidebar: () => { dispatch(actions.showSidebar()) }, - hideSidebar: () => { dispatch(actions.hideSidebar()) }, - showModal: (payload) => { dispatch(actions.showModal(payload)) }, - showSendPage: () => { dispatch(actions.showSendPage()) }, - showSendTokenPage: () => { dispatch(actions.showSendTokenPage()) }, - } -} - -inherits(TxView, Component) -function TxView () { - Component.call(this) -} - -TxView.prototype.renderHeroBalance = function () { - const { selectedToken } = this.props - - return h('div.hero-balance', {}, [ - - h(BalanceComponent, { token: selectedToken }), - - this.renderButtons(), - ]) -} - -TxView.prototype.renderButtons = function () { - const {selectedToken, showModal, history } = this.props - - return !selectedToken - ? ( - h('div.flex-row.flex-center.hero-balance-buttons', [ - h('button.btn-primary.hero-balance-button', { - onClick: () => showModal({ - name: 'DEPOSIT_ETHER', - }), - }, this.context.t('deposit')), - - h('button.btn-primary.hero-balance-button', { - style: { - marginLeft: '0.8em', - }, - onClick: () => history.push(SEND_ROUTE), - }, this.context.t('send')), - ]) - ) - : ( - h('div.flex-row.flex-center.hero-balance-buttons', [ - h('button.btn-primary.hero-balance-button', { - onClick: () => history.push(SEND_ROUTE), - }, this.context.t('send')), - ]) - ) -} - -TxView.prototype.render = function () { - const { hideSidebar, isMascara, showSidebar, sidebarOpen } = this.props - const { t } = this.context - - return h('div.tx-view.flex-column', { - style: {}, - }, [ - - h('div.flex-row.phone-visible', { - style: { - justifyContent: 'center', - alignItems: 'center', - flex: '0 0 auto', - marginBottom: '16px', - padding: '5px', - borderBottom: '1px solid #e5e5e5', - }, - }, [ - - h(Tooltip, { - title: t('menu'), - position: 'bottom', - }, [ - h('div.fa.fa-bars', { - style: { - fontSize: '1.3em', - cursor: 'pointer', - padding: '10px', - }, - onClick: () => sidebarOpen ? hideSidebar() : showSidebar(), - }), - ]), - - h(SelectedAccount), - - !isMascara && h(Tooltip, { - title: t('openInTab'), - position: 'bottom', - }, [ - h('div.open-in-browser', { - onClick: () => global.platform.openExtensionInBrowser(), - }, [h('img', { src: 'images/popout.svg' })]), - ]), - ]), - - this.renderHeroBalance(), - - h(TxList), - - ]) -} diff --git a/ui/app/components/wallet-view.js b/ui/app/components/wallet-view.js index c16133b32..20b5f62b9 100644 --- a/ui/app/components/wallet-view.js +++ b/ui/app/components/wallet-view.js @@ -9,7 +9,7 @@ const classnames = require('classnames') const { checksumAddress } = require('../util') const Identicon = require('./identicon') // const AccountDropdowns = require('./dropdowns/index.js').AccountDropdowns -const Tooltip = require('./tooltip-v2.js') +const Tooltip = require('./tooltip-v2.js').default const copyToClipboard = require('copy-to-clipboard') const actions = require('../actions') const BalanceComponent = require('./balance-component') @@ -17,6 +17,8 @@ const TokenList = require('./token-list') const selectors = require('../selectors') const { ADD_TOKEN_ROUTE } = require('../routes') +import Button from './button' + module.exports = compose( withRouter, connect(mapStateToProps, mapDispatchToProps) @@ -26,11 +28,15 @@ WalletView.contextTypes = { t: PropTypes.func, } +WalletView.defaultProps = { + responsiveDisplayClassname: '', +} + function mapStateToProps (state) { return { network: state.metamask.network, - sidebarOpen: state.appState.sidebarOpen, + sidebarOpen: state.appState.sidebar.isOpen, identities: state.metamask.identities, accounts: state.metamask.accounts, tokens: state.metamask.tokens, @@ -130,8 +136,9 @@ WalletView.prototype.render = function () { } } - return h('div.wallet-view.flex-column' + (responsiveDisplayClassname || ''), { + return h('div.wallet-view.flex-column', { style: {}, + className: responsiveDisplayClassname, }, [ // TODO: Separate component: wallet account details @@ -193,7 +200,9 @@ WalletView.prototype.render = function () { h(TokenList), - h('button.btn-primary.wallet-view__add-token-button', { + h(Button, { + type: 'primary', + className: 'wallet-view__add-token-button', onClick: () => { history.push(ADD_TOKEN_ROUTE) sidebarOpen && hideSidebar() diff --git a/ui/app/constants/common.js b/ui/app/constants/common.js new file mode 100644 index 000000000..a20f6cc02 --- /dev/null +++ b/ui/app/constants/common.js @@ -0,0 +1,3 @@ +export const ETH = 'ETH' +export const GWEI = 'GWEI' +export const WEI = 'WEI' diff --git a/ui/app/constants/transactions.js b/ui/app/constants/transactions.js new file mode 100644 index 000000000..df6c4c8a4 --- /dev/null +++ b/ui/app/constants/transactions.js @@ -0,0 +1,22 @@ +export const UNAPPROVED_STATUS = 'unapproved' +export const REJECTED_STATUS = 'rejected' +export const APPROVED_STATUS = 'approved' +export const SIGNED_STATUS = 'signed' +export const SUBMITTED_STATUS = 'submitted' +export const CONFIRMED_STATUS = 'confirmed' +export const FAILED_STATUS = 'failed' +export const DROPPED_STATUS = 'dropped' + +export const TOKEN_METHOD_TRANSFER = 'transfer' +export const TOKEN_METHOD_APPROVE = 'approve' +export const TOKEN_METHOD_TRANSFER_FROM = 'transferfrom' + +export const SEND_ETHER_ACTION_KEY = 'sentEther' +export const DEPLOY_CONTRACT_ACTION_KEY = 'contractDeployment' +export const APPROVE_ACTION_KEY = 'approve' +export const SEND_TOKEN_ACTION_KEY = 'sentTokens' +export const TRANSFER_FROM_ACTION_KEY = 'transferFrom' +export const SIGNATURE_REQUEST_KEY = 'signatureRequest' +export const UNKNOWN_FUNCTION_KEY = 'unknownFunction' + +export const TRANSACTION_TYPE_SHAPESHIFT = 'shapeshift' diff --git a/ui/app/conversion-util.js b/ui/app/conversion-util.js index 38f5f1c50..f271b5683 100644 --- a/ui/app/conversion-util.js +++ b/ui/app/conversion-util.js @@ -35,6 +35,7 @@ BigNumber.config({ // Big Number Constants const BIG_NUMBER_WEI_MULTIPLIER = new BigNumber('1000000000000000000') const BIG_NUMBER_GWEI_MULTIPLIER = new BigNumber('1000000000') +const BIG_NUMBER_ETH_MULTIPLIER = new BigNumber('1') // Individual Setters const convert = R.invoker(1, 'times') @@ -52,10 +53,12 @@ const toBigNumber = { const toNormalizedDenomination = { WEI: bigNumber => bigNumber.div(BIG_NUMBER_WEI_MULTIPLIER), GWEI: bigNumber => bigNumber.div(BIG_NUMBER_GWEI_MULTIPLIER), + ETH: bigNumber => bigNumber.div(BIG_NUMBER_ETH_MULTIPLIER), } const toSpecifiedDenomination = { WEI: bigNumber => bigNumber.times(BIG_NUMBER_WEI_MULTIPLIER).round(), GWEI: bigNumber => bigNumber.times(BIG_NUMBER_GWEI_MULTIPLIER).round(9), + ETH: bigNumber => bigNumber.times(BIG_NUMBER_ETH_MULTIPLIER).round(9), } const baseChange = { hex: n => n.toString(16), diff --git a/ui/app/css/itcss/components/buttons.scss b/ui/app/css/itcss/components/buttons.scss index 34565767f..655188a3e 100644 --- a/ui/app/css/itcss/components/buttons.scss +++ b/ui/app/css/itcss/components/buttons.scss @@ -2,10 +2,7 @@ Buttons */ -.btn-default, -.btn-primary, -.btn-secondary, -.btn-confirm { +.button { height: 44px; background: $white; display: flex; @@ -79,6 +76,16 @@ background-color: $curious-blue; } +.btn-raised { + color: $curious-blue; + background-color: $white; + box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08); + padding: 6px; + height: initial; + width: initial; + min-width: initial; +} + .btn--large { height: 54px; } diff --git a/ui/app/css/itcss/components/hero-balance.scss b/ui/app/css/itcss/components/hero-balance.scss deleted file mode 100644 index eba93ecb4..000000000 --- a/ui/app/css/itcss/components/hero-balance.scss +++ /dev/null @@ -1,130 +0,0 @@ -.hero-balance { - - @media screen and (max-width: $break-small) { - display: flex; - flex-direction: column; - justify-content: flex-start; - align-items: center; - flex: 0 0 auto; - padding-top: 16px; - } - - @media screen and (min-width: $break-large) { - display: flex; - flex-direction: row; - justify-content: flex-start; - align-items: center; - margin: 2.3em 2.37em .8em; - flex: 0 0 auto; - } - - .balance-container { - display: flex; - margin: 0; - justify-content: flex-start; - align-items: center; - - @media screen and (max-width: $break-small) { - flex-direction: column; - flex: 0 0 auto; - max-width: 100%; - } - - @media screen and (min-width: $break-large) { - flex-direction: row; - flex-grow: 3; - min-width: 0; - } - } - - .balance-display { - .token-amount { - color: $black; - max-width: 100%; - - .token-balance { - display: flex; - } - } - - @media screen and (max-width: $break-small) { - max-width: 100%; - text-align: center; - - .token-amount { - font-size: 1.75rem; - margin-top: 1rem; - - .token-balance { - flex-direction: column; - } - } - - .fiat-amount { - font-size: 115%; - margin-top: 8.5%; - color: #a0a0a0; - } - } - - @media screen and (min-width: $break-large) { - margin: 0 .8em; - justify-content: flex-start; - align-items: flex-start; - min-width: 0; - - .token-amount { - font-size: 1.5rem; - } - - .fiat-amount { - margin-top: .25%; - font-size: 105%; - } - } - - @media #{$sub-mid-size-breakpoint-range} { - margin-left: .4em; - margin-right: .4em; - justify-content: flex-start; - align-items: flex-start; - - .token-amount { - font-size: 1rem; - } - - .fiat-amount { - margin-top: .25%; - font-size: 1rem; - } - } - } - - .hero-balance-buttons { - - @media screen and (max-width: $break-small) { - width: 100%; - // height: 100px; // needed a round number to set the heights of the buttons inside - flex: 0 0 auto; - padding: 16px 0; - } - - @media screen and (min-width: $break-large) { - flex-grow: 2; - justify-content: flex-end; - } - } -} - -.hero-balance-button { - min-width: initial; - width: 6rem; - - @media #{$sub-mid-size-breakpoint-range} { - padding: .4rem; - width: 4rem; - display: flex; - flex: 1; - justify-content: center; - } -} diff --git a/ui/app/css/itcss/components/index.scss b/ui/app/css/itcss/components/index.scss index 96ad5fe64..99deaf918 100644 --- a/ui/app/css/itcss/components/index.scss +++ b/ui/app/css/itcss/components/index.scss @@ -1,7 +1,5 @@ @import './buttons.scss'; -@import './header.scss'; - @import './footer.scss'; @import './network.scss'; @@ -21,8 +19,6 @@ @import './loading-overlay.scss'; // Balances -@import './hero-balance.scss'; - @import './wallet-balance.scss'; // Tx List and Sections @@ -40,8 +36,6 @@ @import './gas-slider.scss'; -@import './settings.scss'; - @import './tab-bar.scss'; @import './simple-dropdown.scss'; diff --git a/ui/app/css/itcss/components/loading-overlay.scss b/ui/app/css/itcss/components/loading-overlay.scss index b07d6af17..b023c8423 100644 --- a/ui/app/css/itcss/components/loading-overlay.scss +++ b/ui/app/css/itcss/components/loading-overlay.scss @@ -1,6 +1,6 @@ .loading-overlay { left: 0; - z-index: 50; + z-index: 51; position: absolute; flex-direction: column; display: flex; @@ -8,25 +8,9 @@ align-items: center; flex: 1 1 auto; width: 100%; + height: 100%; background: rgba(255, 255, 255, .8); - @media screen and (max-width: 575px) { - margin-top: 66px; - height: calc(100% - 66px); - } - - @media screen and (min-width: 576px) { - margin-top: 75px; - height: calc(100% - 75px); - } - - &--full-screen { - position: fixed; - height: 100vh; - width: 100vw; - margin-top: 0; - } - &__container { position: absolute; top: 33%; diff --git a/ui/app/css/itcss/components/newui-sections.scss b/ui/app/css/itcss/components/newui-sections.scss index bbfd85c90..8e963d495 100644 --- a/ui/app/css/itcss/components/newui-sections.scss +++ b/ui/app/css/itcss/components/newui-sections.scss @@ -6,7 +6,6 @@ $sub-mid-size-breakpoint-range: "screen and (min-width: #{$break-large}) and (ma */ // Component Colors -$tx-view-bg: $white; $wallet-view-bg: $alabaster; // Main container @@ -23,6 +22,12 @@ $wallet-view-bg: $alabaster; display: none; } +.main-container-wrapper { + display: flex; + width: 100vw; + justify-content: center; +} + //Account and transaction details .account-and-transaction-details { display: flex; @@ -30,32 +35,6 @@ $wallet-view-bg: $alabaster; min-width: 0; } -// tx view - -.tx-view { - flex: 1 1 66.5%; - background: $tx-view-bg; - min-width: 0; - - // No title on mobile - @media screen and (max-width: 575px) { - .identicon-wrapper { - display: none; - } - - .account-name { - display: none; - } - } -} - -.open-in-browser { - cursor: pointer; - display: flex; - justify-content: center; - padding: 10px; -} - // wallet view and sidebar .wallet-view { @@ -175,7 +154,7 @@ $wallet-view-bg: $alabaster; } } -.wallet-view.sidebar { +.wallet-view.sidebar-right { flex: 1 0 230px; background: rgb(250, 250, 250); z-index: $sidebar-z-index; @@ -193,20 +172,6 @@ $wallet-view-bg: $alabaster; height: calc(100% - 56px); } -.sidebar-overlay { - z-index: $sidebar-overlay-z-index; - position: fixed; - // top: 41px; - height: 100%; - width: 100%; - left: 0; - right: 0; - bottom: 0; - opacity: 1; - visibility: visible; - background-color: rgba(0, 0, 0, .3); -} - // main-container media queries @media screen and (min-width: 576px) { @@ -260,6 +225,10 @@ $wallet-view-bg: $alabaster; overflow-y: auto; background-color: $white; } + + .main-container-wrapper { + height: 100%; + } } // wallet view diff --git a/ui/app/css/itcss/components/request-signature.scss b/ui/app/css/itcss/components/request-signature.scss index b607aded3..445b9ebf5 100644 --- a/ui/app/css/itcss/components/request-signature.scss +++ b/ui/app/css/itcss/components/request-signature.scss @@ -23,6 +23,25 @@ } } + &__typed-container { + padding: 17px; + + h1 { + font-weight: 900; + margin-bottom: 5px; + } + + * { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + > div { + margin-bottom: 10px; + } + } + &__header { height: 64px; width: 100%; diff --git a/ui/app/css/itcss/components/send.scss b/ui/app/css/itcss/components/send.scss index 806ac8536..7fc960d7d 100644 --- a/ui/app/css/itcss/components/send.scss +++ b/ui/app/css/itcss/components/send.scss @@ -622,12 +622,14 @@ position: relative; &__down-caret { + z-index: 1026; position: absolute; top: 18px; right: 12px; } &__qr-code { + z-index: 1026; position: absolute; top: 13px; right: 33px; @@ -647,6 +649,8 @@ &__to-autocomplete, &__memo-text-area, &__hex-data { &__input { + z-index: 1025; + position: relative; height: 54px; width: 100%; border: 1px solid $alto; @@ -833,6 +837,10 @@ line-height: 12px; color: $red; } + + &__cancel { + margin-right: 10px; + } } &__gas-modal-card { @@ -880,12 +888,21 @@ font-size: 18px; color: $tundora; right: 0px; - padding: 1px 4px; + padding: 0; display: flex; justify-content: space-around; align-items: center; } + .gas-tooltip-input-arrow-wrapper { + align-items: center; + align-self: stretch; + display: flex; + flex-direction: column; + flex-grow: 1; + justify-content: center; + } + input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; display: none; diff --git a/ui/app/css/itcss/components/settings.scss b/ui/app/css/itcss/components/settings.scss deleted file mode 100644 index 0dd61ac5e..000000000 --- a/ui/app/css/itcss/components/settings.scss +++ /dev/null @@ -1,214 +0,0 @@ -.settings { - position: relative; - background: $white; - display: flex; - flex-flow: column nowrap; -} - -.settings__header { - padding: 25px; -} - -.settings__close-button::after { - content: '\00D7'; - font-size: 40px; - color: $dusty-gray; - position: absolute; - top: 25px; - right: 30px; - cursor: pointer; -} - -.settings__error { - padding-bottom: 20px; - text-align: center; - color: $crimson; -} - -.settings__content { - padding: 0 25px; - height: auto; - overflow: auto; -} - -.settings__content-row { - display: flex; - flex-direction: row; - padding: 10px 0 20px; - - @media screen and (max-width: 575px) { - flex-direction: column; - padding: 10px 0; - } -} - -.settings__content-item { - flex: 1; - min-width: 0; - display: flex; - flex-direction: column; - padding: 0 5px; - height: 71px; - - @media screen and (max-width: 575px) { - height: initial; - padding: 5px 0; - } - - &--without-height { - height: initial; - } -} - -.settings__content-item-col { - max-width: 300px; - display: flex; - flex-direction: column; - - @media screen and (max-width: 575px) { - max-width: 100%; - width: 100%; - } -} - -.settings__content-description { - font-size: 14px; - color: $dusty-gray; - padding-top: 5px; -} - -.settings__input { - padding-left: 10px; - font-size: 14px; - height: 40px; - border: 1px solid $alto; -} - -.settings__input::-webkit-input-placeholder { - font-weight: 100; - color: $dusty-gray; -} - -.settings__input::-moz-placeholder { - font-weight: 100; - color: $dusty-gray; -} - -.settings__input:-ms-input-placeholder { - font-weight: 100; - color: $dusty-gray; -} - -.settings__input:-moz-placeholder { - font-weight: 100; - color: $dusty-gray; -} - -.settings__provider-wrapper { - font-size: 16px; - border: 1px solid $alto; - border-radius: 2px; - padding: 15px; - background-color: $white; - display: flex; - align-items: center; - justify-content: flex-start; -} - -.settings__provider-icon { - height: 10px; - width: 10px; - margin-right: 10px; - border-radius: 10px; -} - -.settings__rpc-save-button { - align-self: flex-end; - padding: 5px; - text-transform: uppercase; - color: $dusty-gray; - cursor: pointer; -} - -.settings__button--red { - border-color: lighten($monzo, 10%); - color: $monzo; - - &:active { - background: lighten($monzo, 55%); - border-color: $monzo; - } - - &:hover { - border-color: $monzo; - } -} - -.settings__button--orange { - border-color: lighten($ecstasy, 20%); - color: $ecstasy; - - &:active { - background: lighten($ecstasy, 40%); - border-color: $ecstasy; - } - - &:hover { - border-color: $ecstasy; - } -} - -.settings__info-logo-wrapper { - height: 80px; - margin-bottom: 20px; -} - -.settings__info-logo { - max-height: 100%; - max-width: 100%; -} - -.settings__info-item { - padding: 10px 0; -} - -.settings__info-link-header { - padding-bottom: 15px; - - @media screen and (max-width: 575px) { - padding-bottom: 5px; - } -} - -.settings__info-link-item { - padding: 15px 0; - - @media screen and (max-width: 575px) { - padding: 5px 0; - } -} - -.settings__info-version-number { - padding-top: 5px; - font-size: 13px; - color: $dusty-gray; -} - -.settings__info-about { - color: $dusty-gray; - margin-bottom: 15px; -} - -.settings__info-link { - color: $curious-blue; -} - -.settings__info-separator { - margin: 15px 0; - width: 80px; - border-color: $alto; - border: none; - height: 1px; - background-color: $alto; - color: $alto; -} diff --git a/ui/app/css/itcss/components/transaction-list.scss b/ui/app/css/itcss/components/transaction-list.scss index 1d45ff13b..3435353d9 100644 --- a/ui/app/css/itcss/components/transaction-list.scss +++ b/ui/app/css/itcss/components/transaction-list.scss @@ -243,7 +243,7 @@ } .tx-list-item { - border-top: 1px solid rgb(231, 231, 231); + border-bottom: 1px solid $geyser; flex: 0 0 auto; display: flex; flex-flow: row nowrap; diff --git a/ui/app/ducks/confirm-transaction.duck.js b/ui/app/ducks/confirm-transaction.duck.js index 1885e12d1..30c32f2bf 100644 --- a/ui/app/ducks/confirm-transaction.duck.js +++ b/ui/app/ducks/confirm-transaction.duck.js @@ -5,9 +5,7 @@ import { } from '../selectors/confirm-transaction' import { - getTokenData, - getMethodData, - getTransactionAmount, + getValueFromWeiHex, getTransactionFee, getHexGasTotal, addFiat, @@ -16,6 +14,7 @@ import { hexGreaterThan, } from '../helpers/confirm-transaction/util' +import { getTokenData, getMethodData, isSmartContractAddress } from '../helpers/transactions.util' import { getSymbolAndDecimals } from '../token-util' import { conversionUtil } from '../conversion-util' @@ -35,8 +34,9 @@ const UPDATE_TRANSACTION_TOTALS = createActionType('UPDATE_TRANSACTION_TOTALS') const UPDATE_HEX_GAS_TOTAL = createActionType('UPDATE_HEX_GAS_TOTAL') const UPDATE_TOKEN_PROPS = createActionType('UPDATE_TOKEN_PROPS') const UPDATE_NONCE = createActionType('UPDATE_NONCE') -const FETCH_METHOD_DATA_START = createActionType('FETCH_METHOD_DATA_START') -const FETCH_METHOD_DATA_END = createActionType('FETCH_METHOD_DATA_END') +const UPDATE_TO_SMART_CONTRACT = createActionType('UPDATE_TO_SMART_CONTRACT') +const FETCH_DATA_START = createActionType('FETCH_DATA_START') +const FETCH_DATA_END = createActionType('FETCH_DATA_END') // Initial state const initState = { @@ -55,7 +55,8 @@ const initState = { ethTransactionTotal: '', hexGasTotal: '', nonce: '', - fetchingMethodData: false, + toSmartContract: false, + fetchingData: false, } // Reducer @@ -138,15 +139,20 @@ export default function reducer ({ confirmTransaction: confirmState = initState ...confirmState, nonce: action.payload, } - case FETCH_METHOD_DATA_START: + case UPDATE_TO_SMART_CONTRACT: return { ...confirmState, - fetchingMethodData: true, + toSmartContract: action.payload, } - case FETCH_METHOD_DATA_END: + case FETCH_DATA_START: return { ...confirmState, - fetchingMethodData: false, + fetchingData: true, + } + case FETCH_DATA_END: + return { + ...confirmState, + fetchingData: false, } case CLEAR_CONFIRM_TRANSACTION: return initState @@ -237,9 +243,16 @@ export function updateNonce (nonce) { } } -export function setFetchingMethodData (isFetching) { +export function updateToSmartContract (toSmartContract) { return { - type: isFetching ? FETCH_METHOD_DATA_START : FETCH_METHOD_DATA_END, + type: UPDATE_TO_SMART_CONTRACT, + payload: toSmartContract, + } +} + +export function setFetchingData (isFetching) { + return { + type: isFetching ? FETCH_DATA_START : FETCH_DATA_END, } } @@ -286,10 +299,10 @@ export function updateTxDataAndCalculate (txData) { const { txParams: { value, gas: gasLimit = '0x0', gasPrice = '0x0' } = {} } = txData - const fiatTransactionAmount = getTransactionAmount({ + const fiatTransactionAmount = getValueFromWeiHex({ value, toCurrency: currentCurrency, conversionRate, numberOfDecimals: 2, }) - const ethTransactionAmount = getTransactionAmount({ + const ethTransactionAmount = getValueFromWeiHex({ value, toCurrency: 'ETH', conversionRate, numberOfDecimals: 6, }) @@ -338,19 +351,22 @@ export function setTransactionToConfirm (transactionId) { dispatch(updateTxDataAndCalculate(txData)) const { txParams } = transaction + const { to } = txParams if (txParams.data) { const { tokens: existingTokens } = state const { data, to: tokenAddress } = txParams try { - dispatch(setFetchingMethodData(true)) + dispatch(setFetchingData(true)) const methodData = await getMethodData(data) dispatch(updateMethodData(methodData)) - dispatch(setFetchingMethodData(false)) + const toSmartContract = await isSmartContractAddress(to) + dispatch(updateToSmartContract(toSmartContract)) + dispatch(setFetchingData(false)) } catch (error) { dispatch(updateMethodData({})) - dispatch(setFetchingMethodData(false)) + dispatch(setFetchingData(false)) } const tokenData = getTokenData(data) diff --git a/ui/app/ducks/tests/confirm-transaction.duck.test.js b/ui/app/ducks/tests/confirm-transaction.duck.test.js index 111674e33..1bab0add0 100644 --- a/ui/app/ducks/tests/confirm-transaction.duck.test.js +++ b/ui/app/ducks/tests/confirm-transaction.duck.test.js @@ -1,6 +1,7 @@ import assert from 'assert' import configureMockStore from 'redux-mock-store' import thunk from 'redux-thunk' +import sinon from 'sinon' import ConfirmTransactionReducer, * as actions from '../confirm-transaction.duck.js' @@ -20,7 +21,8 @@ const initialState = { ethTransactionTotal: '', hexGasTotal: '', nonce: '', - fetchingMethodData: false, + toSmartContract: false, + fetchingData: false, } const UPDATE_TX_DATA = 'metamask/confirm-transaction/UPDATE_TX_DATA' @@ -35,8 +37,9 @@ const UPDATE_TRANSACTION_TOTALS = 'metamask/confirm-transaction/UPDATE_TRANSACTI const UPDATE_HEX_GAS_TOTAL = 'metamask/confirm-transaction/UPDATE_HEX_GAS_TOTAL' const UPDATE_TOKEN_PROPS = 'metamask/confirm-transaction/UPDATE_TOKEN_PROPS' const UPDATE_NONCE = 'metamask/confirm-transaction/UPDATE_NONCE' -const FETCH_METHOD_DATA_START = 'metamask/confirm-transaction/FETCH_METHOD_DATA_START' -const FETCH_METHOD_DATA_END = 'metamask/confirm-transaction/FETCH_METHOD_DATA_END' +const UPDATE_TO_SMART_CONTRACT = 'metamask/confirm-transaction/UPDATE_TO_SMART_CONTRACT' +const FETCH_DATA_START = 'metamask/confirm-transaction/FETCH_DATA_START' +const FETCH_DATA_END = 'metamask/confirm-transaction/FETCH_DATA_END' const CLEAR_CONFIRM_TRANSACTION = 'metamask/confirm-transaction/CLEAR_CONFIRM_TRANSACTION' describe('Confirm Transaction Duck', () => { @@ -64,7 +67,8 @@ describe('Confirm Transaction Duck', () => { ethTransactionTotal: '469.27', hexGasTotal: '0x1319718a5000', nonce: '0x0', - fetchingMethodData: false, + toSmartContract: false, + fetchingData: false, }, } @@ -271,30 +275,43 @@ describe('Confirm Transaction Duck', () => { ) }) - it('should set fetchingMethodData to true when receiving a FETCH_METHOD_DATA_START action', () => { + it('should update nonce when receiving an UPDATE_TO_SMART_CONTRACT action', () => { assert.deepEqual( ConfirmTransactionReducer(mockState, { - type: FETCH_METHOD_DATA_START, + type: UPDATE_TO_SMART_CONTRACT, + payload: true, }), { ...mockState.confirmTransaction, - fetchingMethodData: true, + toSmartContract: true, } ) }) - it('should set fetchingMethodData to false when receiving a FETCH_METHOD_DATA_END action', () => { + it('should set fetchingData to true when receiving a FETCH_DATA_START action', () => { assert.deepEqual( - ConfirmTransactionReducer({ confirmTransaction: { fetchingMethodData: true } }, { - type: FETCH_METHOD_DATA_END, + ConfirmTransactionReducer(mockState, { + type: FETCH_DATA_START, }), { - fetchingMethodData: false, + ...mockState.confirmTransaction, + fetchingData: true, } ) }) - it('should clear confirmTransaction when receiving a FETCH_METHOD_DATA_END action', () => { + it('should set fetchingData to false when receiving a FETCH_DATA_END action', () => { + assert.deepEqual( + ConfirmTransactionReducer({ confirmTransaction: { fetchingData: true } }, { + type: FETCH_DATA_END, + }), + { + fetchingData: false, + } + ) + }) + + it('should clear confirmTransaction when receiving a FETCH_DATA_END action', () => { assert.deepEqual( ConfirmTransactionReducer(mockState, { type: CLEAR_CONFIRM_TRANSACTION, @@ -460,24 +477,24 @@ describe('Confirm Transaction Duck', () => { ) }) - it('should create an action to set fetchingMethodData to true', () => { + it('should create an action to set fetchingData to true', () => { const expectedAction = { - type: FETCH_METHOD_DATA_START, + type: FETCH_DATA_START, } assert.deepEqual( - actions.setFetchingMethodData(true), + actions.setFetchingData(true), expectedAction ) }) - it('should create an action to set fetchingMethodData to false', () => { + it('should create an action to set fetchingData to false', () => { const expectedAction = { - type: FETCH_METHOD_DATA_END, + type: FETCH_DATA_END, } assert.deepEqual( - actions.setFetchingMethodData(false), + actions.setFetchingData(false), expectedAction ) }) @@ -495,6 +512,18 @@ describe('Confirm Transaction Duck', () => { }) describe('Thunk actions', done => { + beforeEach(() => { + global.eth = { + getCode: sinon.stub().callsFake( + address => Promise.resolve(address && address.match(/isContract/) ? 'not-0x' : '0x') + ), + } + }) + + afterEach(() => { + global.eth.getCode.resetHistory() + }) + it('updates txData and gas on an existing transaction in confirmTransaction', () => { const mockState = { metamask: { @@ -505,7 +534,7 @@ describe('Confirm Transaction Duck', () => { ethTransactionAmount: '1', ethTransactionFee: '0.000021', ethTransactionTotal: '1.000021', - fetchingMethodData: false, + fetchingData: false, fiatTransactionAmount: '469.26', fiatTransactionFee: '0.01', fiatTransactionTotal: '469.27', @@ -581,7 +610,7 @@ describe('Confirm Transaction Duck', () => { ethTransactionAmount: '1', ethTransactionFee: '0.000021', ethTransactionTotal: '1.000021', - fetchingMethodData: false, + fetchingData: false, fiatTransactionAmount: '469.26', fiatTransactionFee: '0.01', fiatTransactionTotal: '469.27', @@ -667,6 +696,7 @@ describe('Confirm Transaction Duck', () => { .then(() => { const storeActions = store.getActions() assert.equal(storeActions.length, expectedActions.length) + storeActions.forEach((action, index) => assert.equal(action.type, expectedActions[index])) done() }) diff --git a/ui/app/helpers/confirm-transaction/util.js b/ui/app/helpers/confirm-transaction/util.js index 76e80a8ac..bcac22500 100644 --- a/ui/app/helpers/confirm-transaction/util.js +++ b/ui/app/helpers/confirm-transaction/util.js @@ -1,15 +1,8 @@ import currencyFormatter from 'currency-formatter' import currencies from 'currency-formatter/currencies' -import abi from 'human-standard-token-abi' -import abiDecoder from 'abi-decoder' import ethUtil from 'ethereumjs-util' import BigNumber from 'bignumber.js' -abiDecoder.addABI(abi) - -import MethodRegistry from 'eth-method-registry' -const registry = new MethodRegistry({ provider: global.ethereumProvider }) - import { conversionUtil, addCurrencies, @@ -19,22 +12,6 @@ import { import { unconfirmedTransactionsCountSelector } from '../../selectors/confirm-transaction' -export function getTokenData (data = {}) { - return abiDecoder.decodeMethod(data) -} - -export async function getMethodData (data = {}) { - const prefixedData = ethUtil.addHexPrefix(data) - const fourBytePrefix = prefixedData.slice(0, 10) - const sig = await registry.lookup(fourBytePrefix) - const parsedResult = registry.parse(sig) - - return { - name: parsedResult.name, - params: parsedResult.args, - } -} - export function increaseLastGasPrice (lastGasPrice) { return ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice, 1.1, { multiplicandBase: 16, @@ -76,11 +53,12 @@ export function addFiat (...args) { }) } -export function getTransactionAmount ({ +export function getValueFromWeiHex ({ value, toCurrency, conversionRate, numberOfDecimals, + toDenomination, }) { return conversionUtil(value, { fromNumericBase: 'hex', @@ -89,6 +67,7 @@ export function getTransactionAmount ({ toCurrency, numberOfDecimals, fromDenomination: 'WEI', + toDenomination, conversionRate, }) } diff --git a/ui/app/helpers/confirm-transaction/util.test.js b/ui/app/helpers/confirm-transaction/util.test.js index a9c8fae34..4c1a3e16b 100644 --- a/ui/app/helpers/confirm-transaction/util.test.js +++ b/ui/app/helpers/confirm-transaction/util.test.js @@ -92,9 +92,9 @@ describe('Confirm Transaction utils', () => { }) }) - describe('getTransactionAmount', () => { + describe('getValueFromWeiHex', () => { it('should get the transaction amount in ETH', () => { - const ethTransactionAmount = utils.getTransactionAmount({ + const ethTransactionAmount = utils.getValueFromWeiHex({ value: '0xde0b6b3a7640000', toCurrency: 'ETH', conversionRate: 468.58, numberOfDecimals: 6, }) @@ -102,7 +102,7 @@ describe('Confirm Transaction utils', () => { }) it('should get the transaction amount in fiat', () => { - const fiatTransactionAmount = utils.getTransactionAmount({ + const fiatTransactionAmount = utils.getValueFromWeiHex({ value: '0xde0b6b3a7640000', toCurrency: 'usd', conversionRate: 468.58, numberOfDecimals: 2, }) diff --git a/ui/app/helpers/conversions.util.js b/ui/app/helpers/conversions.util.js new file mode 100644 index 000000000..5204faa1f --- /dev/null +++ b/ui/app/helpers/conversions.util.js @@ -0,0 +1,51 @@ +import { conversionUtil } from '../conversion-util' +import { ETH, GWEI, WEI } from '../constants/common' + +export function hexToDecimal (hexValue) { + return conversionUtil(hexValue, { + fromNumericBase: 'hex', + toNumericBase: 'dec', + }) +} + +export function getEthConversionFromWeiHex ({ value, conversionRate, numberOfDecimals = 6 }) { + const denominations = [ETH, GWEI, WEI] + + let nonZeroDenomination + + for (let i = 0; i < denominations.length; i++) { + const convertedValue = getValueFromWeiHex({ + value, + conversionRate, + toCurrency: ETH, + numberOfDecimals, + toDenomination: denominations[i], + }) + + if (convertedValue !== '0' || i === denominations.length - 1) { + nonZeroDenomination = `${convertedValue} ${denominations[i]}` + break + } + } + + return nonZeroDenomination +} + +export function getValueFromWeiHex ({ + value, + toCurrency, + conversionRate, + numberOfDecimals, + toDenomination, +}) { + return conversionUtil(value, { + fromNumericBase: 'hex', + toNumericBase: 'dec', + fromCurrency: ETH, + toCurrency, + numberOfDecimals, + fromDenomination: WEI, + toDenomination, + conversionRate, + }) +} diff --git a/ui/app/helpers/tests/transactions.util.test.js b/ui/app/helpers/tests/transactions.util.test.js new file mode 100644 index 000000000..103a84a8c --- /dev/null +++ b/ui/app/helpers/tests/transactions.util.test.js @@ -0,0 +1,22 @@ +import * as utils from '../transactions.util' +import assert from 'assert' + +describe('Transactions utils', () => { + describe('getTokenData', () => { + it('should return token data', () => { + const tokenData = utils.getTokenData('0xa9059cbb00000000000000000000000050a9d56c2b8ba9a5c7f2c08c3d26e0499f23a7060000000000000000000000000000000000000000000000000000000000004e20') + assert.ok(tokenData) + const { name, params } = tokenData + assert.equal(name, 'transfer') + const [to, value] = params + assert.equal(to.name, '_to') + assert.equal(to.type, 'address') + assert.equal(value.name, '_value') + assert.equal(value.type, 'uint256') + }) + + it('should not throw errors when called without arguments', () => { + assert.doesNotThrow(() => utils.getTokenData()) + }) + }) +}) diff --git a/ui/app/helpers/transactions.util.js b/ui/app/helpers/transactions.util.js new file mode 100644 index 000000000..54bb3bcb9 --- /dev/null +++ b/ui/app/helpers/transactions.util.js @@ -0,0 +1,117 @@ +import ethUtil from 'ethereumjs-util' +import MethodRegistry from 'eth-method-registry' +import abi from 'human-standard-token-abi' +import abiDecoder from 'abi-decoder' + +import { + TOKEN_METHOD_TRANSFER, + TOKEN_METHOD_APPROVE, + TOKEN_METHOD_TRANSFER_FROM, + SEND_ETHER_ACTION_KEY, + DEPLOY_CONTRACT_ACTION_KEY, + APPROVE_ACTION_KEY, + SEND_TOKEN_ACTION_KEY, + TRANSFER_FROM_ACTION_KEY, + SIGNATURE_REQUEST_KEY, + UNKNOWN_FUNCTION_KEY, +} from '../constants/transactions' + +import { addCurrencies } from '../conversion-util' + +abiDecoder.addABI(abi) + +export function getTokenData (data = '') { + return abiDecoder.decodeMethod(data) +} + +const registry = new MethodRegistry({ provider: global.ethereumProvider }) + +export async function getMethodData (data = '') { + const prefixedData = ethUtil.addHexPrefix(data) + const fourBytePrefix = prefixedData.slice(0, 10) + const sig = await registry.lookup(fourBytePrefix) + const parsedResult = registry.parse(sig) + + return { + name: parsedResult.name, + params: parsedResult.args, + } +} + +export function isConfirmDeployContract (txData = {}) { + const { txParams = {} } = txData + return !txParams.to +} + +export async function getTransactionActionKey (transaction, methodData) { + const { txParams: { data, to } = {}, msgParams } = transaction + + if (msgParams) { + return SIGNATURE_REQUEST_KEY + } + + if (isConfirmDeployContract(transaction)) { + return DEPLOY_CONTRACT_ACTION_KEY + } + + if (data) { + const toSmartContract = await isSmartContractAddress(to) + + if (!toSmartContract) { + return SEND_ETHER_ACTION_KEY + } + + const { name } = methodData + const methodName = name && name.toLowerCase() + + if (!methodName) { + return UNKNOWN_FUNCTION_KEY + } + + switch (methodName) { + case TOKEN_METHOD_TRANSFER: + return SEND_TOKEN_ACTION_KEY + case TOKEN_METHOD_APPROVE: + return APPROVE_ACTION_KEY + case TOKEN_METHOD_TRANSFER_FROM: + return TRANSFER_FROM_ACTION_KEY + default: + return name + } + } else { + return SEND_ETHER_ACTION_KEY + } +} + +export function getLatestSubmittedTxWithNonce (transactions = [], nonce = '0x0') { + if (!transactions.length) { + return {} + } + + return transactions.reduce((acc, current) => { + const { submittedTime, txParams: { nonce: currentNonce } = {} } = current + + if (currentNonce === nonce) { + return acc.submittedTime + ? submittedTime > acc.submittedTime ? current : acc + : current + } else { + return acc + } + }, {}) +} + +export async function isSmartContractAddress (address) { + const code = await global.eth.getCode(address) + return code && code !== '0x' +} + +export function sumHexes (...args) { + const total = args.reduce((acc, base) => { + return addCurrencies(acc, base, { + toNumericBase: 'hex', + }) + }) + + return ethUtil.addHexPrefix(total) +} diff --git a/ui/app/higher-order-components/with-method-data/index.js b/ui/app/higher-order-components/with-method-data/index.js new file mode 100644 index 000000000..f511e1ae7 --- /dev/null +++ b/ui/app/higher-order-components/with-method-data/index.js @@ -0,0 +1 @@ +export { default } from './with-method-data.component' diff --git a/ui/app/higher-order-components/with-method-data/with-method-data.component.js b/ui/app/higher-order-components/with-method-data/with-method-data.component.js new file mode 100644 index 000000000..fed7d9865 --- /dev/null +++ b/ui/app/higher-order-components/with-method-data/with-method-data.component.js @@ -0,0 +1,52 @@ +import React, { PureComponent } from 'react' +import PropTypes from 'prop-types' +import { getMethodData } from '../../helpers/transactions.util' + +export default function withMethodData (WrappedComponent) { + return class MethodDataWrappedComponent extends PureComponent { + static propTypes = { + transaction: PropTypes.object, + } + + static defaultProps = { + transaction: {}, + } + + state = { + methodData: {}, + done: false, + error: null, + } + + componentDidMount () { + this.fetchMethodData() + } + + async fetchMethodData () { + const { transaction } = this.props + const { txParams: { data = '' } = {} } = transaction + + if (data) { + try { + const methodData = await getMethodData(data) + this.setState({ methodData, done: true }) + } catch (error) { + this.setState({ done: true, error }) + } + } else { + this.setState({ done: true }) + } + } + + render () { + const { methodData, done, error } = this.state + + return ( + + ) + } + } +} diff --git a/ui/app/higher-order-components/with-token-tracker/index.js b/ui/app/higher-order-components/with-token-tracker/index.js new file mode 100644 index 000000000..d401e81f1 --- /dev/null +++ b/ui/app/higher-order-components/with-token-tracker/index.js @@ -0,0 +1 @@ +export { default } from './with-token-tracker.component' diff --git a/ui/app/higher-order-components/with-token-tracker/with-token-tracker.component.js b/ui/app/higher-order-components/with-token-tracker/with-token-tracker.component.js new file mode 100644 index 000000000..d9912d44b --- /dev/null +++ b/ui/app/higher-order-components/with-token-tracker/with-token-tracker.component.js @@ -0,0 +1,106 @@ +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import TokenTracker from 'eth-token-watcher' + +export default function withTokenTracker (WrappedComponent) { + return class TokenTrackerWrappedComponent extends Component { + static propTypes = { + userAddress: PropTypes.string.isRequired, + token: PropTypes.object.isRequired, + } + + constructor (props) { + super(props) + + this.state = { + string: '', + symbol: '', + error: null, + } + + this.tracker = null + this.updateBalance = this.updateBalance.bind(this) + this.setError = this.setError.bind(this) + } + + componentDidMount () { + this.createFreshTokenTracker() + } + + componentDidUpdate (prevProps) { + const { userAddress: newAddress, token: { address: newTokenAddress } } = this.props + const { userAddress: oldAddress, token: { address: oldTokenAddress } } = prevProps + + if ((oldAddress === newAddress) && (oldTokenAddress === newTokenAddress)) { + return + } + + if ((!oldAddress || !newAddress) && (!oldTokenAddress || !newTokenAddress)) { + return + } + + this.createFreshTokenTracker() + } + + componentWillUnmount () { + this.removeListeners() + } + + createFreshTokenTracker () { + this.removeListeners() + + if (!global.ethereumProvider) { + return + } + + const { userAddress, token } = this.props + + this.tracker = new TokenTracker({ + userAddress, + provider: global.ethereumProvider, + tokens: [token], + pollingInterval: 8000, + }) + + this.tracker.on('update', this.updateBalance) + this.tracker.on('error', this.setError) + + this.tracker.updateBalances() + .then(() => this.updateBalance(this.tracker.serialize())) + .catch(error => this.setState({ error: error.message })) + } + + setError (error) { + this.setState({ error }) + } + + updateBalance (tokens = []) { + if (!this.tracker.running) { + return + } + const [{ string, symbol }] = tokens + this.setState({ string, symbol, error: null }) + } + + removeListeners () { + if (this.tracker) { + this.tracker.stop() + this.tracker.removeListener('update', this.updateBalance) + this.tracker.removeListener('error', this.setError) + } + } + + render () { + const { string, symbol, error } = this.state + + return ( + + ) + } + } +} diff --git a/ui/app/i18n-provider.js b/ui/app/i18n-provider.js index c0f6d00ec..76cbf099b 100644 --- a/ui/app/i18n-provider.js +++ b/ui/app/i18n-provider.js @@ -5,6 +5,11 @@ const { compose } = require('recompose') const t = require('../i18n-helper').getMessage class I18nProvider extends Component { + tOrDefault = (key, defaultValue, ...args) => { + const { localeMessages: { current, en } = {} } = this.props + return t(current, key, ...args) || t(en, key, ...args) || defaultValue + } + getChildContext () { const { localeMessages } = this.props const { current, en } = localeMessages @@ -12,6 +17,10 @@ class I18nProvider extends Component { t (key, ...args) { return t(current, key, ...args) || t(en, key, ...args) || `[${key}]` }, + tOrDefault: this.tOrDefault, + tOrKey (key, ...args) { + return this.tOrDefault(key, key, ...args) + }, } } @@ -27,6 +36,8 @@ I18nProvider.propTypes = { I18nProvider.childContextTypes = { t: PropTypes.func, + tOrDefault: PropTypes.func, + tOrKey: PropTypes.func, } const mapStateToProps = state => { diff --git a/ui/app/main-container.js b/ui/app/main-container.js deleted file mode 100644 index 8a0708025..000000000 --- a/ui/app/main-container.js +++ /dev/null @@ -1,49 +0,0 @@ -const Component = require('react').Component -const h = require('react-hyperscript') -const inherits = require('util').inherits -const AccountAndTransactionDetails = require('./account-and-transaction-details') -const Settings = require('./components/pages/settings') -const log = require('loglevel') - -import UnlockScreen from './components/pages/unlock-page' - -module.exports = MainContainer - -inherits(MainContainer, Component) -function MainContainer () { - Component.call(this) -} - -MainContainer.prototype.render = function () { - // 3. summarize: - // switch statement goes inside MainContainer, - // or a method in renderPrimary - // - pass resulting h() to MainContainer - // - error checking in separate func - // - router in separate func - const contents = { - component: AccountAndTransactionDetails, - key: 'account-detail', - style: {}, - } - - if (this.props.isUnlocked === false) { - switch (this.props.currentViewName) { - case 'config': - log.debug('rendering config screen from unlock screen.') - return h(Settings, {key: 'config'}) - default: - log.debug('rendering locked screen') - return h('.unlock-screen-container', {}, h(UnlockScreen, { key: 'locked' })) - } - } - - return h('div.main-container', { - style: contents.style, - }, [ - h(contents.component, { - key: contents.key, - }, []), - ]) -} - diff --git a/ui/app/new-keychain.js b/ui/app/new-keychain.js deleted file mode 100644 index cc9633166..000000000 --- a/ui/app/new-keychain.js +++ /dev/null @@ -1,29 +0,0 @@ -const inherits = require('util').inherits -const Component = require('react').Component -const h = require('react-hyperscript') -const connect = require('react-redux').connect - -module.exports = connect(mapStateToProps)(NewKeychain) - -function mapStateToProps (state) { - return {} -} - -inherits(NewKeychain, Component) -function NewKeychain () { - Component.call(this) -} - -NewKeychain.prototype.render = function () { - // const props = this.props - - return ( - h('div', { - style: { - background: 'blue', - }, - }, [ - h('h1', `Here's a list!!!!`), - ]) - ) -} diff --git a/ui/app/reducers/app.js b/ui/app/reducers/app.js index 5a2d550b0..799bae0bd 100644 --- a/ui/app/reducers/app.js +++ b/ui/app/reducers/app.js @@ -48,7 +48,11 @@ function reduceApp (state, action) { name: null, }, }, - sidebarOpen: false, + sidebar: { + isOpen: false, + transitionName: '', + type: '', + }, alertOpen: false, alertMessage: null, qrCodeData: null, @@ -90,12 +94,18 @@ function reduceApp (state, action) { // sidebar methods case actions.SIDEBAR_OPEN: return extend(appState, { - sidebarOpen: true, + sidebar: { + ...action.value, + isOpen: true, + }, }) case actions.SIDEBAR_CLOSE: return extend(appState, { - sidebarOpen: false, + sidebar: { + ...appState.sidebar, + isOpen: false, + }, }) // alert methods @@ -221,6 +231,15 @@ function reduceApp (state, action) { transForward: action.value, }) + case actions.SHOW_ADD_SUGGESTED_TOKEN_PAGE: + return extend(appState, { + currentView: { + name: 'add-suggested-token', + context: appState.currentView.context, + }, + transForward: action.value, + }) + case actions.SHOW_REMOVE_TOKEN_PAGE: return extend(appState, { currentView: { diff --git a/ui/app/routes.js b/ui/app/routes.js index f6b2a7a55..76afed5db 100644 --- a/ui/app/routes.js +++ b/ui/app/routes.js @@ -7,6 +7,7 @@ const CONFIRM_SEED_ROUTE = '/confirm-seed' const RESTORE_VAULT_ROUTE = '/restore-vault' const ADD_TOKEN_ROUTE = '/add-token' const CONFIRM_ADD_TOKEN_ROUTE = '/confirm-add-token' +const CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE = '/confirm-add-suggested-token' const NEW_ACCOUNT_ROUTE = '/new-account' const IMPORT_ACCOUNT_ROUTE = '/new-account/import' const CONNECT_HARDWARE_ROUTE = '/new-account/connect' @@ -41,6 +42,7 @@ module.exports = { RESTORE_VAULT_ROUTE, ADD_TOKEN_ROUTE, CONFIRM_ADD_TOKEN_ROUTE, + CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE, NEW_ACCOUNT_ROUTE, IMPORT_ACCOUNT_ROUTE, CONNECT_HARDWARE_ROUTE, diff --git a/ui/app/selectors.js b/ui/app/selectors.js index 2432c0a6b..fb4517628 100644 --- a/ui/app/selectors.js +++ b/ui/app/selectors.js @@ -1,6 +1,9 @@ -const valuesFor = require('./util').valuesFor const abi = require('human-standard-token-abi') +import { + transactionsSelector, +} from './selectors/transactions' + const { multiplyCurrencies, } = require('./conversion-util') @@ -11,6 +14,8 @@ const selectors = { getSelectedAccount, getSelectedToken, getSelectedTokenExchangeRate, + getSelectedTokenAssetImage, + getAssetImages, getTokenExchangeRate, conversionRateSelector, transactionsSelector, @@ -68,6 +73,18 @@ function getSelectedTokenExchangeRate (state) { return contractExchangeRates[address] || 0 } +function getSelectedTokenAssetImage (state) { + const assetImages = state.metamask.assetImages || {} + const selectedToken = getSelectedToken(state) || {} + const { address } = selectedToken + return assetImages[address] +} + +function getAssetImages (state) { + const assetImages = state.metamask.assetImages || {} + return assetImages +} + function getTokenExchangeRate (state, address) { const contractExchangeRates = state.metamask.contractExchangeRates return contractExchangeRates[address] || 0 @@ -101,21 +118,6 @@ function getCurrentAccountWithSendEtherInfo (state) { return accounts.find(({ address }) => address === currentAddress) } -function transactionsSelector (state) { - const { network, selectedTokenAddress } = state.metamask - const unapprovedMsgs = valuesFor(state.metamask.unapprovedMsgs) - const shapeShiftTxList = (network === '1') ? state.metamask.shapeShiftTxList : undefined - const transactions = state.metamask.selectedAddressTxList || [] - const txsToRender = !shapeShiftTxList ? transactions.concat(unapprovedMsgs) : transactions.concat(unapprovedMsgs, shapeShiftTxList) - - return selectedTokenAddress - ? txsToRender - .filter(({ txParams }) => txParams && txParams.to === selectedTokenAddress) - .sort((a, b) => b.time - a.time) - : txsToRender - .sort((a, b) => b.time - a.time) -} - function getGasIsLoading (state) { return state.appState.gasIsLoading } diff --git a/ui/app/selectors/tokens.js b/ui/app/selectors/tokens.js new file mode 100644 index 000000000..47b6e0192 --- /dev/null +++ b/ui/app/selectors/tokens.js @@ -0,0 +1,11 @@ +import { createSelector } from 'reselect' + +export const selectedTokenAddressSelector = state => state.metamask.selectedTokenAddress +export const tokenSelector = state => state.metamask.tokens +export const selectedTokenSelector = createSelector( + tokenSelector, + selectedTokenAddressSelector, + (tokens = [], selectedTokenAddress = '') => { + return tokens.find(({ address }) => address === selectedTokenAddress) + } +) diff --git a/ui/app/selectors/transactions.js b/ui/app/selectors/transactions.js new file mode 100644 index 000000000..3e9843722 --- /dev/null +++ b/ui/app/selectors/transactions.js @@ -0,0 +1,58 @@ +import { createSelector } from 'reselect' +import { valuesFor } from '../util' +import { + UNAPPROVED_STATUS, + APPROVED_STATUS, + SUBMITTED_STATUS, +} from '../constants/transactions' + +import { selectedTokenAddressSelector } from './tokens' + +export const shapeShiftTxListSelector = state => state.metamask.shapeShiftTxList +export const unapprovedMsgsSelector = state => state.metamask.unapprovedMsgs +export const selectedAddressTxListSelector = state => state.metamask.selectedAddressTxList + +const pendingStatusHash = { + [UNAPPROVED_STATUS]: true, + [APPROVED_STATUS]: true, + [SUBMITTED_STATUS]: true, +} + +export const transactionsSelector = createSelector( + selectedTokenAddressSelector, + unapprovedMsgsSelector, + shapeShiftTxListSelector, + selectedAddressTxListSelector, + (selectedTokenAddress, unapprovedMsgs = {}, shapeShiftTxList = [], transactions = []) => { + const unapprovedMsgsList = valuesFor(unapprovedMsgs) + const txsToRender = transactions.concat(unapprovedMsgsList, shapeShiftTxList) + + return selectedTokenAddress + ? txsToRender + .filter(({ txParams }) => txParams && txParams.to === selectedTokenAddress) + .sort((a, b) => b.time - a.time) + : txsToRender + .sort((a, b) => b.time - a.time) + } +) + +export const pendingTransactionsSelector = createSelector( + transactionsSelector, + (transactions = []) => ( + transactions.filter(transaction => transaction.status in pendingStatusHash) + ) +) + +export const submittedPendingTransactionsSelector = createSelector( + transactionsSelector, + (transactions = []) => ( + transactions.filter(transaction => transaction.status === SUBMITTED_STATUS) + ) +) + +export const completedTransactionsSelector = createSelector( + transactionsSelector, + (transactions = []) => ( + transactions.filter(transaction => !(transaction.status in pendingStatusHash)) + ) +) diff --git a/ui/app/token-util.js b/ui/app/token-util.js index 016efdac1..007efbdb8 100644 --- a/ui/app/token-util.js +++ b/ui/app/token-util.js @@ -1,8 +1,99 @@ const log = require('loglevel') const util = require('./util') const BigNumber = require('bignumber.js') +import contractMap from 'eth-contract-metadata' -function tokenInfoGetter () { +const casedContractMap = Object.keys(contractMap).reduce((acc, base) => { + return { + ...acc, + [base.toLowerCase()]: contractMap[base], + } +}, {}) + +const DEFAULT_SYMBOL = '' +const DEFAULT_DECIMALS = '0' + +async function getSymbolFromContract (tokenAddress) { + const token = util.getContractAtAddress(tokenAddress) + + try { + const result = await token.symbol() + return result[0] + } catch (error) { + log.warn(`symbol() call for token at address ${tokenAddress} resulted in error:`, error) + } +} + +async function getDecimalsFromContract (tokenAddress) { + const token = util.getContractAtAddress(tokenAddress) + + try { + const result = await token.decimals() + const decimalsBN = result[0] + return decimalsBN && decimalsBN.toString() + } catch (error) { + log.warn(`decimals() call for token at address ${tokenAddress} resulted in error:`, error) + } +} + +function getContractMetadata (tokenAddress) { + return tokenAddress && casedContractMap[tokenAddress.toLowerCase()] +} + +async function getSymbol (tokenAddress) { + let symbol = await getSymbolFromContract(tokenAddress) + + if (!symbol) { + const contractMetadataInfo = getContractMetadata(tokenAddress) + + if (contractMetadataInfo) { + symbol = contractMetadataInfo.symbol + } + } + + return symbol +} + +async function getDecimals (tokenAddress) { + let decimals = await getDecimalsFromContract(tokenAddress) + + if (!decimals || decimals === '0') { + const contractMetadataInfo = getContractMetadata(tokenAddress) + + if (contractMetadataInfo) { + decimals = contractMetadataInfo.decimals + } + } + + return decimals +} + +export async function getSymbolAndDecimals (tokenAddress, existingTokens = []) { + const existingToken = existingTokens.find(({ address }) => tokenAddress === address) + + if (existingToken) { + return { + symbol: existingToken.symbol, + decimals: existingToken.decimals, + } + } + + let symbol, decimals + + try { + symbol = await getSymbol(tokenAddress) + decimals = await getDecimals(tokenAddress) + } catch (error) { + log.warn(`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`, error) + } + + return { + symbol: symbol || DEFAULT_SYMBOL, + decimals: decimals || DEFAULT_DECIMALS, + } +} + +export function tokenInfoGetter () { const tokens = {} return async (address) => { @@ -16,46 +107,12 @@ function tokenInfoGetter () { } } -async function getSymbolAndDecimals (tokenAddress, existingTokens = []) { - const existingToken = existingTokens.find(({ address }) => tokenAddress === address) - if (existingToken) { - return existingToken - } - - let result = [] - try { - const token = util.getContractAtAddress(tokenAddress) - - result = await Promise.all([ - token.symbol(), - token.decimals(), - ]) - } catch (err) { - log.warn(`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`, err) - } - - const [ symbol = [], decimals = [] ] = result - - return { - symbol: symbol[0] || null, - decimals: decimals[0] && decimals[0].toString() || null, - } -} - -function calcTokenAmount (value, decimals) { +export function calcTokenAmount (value, decimals) { const multiplier = Math.pow(10, Number(decimals || 0)) return new BigNumber(String(value)).div(multiplier).toNumber() } -function calcTokenAmountWithDec (valueWithoutDec, decimals) { +export function calcTokenAmountWithDec (valueWithoutDec, decimals) { const multiplier = Math.pow(10, Number(decimals || 0)) return new BigNumber(valueWithoutDec).mul(multiplier).toNumber() } - - -module.exports = { - tokenInfoGetter, - calcTokenAmount, - calcTokenAmountWithDec, - getSymbolAndDecimals, -} diff --git a/ui/app/util.js b/ui/app/util.js index ade4fec8a..37c0fb698 100644 --- a/ui/app/util.js +++ b/ui/app/util.js @@ -9,7 +9,7 @@ const MIN_GAS_PRICE_BN = MIN_GAS_PRICE_GWEI_BN.mul(GWEI_FACTOR) // formatData :: ( date: ) -> String function formatDate (date) { - return vreme.format(new Date(date), 'March 16 2014 14:30') + return vreme.format(new Date(date), '3/16/2014 at 14:30') } var valueTable = { diff --git a/ui/i18n-helper.js b/ui/i18n-helper.js index bc927ee65..c6a7d0bf1 100644 --- a/ui/i18n-helper.js +++ b/ui/i18n-helper.js @@ -20,10 +20,10 @@ const getMessage = (locale, key, substitutions) => { let phrase = entry.message // perform substitutions if (substitutions && substitutions.length) { - phrase = phrase.replace(/\$1/g, substitutions[0]) - if (substitutions.length > 1) { - phrase = phrase.replace(/\$2/g, substitutions[1]) - } + substitutions.forEach((substitution, index) => { + const regex = new RegExp(`\\$${index + 1}`, 'g') + phrase = phrase.replace(regex, substitution) + }) } return phrase }