diff --git a/.circleci/config.yml b/.circleci/config.yml index 5270da98f1..af3b70ebbe 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -22,7 +22,6 @@ workflows: - test-lint: requires: - prep-deps - - test-lint-shellcheck - test-e2e-chrome: requires: - prep-deps @@ -50,7 +49,6 @@ workflows: - all-tests-pass: requires: - test-lint - - test-lint-shellcheck - test-unit - test-unit-global - test-mozilla-lint @@ -175,16 +173,6 @@ jobs: name: Verify locales command: yarn verify-locales --quiet - test-lint-shellcheck: - docker: - - image: circleci/node:10.17-browsers - steps: - - checkout - - run: sudo apt-get install shellcheck - - run: - name: Shellcheck Lint - command: yarn lint:shellcheck - test-deps: docker: - image: circleci/node:10.17-browsers diff --git a/.eslintrc b/.eslintrc index b5f1671544..5ab07152eb 100644 --- a/.eslintrc +++ b/.eslintrc @@ -51,13 +51,13 @@ "accessor-pairs": 2, "arrow-spacing": [2, { "before": true, "after": true }], "block-spacing": [2, "always"], - "brace-style": 2, + "brace-style": [2, "1tbs", { "allowSingleLine": true }], "camelcase": [2, { "properties": "never" }], "comma-dangle": [2, "always-multiline"], "comma-spacing": [2, { "before": false, "after": true }], "comma-style": [2, "last"], "constructor-super": 2, - "curly": 2, + "curly": [2, "multi-line"], "dot-location": [2, "property"], "eol-last": 2, "eqeqeq": [2, "allow-null"], @@ -144,14 +144,12 @@ "no-useless-computed-key": 2, "no-useless-constructor": 2, "no-useless-escape": 2, - "no-var": 2, "no-whitespace-before-property": 2, "no-with": 2, "one-var": [2, { "initialized": "never" }], "operator-linebreak": [2, "after", { "overrides": { "?": "ignore", ":": "ignore" } }], "padded-blocks": "off", "quotes": [2, "single", {"avoidEscape": true, "allowTemplateLiterals": true}], - "react/no-unused-state": 2, "react/jsx-boolean-value": 2, "react/jsx-curly-brace-presence": [2, { "props": "never", "children": "never" }], "react/jsx-equals-spacing": 2, diff --git a/.gitattributes b/.gitattributes index 561741e377..590ac71c00 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,3 @@ -* text=auto CHANGELOG.md merge=union # Reviewing the lockfile contents is an important step in verifying that diff --git a/CHANGELOG.md b/CHANGELOG.md index 65b25c13d7..02d6a0b647 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,19 +2,6 @@ ## Current Develop Branch -## 7.7.0 Thu Nov 28 2019 -- [#7004](https://github.com/MetaMask/metamask-extension/pull/7004): Connect distinct accounts per site -- [#7480](https://github.com/MetaMask/metamask-extension/pull/7480): Fixed link on root README.md -- [#7482](https://github.com/MetaMask/metamask-extension/pull/7482): Update Wyre ETH purchase url -- [#7484](https://github.com/MetaMask/metamask-extension/pull/7484): Ensure transactions are shown in the order they are received -- [#7491](https://github.com/MetaMask/metamask-extension/pull/7491): Update gas when token is changed on the send screen -- [#7501](https://github.com/MetaMask/metamask-extension/pull/7501): Fix accessibility of first-time-flow terms checkboxes -- [#7502](https://github.com/MetaMask/metamask-extension/pull/7502): Fix chainId for non standard networks -- [#7579](https://github.com/MetaMask/metamask-extension/pull/7579): Fix timing of DAI migration notifications after dismissal -- [#7519](https://github.com/MetaMask/metamask-extension/pull/7519): Fixing hardware connect error display -- [#7558](https://github.com/MetaMask/metamask-extension/pull/7558): Use localized messages for NotificationModal buttons -- [#7488](https://github.com/MetaMask/metamask-extension/pull/7488): Fix text overlap when expanding transaction - ## 7.6.1 Tue Nov 19 2019 - [#7475](https://github.com/MetaMask/metamask-extension/pull/7475): Add 'Remind Me Later' to the Maker notification - [#7436](https://github.com/MetaMask/metamask-extension/pull/7436): Add additional rpcUrl verification diff --git a/README.md b/README.md index c2f657f703..a79a5b66fa 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,6 @@ To write tests that will be run in the browser using QUnit, add your test files - [How to add new networks to the Provider Menu](./docs/adding-new-networks.md) - [How to port MetaMask to a new platform](./docs/porting_to_new_environment.md) - [How to use the TREZOR emulator](./docs/trezor-emulator.md) -- [How to generate a visualization of this repository's development](./development/gource-viz.sh) +- [How to generate a visualization of this repository's development](./docs/development-visualization.md) [1]: http://www.nomnoml.com/#view/%5B%3Cactor%3Euser%5D%0A%0A%5Bmetamask-ui%7C%0A%20%20%20%5Btools%7C%0A%20%20%20%20%20react%0A%20%20%20%20%20redux%0A%20%20%20%20%20thunk%0A%20%20%20%20%20ethUtils%0A%20%20%20%20%20jazzicon%0A%20%20%20%5D%0A%20%20%20%5Bcomponents%7C%0A%20%20%20%20%20app%0A%20%20%20%20%20account-detail%0A%20%20%20%20%20accounts%0A%20%20%20%20%20locked-screen%0A%20%20%20%20%20restore-vault%0A%20%20%20%20%20identicon%0A%20%20%20%20%20config%0A%20%20%20%20%20info%0A%20%20%20%5D%0A%20%20%20%5Breducers%7C%0A%20%20%20%20%20app%0A%20%20%20%20%20metamask%0A%20%20%20%20%20identities%0A%20%20%20%5D%0A%20%20%20%5Bactions%7C%0A%20%20%20%20%20%5BbackgroundConnection%5D%0A%20%20%20%5D%0A%20%20%20%5Bcomponents%5D%3A-%3E%5Bactions%5D%0A%20%20%20%5Bactions%5D%3A-%3E%5Breducers%5D%0A%20%20%20%5Breducers%5D%3A-%3E%5Bcomponents%5D%0A%5D%0A%0A%5Bweb%20dapp%7C%0A%20%20%5Bui%20code%5D%0A%20%20%5Bweb3%5D%0A%20%20%5Bmetamask-inpage%5D%0A%20%20%0A%20%20%5B%3Cactor%3Eui%20developer%5D%0A%20%20%5Bui%20developer%5D-%3E%5Bui%20code%5D%0A%20%20%5Bui%20code%5D%3C-%3E%5Bweb3%5D%0A%20%20%5Bweb3%5D%3C-%3E%5Bmetamask-inpage%5D%0A%5D%0A%0A%5Bmetamask-background%7C%0A%20%20%5Bprovider-engine%5D%0A%20%20%5Bhooked%20wallet%20subprovider%5D%0A%20%20%5Bid%20store%5D%0A%20%20%0A%20%20%5Bprovider-engine%5D%3C-%3E%5Bhooked%20wallet%20subprovider%5D%0A%20%20%5Bhooked%20wallet%20subprovider%5D%3C-%3E%5Bid%20store%5D%0A%20%20%5Bconfig%20manager%7C%0A%20%20%20%20%5Brpc%20configuration%5D%0A%20%20%20%20%5Bencrypted%20keys%5D%0A%20%20%20%20%5Bwallet%20nicknames%5D%0A%20%20%5D%0A%20%20%0A%20%20%5Bprovider-engine%5D%3C-%5Bconfig%20manager%5D%0A%20%20%5Bid%20store%5D%3C-%3E%5Bconfig%20manager%5D%0A%5D%0A%0A%5Buser%5D%3C-%3E%5Bmetamask-ui%5D%0A%0A%5Buser%5D%3C%3A--%3A%3E%5Bweb%20dapp%5D%0A%0A%5Bmetamask-contentscript%7C%0A%20%20%5Bplugin%20restart%20detector%5D%0A%20%20%5Brpc%20passthrough%5D%0A%5D%0A%0A%5Brpc%20%7C%0A%20%20%5Bethereum%20blockchain%20%7C%0A%20%20%20%20%5Bcontracts%5D%0A%20%20%20%20%5Baccounts%5D%0A%20%20%5D%0A%5D%0A%0A%5Bweb%20dapp%5D%3C%3A--%3A%3E%5Bmetamask-contentscript%5D%0A%5Bmetamask-contentscript%5D%3C-%3E%5Bmetamask-background%5D%0A%5Bmetamask-background%5D%3C-%3E%5Bmetamask-ui%5D%0A%5Bmetamask-background%5D%3C-%3E%5Brpc%5D%0A diff --git a/app/_locales/cs/messages.json b/app/_locales/cs/messages.json index 9d04ae048c..cd768d4d87 100644 --- a/app/_locales/cs/messages.json +++ b/app/_locales/cs/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Naozaj chcete vymazať schválené webové stránky?" + }, + "clearApprovalData": { + "message": "Jasné údaje o schválení" + }, "reject": { "message": "Odmítnout" }, + "providerRequestInfo": { + "message": "Níže uvedená doména se pokouší požádat o přístup k API Ethereum, aby mohla komunikovat s blokádou Ethereum. Před schválením přístupu Ethereum vždy zkontrolujte, zda jste na správném místě." + }, "account": { "message": "Účet" }, @@ -49,6 +58,10 @@ "balanceIsInsufficientGas": { "message": "Nedostatek prostředků pro aktuální množství paliva" }, + "betweenMinAndMax": { + "message": "musí být větší nebo roven $1 a menší nebo roven $2.", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Použít Blockies Identicon" }, @@ -100,6 +113,9 @@ "copiedExclamation": { "message": "Zkopírováno!" }, + "copy": { + "message": "Kopírovat" + }, "copyToClipboard": { "message": "Kopírovat do schránky" }, @@ -211,6 +227,10 @@ "message": "Získejte Ether z faucetu za $1.", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "musí být větší nebo roven $1.", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "zde", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -265,6 +285,10 @@ "learnMore": { "message": "Zjistěte více." }, + "lessThanMax": { + "message": "musí být menší nebo roven $1.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Chcete přidat tyto tokeny?" }, @@ -343,6 +367,9 @@ "message": "Vložte zde svůj privátní klíč:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Svou klíčovou frázi vložte zde!" + }, "personalAddressDetected": { "message": "Detekována osobní adresa. Zadejte adresu kontraktu tokenu." }, @@ -449,6 +476,9 @@ "stateLogError": { "message": "Chyba během získávání stavových protokolů." }, + "submit": { + "message": "Odeslat" + }, "submitted": { "message": "Odesláno" }, @@ -505,6 +535,9 @@ "usedByClients": { "message": "Používána různými klienty" }, + "validFileImport": { + "message": "Musíte vybrat validní soubor k importu." + }, "viewAccount": { "message": "Zobrazit účet" }, diff --git a/app/_locales/de/messages.json b/app/_locales/de/messages.json index 8d11cd9b98..f43c3626cb 100644 --- a/app/_locales/de/messages.json +++ b/app/_locales/de/messages.json @@ -50,9 +50,12 @@ "reject": { "message": "Ablehnen" }, - "likeToConnect": { + "providerRequest": { "message": "$1 möchte sich mit deinem Account verbinden" }, + "providerRequestInfo": { + "message": "Diese Website fordert Zugriff auf Ihre aktuelle Kontoadresse. Stellen Sie immer sicher, dass Sie den Websites vertrauen, mit denen Sie interagieren." + }, "about": { "message": "Über" }, @@ -217,6 +220,10 @@ "basic": { "message": "Grundlegend" }, + "betweenMinAndMax": { + "message": "Muss größer oder gleich $1 und kleiner oder gleich $2 sein.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "Block-Explorer" }, @@ -386,6 +393,9 @@ "copiedExclamation": { "message": "Kopiert!" }, + "copy": { + "message": "Kopieren" + }, "copyAddress": { "message": "Adresse in die Zwischenablage kopieren" }, @@ -476,6 +486,9 @@ "directDepositEtherExplainer": { "message": "Wenn du bereits Ether besitzt, ist die sofortige Einzahlung die schnellste Methode Ether in deine neue Wallet zu bekommen." }, + "dismiss": { + "message": "Schließen" + }, "done": { "message": "Fertig" }, @@ -675,6 +688,10 @@ "getStarted": { "message": "Erste Schritte" }, + "greaterThanMin": { + "message": "Muss größer oder gleich $1 sein.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Wir freuen uns, Sie zu sehen." }, @@ -1063,6 +1080,9 @@ "message": "Füge deine Private Key Zeichenfolge hier ein:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Füge deine Seed-Wörterfolge hier ein!" + }, "pending": { "message": "ausstehend" }, @@ -1622,6 +1642,9 @@ "userName": { "message": "Nutzername" }, + "validFileImport": { + "message": "Du musst eine gültige Datei für den Import auswählen." + }, "viewAccount": { "message": " Account einsehen" }, diff --git a/app/_locales/en/messages.json b/app/_locales/en/messages.json index d85b0a80ef..e9e42f5600 100644 --- a/app/_locales/en/messages.json +++ b/app/_locales/en/messages.json @@ -14,39 +14,53 @@ "showIncomingTransactionsDescription": { "message": "Select this to use Etherscan to show incoming transactions in the transactions list" }, - "cancelledConnectionWithMetaMask": { - "message": "Cancelled Connection With MetaMask" - }, "chartOnlyAvailableEth": { "message": "Chart only available on Ethereum networks." }, - "connectedSites": { - "message": "Connected Sites" + "confirmClear": { + "message": "Are you sure you want to clear approved websites?" + }, + "connections": { + "message": "Connections" + }, + "connectionsSettingsDescription": { + "message": "Sites allowed to read your accounts" + }, + "addSite": { + "message": "Add Site" }, - "connectingWithMetaMask": { - "message": "Connecting With MetaMask..." + "addSiteDescription": { + "message": "Manually add a site to allow it access to your accounts, useful for older dapps" }, - "connectTo": { - "message": "Connect to $1", - "description": "$1 is the name/origin of a site/dapp that the user can connect to metamask" + "connected": { + "message": "Connected" }, - "chooseAnAcount": { - "message": "Choose an account" + "connectedDescription": { + "message": "The list of sites allowed access to your addresses" + }, + "privacyModeDefault": { + "message": "Privacy Mode is now enabled by default" }, "contractInteraction": { "message": "Contract Interaction" }, + "clearApprovalData": { + "message": "Remove all sites" + }, "reject": { "message": "Reject" }, - "redirectingBackToDapp": { - "message": "Redirecting back to dapp..." + "providerRequest": { + "message": "$1 would like to connect to your account" + }, + "providerRequestInfo": { + "message": "This site is requesting access to view your current account address. Always make sure you trust the sites you interact with." }, "about": { "message": "About" }, "aboutSettingsDescription": { - "message": "Version, support center, and contact info" + "message": "Version, support center, and contact info." }, "acceleratingATransaction": { "message": "* Accelerating a transaction by using a higher gas price increases its chances of getting processed by the network faster, but it is not always guaranteed." @@ -86,7 +100,7 @@ "message": "Advanced" }, "advancedSettingsDescription": { - "message": "Access developer features, download State Logs, Reset Account, setup testnets and custom RPC" + "message": "Access developer features, download State Logs, Reset Account, setup testnets and custom RPC." }, "advancedOptions": { "message": "Advanced Options" @@ -191,6 +205,10 @@ "basic": { "message": "Basic" }, + "betweenMinAndMax": { + "message": "must be greater than or equal to $1 and less than or equal to $2.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "Block Explorer" }, @@ -291,6 +309,9 @@ "connect": { "message": "Connect" }, + "connectRequest": { + "message": "Connect Request" + }, "connectingTo": { "message": "Connecting to $1" }, @@ -336,6 +357,9 @@ "copiedExclamation": { "message": "Copied!" }, + "copy": { + "message": "Copy" + }, "copyAddress": { "message": "Copy address to clipboard" }, @@ -414,36 +438,14 @@ "details": { "message": "Details" }, - "disconnectAccount": { - "message": "Disconnect account" - }, - "disconnectAll": { - "message": "Disconnect All" - }, - "disconnectAllModalDescription": { - "message": "Are you sure? You will be disconnected from all sites on all accounts." - }, - "disconnectAccountModalDescription": { - "message": "Are you sure? Your account (\"$1\") will be disconnected from this site." - }, - "disconnectAccountQuestion": { - "message": "Disconnect account?" - }, - "disconnectFromThisAccount": { - "message": "Disconnect from this account?" - }, - "disconnectAllAccountsQuestion": { - "message": "Disconnect all accounts?" - }, "directDepositEther": { "message": "Directly Deposit Ether" }, "directDepositEtherExplainer": { "message": "If you already have some Ether, the quickest way to get Ether in your new wallet by direct deposit." }, - "domainLastConnect": { - "message": "Last Connected: $1", - "description": "$1 is the date at which the user was last connected to a given domain" + "dismiss": { + "message": "Dismiss" }, "done": { "message": "Done" @@ -505,17 +507,6 @@ "endOfFlowMessage10": { "message": "All Done" }, - "extensionId": { - "message": "Extension ID: $1", - "description": "$1 is a string of random letters that are the id of another extension connecting to MetaMask" - }, - "externalExtension": { - "message": "External Extension" - }, - "onboardingReturnNotice": { - "message": "\"$1\" will close this tab and direct back to $2", - "description": "Return the user to the site that initiated onboarding" - }, "ensRegistrationError": { "message": "Error in ENS name registration" }, @@ -633,6 +624,10 @@ "getStarted": { "message": "Get Started" }, + "greaterThanMin": { + "message": "must be greater than or equal to $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "We’re happy to see you." }, @@ -745,28 +740,22 @@ "max": { "message": "Max" }, - "lastConnected": { - "message": "Last Connected" - }, "learnMore": { "message": "Learn more" }, - "learnAboutRisks": { - "message": "Learn about the risks here." - }, "ledgerAccountRestriction": { "message": "You need to make use your last account before you can add a new one." }, + "lessThanMax": { + "message": "must be less than or equal to $1.", + "description": "helper for inputting hex as decimal input" + }, "letsGoSetUp": { "message": "Yes, let’s get set up!" }, "likeToAddTokens": { "message": "Would you like to add these tokens?" }, - "likeToConnect": { - "message": "$1 would like to connect to your MetaMask account", - "description": "$1 is the name/url of a site/dapp asking to connect to MetaMask" - }, "links": { "message": "Links" }, @@ -898,9 +887,6 @@ "rpcUrl": { "message": "New RPC URL" }, - "onlyConnectTrust": { - "message": "Only connect with sites you trust." - }, "optionalChainId": { "message": "ChainID (optional)" }, @@ -975,6 +961,9 @@ "message": "Paste your private key string here:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Paste your seed phrase here!" + }, "pending": { "message": "pending" }, @@ -1103,9 +1092,6 @@ "readyToConnect": { "message": "Ready to Connect?" }, - "revokeInPermissions": { - "message": "* You can view and revoke permissions in MetaMask settings." - }, "rinkeby": { "message": "Rinkeby Test Network" }, @@ -1362,14 +1348,6 @@ "testFaucet": { "message": "Test Faucet" }, - "thisWillAllow": { - "message": "This will allow $1 to:", - "description": "$1 is the name or domain of a site/dapp that is requesting permissions" - }, - "thisWillAllowExternalExtension": { - "message": "This will allow an external extension with id $1 to:", - "description": "$1 is a string of random letters that are the id of another extension connecting to MetaMask" - }, "thisWillCreate": { "message": "This will create a new wallet and seed phrase" }, @@ -1382,10 +1360,6 @@ "toWithColon": { "message": "To:" }, - "toConnectWith": { - "message": "To connect with $1", - "description": "$1 is the name or domain of a site/dapp that asking to connect with MetaMask" - }, "toETHviaShapeShift": { "message": "$1 to ETH via ShapeShift", "description": "system will fill in deposit type in start of message" @@ -1515,6 +1489,9 @@ "userName": { "message": "Username" }, + "validFileImport": { + "message": "You must select a valid file to import." + }, "viewAccount": { "message": "View Account" }, diff --git a/app/_locales/es/messages.json b/app/_locales/es/messages.json index f64105f263..e503cd977e 100644 --- a/app/_locales/es/messages.json +++ b/app/_locales/es/messages.json @@ -1,16 +1,28 @@ { + "privacyModeDefault": { + "message": "Modo Privado está activado ahora por defecto" + }, "chartOnlyAvailableEth": { "message": "Tabla solo disponible en redes Ethereum." }, + "confirmClear": { + "message": "¿Seguro que quieres borrar los sitios web aprobados?" + }, "contractInteraction": { "message": "Interacción con contrato" }, + "clearApprovalData": { + "message": "Borrar datos de aprobación" + }, "reject": { "message": "Rechazar" }, - "likeToConnect": { + "providerRequest": { "message": "$1 quisiera conectar con tu cuenta" }, + "providerRequestInfo": { + "message": "El dominio que se muestra a continuación intenta solicitar acceso a la API Ethereum para que pueda interactuar con la blockchain de Ethereum. Siempre verifique que esté en el sitio correcto antes de aprobar el acceso Ethereum." + }, "about": { "message": "Acerca" }, @@ -133,6 +145,10 @@ "basic": { "message": "Básico" }, + "betweenMinAndMax": { + "message": "Debe ser mayor o igual a $1 y menor o igual a $2", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Usar Blockies Identicon (Iconos)" }, @@ -193,6 +209,9 @@ "connect": { "message": "Conectar" }, + "connectRequest": { + "message": "Petición para conectar" + }, "connectingTo": { "message": "Conectánodse a $1" }, @@ -232,6 +251,9 @@ "copiedExclamation": { "message": "¡Copiado!" }, + "copy": { + "message": "Copiar" + }, "copyAddress": { "message": "Copiar la dirección al portapapeles" }, @@ -310,6 +332,9 @@ "directDepositEtherExplainer": { "message": "Si posees Ether, la forma más rápida de transferirlo a tu nueva billetera es depositándolo directamente" }, + "dismiss": { + "message": "Descartar" + }, "done": { "message": "Completo" }, @@ -424,6 +449,10 @@ "getHelp": { "message": "Pedir ayuda." }, + "greaterThanMin": { + "message": "Debe ser mayor o igual a $1", + "description": "helper for inputting hex as decimal input" + }, "hardwareWalletConnected": { "message": "Se ha conectado el monedero físico" }, @@ -524,6 +553,10 @@ "ledgerAccountRestriction": { "message": "Hay que hacer uso de tu última cuenta antes de agregarle una nueva." }, + "lessThanMax": { + "message": "Debe ser menor o igual a $1", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "¿Te gustaría agregar estos tokens?" }, @@ -668,6 +701,9 @@ "message": "Pega tu clave privada aqui", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "¡Pega tu frase semilla aquí!" + }, "pending": { "message": "pendiente" }, @@ -930,6 +966,9 @@ "step3HardwareWalletMsg": { "message": "Usa tu cuenta física igual que harías con cualquier cuenta de Ethereum. Regístrate con dApps, manda Eth, compra y almacena tokens de ERC20 y otros tokens no-fungibles, como CryptoKitties." }, + "submit": { + "message": "Enviar" + }, "submitted": { "message": "Enviado" }, @@ -1058,6 +1097,9 @@ "usedByClients": { "message": "Utilizado por una variedad de clientes diferentes" }, + "validFileImport": { + "message": "Debes selecionar un archivo valido para importar" + }, "viewAccount": { "message": "Mirar cuenta" }, diff --git a/app/_locales/fr/messages.json b/app/_locales/fr/messages.json index 94fe260fdd..e9fef5d768 100644 --- a/app/_locales/fr/messages.json +++ b/app/_locales/fr/messages.json @@ -32,6 +32,9 @@ "confirmClear": { "message": "Êtes-vous sûr de vouloir supprimer les sites Web approuvés?" }, + "confirmClear": { + "message": "Êtes-vous sûr de vouloir supprimer les sites Web approuvés?" + }, "contractInteraction": { "message": "Interaction avec un contrat" }, @@ -223,6 +226,10 @@ "basic": { "message": "Général" }, + "betweenMinAndMax": { + "message": "doit être supérieur ou égal à $1 et inférieur ou égal à $2", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerView": { "message": "Afficher le compte à $1", "description": "$1 replaced by URL for custom block explorer" @@ -389,6 +396,9 @@ "copiedExclamation": { "message": "Copié!" }, + "copy": { + "message": "Copier" + }, "copyAddress": { "message": "Copier l'addresse dans le presse-papier" }, @@ -477,6 +487,9 @@ "directDepositEtherExplainer": { "message": "Si vous avez déjà de l'Ether, le moyen le plus rapide d'obtenir des Ether dans votre nouveau portefeuille est par dépôt direct." }, + "dismiss": { + "message": "Ignorer" + }, "done": { "message": "Terminé" }, @@ -672,6 +685,10 @@ "getStarted": { "message": "Démarrer" }, + "greaterThanMin": { + "message": "doit être supérieur ou égal à $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Nous sommes ravis de vous voir.\n" }, @@ -1054,6 +1071,9 @@ "message": "Collez votre clé privée ici:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Collez votre seed phrase ici!" + }, "pending": { "message": "En attente" }, @@ -1392,6 +1412,9 @@ "submit": { "message": "Soumettre" }, + "submit": { + "message": "Soumettre" + }, "submitted": { "message": "Envoyé" }, @@ -1577,6 +1600,9 @@ "userName": { "message": "Nom d'utilisateur" }, + "validFileImport": { + "message": "Vous devez selectionner un fichier valide à importer." + }, "viewAccount": { "message": "Afficher le compte" }, diff --git a/app/_locales/gu/messages.json b/app/_locales/gu/messages.json index d04514fd90..bcd467be18 100644 --- a/app/_locales/gu/messages.json +++ b/app/_locales/gu/messages.json @@ -42,6 +42,9 @@ "connect": { "message": "કનેક્ટ કરો" }, + "copy": { + "message": "કૉપિ કરો" + }, "copyToClipboard": { "message": "ક્લિપબોર્ડ પર કૉપિ કરો" }, @@ -54,6 +57,9 @@ "details": { "message": "વિગતો" }, + "dismiss": { + "message": "કાઢી નાખો" + }, "done": { "message": "થઈ ગયું" }, @@ -125,6 +131,9 @@ "settings": { "message": "સેટિંગ્સ" }, + "submit": { + "message": "સબમિટ કરો" + }, "tryAgain": { "message": "ફરી પ્રયાસ કરો" }, diff --git a/app/_locales/hn/messages.json b/app/_locales/hn/messages.json index 8009077982..91d9bde7ed 100644 --- a/app/_locales/hn/messages.json +++ b/app/_locales/hn/messages.json @@ -1,10 +1,19 @@ { + "confirmClear": { + "message": "क्या आप वाकई अनुमोदित वेबसाइटों को साफ़ करना चाहते हैं?" + }, + "clearApprovalData": { + "message": "अनुमोदन डेटा साफ़ करें" + }, "approve": { "message": "मंजूर" }, "reject": { "message": "अस्वीकार" }, + "providerRequestInfo": { + "message": "नीचे सूचीबद्ध डोमेन वेब 3 एपीआई तक पहुंच का अनुरोध करने का प्रयास कर रहा है ताकि यह एथेरियम ब्लॉकचेन से बातचीत कर सके। वेब 3 एक्सेस को मंजूरी देने से पहले हमेशा सही जांच करें कि आप सही साइट पर हैं।" + }, "account": { "message": "खाता" }, @@ -46,6 +55,10 @@ "balanceIsInsufficientGas": { "message": "वर्तमान गैस कुल के लिए अपर्याप्त शेष" }, + "betweenMinAndMax": { + "message": "$1 के बराबर या ज्यदा या, $2 के बराबर या कम होना चाहिए।", + "description": "हेक्स इनपुट के लिए दशमलव इनपुट के रूप में सहायक" + }, "blockiesIdenticon": { "message": "ब्लॉकीज पहचान का उपयोग करें" }, @@ -82,6 +95,9 @@ "copiedExclamation": { "message": "कॉपी कर दिया गया!" }, + "copy": { + "message": "कॉपी / प्रतिलिपि कर्रे" + }, "copyToClipboard": { "message": "क्लिपबोर्ड पर कॉपी करें" }, @@ -187,6 +203,10 @@ "message": "$1 के लिए एक नल से ईथर प्राप्त करें", "description": "ईथर नल के लिए नेटवर्क नाम प्रदर्शित करता है" }, + "greaterThanMin": { + "message": "$1 के बराबर या बराबर होना चाहिए।", + "description": "हेक्स इनपुट के लिए दशमलव इनपुट के रूप में सहायक" + }, "here": { "message": "यहां", "description": "अधिक जानकारी के लिए यहां क्लिक करें- (परेशानी के साथ जाता है टोकनबैलेंस) (troubleTokenBalances)" @@ -245,6 +265,10 @@ "kovan": { "message": "कोवान टेस्ट नेटवर्क" }, + "lessThanMax": { + "message": "$1 से कम या बराबर होना चाहिए।", + "description": "हेक्स इनपुट के लिए दशमलव इनपुट के रूप में सहायक" + }, "likeToAddTokens": { "message": "क्या आप इन टोकनों को जोड़ना चाहते हैं?" }, @@ -320,6 +344,9 @@ "message": "यहां अपनी निजी कुंजी स्ट्रिंग चिपकाएं:", "description": "किसी निजी कुंजी से किसी खाते को आयात करने के लिए" }, + "pasteSeed": { + "message": "यहां अपने बीज वाक्यांश पेस्ट करें!" + }, "personalAddressDetected": { "message": "व्यक्तिगत पता मिला। टोकन अनुबंध का पता इनपुट।" }, @@ -420,6 +447,9 @@ "stateLogsDescription": { "message": "स्थिति संदेश में आपका सार्वजनिक खाता, पतों और भेजे गए लेनदेन, होते हैं।" }, + "submit": { + "message": "सबमिट करें" + }, "supportCenter": { "message": "हमारे सहायता केंद्र पर जाएं" }, @@ -467,6 +497,9 @@ "usedByClients": { "message": "विभिन्न क्लाइंट्स द्वारा उपयोग किया जाता है" }, + "validFileImport": { + "message": "आयात करने के लिए आपको एक वैध फ़ाइल चुननी होगी।" + }, "viewAccount": { "message": "खाता देखें" }, diff --git a/app/_locales/ht/messages.json b/app/_locales/ht/messages.json index dd63dce0c1..d973aeef54 100644 --- a/app/_locales/ht/messages.json +++ b/app/_locales/ht/messages.json @@ -1,4 +1,13 @@ { + "confirmClear": { + "message": "Èske ou sèten ou vle klè sitwèb apwouve?" + }, + "clearApprovalData": { + "message": "Klè Done sou vi prive" + }, + "providerRequestInfo": { + "message": "Domèn ki nan lis anba a ap mande pou jwenn aksè a blòkchou Ethereum ak pou wè kont ou ye kounye a. Toujou double tcheke ke ou sou sit ki kòrèk la anvan apwouve aksè." + }, "accessingYourCamera": { "message": "Aksè a Kamera" }, @@ -70,6 +79,10 @@ "balanceIsInsufficientGas": { "message": "Ensifizan balans pou total gaz aktyèl la" }, + "betweenMinAndMax": { + "message": "dwe plis pase oswa egal a $ 1 mwens ke oswa egal a $ 2.", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Itilize Blockies Identicon" }, @@ -148,6 +161,9 @@ "copiedExclamation": { "message": "Kopye!" }, + "copy": { + "message": "Kopye" + }, "copyAddress": { "message": "Kopi adrès clipboard" }, @@ -289,6 +305,10 @@ "getHelp": { "message": "Jwenn èd." }, + "greaterThanMin": { + "message": "dwe pi gran pase oswa egal a $ 1.", + "description": "helper for inputting hex as decimal input" + }, "hardware": { "message": "materyèl" }, @@ -383,6 +403,10 @@ "ledgerAccountRestriction": { "message": "Ou bezwen sèvi ak dènye kont ou anvan ou ka ajoute yon nouvo." }, + "lessThanMax": { + "message": "dwe mwens pase oswa egal a $ 1.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Èske ou ta renmen ajoute sa nan tokens?" }, @@ -500,6 +524,9 @@ "message": "Kole fraz prive ou a la:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Kole seed fraz ou a la!" + }, "pending": { "message": "l ap mache" }, @@ -729,6 +756,9 @@ "step3HardwareWalletMsg": { "message": "Sèvi ak kont materyèl ou menm jan ou t ap fè pou kont Etherum. Ouvri sesyon an nan dApps, voye Eth, achte ak stòke ERC20 tokens ak e ki pake chanje tokens tankou CryptoKitties." }, + "submit": { + "message": "Soumèt" + }, "submitted": { "message": "Te Soumèt" }, @@ -827,6 +857,9 @@ "usedByClients": { "message": "Itilize pa yon varyete de kliyan diferan" }, + "validFileImport": { + "message": "Ou dwe chwazi yon dosye ki valab pou enpòte." + }, "viewAccount": { "message": "Wè Kont" }, diff --git a/app/_locales/it/messages.json b/app/_locales/it/messages.json index 3581e48cbe..40d8fd488b 100644 --- a/app/_locales/it/messages.json +++ b/app/_locales/it/messages.json @@ -26,20 +26,29 @@ "chartOnlyAvailableEth": { "message": "Grafico disponibile solo per le reti Ethereum." }, + "confirmClear": { + "message": "Sei sicuro di voler cancellare i siti Web approvati?" + }, "contractInteraction": { "message": "Interazione Contratto" }, + "clearApprovalData": { + "message": "Cancella i dati di approvazione" + }, "reject": { "message": "Annulla" }, - "likeToConnect": { + "providerRequest": { "message": "$1 vorrebbe connettersi al tuo account" }, + "providerRequestInfo": { + "message": "Il dominio elencato di seguito sta tentando di richiedere l'accesso all'API Ethereum in modo che possa interagire con la blockchain di Ethereum. Controlla sempre di essere sul sito corretto prima di approvare l'accesso a Ethereum." + }, "about": { "message": "Informazioni" }, "aboutSettingsDescription": { - "message": "Version, centro di supporto e contatti" + "message": "Version, centro di supporto e contatti." }, "acceleratingATransaction": { "message": "* Accelerare una transazione usando un prezzo del gas maggiore aumenta la probabilità che la rete la elabori più velocemente, ma non è garantito." @@ -75,7 +84,7 @@ "message": "Avanzate" }, "advancedSettingsDescription": { - "message": "Accedi alle funzionalità sviluppatore, download dei log di Stato, Reset Account, imposta reti di test e RPC personalizzata" + "message": "Accedi alle funzionalità sviluppatore, download dei log di Stato, Reset Account, imposta reti di test e RPC personalizzata." }, "advancedOptions": { "message": "Opzioni Avanzate" @@ -169,6 +178,10 @@ "basic": { "message": "Base" }, + "betweenMinAndMax": { + "message": "deve essere maggiore o uguale a $1 e minore o uguale a $2.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerView": { "message": "Visualizza account su $1", "description": "$1 replaced by URL for custom block explorer" @@ -245,6 +258,9 @@ "connect": { "message": "Connetti" }, + "connectRequest": { + "message": "Richiesta Connessione" + }, "connectingTo": { "message": "Connessione in corso a $1" }, @@ -305,6 +321,9 @@ "copiedExclamation": { "message": "Copiato!" }, + "copy": { + "message": "Copia" + }, "copyAddress": { "message": "Copia l'indirizzo" }, @@ -386,6 +405,9 @@ "directDepositEtherExplainer": { "message": "Se possiedi già degli Ether, questa è la via più veloce per aggiungere Ether al tuo portafoglio con un deposito diretto." }, + "dismiss": { + "message": "Ignora" + }, "done": { "message": "Finito" }, @@ -560,6 +582,10 @@ "getStarted": { "message": "Inizia" }, + "greaterThanMin": { + "message": "deve essere maggiore o uguale a $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Siamo contenti di vederti." }, @@ -675,6 +701,10 @@ "ledgerAccountRestriction": { "message": "E' necessario utilizzare l'ultimo account prima di poterne aggiungere uno nuovo." }, + "lessThanMax": { + "message": "deve essere minore o uguale a $1.", + "description": "helper for inputting hex as decimal input" + }, "letsGoSetUp": { "message": "Si, iniziamo!" }, @@ -873,6 +903,9 @@ "message": "Incolla la tua chiave privata qui:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Incolla la tua frase seed qui!" + }, "pending": { "message": "in corso" }, @@ -1189,6 +1222,9 @@ "storePhrase": { "message": "Conserva questa frase in un gestore di password come 1Password." }, + "submit": { + "message": "Invia" + }, "submitted": { "message": "Inviata" }, @@ -1353,6 +1389,9 @@ "userName": { "message": "Nome utente" }, + "validFileImport": { + "message": "Devi selezionare un file valido da importare." + }, "viewAccount": { "message": "Vedi Account" }, @@ -1401,6 +1440,24 @@ "zeroGasPriceOnSpeedUpError": { "message": "Prezzo del gas maggiore di zero" }, + "connections": { + "message": "Connessioni" + }, + "connectionsSettingsDescription": { + "message": "Siti autorizzati ad accedere ai tuoi accounts" + }, + "addSite": { + "message": "Aggiungi Sito" + }, + "addSiteDescription": { + "message": "Aggiungi un sito autorizzato ad accedere ai tuoi accounts, utile per dapps obsolete" + }, + "connected": { + "message": "Connesso" + }, + "connectedDescription": { + "message": "La lista di siti web autorizzati ad accedere ai tuoi indirizzi" + }, "contacts": { "message": "Contatti" }, diff --git a/app/_locales/ja/messages.json b/app/_locales/ja/messages.json index 18dfb068ee..5b85291b9a 100644 --- a/app/_locales/ja/messages.json +++ b/app/_locales/ja/messages.json @@ -1,16 +1,28 @@ { + "privacyModeDefault": { + "message": "プライバシーモードがデフォルトで有効になりました" + }, "chartOnlyAvailableEth": { "message": "チャートはEthereumネットワークでのみ利用可能です。" }, + "confirmClear": { + "message": "承認されたウェブサイトをクリアしてもよろしいですか?" + }, "contractInteraction": { "message": "コントラクトへのアクセス" }, + "clearApprovalData": { + "message": "承認データのクリア" + }, "reject": { "message": "拒否" }, - "likeToConnect": { + "providerRequest": { "message": "$1 はあなたのアカウントにアクセスしようとしています。" }, + "providerRequestInfo": { + "message": "下記のドメインは、Ethereumブロックチェーンとやり取りできるようにEthereum APIへのアクセスをリクエストしようとしています。 Web3アクセスを承認する前に、正しいサイトにいることを常に確認してください。" + }, "aboutSettingsDescription": { "message": "バージョンやサポート、問合せ先など" }, @@ -72,7 +84,7 @@ "message": "推奨トークンを追加" }, "addAcquiredTokens": { - "message": "MetaMaskで獲得したトークンを追加する" + "message": "Metamaskで獲得したトークンを追加する" }, "amount": { "message": "金額" @@ -124,6 +136,10 @@ "balanceIsInsufficientGas": { "message": "現在のガス総量に対して残高が不足しています" }, + "betweenMinAndMax": { + "message": " $1以上 $2以下にして下さい。", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Blockies Identicon を使用" }, @@ -157,6 +173,9 @@ "copiedExclamation": { "message": "コピー完了!" }, + "copy": { + "message": "コピー" + }, "copyToClipboard": { "message": "クリップボードへコピー" }, @@ -259,6 +278,10 @@ "message": "フォーセットで $1のEtherを得ることができます。", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": " $1以上にして下さい。", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "ここ", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -311,6 +334,10 @@ "learnMore": { "message": "詳細" }, + "lessThanMax": { + "message": " $1以下にして下さい。", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "トークンを追加しますか?" }, @@ -389,6 +416,9 @@ "message": "秘密鍵をここにペーストして下さい:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "パスフレーズをここにペーストして下さい!" + }, "privacyMsg": { "message": "プライバシーポリシー" }, @@ -480,6 +510,9 @@ "sigRequest": { "message": "署名リクエスト" }, + "submit": { + "message": "送信" + }, "terms": { "message": "利用規約" }, diff --git a/app/_locales/ko/messages.json b/app/_locales/ko/messages.json index 96d527f23b..2afce74af6 100644 --- a/app/_locales/ko/messages.json +++ b/app/_locales/ko/messages.json @@ -50,9 +50,12 @@ "reject": { "message": "거부" }, - "likeToConnect": { + "providerRequest": { "message": "$1이 당신의 계정에 연결하길 원합니다." }, + "providerRequestInfo": { + "message": "아래 나열된 도메인은 Web3 API에 대한 액세스를 요청하여 Ethereum 블록 체인과 상호 작용할 수 있습니다. Ethereum 액세스를 승인하기 전에 항상 올바른 사이트에 있는지 다시 확인하십시오." + }, "about": { "message": "정보" }, @@ -211,6 +214,10 @@ "balanceIsInsufficientGas": { "message": "현재 가스 총합에 대해 잔액이 부족합니다" }, + "betweenMinAndMax": { + "message": "$1 이상 $2 이하여야 합니다.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "익스플로러 차단" }, @@ -311,6 +318,9 @@ "connect": { "message": "연결" }, + "connectRequest": { + "message": "연결 요청" + }, "connectingTo": { "message": "$1에 연결" }, @@ -371,6 +381,9 @@ "copiedExclamation": { "message": "복사됨!" }, + "copy": { + "message": "복사" + }, "copyAddress": { "message": "클립보드로 주소 복사" }, @@ -452,6 +465,9 @@ "directDepositEtherExplainer": { "message": "약간의 이더를 이미 보유하고 있다면, 새로 만든 지갑에 직접 입금하여 이더를 보유할 수 있습니다." }, + "dismiss": { + "message": "숨기기" + }, "done": { "message": "완료" }, @@ -635,6 +651,10 @@ "getStarted": { "message": "시작하기" }, + "greaterThanMin": { + "message": "$1 이상이어야 합니다.", + "description": "helper for inputting hex as decimal input" + }, "hardware": { "message": "하드웨어" }, @@ -1005,6 +1025,9 @@ "message": "개인키를 입력해주세요:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "시드 구문을 이곳에 붙여넣어 주세요!" + }, "pending": { "message": "펜딩 중" }, @@ -1334,6 +1357,9 @@ "storePhrase": { "message": "이 구문을 1Password같은 암호 관리자에 저장하세요." }, + "submit": { + "message": "제출" + }, "submitted": { "message": "제출됨" }, @@ -1504,6 +1530,9 @@ "userName": { "message": "사용자이름" }, + "validFileImport": { + "message": "가져오기 위해 유효한 파일을 선택해야 합니다." + }, "viewAccount": { "message": "계정 보기" }, diff --git a/app/_locales/ml/messages.json b/app/_locales/ml/messages.json index c898d1dc2c..cbcee41866 100644 --- a/app/_locales/ml/messages.json +++ b/app/_locales/ml/messages.json @@ -42,6 +42,9 @@ "connect": { "message": "കണക്റ്റുചെയ്യുക" }, + "copy": { + "message": "പകര്ത്തുക" + }, "copyToClipboard": { "message": "ക്ലിപ്പ്ബോർഡിലേക്ക് പകർത്തുക" }, @@ -54,6 +57,9 @@ "details": { "message": "വിശദാംശങ്ങൾ" }, + "dismiss": { + "message": "ബഹിഷ്ക്കരിക്കുക" + }, "done": { "message": "പൂർത്തിയാക്കി" }, @@ -125,6 +131,9 @@ "settings": { "message": "ക്രമീകരണങ്ങള്" }, + "submit": { + "message": "സമര്പ്പിക്കൂ" + }, "tryAgain": { "message": "വീണ്ടും ശ്രമിക്കുക" }, diff --git a/app/_locales/mr/messages.json b/app/_locales/mr/messages.json index ef341f40ce..af06c03fb9 100644 --- a/app/_locales/mr/messages.json +++ b/app/_locales/mr/messages.json @@ -42,6 +42,9 @@ "connect": { "message": "कनेक्ट करा" }, + "copy": { + "message": "कॉपी करा" + }, "copyToClipboard": { "message": "क्लिपबोर्डवर कॉपी करा" }, @@ -54,6 +57,9 @@ "details": { "message": "तपशील" }, + "dismiss": { + "message": "डिसमिस करा" + }, "done": { "message": "पूर्ण झाले" }, @@ -125,6 +131,9 @@ "settings": { "message": "सेटिंग्ज" }, + "submit": { + "message": "सबमिट करा" + }, "tryAgain": { "message": "पुन्हा प्रयत्न करा" }, diff --git a/app/_locales/nl/messages.json b/app/_locales/nl/messages.json index 7ba285208d..ba83e37a11 100644 --- a/app/_locales/nl/messages.json +++ b/app/_locales/nl/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Weet je zeker dat je goedgekeurde websites wilt wissen?" + }, + "clearApprovalData": { + "message": "Gegevens over goedkeuring wissen" + }, "reject": { "message": "Afwijzen" }, + "providerRequestInfo": { + "message": "Het onderstaande domein probeert toegang tot de Ethereum API te vragen zodat deze kan communiceren met de Ethereum-blockchain. Controleer altijd eerst of u op de juiste site bent voordat u Ethereum-toegang goedkeurt." + }, "accountDetails": { "message": "Accountgegevens" }, @@ -43,6 +52,10 @@ "balanceIsInsufficientGas": { "message": "Onvoldoende saldo voor huidig gastotaal" }, + "betweenMinAndMax": { + "message": "moet groter zijn dan of gelijk zijn aan $1 en kleiner dan of gelijk aan $2.", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Gebruik Blockies Identicon" }, @@ -79,6 +92,9 @@ "copiedExclamation": { "message": "Gekopieerde!" }, + "copy": { + "message": "Kopiëren" + }, "copyToClipboard": { "message": "Kopieer naar klembord" }, @@ -181,6 +197,10 @@ "message": "Haal Ether uit een kraan voor de $1", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "moet groter zijn dan of gelijk zijn aan $1.", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "hier", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -239,6 +259,10 @@ "kovan": { "message": "Kovan-testnetwerk" }, + "lessThanMax": { + "message": "moet kleiner zijn dan of gelijk zijn aan $1.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Wil je deze tokens toevoegen?" }, @@ -307,6 +331,9 @@ "message": "Plak hier uw privésleutelstring:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Plak je back-up woorden hier!" + }, "personalAddressDetected": { "message": "Persoonlijk adres gedetecteerd. Voer het tokencontractadres in." }, @@ -410,6 +437,9 @@ "stateLogsDescription": { "message": "Staatslogboeken bevatten uw openbare accountadressen en verzonden transacties." }, + "submit": { + "message": "voorleggen" + }, "supportCenter": { "message": "Bezoek ons ondersteuningscentrum" }, @@ -454,6 +484,9 @@ "usedByClients": { "message": "Gebruikt door verschillende klanten" }, + "validFileImport": { + "message": "U moet een geldig bestand selecteren om te importeren." + }, "viewAccount": { "message": "Bekijk account" }, diff --git a/app/_locales/ph/messages.json b/app/_locales/ph/messages.json index 1a3807ad55..a3df5d4edf 100644 --- a/app/_locales/ph/messages.json +++ b/app/_locales/ph/messages.json @@ -1,4 +1,10 @@ { + "confirmClear": { + "message": "Sigurado ka bang gusto mong i-clear ang mga naaprubahang website?" + }, + "clearApprovalData": { + "message": "Tanggalin ang data ng pag-apruba" + }, "appName": { "message": "MetaMask", "description": "The name of the application" @@ -9,6 +15,9 @@ "reject": { "message": "Tanggihan" }, + "providerRequestInfo": { + "message": "Ang domain na nakalista sa ibaba ay sinusubukang humiling ng access sa Ethereum API upang maaari itong makipag-ugnayan sa Ethereum blockchain. Laging i-double check na ikaw ay nasa tamang site bago aprubahan ang Ethereum access." + }, "accountDetails": { "message": "Detalye ng Account" }, @@ -37,6 +46,10 @@ "balanceIsInsufficientGas": { "message": "Kulang ang balanse para sa kasalukuyang gas total" }, + "betweenMinAndMax": { + "message": "dapat mas malaki o katumbas ng $1 at mas mababa o katumbas ng $2.", + "description": "helper para sa pag-input ng hex bilang decimal input" + }, "buyCoinSwitch": { "message": "Bumili sa CoinSwitch" }, @@ -67,6 +80,9 @@ "copiedExclamation": { "message": "Kinopya!" }, + "copy": { + "message": "Kinopya" + }, "copyToClipboard": { "message": "Kinopya sa clipboard" }, @@ -151,6 +167,10 @@ "message": "Kumuha ng Ether mula sa faucet para sa $1", "description": "Ipinapakita ang pangalan ng network para sa Ether faucet" }, + "greaterThanMin": { + "message": "dapat mas malaki o katumbas ng $1.", + "description": "helper para sa pag-input ng hex bilang decimal input" + }, "here": { "message": "i-click ito", "description": "tulad ng -i-click dito- para sa mas maraming impormasyon (kasama ng troubleTokenBalances)" @@ -184,6 +204,10 @@ "invalidInput": { "message": "Invalid ang input." }, + "lessThanMax": { + "message": "dapat mas mababa o katumbas ng $1.", + "description": "helper para sa pag-input ng hex bilang decimal input" + }, "loading": { "message": "Naglo-load..." }, @@ -228,6 +252,9 @@ "message": "I-paste dito ang iyong private key string:", "description": "Para sa pag-import ng account mula sa private key" }, + "pasteSeed": { + "message": "I-paste dito ang iyong seed phrase!" + }, "privateKeyWarning": { "message": "Babala: Huwag sabihin sa kahit na sino ang key na ito. Maaring makuha at manakaw ng sinumang nakakaalam ng iyong private key ang mga assets sa iyong account." }, @@ -276,6 +303,9 @@ "sigRequest": { "message": "Hiling na Signature" }, + "submit": { + "message": "I-submit" + }, "toETHviaShapeShift": { "message": "$1 sa ETH sa pamamagitan ng ShapeShift", "description": "Pupunan ng system ang deposit type sa simula ng mensahe" diff --git a/app/_locales/pl/messages.json b/app/_locales/pl/messages.json index 689b2d909a..243f4c7933 100644 --- a/app/_locales/pl/messages.json +++ b/app/_locales/pl/messages.json @@ -226,6 +226,10 @@ "basic": { "message": "Podstawy" }, + "betweenMinAndMax": { + "message": "musi być większe lub równe $1 i mniejsze lub równe $2,", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "Przeglądaj blok" }, @@ -317,6 +321,9 @@ "connect": { "message": "Połącz" }, + "connectRequest": { + "message": "Potwierdź żądanie" + }, "connectingTo": { "message": "Łączenie z $1" }, @@ -377,6 +384,9 @@ "copiedExclamation": { "message": "Skopiowane!" }, + "copy": { + "message": "Skopiuj" + }, "copyAddress": { "message": "Skopiuj adres do schowka" }, @@ -455,6 +465,9 @@ "directDepositEtherExplainer": { "message": "Jeśli już masz Eter, najszybciej umieścisz go w swoim nowym portfelu przy pomocy bezpośredniego depozytu." }, + "dismiss": { + "message": "Zamknij" + }, "done": { "message": "Gotowe" }, @@ -635,6 +648,10 @@ "getStarted": { "message": "Rozpocznij" }, + "greaterThanMin": { + "message": "musi być większe lub równe $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Cieszymy się, że tu jesteś." }, @@ -1017,6 +1034,9 @@ "message": "Tutaj wklej swój prywatny klucz:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Tutaj wklej swoją frazę seed!" + }, "pending": { "message": "oczekiwanie" }, @@ -1540,6 +1560,9 @@ "userName": { "message": "Nazwa użytkownika" }, + "validFileImport": { + "message": "Należy wybrać prawidłowy plik do zaimportowania." + }, "viewAccount": { "message": "Zobacz konto" }, diff --git a/app/_locales/pt/messages.json b/app/_locales/pt/messages.json index 9d9ed04509..70c2e52aeb 100644 --- a/app/_locales/pt/messages.json +++ b/app/_locales/pt/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Tem certeza de que deseja limpar sites aprovados?" + }, + "clearApprovalData": { + "message": "Limpar dados de aprovação" + }, "reject": { "message": "Rejeitar" }, + "providerRequestInfo": { + "message": "O domínio listado abaixo está tentando solicitar acesso à API Ethereum para que ele possa interagir com o blockchain Ethereum. Sempre verifique se você está no site correto antes de aprovar o acesso à Ethereum." + }, "account": { "message": "Conta" }, @@ -46,6 +55,10 @@ "balanceIsInsufficientGas": { "message": "Saldo insuficiente para a quantidade de gas total" }, + "betweenMinAndMax": { + "message": "tem de ser maior ou igual a $1 e menor ou igual a $2.", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Usar Blockies Identicon" }, @@ -82,6 +95,9 @@ "copiedExclamation": { "message": "Copiado!" }, + "copy": { + "message": "Copiar" + }, "copyToClipboard": { "message": "Copiar para o clipboard" }, @@ -187,6 +203,10 @@ "message": "Obter Ether de um faucet por $1", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "tem de ser maior ou igual a $1.", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "aqui", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -245,6 +265,10 @@ "kovan": { "message": "Rede de Teste Kovan" }, + "lessThanMax": { + "message": "tem de ser menor ou igual a $1.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Gostaria de adicionar estes tokens?" }, @@ -317,6 +341,9 @@ "message": "Cole aqui a sua chave privada:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Cole aqui a sua frase seed!" + }, "personalAddressDetected": { "message": "Endereço pessoal detectado. Introduza o endereço do contrato do token." }, @@ -420,6 +447,9 @@ "stateLogsDescription": { "message": "Registo de estado podem conter o seu endereço e transações enviadas da sua conta pública." }, + "submit": { + "message": "Submeter" + }, "supportCenter": { "message": "Visitar o nosso Centro de Suporte" }, @@ -464,6 +494,9 @@ "usedByClients": { "message": "Utilizado por vários tipos de clientes" }, + "validFileImport": { + "message": "Deve selecionar um ficheiro válido para importar." + }, "viewAccount": { "message": "Ver Conta" }, diff --git a/app/_locales/pt_PT/messages.json b/app/_locales/pt_PT/messages.json index ae85eb26c1..ce35721de0 100644 --- a/app/_locales/pt_PT/messages.json +++ b/app/_locales/pt_PT/messages.json @@ -48,6 +48,9 @@ "copiedExclamation": { "message": "Copiado!" }, + "copy": { + "message": "Copiar" + }, "copyToClipboard": { "message": "Copiar para a área de transferência" }, @@ -63,6 +66,9 @@ "details": { "message": "Detalhes" }, + "dismiss": { + "message": "Ignorar" + }, "done": { "message": "Concluído" }, @@ -150,6 +156,9 @@ "settings": { "message": "Definições" }, + "submit": { + "message": "Submeter" + }, "tips": { "message": "Doações" }, diff --git a/app/_locales/ru/messages.json b/app/_locales/ru/messages.json index 43249d6bcd..082e450da1 100644 --- a/app/_locales/ru/messages.json +++ b/app/_locales/ru/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Вы уверены, что хотите очистить утвержденные веб-сайты?Tem certeza de que deseja limpar sites aprovados?" + }, + "clearApprovalData": { + "message": "Четкие данные об утверждении" + }, "reject": { "message": "Отклонить" }, + "providerRequestInfo": { + "message": "Домен, указанный ниже, пытается запросить доступ к API-интерфейсу Ethereum, чтобы он мог взаимодействовать с блокчейном Ethereum. Всегда проверяйте, что вы находитесь на правильном сайте, прежде чем одобрять доступ к веб-сайту." + }, "account": { "message": "Счет" }, @@ -49,6 +58,10 @@ "balanceIsInsufficientGas": { "message": "Недостаточный баланс для текущего объема газа" }, + "betweenMinAndMax": { + "message": "должно быть больше или равно $1 и меньше или равно $2.", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Использовать Blockies Identicon" }, @@ -103,6 +116,9 @@ "copiedExclamation": { "message": "Скопировано!" }, + "copy": { + "message": "Скопировать" + }, "copyToClipboard": { "message": "Скопировать в буфер обмена" }, @@ -214,6 +230,10 @@ "message": "Получить Ether из крана для $1", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "должно быть больше или равно $1.", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "тут", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -278,6 +298,10 @@ "learnMore": { "message": "Узнать больше." }, + "lessThanMax": { + "message": "должно быть меньше или равно $1.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Вы хотите добавить эти токены?" }, @@ -353,6 +377,9 @@ "message": "Вставьте ваш закрытый ключ тут:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Вставьте вашу ключевую фразу!" + }, "personalAddressDetected": { "message": "Обнаружен персональный адрес. Введите адрес контракта токена." }, @@ -465,6 +492,9 @@ "stateLogError": { "message": "Ошибка при получении журнала состояния." }, + "submit": { + "message": "Отправить" + }, "submitted": { "message": "Отправлена" }, @@ -518,6 +548,9 @@ "usedByClients": { "message": "Используется различными клиентами" }, + "validFileImport": { + "message": "Вам нужно выбрать правильный файл для импорта." + }, "viewAccount": { "message": "Посмотреть счет" }, @@ -536,13 +569,16 @@ "youSign": { "message": "Вы подписываете" }, + "privacyModeDefault": { + "message": "Режим конфиденциальности теперь включен по умолчанию" + }, "chartOnlyAvailableEth": { "message": "Диаграмма доступна только в сетях Ethereum." }, "contractInteraction": { "message": "Взаимодействие с контрактом" }, - "likeToConnect": { + "providerRequest": { "message": "$1 запрашивает доступ к вашему аккаунту" }, "about": { @@ -695,6 +731,9 @@ "connect": { "message": "Подключиться" }, + "connectRequest": { + "message": "Запрос на подключение" + }, "connectingTo": { "message": "Подключение к $1" }, @@ -737,6 +776,9 @@ "deleteAccount": { "message": "Удалить аккаунт" }, + "dismiss": { + "message": "Отклюнить" + }, "downloadGoogleChrome": { "message": "Скачать Google Chrome" }, diff --git a/app/_locales/sk/messages.json b/app/_locales/sk/messages.json index 9c333786cb..1d235da380 100644 --- a/app/_locales/sk/messages.json +++ b/app/_locales/sk/messages.json @@ -229,6 +229,10 @@ "basic": { "message": "Základné" }, + "betweenMinAndMax": { + "message": "musí být větší nebo roven $1 a menší nebo roven $2.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerView": { "message": "Zobraziť účet na $1", "description": "$1 replaced by URL for custom block explorer" @@ -398,6 +402,9 @@ "copiedExclamation": { "message": "Zkopírováno!" }, + "copy": { + "message": "Kopírovat" + }, "copyAddress": { "message": "Kopírovať adresu do schránky" }, @@ -492,6 +499,9 @@ "directDepositEtherExplainer": { "message": "Pokud už vlastníte nějaký Ether, nejrychleji ho dostanete do peněženky přímým vkladem." }, + "dismiss": { + "message": "Zatvoriť" + }, "done": { "message": "Hotovo" }, @@ -697,6 +707,10 @@ "getStarted": { "message": "Začať" }, + "greaterThanMin": { + "message": "musí být větší nebo roven $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Sme radi, že vás vidíme." }, @@ -1072,6 +1086,9 @@ "message": "Vložte zde svůj privátní klíč:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Svou klíčovou frázi vložte zde!" + }, "pending": { "message": "prebieha" }, @@ -1629,6 +1646,9 @@ "userName": { "message": "Meno používateľa" }, + "validFileImport": { + "message": "Musíte vybrat validní soubor k importu." + }, "viewAccount": { "message": "Zobrazit účet" }, diff --git a/app/_locales/sl/messages.json b/app/_locales/sl/messages.json index b25e30efe5..30965aa1b2 100644 --- a/app/_locales/sl/messages.json +++ b/app/_locales/sl/messages.json @@ -35,6 +35,9 @@ "contractInteraction": { "message": "Interakcija s pogodbo" }, + "clearApprovalData": { + "message": "Počisti podatke o odobritvi" + }, "reject": { "message": "Zavrni" }, @@ -205,6 +208,10 @@ "basic": { "message": "Osnovno" }, + "betweenMinAndMax": { + "message": "mora biti večji ali enak $1 in manjši ali enak $1.", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "Blokiraj Explorer" }, @@ -374,6 +381,9 @@ "copiedExclamation": { "message": "Kopirano!" }, + "copy": { + "message": "Kopiraj" + }, "copyAddress": { "message": "Kopiraj naslov v odložišče" }, @@ -458,6 +468,9 @@ "directDepositEtherExplainer": { "message": "Če že imate Ether, ga lahko najhitreje dobite v MetaMask z neposrednim vplačilom." }, + "dismiss": { + "message": "Opusti" + }, "done": { "message": "Končano" }, @@ -635,6 +648,10 @@ "getStarted": { "message": "Začnite" }, + "greaterThanMin": { + "message": "mora biti večji ali enak $1.", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "Veseli nas, da ste nas spet obiskali." }, @@ -1008,6 +1025,9 @@ "message": "Tukaj prilepite vaš zasebni ključ:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Tukaj prilepite seed phase!" + }, "pending": { "message": "v obdelavi" }, @@ -1519,6 +1539,9 @@ "userName": { "message": "Uporabniško ime" }, + "validFileImport": { + "message": "Za uvoz morate izbrati pravilno datoteko." + }, "viewAccount": { "message": "Poglej račun" }, diff --git a/app/_locales/ta/messages.json b/app/_locales/ta/messages.json index dc48abb02d..b5be675206 100644 --- a/app/_locales/ta/messages.json +++ b/app/_locales/ta/messages.json @@ -1,10 +1,19 @@ { + "confirmClear": { + "message": "அங்கீகரிக்கப்பட்ட வலைத்தளங்களை நிச்சயமாக நீக்க விரும்புகிறீர்களா?" + }, + "clearApprovalData": { + "message": "ஒப்புதல் தரவை அழி" + }, "approve": { "message": "ஒப்புதல்" }, "reject": { "message": "நிராகரி" }, + "providerRequestInfo": { + "message": "கீழே பட்டியலிடப்பட்டுள்ள டொமைன் Web3 ஏபிஐ அணுகலைக் கோருவதற்கு முயற்சிக்கிறது, எனவே இது Ethereum blockchain உடன் தொடர்பு கொள்ள முடியும். Web3 அணுகுமுறையை அங்கீகரிப்பதற்கு முன் சரியான தளத்தில் இருப்பதை எப்போதும் இருமுறை சரிபார்க்கவும்." + }, "account": { "message": "கணக்கு" }, @@ -49,6 +58,10 @@ "balanceIsInsufficientGas": { "message": "நடப்பு வாயு மொத்தம் போதுமான சமநிலை" }, + "betweenMinAndMax": { + "message": "$ 1 க்கும் அதிகமாகவும் அல்லது $ 2 க்கு சமமாகவும் இருக்க வேண்டும்.", + "description": "ஹெக்ஸ் உள்ளீடு தசம உள்ளீடு என உதவி" + }, "blockiesIdenticon": { "message": "ப்ளாக்கிஸ் ஐடென்டிகோன் பயன்பாட்டு" }, @@ -91,6 +104,9 @@ "copiedExclamation": { "message": "நகலெடுக்கப்பட்டன!" }, + "copy": { + "message": "நகலெடு" + }, "copyToClipboard": { "message": "கிளிப்போர்டுக்கு நகலெடு" }, @@ -208,6 +224,10 @@ "message": "$ 1 க்கு ஒரு குழாய் இருந்து ஈதர் கிடைக்கும்$1", "description": "ஈத்தர் குழாய் ஐந்து பிணைய பெயர் காட்டுகிறது" }, + "greaterThanMin": { + "message": "$ 1 க்கும் அதிகமாகவோ அல்லது சமமாகவோ இருக்க வேண்டும்", + "description": "ஹெக்ஸ் உள்ளீடு தசம உள்ளீடு என உதவி" + }, "here": { "message": "இங்கே", "description": "இங்கே-கிளிக் செய்யவும்- மேலும் தகவலுக்கு (troubleTokenBalances செல்கிறது)" @@ -272,6 +292,10 @@ "learnMore": { "message": "மேலும் அறிக" }, + "lessThanMax": { + "message": "$ 1 க்கும் குறைவாகவோ அல்லது சமமாகவோ இருக்க வேண்டும்.", + "description": "ஹெக்ஸ் உள்ளீடு தசம உள்ளீடு என உதவி" + }, "likeToAddTokens": { "message": "இந்த டோக்கன்களைச் சேர்க்க விரும்புகிறீர்களா?" }, @@ -350,6 +374,9 @@ "message": "இங்கே உங்கள் தனிப்பட்ட விசை சரத்தை ஒட்டுக:", "description": "ஒரு தனிப்பட்ட விசை ஒரு கணக்கை இறக்குமதி செய்ய" }, + "pasteSeed": { + "message": "இங்கே உங்கள் விதை சொற்றொடரை ஒட்டவும்!" + }, "personalAddressDetected": { "message": "தனிப்பட்ட முகவரி கண்டறியப்பட்டது. டோக்கன் ஒப்பந்த முகவரியை உள்ளிடவும்." }, @@ -474,6 +501,9 @@ "stateLogError": { "message": "மாநில பதிவுகளை மீட்டெடுப்பதில் பிழை." }, + "submit": { + "message": "சமர்ப்பி" + }, "submitted": { "message": "சமர்ப்பிக்கப்பட்டது" }, @@ -530,6 +560,9 @@ "usedByClients": { "message": "பல்வேறு வாடிக்கையாளர்கள் பல்வேறு பயன்படுத்திய" }, + "validFileImport": { + "message": "இறக்குமதி செய்ய சரியான கோப்பு தேர்ந்தெடுக்க வேண்டும்." + }, "viewAccount": { "message": "கணக்கைப் பார்" }, @@ -569,6 +602,9 @@ "delete": { "message": "நீக்கு" }, + "dismiss": { + "message": "நிராகரி" + }, "fast": { "message": "வேகமான" }, diff --git a/app/_locales/te/messages.json b/app/_locales/te/messages.json index 2df11217d5..ba588ca469 100644 --- a/app/_locales/te/messages.json +++ b/app/_locales/te/messages.json @@ -42,6 +42,9 @@ "connect": { "message": "కనెక్ట్ చేయండి" }, + "copy": { + "message": "కాపీ చెయ్యి" + }, "copyToClipboard": { "message": "క్లిప్బోర్డ్కు కాపీ చేయి" }, @@ -54,6 +57,9 @@ "details": { "message": "వివరాలు" }, + "dismiss": { + "message": "తొలగించు" + }, "done": { "message": "పూర్తయింది" }, @@ -125,6 +131,9 @@ "settings": { "message": "సెట్టింగ్లు" }, + "submit": { + "message": "సమర్పించు" + }, "tryAgain": { "message": "మళ్లీ ప్రయత్నించు" }, diff --git a/app/_locales/th/messages.json b/app/_locales/th/messages.json index 45ebd50309..072281dd42 100644 --- a/app/_locales/th/messages.json +++ b/app/_locales/th/messages.json @@ -1,4 +1,10 @@ { + "confirmClear": { + "message": "คุณแน่ใจหรือไม่ว่าต้องการล้างเว็บไซต์ที่ผ่านการอนุมัติ" + }, + "clearApprovalData": { + "message": "ล้างข้อมูลการอนุมัติ" + }, "reject": { "message": "ปฏิเสธ" }, @@ -64,6 +70,10 @@ "balanceIsInsufficientGas": { "message": "ยอดคงเหลือไม่พอสำหรับจ่ายค่าแก๊สทั้งหมด" }, + "betweenMinAndMax": { + "message": "ต้องมากกว่าหรือเท่ากับ $1 และน้อยกว่าหรือเท่ากับ $2", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "ใช้งาน Blockies Identicon" }, @@ -202,6 +212,9 @@ "copiedExclamation": { "message": "คัดลอกแล้ว!" }, + "copy": { + "message": "คัดลอก" + }, "copyToClipboard": { "message": "คัดลอกไปคลิปบอร์ด" }, @@ -284,6 +297,9 @@ "directDepositEtherExplainer": { "message": "ถ้าคุณมีอีเธอร์อยู่แล้ววิธีการที่เร็วที่สุดในการเอาเงินเข้ากระเป๋าใหม่ก็คือการโอนตรงๆ" }, + "dismiss": { + "message": "ปิด" + }, "done": { "message": "เสร็จสิ้น" }, @@ -431,6 +447,10 @@ "message": "รับอีเธอร์ที่ปล่อยจาก $1", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "ต้องมากกว่าหรือเท่ากับ $1.", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "ที่นี่", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -719,6 +739,9 @@ "message": "วางคีย์ส่วนตัวของคุณที่นี่:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "วางคำชีดของคุณที่นี่!" + }, "personalAddressDetected": { "message": "ตรวจพบแอดแดรสส่วนตัวแล้ว ใส่แอดแดรสสัญญาโทเค็น" }, @@ -1053,6 +1076,9 @@ "usedByClients": { "message": "ถูกใช้งานโดยหลายไคลเอนท์" }, + "validFileImport": { + "message": "คุณต้องเลือกไฟล์ที่ถูกต้องเพื่อนำเข้า" + }, "viewAccount": { "message": "ดูบัญชี" }, diff --git a/app/_locales/tr/messages.json b/app/_locales/tr/messages.json index fdb1ae927c..fe2332f2f0 100644 --- a/app/_locales/tr/messages.json +++ b/app/_locales/tr/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Onaylanmış web sitelerini silmek istediğinizden emin misiniz?" + }, + "clearApprovalData": { + "message": "Onay verilerini temizle" + }, "reject": { "message": "Reddetmek" }, + "providerRequestInfo": { + "message": "Aşağıda listelenen etki alanı, Ethereum API'sine erişim talep etmeye çalışmaktadır, böylece Ethereum blockchain ile etkileşime girebilir. Web3 erişimini onaylamadan önce her zaman doğru sitede olduğunuzu kontrol edin." + }, "account": { "message": "Hesap" }, @@ -49,6 +58,10 @@ "balanceIsInsufficientGas": { "message": "Toplam gas için yetersiz bakiye" }, + "betweenMinAndMax": { + "message": "$1'e eşit veya daha büyük olmalı ve $2'den küçük veya eşit olmalı", + "description": "helper for inputting hex as decimal input" + }, "blockiesIdenticon": { "message": "Blockies Identicon kullan" }, @@ -103,6 +116,9 @@ "copiedExclamation": { "message": "Kopyalandı!" }, + "copy": { + "message": "Kopyala" + }, "copyToClipboard": { "message": "Panoya kopyala" }, @@ -278,6 +294,10 @@ "learnMore": { "message": "Daha fazla bilgi." }, + "lessThanMax": { + "message": "$1'den az veya eşit olmalıdır.", + "description": "helper for inputting hex as decimal input" + }, "likeToAddTokens": { "message": "Bu jetonlara adres eklemek ister misiniz?" }, @@ -359,6 +379,9 @@ "message": "Özel anahtar dizinizi buraya yapıştırın:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Kaynak ifadenizi buraya yapıştırın!" + }, "personalAddressDetected": { "message": "Kişisel adres tespit edilidi. Jeton sözleşme adresini girin." }, @@ -471,6 +494,9 @@ "stateLogError": { "message": "Durum kayıtlarını alma hatası" }, + "submit": { + "message": "Gönder" + }, "submitted": { "message": "Gönderildi" }, @@ -527,6 +553,9 @@ "usedByClients": { "message": "Farklı istemciler tarafından kullanılmakta" }, + "validFileImport": { + "message": "Almak için geçerli bir dosya seçmelisiniz" + }, "viewAccount": { "message": "Hesabı İncele" }, diff --git a/app/_locales/vi/messages.json b/app/_locales/vi/messages.json index 6136403bae..b223616787 100644 --- a/app/_locales/vi/messages.json +++ b/app/_locales/vi/messages.json @@ -1,7 +1,16 @@ { + "confirmClear": { + "message": "Bạn có chắc chắn muốn xóa các trang web được phê duyệt không?" + }, + "clearApprovalData": { + "message": "Xóa dữ liệu phê duyệt" + }, "reject": { "message": "Từ chối" }, + "providerRequestInfo": { + "message": "Miền được liệt kê bên dưới đang cố gắng yêu cầu quyền truy cập vào API Ethereum để nó có thể tương tác với chuỗi khối Ethereum. Luôn kiểm tra kỹ xem bạn có đang ở đúng trang web trước khi phê duyệt quyền truy cập Ethereum hay không." + }, "account": { "message": "Tài khoản" }, @@ -40,6 +49,10 @@ "balanceIsInsufficientGas": { "message": "Số dư không đủ để thanh toán tổng tiền gas hiện tại" }, + "betweenMinAndMax": { + "message": "phải nhiều hơn hoặc bằng $1 và ít hơn hoặc bằng $2.", + "description": "helper for inputting hex as decimal input" + }, "buyCoinSwitch": { "message": "Mua trên CoinSwitch" }, @@ -70,6 +83,9 @@ "copiedExclamation": { "message": "Đã sao chép!" }, + "copy": { + "message": "Sao chép" + }, "copyToClipboard": { "message": "Đã sao chép vào clipboard" }, @@ -163,6 +179,10 @@ "message": "Lấy Ether từ vòi với giá $1", "description": "Displays network name for Ether faucet" }, + "greaterThanMin": { + "message": "phải nhiều hơn hoặc bằng $1", + "description": "helper for inputting hex as decimal input" + }, "here": { "message": "tại đây", "description": "as in -click here- for more information (goes with troubleTokenBalances)" @@ -203,6 +223,10 @@ "kovan": { "message": "Mạng thử nghiệm Kovan" }, + "lessThanMax": { + "message": "phải ít hơn hoặc bằng $1.", + "description": "helper for inputting hex as decimal input" + }, "loading": { "message": "Đang tải..." }, @@ -260,6 +284,9 @@ "message": "Dán dãy khóa cá nhân của bạn tại đây:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "Dán Mật Khẩu Sinh Khoá (seed phrase) của bạn tại đây!" + }, "privateKey": { "message": "Khóa Bí Mật", "description": "select this type of file to use to import an account" @@ -321,6 +348,9 @@ "sigRequest": { "message": "Yêu cầu chữ ký" }, + "submit": { + "message": "Gửi đi" + }, "testFaucet": { "message": "Vòi nhận tiền ETH ảo để thử nghiệm" }, diff --git a/app/_locales/zh_CN/messages.json b/app/_locales/zh_CN/messages.json index c52fe7934c..fec03d71de 100644 --- a/app/_locales/zh_CN/messages.json +++ b/app/_locales/zh_CN/messages.json @@ -232,6 +232,10 @@ "basic": { "message": "基本" }, + "betweenMinAndMax": { + "message": "必须大于等于 $1 并且小于等于 $2 。", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "屏蔽管理器" }, @@ -407,6 +411,9 @@ "copiedExclamation": { "message": "已复制" }, + "copy": { + "message": "复制" + }, "copyAddress": { "message": "将地址复制到剪贴板" }, @@ -501,6 +508,9 @@ "directDepositEtherExplainer": { "message": "如果你已经有了一些 Ether,通过直接转入是你的新钱包获取 Ether 的最快捷方式。" }, + "dismiss": { + "message": "关闭" + }, "done": { "message": "完成" }, @@ -703,6 +713,10 @@ "getStarted": { "message": "开始使用" }, + "greaterThanMin": { + "message": "必须要大于等于 $1。", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "我们很高兴与您见面。" }, @@ -1088,6 +1102,9 @@ "message": "请粘贴你的私钥:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "请粘贴你的助记词!" + }, "pending": { "message": "待处理" }, @@ -1651,6 +1668,9 @@ "userName": { "message": "用户名" }, + "validFileImport": { + "message": "您必须选择一个有效的文件进行导入." + }, "viewAccount": { "message": "查看账户" }, diff --git a/app/_locales/zh_TW/messages.json b/app/_locales/zh_TW/messages.json index 5997e1c8e1..cb104f6cad 100644 --- a/app/_locales/zh_TW/messages.json +++ b/app/_locales/zh_TW/messages.json @@ -35,12 +35,18 @@ "contractInteraction": { "message": "合約互動" }, + "clearApprovalData": { + "message": "清除批准數據" + }, "reject": { "message": "拒絕" }, - "likeToConnect": { + "providerRequest": { "message": "$1 請求訪問帳戶權限" }, + "providerRequestInfo": { + "message": "此網站希望能讀取您的帳戶資訊。請務必確認您信任這個網站、並了解後續可能的交易行為。" + }, "about": { "message": "關於" }, @@ -199,6 +205,10 @@ "basic": { "message": "基本" }, + "betweenMinAndMax": { + "message": "必須大於等於 $1 並且小於等於 $2 。", + "description": "helper for inputting hex as decimal input" + }, "blockExplorerUrl": { "message": "封鎖 Explorer" }, @@ -296,6 +306,9 @@ "connect": { "message": "連線" }, + "connectRequest": { + "message": "連線請求" + }, "connectingTo": { "message": "連線到$1" }, @@ -356,6 +369,9 @@ "copiedExclamation": { "message": "已複製!" }, + "copy": { + "message": "複製" + }, "copyAddress": { "message": "複製到剪貼簿" }, @@ -440,6 +456,9 @@ "directDepositEtherExplainer": { "message": "如果您已經擁有乙太幣,直接存入功能是讓新錢包最快取得乙太幣的方式。" }, + "dismiss": { + "message": "關閉" + }, "done": { "message": "完成" }, @@ -620,6 +639,10 @@ "getStarted": { "message": "開始使用" }, + "greaterThanMin": { + "message": "必須要大於等於 $1。", + "description": "helper for inputting hex as decimal input" + }, "happyToSeeYou": { "message": "我們很高興看到你。" }, @@ -961,6 +984,9 @@ "message": "請貼上您的私鑰字串:", "description": "For importing an account from a private key" }, + "pasteSeed": { + "message": "請貼上您的助憶詞!" + }, "pending": { "message": "等待處理" }, @@ -1281,6 +1307,9 @@ "storePhrase": { "message": "您可以用密碼管理系統例如 1Password 等軟體儲存助憶詞。" }, + "submit": { + "message": "送出" + }, "submitted": { "message": "已送出" }, @@ -1451,6 +1480,9 @@ "userName": { "message": "使用者名稱" }, + "validFileImport": { + "message": "您必須選擇一個合法的檔案來匯入." + }, "viewAccount": { "message": "查看帳戶" }, diff --git a/app/images/broken-line.svg b/app/images/broken-line.svg deleted file mode 100644 index ec4ed0d9c6..0000000000 --- a/app/images/broken-line.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/app/images/connect-white.svg b/app/images/connect-white.svg deleted file mode 100644 index e9063ae463..0000000000 --- a/app/images/connect-white.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/app/images/permissions-check.svg b/app/images/provider-approval-check.svg similarity index 100% rename from app/images/permissions-check.svg rename to app/images/provider-approval-check.svg diff --git a/app/manifest.json b/app/manifest.json index 58d4e13081..f9e25ceda6 100644 --- a/app/manifest.json +++ b/app/manifest.json @@ -1,7 +1,7 @@ { "name": "__MSG_appName__", "short_name": "__MSG_appName__", - "version": "7.7.0", + "version": "7.6.1", "manifest_version": 2, "author": "https://metamask.io", "description": "__MSG_appDescription__", diff --git a/app/scripts/background.js b/app/scripts/background.js index e5c9ea6651..2639d77038 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -64,7 +64,6 @@ const isEdge = !isIE && !!window.StyleMedia let popupIsOpen = false let notificationIsOpen = false const openMetamaskTabsIDs = {} -const requestAccountTabIds = {} // state persistence const localStore = new LocalStore() @@ -76,6 +75,7 @@ initialize().catch(log.error) // setup metamask mesh testing container const { submitMeshMetricsEntry } = setupMetamaskMeshMetrics() + /** * An object representing a transaction, in whatever state it is in. * @typedef TransactionMeta @@ -248,12 +248,6 @@ function setupController (initState, initLangCode) { // platform specific api platform, encryptor: isEdge ? new EdgeEncryptor() : undefined, - getRequestAccountTabIds: () => { - return requestAccountTabIds - }, - getOpenMetamaskTabsIds: () => { - return openMetamaskTabsIDs - }, }) const provider = controller.provider @@ -266,9 +260,7 @@ function setupController (initState, initLangCode) { // report failed transactions to Sentry controller.txController.on(`tx:status-update`, (txId, status) => { - if (status !== 'failed') { - return - } + if (status !== 'failed') return const txMeta = controller.txController.txStateManager.getTx(txId) try { reportFailedTxToSentry({ sentry, txMeta }) @@ -320,7 +312,6 @@ function setupController (initState, initLangCode) { // extension.runtime.onConnect.addListener(connectRemote) extension.runtime.onConnectExternal.addListener(connectExternal) - extension.runtime.onMessage.addListener(controller.onMessage.bind(controller)) const metamaskInternalProcessHash = { [ENVIRONMENT_TYPE_POPUP]: true, @@ -393,17 +384,6 @@ function setupController (initState, initLangCode) { }) } } else { - if (remotePort.sender && remotePort.sender.tab && remotePort.sender.url) { - const tabId = remotePort.sender.tab.id - const url = new URL(remotePort.sender.url) - const origin = url.hostname - - remotePort.onMessage.addListener(msg => { - if (msg.data && msg.data.method === 'eth_requestAccounts') { - requestAccountTabIds[origin] = tabId - } - }) - } connectExternal(remotePort) } } @@ -428,7 +408,7 @@ function setupController (initState, initLangCode) { controller.messageManager.on('updateBadge', updateBadge) controller.personalMessageManager.on('updateBadge', updateBadge) controller.typedMessageManager.on('updateBadge', updateBadge) - controller.permissionsController.permissions.subscribe(updateBadge) + controller.providerApprovalController.memStore.on('update', updateBadge) /** * Updates the Web Extension's "badge" number, on the little fox in the toolbar. @@ -440,8 +420,8 @@ function setupController (initState, initLangCode) { const unapprovedMsgCount = controller.messageManager.unapprovedMsgCount const unapprovedPersonalMsgs = controller.personalMessageManager.unapprovedPersonalMsgCount const unapprovedTypedMsgs = controller.typedMessageManager.unapprovedTypedMessagesCount - const pendingPermissionRequests = Object.keys(controller.permissionsController.permissions.state.permissionsRequests).length - const count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgs + unapprovedTypedMsgs + pendingPermissionRequests + const pendingProviderRequests = controller.providerApprovalController.memStore.getState().providerRequests.length + const count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgs + unapprovedTypedMsgs + pendingProviderRequests if (count) { label = String(count) } diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index d583399aef..db4d5fd63a 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -2,8 +2,8 @@ const fs = require('fs') const path = require('path') const pump = require('pump') const log = require('loglevel') +const Dnode = require('dnode') const querystring = require('querystring') -const { Writable } = require('readable-stream') const LocalMessageDuplexStream = require('post-message-stream') const ObjectMultiplex = require('obj-multiplex') const extension = require('extensionizer') @@ -20,7 +20,7 @@ const inpageBundle = inpageContent + inpageSuffix // If we create a FireFox-only code path using that API, // MetaMask will be much faster loading and performant on Firefox. -if (shouldInjectProvider()) { +if (shouldInjectWeb3()) { injectScript(inpageBundle) start() } @@ -39,7 +39,7 @@ function injectScript (content) { container.insertBefore(scriptTag, container.children[0]) container.removeChild(scriptTag) } catch (e) { - console.error('MetaMask provider injection failed.', e) + console.error('MetaMask script injection failed', e) } } @@ -86,44 +86,6 @@ async function setupStreams () { (err) => logStreamDisconnectWarning('MetaMask Background Multiplex', err) ) - const onboardingStream = pageMux.createStream('onboarding') - const addCurrentTab = new Writable({ - objectMode: true, - write: (chunk, _, callback) => { - if (!chunk) { - return callback(new Error('Malformed onboarding message')) - } - - const handleSendMessageResponse = (error, success) => { - if (!error && !success) { - error = extension.runtime.lastError - } - if (error) { - log.error(`Failed to send ${chunk.type} message`, error) - return callback(error) - } - callback(null) - } - - try { - if (chunk.type === 'registerOnboarding') { - extension.runtime.sendMessage({ type: 'metamask:registerOnboarding', location: window.location.href }, handleSendMessageResponse) - } else { - throw new Error(`Unrecognized onboarding message type: '${chunk.type}'`) - } - } catch (error) { - log.error(error) - return callback(error) - } - }, - }) - - pump( - onboardingStream, - addCurrentTab, - error => console.error('MetaMask onboarding channel traffic failed', error), - ) - // forward communication across inpage-background for these channels only forwardTrafficBetweenMuxers('provider', pageMux, extensionMux) forwardTrafficBetweenMuxers('publicConfig', pageMux, extensionMux) @@ -131,6 +93,12 @@ async function setupStreams () { // connect "phishing" channel to warning system const phishingStream = extensionMux.createStream('phishing') phishingStream.once('data', redirectToPhishingWarning) + + // connect "publicApi" channel to submit page metadata + const publicApiStream = extensionMux.createStream('publicApi') + const background = await setupPublicApi(publicApiStream) + + return { background } } function forwardTrafficBetweenMuxers (channelName, muxA, muxB) { @@ -144,6 +112,37 @@ function forwardTrafficBetweenMuxers (channelName, muxA, muxB) { ) } +async function setupPublicApi (outStream) { + const api = { + getSiteMetadata: (cb) => cb(null, getSiteMetadata()), + } + const dnode = Dnode(api) + pump( + outStream, + dnode, + outStream, + (err) => { + // report any error + if (err) log.error(err) + } + ) + const background = await new Promise(resolve => dnode.once('remote', resolve)) + return background +} + +/** + * Gets site metadata and returns it + * + */ +function getSiteMetadata () { + // get metadata + const metadata = { + name: getSiteName(window), + icon: getSiteIcon(window), + } + return metadata +} + /** * Error handler for page to extension stream disconnections * @@ -152,18 +151,16 @@ function forwardTrafficBetweenMuxers (channelName, muxA, muxB) { */ function logStreamDisconnectWarning (remoteLabel, err) { let warningMsg = `MetamaskContentscript - lost connection to ${remoteLabel}` - if (err) { - warningMsg += '\n' + err.stack - } + if (err) warningMsg += '\n' + err.stack console.warn(warningMsg) } /** - * Determines if the provider should be injected + * Determines if Web3 should be injected * - * @returns {boolean} {@code true} if the provider should be injected + * @returns {boolean} {@code true} if Web3 should be injected */ -function shouldInjectProvider () { +function shouldInjectWeb3 () { return doctypeCheck() && suffixCheck() && documentElementCheck() && !blacklistedDomainCheck() } @@ -186,8 +183,8 @@ function doctypeCheck () { * Returns whether or not the extension (suffix) of the current document is prohibited * * This checks {@code window.location.pathname} against a set of file extensions - * that we should not inject the provider into. This check is indifferent of - * query parameters in the location. + * that should not have web3 injected into them. This check is indifferent of query parameters + * in the location. * * @returns {boolean} whether or not the extension of the current document is prohibited */ @@ -260,14 +257,52 @@ function redirectToPhishingWarning () { })}` } + +/** + * Extracts a name for the site from the DOM + */ +function getSiteName (window) { + const document = window.document + const siteName = document.querySelector('head > meta[property="og:site_name"]') + if (siteName) { + return siteName.content + } + + const metaTitle = document.querySelector('head > meta[name="title"]') + if (metaTitle) { + return metaTitle.content + } + + return document.title +} + +/** + * Extracts an icon for the site from the DOM + */ +function getSiteIcon (window) { + const document = window.document + + // Use the site's favicon if it exists + const shortcutIcon = document.querySelector('head > link[rel="shortcut icon"]') + if (shortcutIcon) { + return shortcutIcon.href + } + + // Search through available icons in no particular order + const icon = Array.from(document.querySelectorAll('head > link[rel="icon"]')).find((icon) => Boolean(icon.href)) + if (icon) { + return icon.href + } + + return null +} + /** * Returns a promise that resolves when the DOM is loaded (does not wait for images to load) */ async function domIsReady () { // already loaded - if (['interactive', 'complete'].includes(document.readyState)) { - return - } + if (['interactive', 'complete'].includes(document.readyState)) return // wait for load - return new Promise(resolve => window.addEventListener('DOMContentLoaded', resolve, { once: true })) + await new Promise(resolve => window.addEventListener('DOMContentLoaded', resolve, { once: true })) } diff --git a/app/scripts/controllers/app-state.js b/app/scripts/controllers/app-state.js index c60a1c4f50..8d67874ad0 100644 --- a/app/scripts/controllers/app-state.js +++ b/app/scripts/controllers/app-state.js @@ -45,7 +45,7 @@ class AppStateController { * @private */ _setInactiveTimeout (timeoutMinutes) { - this.store.updateState({ + this.store.putState({ timeoutMinutes, }) diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js index 923aa2d15f..e6e9930735 100644 --- a/app/scripts/controllers/detect-tokens.js +++ b/app/scripts/controllers/detect-tokens.js @@ -29,12 +29,8 @@ class DetectTokensController { * */ async detectNewTokens () { - if (!this.isActive) { - return - } - if (this._network.store.getState().provider.type !== MAINNET) { - return - } + if (!this.isActive) { return } + if (this._network.store.getState().provider.type !== MAINNET) { return } const tokensToDetect = [] this.web3.setProvider(this._network._provider) for (const contractAddress in contracts) { @@ -84,9 +80,7 @@ class DetectTokensController { * */ restartTokenDetection () { - if (!(this.isActive && this.selectedAddress)) { - return - } + if (!(this.isActive && this.selectedAddress)) { return } this.detectNewTokens() this.interval = DEFAULT_INTERVAL } @@ -96,12 +90,8 @@ class DetectTokensController { */ set interval (interval) { this._handle && clearInterval(this._handle) - if (!interval) { - return - } - this._handle = setInterval(() => { - this.detectNewTokens() - }, interval) + if (!interval) { return } + this._handle = setInterval(() => { this.detectNewTokens() }, interval) } /** @@ -109,15 +99,9 @@ class DetectTokensController { * @type {Object} */ set preferences (preferences) { - if (!preferences) { - return - } + if (!preferences) { return } this._preferences = preferences - preferences.store.subscribe(({ tokens = [] }) => { - this.tokenAddresses = tokens.map((obj) => { - return obj.address - }) - }) + preferences.store.subscribe(({ tokens = [] }) => { this.tokenAddresses = tokens.map((obj) => { return obj.address }) }) preferences.store.subscribe(({ selectedAddress }) => { if (this.selectedAddress !== selectedAddress) { this.selectedAddress = selectedAddress @@ -130,9 +114,7 @@ class DetectTokensController { * @type {Object} */ set network (network) { - if (!network) { - return - } + if (!network) { return } this._network = network this.web3 = new Web3(network._provider) } @@ -142,16 +124,12 @@ class DetectTokensController { * @type {Object} */ set keyringMemStore (keyringMemStore) { - if (!keyringMemStore) { - return - } + if (!keyringMemStore) { return } this._keyringMemStore = keyringMemStore this._keyringMemStore.subscribe(({ isUnlocked }) => { if (this.isUnlocked !== isUnlocked) { this.isUnlocked = isUnlocked - if (isUnlocked) { - this.restartTokenDetection() - } + if (isUnlocked) { this.restartTokenDetection() } } }) } diff --git a/app/scripts/controllers/incoming-transactions.js b/app/scripts/controllers/incoming-transactions.js index 10735b3f92..029bf47aa5 100644 --- a/app/scripts/controllers/incoming-transactions.js +++ b/app/scripts/controllers/incoming-transactions.js @@ -163,9 +163,7 @@ class IncomingTransactionsController { const newIncomingTransactions = { ...currentIncomingTxs, } - newTxs.forEach(tx => { - newIncomingTransactions[tx.hash] = tx - }) + newTxs.forEach(tx => { newIncomingTransactions[tx.hash] = tx }) this.store.updateState({ incomingTxLastFetchedBlocksByNetwork: { diff --git a/app/scripts/controllers/network/middleware/pending.js b/app/scripts/controllers/network/middleware/pending.js index 96a5d40be8..542d8bde6f 100644 --- a/app/scripts/controllers/network/middleware/pending.js +++ b/app/scripts/controllers/network/middleware/pending.js @@ -4,13 +4,9 @@ const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware function createPendingNonceMiddleware ({ getPendingNonce }) { return createAsyncMiddleware(async (req, res, next) => { const {method, params} = req - if (method !== 'eth_getTransactionCount') { - return next() - } + if (method !== 'eth_getTransactionCount') return next() const [param, blockRef] = params - if (blockRef !== 'pending') { - return next() - } + if (blockRef !== 'pending') return next() res.result = await getPendingNonce(param) }) } @@ -18,14 +14,10 @@ function createPendingNonceMiddleware ({ getPendingNonce }) { function createPendingTxMiddleware ({ getPendingTransactionByHash }) { return createAsyncMiddleware(async (req, res, next) => { const {method, params} = req - if (method !== 'eth_getTransactionByHash') { - return next() - } + if (method !== 'eth_getTransactionByHash') return next() const [hash] = params const txMeta = getPendingTransactionByHash(hash) - if (!txMeta) { - return next() - } + if (!txMeta) return next() res.result = formatTxMetaForRpcResult(txMeta) }) } diff --git a/app/scripts/controllers/network/network.js b/app/scripts/controllers/network/network.js index d78f92f93d..7b5d8ef383 100644 --- a/app/scripts/controllers/network/network.js +++ b/app/scripts/controllers/network/network.js @@ -81,9 +81,7 @@ module.exports = class NetworkController extends EventEmitter { verifyNetwork () { // Check network when restoring connectivity: - if (this.isNetworkLoading()) { - this.lookupNetwork() - } + if (this.isNetworkLoading()) this.lookupNetwork() } getNetworkState () { @@ -198,7 +196,7 @@ module.exports = class NetworkController extends EventEmitter { }) this._setNetworkClient(networkClient) // setup networkConfig - const settings = { + var settings = { ticker: 'ETH', } this.networkConfig.putState(settings) @@ -221,7 +219,7 @@ module.exports = class NetworkController extends EventEmitter { nickname, } // setup networkConfig - let settings = { + var settings = { network: chainId, } settings = extend(settings, networks.networkList['rpc']) diff --git a/app/scripts/controllers/onboarding.js b/app/scripts/controllers/onboarding.js index 5d00fb7755..a29c8407a4 100644 --- a/app/scripts/controllers/onboarding.js +++ b/app/scripts/controllers/onboarding.js @@ -1,6 +1,5 @@ const ObservableStore = require('obs-store') const extend = require('xtend') -const log = require('loglevel') /** * @typedef {Object} InitState @@ -10,12 +9,11 @@ const log = require('loglevel') /** * @typedef {Object} OnboardingOptions * @property {InitState} initState The initial controller state - * @property {PreferencesController} preferencesController Controller for managing user perferences */ /** * Controller responsible for maintaining - * state related to onboarding + * a cache of account balances in local storage */ class OnboardingController { /** @@ -24,28 +22,10 @@ class OnboardingController { * @param {OnboardingOptions} [opts] Controller configuration parameters */ constructor (opts = {}) { - const initialTransientState = { - onboardingTabs: {}, - } - const initState = extend( - { - seedPhraseBackedUp: true, - }, - opts.initState, - initialTransientState, - ) + const initState = extend({ + seedPhraseBackedUp: true, + }, opts.initState) this.store = new ObservableStore(initState) - this.preferencesController = opts.preferencesController - this.completedOnboarding = this.preferencesController.store.getState().completedOnboarding - - this.preferencesController.store.subscribe(({ completedOnboarding }) => { - if (completedOnboarding !== this.completedOnboarding) { - this.completedOnboarding = completedOnboarding - if (completedOnboarding) { - this.store.updateState(initialTransientState) - } - } - }) } setSeedPhraseBackedUp (newSeedPhraseBackUpState) { @@ -58,24 +38,6 @@ class OnboardingController { return this.store.getState().seedPhraseBackedUp } - /** - * Registering a site as having initiated onboarding - * - * @param {string} location - The location of the site registering - * @param {string} tabId - The id of the tab registering - */ - async registerOnboarding (location, tabId) { - if (this.completedOnboarding) { - log.debug('Ignoring registerOnboarding; user already onboarded') - return - } - const onboardingTabs = Object.assign({}, this.store.getState().onboardingTabs) - if (!onboardingTabs[location] || onboardingTabs[location] !== tabId) { - log.debug(`Registering onboarding tab at location '${location}' with tabId '${tabId}'`) - onboardingTabs[location] = tabId - this.store.updateState({ onboardingTabs }) - } - } } module.exports = OnboardingController diff --git a/app/scripts/controllers/permissions/index.js b/app/scripts/controllers/permissions/index.js deleted file mode 100644 index 899044b13e..0000000000 --- a/app/scripts/controllers/permissions/index.js +++ /dev/null @@ -1,377 +0,0 @@ -const JsonRpcEngine = require('json-rpc-engine') -const asMiddleware = require('json-rpc-engine/src/asMiddleware') -const ObservableStore = require('obs-store') -const RpcCap = require('rpc-cap').CapabilitiesController -const { ethErrors } = require('eth-json-rpc-errors') - -const getRestrictedMethods = require('./restrictedMethods') -const createMethodMiddleware = require('./methodMiddleware') -const createLoggerMiddleware = require('./loggerMiddleware') - -// Methods that do not require any permissions to use: -const SAFE_METHODS = require('./permissions-safe-methods.json') - -// some constants -const METADATA_STORE_KEY = 'domainMetadata' -const LOG_STORE_KEY = 'permissionsLog' -const HISTORY_STORE_KEY = 'permissionsHistory' -const WALLET_METHOD_PREFIX = 'wallet_' -const CAVEAT_NAMES = { - exposedAccounts: 'exposedAccounts', -} -const ACCOUNTS_CHANGED_NOTIFICATION = 'wallet_accountsChanged' - -class PermissionsController { - - constructor ( - { - platform, notifyDomain, notifyAllDomains, keyringController, - } = {}, - restoredPermissions = {}, - restoredState = {}) { - this.store = new ObservableStore({ - [METADATA_STORE_KEY]: restoredState[METADATA_STORE_KEY] || {}, - [LOG_STORE_KEY]: restoredState[LOG_STORE_KEY] || [], - [HISTORY_STORE_KEY]: restoredState[HISTORY_STORE_KEY] || {}, - }) - this.notifyDomain = notifyDomain - this.notifyAllDomains = notifyAllDomains - this.keyringController = keyringController - this._platform = platform - this._restrictedMethods = getRestrictedMethods(this) - this._initializePermissions(restoredPermissions) - } - - createMiddleware ({ origin, extensionId }) { - - if (extensionId) { - this.store.updateState({ - [METADATA_STORE_KEY]: { - ...this.store.getState()[METADATA_STORE_KEY], - [origin]: { extensionId }, - }, - }) - } - - const engine = new JsonRpcEngine() - - engine.push(createLoggerMiddleware({ - walletPrefix: WALLET_METHOD_PREFIX, - restrictedMethods: Object.keys(this._restrictedMethods), - ignoreMethods: [ 'wallet_sendDomainMetadata' ], - store: this.store, - logStoreKey: LOG_STORE_KEY, - historyStoreKey: HISTORY_STORE_KEY, - })) - - engine.push(createMethodMiddleware({ - store: this.store, - storeKey: METADATA_STORE_KEY, - getAccounts: this.getAccounts.bind(this, origin), - requestAccountsPermission: this._requestPermissions.bind( - this, origin, { eth_accounts: {} } - ), - })) - - engine.push(this.permissions.providerMiddlewareFunction.bind( - this.permissions, { origin } - )) - return asMiddleware(engine) - } - - /** - * Returns the accounts that should be exposed for the given origin domain, - * if any. This method exists for when a trusted context needs to know - * which accounts are exposed to a given domain. - * - * @param {string} origin - The origin string. - */ - getAccounts (origin) { - return new Promise((resolve, _) => { - - const req = { method: 'eth_accounts' } - const res = {} - this.permissions.providerMiddlewareFunction( - { origin }, req, res, () => {}, _end - ) - - function _end () { - if (res.error || !Array.isArray(res.result)) { - resolve([]) - } else { - resolve(res.result) - } - } - }) - } - - /** - * Submits a permissions request to rpc-cap. Internal use only. - * - * @param {string} origin - The origin string. - * @param {IRequestedPermissions} permissions - The requested permissions. - */ - _requestPermissions (origin, permissions) { - return new Promise((resolve, reject) => { - - const req = { method: 'wallet_requestPermissions', params: [permissions] } - const res = {} - this.permissions.providerMiddlewareFunction( - { origin }, req, res, () => {}, _end - ) - - function _end (err) { - if (err || res.error) { - reject(err || res.error) - } else { - resolve(res.result) - } - } - }) - } - - /** - * User approval callback. The request can fail if the request is invalid. - * - * @param {object} approved the approved request object - */ - async approvePermissionsRequest (approved, accounts) { - - const { id } = approved.metadata - const approval = this.pendingApprovals[id] - - try { - - // attempt to finalize the request and resolve it - await this.finalizePermissionsRequest(approved.permissions, accounts) - approval.resolve(approved.permissions) - - } catch (err) { - - // if finalization fails, reject the request - approval.reject(ethErrors.rpc.invalidRequest({ - message: err.message, data: err, - })) - } - - delete this.pendingApprovals[id] - } - - /** - * User rejection callback. - * - * @param {string} id the id of the rejected request - */ - async rejectPermissionsRequest (id) { - const approval = this.pendingApprovals[id] - approval.reject(ethErrors.provider.userRejectedRequest()) - delete this.pendingApprovals[id] - } - - /** - * Grants the given origin the eth_accounts permission for the given account(s). - * This method should ONLY be called as a result of direct user action in the UI, - * with the intention of supporting legacy dapps that don't support EIP 1102. - * - * @param {string} origin - The origin to expose the account(s) to. - * @param {Array} accounts - The account(s) to expose. - */ - async legacyExposeAccounts (origin, accounts) { - - const permissions = { - eth_accounts: {}, - } - - await this.finalizePermissionsRequest(permissions, accounts) - - let error - try { - await new Promise((resolve, reject) => { - this.permissions.grantNewPermissions(origin, permissions, {}, err => err ? resolve() : reject(err)) - }) - } catch (err) { - error = err - } - - if (error) { - if (error.code === 4001) { - throw error - } else { - throw ethErrors.rpc.internal({ - message: `Failed to add 'eth_accounts' to '${origin}'.`, - data: { - originalError: error, - accounts, - }, - }) - } - } - } - - /** - * Update the accounts exposed to the given origin. - * Throws error if the update fails. - * - * @param {string} origin - The origin to change the exposed accounts for. - * @param {string[]} accounts - The new account(s) to expose. - */ - async updateExposedAccounts (origin, accounts) { - - await this.validateExposedAccounts(accounts) - - this.permissions.updateCaveatFor( - origin, 'eth_accounts', CAVEAT_NAMES.exposedAccounts, accounts - ) - - this.notifyDomain(origin, { - method: ACCOUNTS_CHANGED_NOTIFICATION, - result: accounts, - }) - } - - /** - * Finalizes a permissions request. - * Throws if request validation fails. - * - * @param {Object} requestedPermissions - The requested permissions. - * @param {string[]} accounts - The accounts to expose, if any. - */ - async finalizePermissionsRequest (requestedPermissions, accounts) { - - const { eth_accounts: ethAccounts } = requestedPermissions - - if (ethAccounts) { - - await this.validateExposedAccounts(accounts) - - if (!ethAccounts.caveats) { - ethAccounts.caveats = [] - } - - // caveat names are unique, and we will only construct this caveat here - ethAccounts.caveats = ethAccounts.caveats.filter(c => ( - c.name !== CAVEAT_NAMES.exposedAccounts - )) - - ethAccounts.caveats.push( - { - type: 'filterResponse', - value: accounts, - name: CAVEAT_NAMES.exposedAccounts, - }, - ) - } - } - - /** - * Validate an array of accounts representing accounts to be exposed - * to a domain. Throws error if validation fails. - * - * @param {string[]} accounts - An array of addresses. - */ - async validateExposedAccounts (accounts) { - - if (!Array.isArray(accounts) || accounts.length === 0) { - throw new Error('Must provide non-empty array of account(s).') - } - - // assert accounts exist - const allAccounts = await this.keyringController.getAccounts() - accounts.forEach(acc => { - if (!allAccounts.includes(acc)) { - throw new Error(`Unknown account: ${acc}`) - } - }) - } - - /** - * Removes the given permissions for the given domain. - * @param {object} domains { origin: [permissions] } - */ - removePermissionsFor (domains) { - - Object.entries(domains).forEach(([origin, perms]) => { - - this.permissions.removePermissionsFor( - origin, - perms.map(methodName => { - - if (methodName === 'eth_accounts') { - this.notifyDomain( - origin, - { method: ACCOUNTS_CHANGED_NOTIFICATION, result: [] } - ) - } - - return { parentCapability: methodName } - }) - ) - }) - } - - /** - * Removes all known domains and their related permissions. - */ - clearPermissions () { - this.permissions.clearDomains() - this.notifyAllDomains({ - method: ACCOUNTS_CHANGED_NOTIFICATION, - result: [], - }) - } - - /** - * A convenience method for retrieving a login object - * or creating a new one if needed. - * - * @param {string} origin = The origin string representing the domain. - */ - _initializePermissions (restoredState) { - - // these permission requests are almost certainly stale - const initState = { ...restoredState, permissionsRequests: [] } - - this.pendingApprovals = {} - - this.permissions = new RpcCap({ - - // Supports passthrough methods: - safeMethods: SAFE_METHODS, - - // optional prefix for internal methods - methodPrefix: WALLET_METHOD_PREFIX, - - restrictedMethods: this._restrictedMethods, - - /** - * A promise-returning callback used to determine whether to approve - * permissions requests or not. - * - * Currently only returns a boolean, but eventually should return any - * specific parameters or amendments to the permissions. - * - * @param {string} req - The internal rpc-cap user request object. - */ - requestUserApproval: async (req) => { - const { metadata: { id } } = req - - this._platform.openExtensionInBrowser('connect') - - return new Promise((resolve, reject) => { - this.pendingApprovals[id] = { resolve, reject } - }) - }, - }, initState) - } -} - -module.exports = { - PermissionsController, - addInternalMethodPrefix: prefix, - CAVEAT_NAMES, -} - - -function prefix (method) { - return WALLET_METHOD_PREFIX + method -} diff --git a/app/scripts/controllers/permissions/loggerMiddleware.js b/app/scripts/controllers/permissions/loggerMiddleware.js deleted file mode 100644 index 0e3c7f3932..0000000000 --- a/app/scripts/controllers/permissions/loggerMiddleware.js +++ /dev/null @@ -1,169 +0,0 @@ - -const clone = require('clone') -const { isValidAddress } = require('ethereumjs-util') - -const LOG_LIMIT = 100 - -/** - * Create middleware for logging requests and responses to restricted and - * permissions-related methods. - */ -module.exports = function createLoggerMiddleware ({ - walletPrefix, restrictedMethods, store, logStoreKey, historyStoreKey, ignoreMethods, -}) { - return (req, res, next, _end) => { - let activityEntry, requestedMethods - const { origin, method } = req - const isInternal = method.startsWith(walletPrefix) - if ((isInternal || restrictedMethods.includes(method)) && !ignoreMethods.includes(method)) { - activityEntry = logActivity(req, isInternal) - if (method === `${walletPrefix}requestPermissions`) { - requestedMethods = getRequestedMethods(req) - } - } else if (method === 'eth_requestAccounts') { - activityEntry = logActivity(req, isInternal) - requestedMethods = [ 'eth_accounts' ] - } else { - return next() - } - - next(cb => { - const time = Date.now() - addResponse(activityEntry, res, time) - if (!res.error && requestedMethods) { - logHistory(requestedMethods, origin, res.result, time, method === 'eth_requestAccounts') - } - cb() - }) - } - - function logActivity (request, isInternal) { - const activityEntry = { - id: request.id, - method: request.method, - methodType: isInternal ? 'internal' : 'restricted', - origin: request.origin, - request: cloneObj(request), - requestTime: Date.now(), - response: null, - responseTime: null, - success: null, - } - commitActivity(activityEntry) - return activityEntry - } - - function addResponse (activityEntry, response, time) { - if (!response) { - return - } - activityEntry.response = cloneObj(response) - activityEntry.responseTime = time - activityEntry.success = !response.error - } - - function commitActivity (entry) { - const logs = store.getState()[logStoreKey] - if (logs.length > LOG_LIMIT - 2) { - logs.pop() - } - logs.push(entry) - store.updateState({ [logStoreKey]: logs }) - } - - function getRequestedMethods (request) { - if ( - !request.params || - typeof request.params[0] !== 'object' || - Array.isArray(request.params[0]) - ) { - return null - } - return Object.keys(request.params[0]) - } - - function logHistory (requestedMethods, origin, result, time, isEthRequestAccounts) { - let accounts, entries - if (isEthRequestAccounts) { - accounts = result - const accountToTimeMap = accounts.reduce((acc, account) => ({ ...acc, [account]: time }), {}) - entries = { 'eth_accounts': { accounts: accountToTimeMap, lastApproved: time } } - } else { - entries = result - ? result - .map(perm => { - if (perm.parentCapability === 'eth_accounts') { - accounts = getAccountsFromPermission(perm) - } - return perm.parentCapability - }) - .reduce((acc, m) => { - if (requestedMethods.includes(m)) { - if (m === 'eth_accounts') { - const accountToTimeMap = accounts.reduce((acc, account) => ({ ...acc, [account]: time }), {}) - acc[m] = { lastApproved: time, accounts: accountToTimeMap } - } else { - acc[m] = { lastApproved: time } - } - } - return acc - }, {}) - : {} - } - - if (Object.keys(entries).length > 0) { - commitHistory(origin, entries) - } - } - - function commitHistory (origin, entries) { - const history = store.getState()[historyStoreKey] || {} - const newOriginHistory = { - ...history[origin], - ...entries, - } - - if (history[origin] && history[origin]['eth_accounts'] && entries['eth_accounts']) { - newOriginHistory['eth_accounts'] = { - lastApproved: entries['eth_accounts'].lastApproved, - accounts: { - ...history[origin]['eth_accounts'].accounts, - ...entries['eth_accounts'].accounts, - }, - } - } - - history[origin] = newOriginHistory - - store.updateState({ [historyStoreKey]: history }) - } -} - -// the call to clone is set to disallow circular references -// we attempt cloning at a depth of 3 and 2, then return a -// shallow copy of the object -function cloneObj (obj) { - for (let i = 3; i > 1; i--) { - try { - return clone(obj, false, i) - } catch (_) {} - } - return { ...obj } -} - -function getAccountsFromPermission (perm) { - if (perm.parentCapability !== 'eth_accounts' || !perm.caveats) { - return [] - } - const accounts = {} - for (const c of perm.caveats) { - if (c.type === 'filterResponse' && Array.isArray(c.value)) { - for (const v of c.value) { - if (isValidAddress(v)) { - accounts[v] = true - } - } - } - } - return Object.keys(accounts) -} diff --git a/app/scripts/controllers/permissions/methodMiddleware.js b/app/scripts/controllers/permissions/methodMiddleware.js deleted file mode 100644 index e0b451c9f6..0000000000 --- a/app/scripts/controllers/permissions/methodMiddleware.js +++ /dev/null @@ -1,90 +0,0 @@ - -const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') -const { ethErrors } = require('eth-json-rpc-errors') - -/** - * Create middleware for handling certain methods and preprocessing permissions requests. - */ -module.exports = function createMethodMiddleware ({ - store, storeKey, getAccounts, requestAccountsPermission, -}) { - return createAsyncMiddleware(async (req, res, next) => { - - if (typeof req.method !== 'string') { - res.error = ethErrors.rpc.invalidRequest({ data: req}) - return - } - - switch (req.method) { - - // intercepting eth_accounts requests for backwards compatibility, - // i.e. return an empty array instead of an error - case 'eth_accounts': - - res.result = await getAccounts() - return - - case 'eth_requestAccounts': - - // first, just try to get accounts - let accounts = await getAccounts() - if (accounts.length > 0) { - res.result = accounts - return - } - - // if no accounts, request the accounts permission - try { - await requestAccountsPermission() - } catch (err) { - res.error = err - return - } - - // get the accounts again - accounts = await getAccounts() - if (accounts.length > 0) { - res.result = accounts - } else { - // this should never happen - res.error = ethErrors.rpc.internal( - 'Accounts unexpectedly unavailable. Please report this bug.' - ) - } - - return - - // custom method for getting metadata from the requesting domain - case 'wallet_sendDomainMetadata': - - const storeState = store.getState()[storeKey] - const extensionId = storeState[req.origin] - ? storeState[req.origin].extensionId - : undefined - - if ( - req.domainMetadata && - typeof req.domainMetadata.name === 'string' - ) { - - store.updateState({ - [storeKey]: { - ...storeState, - [req.origin]: { - extensionId, - ...req.domainMetadata, - }, - }, - }) - } - - res.result = true - return - - default: - break - } - - next() - }) -} diff --git a/app/scripts/controllers/permissions/permissions-safe-methods.json b/app/scripts/controllers/permissions/permissions-safe-methods.json deleted file mode 100644 index 17b46b5313..0000000000 --- a/app/scripts/controllers/permissions/permissions-safe-methods.json +++ /dev/null @@ -1,49 +0,0 @@ -[ - "web3_sha3", - "net_listening", - "net_peerCount", - "net_version", - "eth_blockNumber", - "eth_call", - "eth_chainId", - "eth_coinbase", - "eth_estimateGas", - "eth_gasPrice", - "eth_getBalance", - "eth_getBlockByHash", - "eth_getBlockByNumber", - "eth_getBlockTransactionCountByHash", - "eth_getBlockTransactionCountByNumber", - "eth_getCode", - "eth_getFilterChanges", - "eth_getFilterLogs", - "eth_getLogs", - "eth_getStorageAt", - "eth_getTransactionByBlockHashAndIndex", - "eth_getTransactionByBlockNumberAndIndex", - "eth_getTransactionByHash", - "eth_getTransactionCount", - "eth_getTransactionReceipt", - "eth_getUncleByBlockHashAndIndex", - "eth_getUncleByBlockNumberAndIndex", - "eth_getUncleCountByBlockHash", - "eth_getUncleCountByBlockNumber", - "eth_getWork", - "eth_hashrate", - "eth_mining", - "eth_newBlockFilter", - "eth_newFilter", - "eth_newPendingTransactionFilter", - "eth_protocolVersion", - "eth_sendRawTransaction", - "eth_sendTransaction", - "eth_sign", - "personal_sign", - "eth_signTypedData", - "eth_signTypedData_v1", - "eth_signTypedData_v3", - "eth_submitHashrate", - "eth_submitWork", - "eth_syncing", - "eth_uninstallFilter" -] \ No newline at end of file diff --git a/app/scripts/controllers/permissions/restrictedMethods.js b/app/scripts/controllers/permissions/restrictedMethods.js deleted file mode 100644 index cd87b2d574..0000000000 --- a/app/scripts/controllers/permissions/restrictedMethods.js +++ /dev/null @@ -1,20 +0,0 @@ - -module.exports = function getRestrictedMethods (permissionsController) { - return { - - 'eth_accounts': { - description: 'View the address of the selected account', - method: (_, res, __, end) => { - permissionsController.keyringController.getAccounts() - .then((accounts) => { - res.result = accounts - end() - }) - .catch((err) => { - res.error = err - end(err) - }) - }, - }, - } -} diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 409ce68766..1cfbb4d4c2 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -1,5 +1,4 @@ const ObservableStore = require('obs-store') -const { addInternalMethodPrefix } = require('./permissions') const normalizeAddress = require('eth-sig-util').normalize const { isValidAddress, sha3, bufferToHex } = require('ethereumjs-util') const extend = require('xtend') @@ -58,6 +57,7 @@ class PreferencesController { useNativeCurrencyAsPrimaryCurrency: true, }, completedOnboarding: false, + migratedPrivacyMode: false, metaMetricsId: null, metaMetricsSendCount: 0, }, opts.initState) @@ -187,10 +187,7 @@ class PreferencesController { * @param {Function} - end */ async requestWatchAsset (req, res, next, end) { - if ( - req.method === 'metamask_watchAsset' || - req.method === addInternalMethodPrefix('watchAsset') - ) { + if (req.method === 'metamask_watchAsset' || req.method === 'wallet_watchAsset') { const { type, options } = req.params switch (type) { case 'ERC20': @@ -306,9 +303,7 @@ class PreferencesController { const accountTokens = this.store.getState().accountTokens addresses.forEach((address) => { // skip if already exists - if (identities[address]) { - return - } + if (identities[address]) return // add missing identity const identityCount = Object.keys(identities).length @@ -340,9 +335,7 @@ class PreferencesController { if (Object.keys(newlyLost).length > 0) { // Notify our servers: - if (this.diagnostics) { - this.diagnostics.reportOrphans(newlyLost) - } + if (this.diagnostics) this.diagnostics.reportOrphans(newlyLost) // store lost accounts for (const key in newlyLost) { @@ -470,9 +463,7 @@ class PreferencesController { * @return {Promise} */ setAccountLabel (account, label) { - if (!account) { - throw new Error('setAccountLabel requires a valid address, got ' + String(account)) - } + if (!account) throw new Error('setAccountLabel requires a valid address, got ' + String(account)) const address = normalizeAddress(account) const {identities} = this.store.getState() identities[address] = identities[address] || {} @@ -509,9 +500,7 @@ class PreferencesController { updateRpc (newRpcDetails) { const rpcList = this.getFrequentRpcListDetail() - const index = rpcList.findIndex((element) => { - return element.rpcUrl === newRpcDetails.rpcUrl - }) + const index = rpcList.findIndex((element) => { return element.rpcUrl === newRpcDetails.rpcUrl }) if (index > -1) { const rpcDetail = rpcList[index] const updatedRpc = extend(rpcDetail, newRpcDetails) @@ -535,9 +524,7 @@ class PreferencesController { */ addToFrequentRpcList (url, chainId, ticker = 'ETH', nickname = '', rpcPrefs = {}) { const rpcList = this.getFrequentRpcListDetail() - const index = rpcList.findIndex((element) => { - return element.rpcUrl === url - }) + const index = rpcList.findIndex((element) => { return element.rpcUrl === url }) if (index !== -1) { rpcList.splice(index, 1) } @@ -561,9 +548,7 @@ class PreferencesController { */ removeFromFrequentRpcList (url) { const rpcList = this.getFrequentRpcListDetail() - const index = rpcList.findIndex((element) => { - return element.rpcUrl === url - }) + const index = rpcList.findIndex((element) => { return element.rpcUrl === url }) if (index !== -1) { rpcList.splice(index, 1) } @@ -647,6 +632,13 @@ class PreferencesController { return Promise.resolve(true) } + unsetMigratedPrivacyMode () { + this.store.updateState({ + migratedPrivacyMode: false, + }) + return Promise.resolve() + } + // // PRIVATE METHODS // @@ -695,16 +687,10 @@ class PreferencesController { */ _getTokenRelatedStates (selectedAddress) { const accountTokens = this.store.getState().accountTokens - if (!selectedAddress) { - selectedAddress = this.store.getState().selectedAddress - } + if (!selectedAddress) selectedAddress = this.store.getState().selectedAddress const providerType = this.network.providerStore.getState().type - if (!(selectedAddress in accountTokens)) { - accountTokens[selectedAddress] = {} - } - if (!(providerType in accountTokens[selectedAddress])) { - accountTokens[selectedAddress][providerType] = [] - } + if (!(selectedAddress in accountTokens)) accountTokens[selectedAddress] = {} + if (!(providerType in accountTokens[selectedAddress])) accountTokens[selectedAddress][providerType] = [] const tokens = accountTokens[selectedAddress][providerType] return { tokens, accountTokens, providerType, selectedAddress } } @@ -741,19 +727,13 @@ class PreferencesController { */ _validateERC20AssetParams (opts) { const { rawAddress, symbol, decimals } = opts - if (!rawAddress || !symbol || typeof decimals === 'undefined') { - throw new Error(`Cannot suggest token without address, symbol, and decimals`) - } - if (!(symbol.length < 7)) { - throw new Error(`Invalid symbol ${symbol} more than six characters`) - } + if (!rawAddress || !symbol || typeof decimals === 'undefined') throw new Error(`Cannot suggest token without address, symbol, and decimals`) + if (!(symbol.length < 7)) throw new Error(`Invalid symbol ${symbol} more than six 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}`) - } + if (!isValidAddress(rawAddress)) throw new Error(`Invalid address ${rawAddress}`) } } diff --git a/app/scripts/controllers/provider-approval.js b/app/scripts/controllers/provider-approval.js new file mode 100644 index 0000000000..00ff626f71 --- /dev/null +++ b/app/scripts/controllers/provider-approval.js @@ -0,0 +1,175 @@ +const ObservableStore = require('obs-store') +const SafeEventEmitter = require('safe-event-emitter') +const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') +const { errors: rpcErrors } = require('eth-json-rpc-errors') + +/** + * A controller that services user-approved requests for a full Ethereum provider API + */ +class ProviderApprovalController extends SafeEventEmitter { + /** + * Creates a ProviderApprovalController + * + * @param {Object} [config] - Options to configure controller + */ + constructor ({ closePopup, initState, keyringController, openPopup, preferencesController } = {}) { + super() + this.closePopup = closePopup + this.keyringController = keyringController + this.openPopup = openPopup + this.preferencesController = preferencesController + this.memStore = new ObservableStore({ + providerRequests: [], + }) + + const defaultState = { approvedOrigins: {} } + this.store = new ObservableStore(Object.assign(defaultState, initState)) + } + + /** + * Called when a user approves access to a full Ethereum provider API + * + * @param {object} opts - opts for the middleware contains the origin for the middleware + */ + createMiddleware ({ senderUrl, extensionId, getSiteMetadata }) { + return createAsyncMiddleware(async (req, res, next) => { + // only handle requestAccounts + if (req.method !== 'eth_requestAccounts') return next() + // if already approved or privacy mode disabled, return early + const isUnlocked = this.keyringController.memStore.getState().isUnlocked + const origin = senderUrl.hostname + if (this.shouldExposeAccounts(origin) && isUnlocked) { + res.result = [this.preferencesController.getSelectedAddress()] + return + } + // register the provider request + const metadata = { hostname: senderUrl.hostname, origin } + if (extensionId) { + metadata.extensionId = extensionId + } else { + const siteMetadata = await getSiteMetadata(origin) + Object.assign(metadata, { siteTitle: siteMetadata.name, siteImage: siteMetadata.icon}) + } + this._handleProviderRequest(metadata) + // wait for resolution of request + const approved = await new Promise(resolve => this.once(`resolvedRequest:${origin}`, ({ approved }) => resolve(approved))) + if (approved) { + res.result = [this.preferencesController.getSelectedAddress()] + } else { + throw rpcErrors.eth.userRejectedRequest('User denied account authorization') + } + }) + } + + /** + * @typedef {Object} SiteMetadata + * @param {string} hostname - The hostname of the site + * @param {string} origin - The origin of the site + * @param {string} [siteTitle] - The title of the site + * @param {string} [siteImage] - The icon for the site + * @param {string} [extensionId] - The extension ID of the extension + */ + /** + * Called when a tab requests access to a full Ethereum provider API + * + * @param {SiteMetadata} siteMetadata - The metadata for the site requesting full provider access + */ + _handleProviderRequest (siteMetadata) { + const { providerRequests } = this.memStore.getState() + const origin = siteMetadata.origin + this.memStore.updateState({ + providerRequests: [ + ...providerRequests, + siteMetadata, + ], + }) + const isUnlocked = this.keyringController.memStore.getState().isUnlocked + const { approvedOrigins } = this.store.getState() + const originAlreadyHandled = approvedOrigins[origin] + if (originAlreadyHandled && isUnlocked) { + return + } + this.openPopup && this.openPopup() + } + + /** + * Called when a user approves access to a full Ethereum provider API + * + * @param {string} origin - origin of the domain that had provider access approved + */ + approveProviderRequestByOrigin (origin) { + if (this.closePopup) { + this.closePopup() + } + + const { approvedOrigins } = this.store.getState() + const { providerRequests } = this.memStore.getState() + const providerRequest = providerRequests.find((request) => request.origin === origin) + const remainingProviderRequests = providerRequests.filter(request => request.origin !== origin) + this.store.updateState({ + approvedOrigins: { + ...approvedOrigins, + [origin]: { + siteTitle: providerRequest ? providerRequest.siteTitle : null, + siteImage: providerRequest ? providerRequest.siteImage : null, + hostname: providerRequest ? providerRequest.hostname : null, + }, + }, + }) + this.memStore.updateState({ providerRequests: remainingProviderRequests }) + this.emit(`resolvedRequest:${origin}`, { approved: true }) + } + + /** + * Called when a tab rejects access to a full Ethereum provider API + * + * @param {string} origin - origin of the domain that had provider access approved + */ + rejectProviderRequestByOrigin (origin) { + if (this.closePopup) { + this.closePopup() + } + + const { approvedOrigins } = this.store.getState() + const { providerRequests } = this.memStore.getState() + const remainingProviderRequests = providerRequests.filter(request => request.origin !== origin) + + // We're cloning and deleting keys here because we don't want to keep unneeded keys + const _approvedOrigins = Object.assign({}, approvedOrigins) + delete _approvedOrigins[origin] + + this.store.putState({ approvedOrigins: _approvedOrigins }) + this.memStore.putState({ providerRequests: remainingProviderRequests }) + this.emit(`resolvedRequest:${origin}`, { approved: false }) + } + + /** + * Clears any approvals for user-approved origins + */ + clearApprovedOrigins () { + this.store.updateState({ + approvedOrigins: {}, + }) + } + + /** + * Determines if a given origin should have accounts exposed + * + * @param {string} origin - Domain origin to check for approval status + * @returns {boolean} - True if the origin has been approved + */ + shouldExposeAccounts (origin) { + return Boolean(this.store.getState().approvedOrigins[origin]) + } + + /** + * Returns a merged state representation + * @return {object} + * @private + */ + _getMergedState () { + return Object.assign({}, this.memStore.getState(), this.store.getState()) + } +} + +module.exports = ProviderApprovalController diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js index 9e5a384a9f..a2b5d1bae6 100644 --- a/app/scripts/controllers/recent-blocks.js +++ b/app/scripts/controllers/recent-blocks.js @@ -90,9 +90,7 @@ class RecentBlocksController { async processBlock (newBlockNumberHex) { const newBlockNumber = Number.parseInt(newBlockNumberHex, 16) const newBlock = await this.getBlockByNumber(newBlockNumber, true) - if (!newBlock) { - return - } + if (!newBlock) return const block = this.mapTransactionsToPrices(newBlock) @@ -164,9 +162,7 @@ class RecentBlocksController { await Promise.all(targetBlockNumbers.map(async (targetBlockNumber) => { try { const newBlock = await this.getBlockByNumber(targetBlockNumber, true) - if (!newBlock) { - return - } + if (!newBlock) return this.backfillBlock(newBlock) } catch (e) { diff --git a/app/scripts/controllers/threebox.js b/app/scripts/controllers/threebox.js index 8226fb6b1f..5bcab29ed4 100644 --- a/app/scripts/controllers/threebox.js +++ b/app/scripts/controllers/threebox.js @@ -28,9 +28,7 @@ class ThreeBoxController { this.provider = this._createProvider({ version, getAccounts: async ({ origin }) => { - if (origin !== '3Box') { - return [] - } + if (origin !== '3Box') { return [] } const isUnlocked = getKeyringControllerState().isUnlocked const accounts = await this.keyringController.getAccounts() diff --git a/app/scripts/controllers/token-rates.js b/app/scripts/controllers/token-rates.js index 7c8526c343..9b86a9ebf0 100644 --- a/app/scripts/controllers/token-rates.js +++ b/app/scripts/controllers/token-rates.js @@ -28,9 +28,7 @@ class TokenRatesController { * Updates exchange rates for all tokens */ async updateExchangeRates () { - if (!this.isActive) { - return - } + if (!this.isActive) { return } const contractExchangeRates = {} const nativeCurrency = this.currency ? this.currency.state.nativeCurrency.toLowerCase() : 'eth' const pairs = this._tokens.map(token => token.address).join(',') @@ -55,12 +53,8 @@ class TokenRatesController { */ set interval (interval) { this._handle && clearInterval(this._handle) - if (!interval) { - return - } - this._handle = setInterval(() => { - this.updateExchangeRates() - }, interval) + if (!interval) { return } + this._handle = setInterval(() => { this.updateExchangeRates() }, interval) } /** @@ -68,14 +62,10 @@ class TokenRatesController { */ set preferences (preferences) { this._preferences && this._preferences.unsubscribe() - if (!preferences) { - return - } + if (!preferences) { return } this._preferences = preferences this.tokens = preferences.getState().tokens - preferences.subscribe(({ tokens = [] }) => { - this.tokens = tokens - }) + preferences.subscribe(({ tokens = [] }) => { this.tokens = tokens }) } /** diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 85733aa382..df9fb65023 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -3,7 +3,7 @@ const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const Transaction = require('ethereumjs-tx') const EthQuery = require('ethjs-query') -const { ethErrors } = require('eth-json-rpc-errors') +const { errors: rpcErrors } = require('eth-json-rpc-errors') const abi = require('human-standard-token-abi') const abiDecoder = require('abi-decoder') abiDecoder.addABI(abi) @@ -54,7 +54,6 @@ const { hexToBn, bnToHex, BnMultiplyByFraction } = require('../../lib/util') @param {Object} opts.blockTracker - An instance of eth-blocktracker @param {Object} opts.provider - A network provider. @param {Function} opts.signTransaction - function the signs an ethereumjs-tx - @param {object} opts.getPermittedAccounts - get accounts that an origin has permissions for @param {Function} [opts.getGasPrice] - optional gas price calculator @param {Function} opts.signTransaction - ethTx signer that returns a rawTx @param {Number} [opts.txHistoryLimit] - number *optional* for limiting how many transactions are in state @@ -67,7 +66,6 @@ class TransactionController extends EventEmitter { this.networkStore = opts.networkStore || new ObservableStore({}) this.preferencesStore = opts.preferencesStore || new ObservableStore({}) this.provider = opts.provider - this.getPermittedAccounts = opts.getPermittedAccounts this.blockTracker = opts.blockTracker this.signEthTx = opts.signTransaction this.getGasPrice = opts.getGasPrice @@ -135,7 +133,7 @@ class TransactionController extends EventEmitter { /** Adds a tx to the txlist @emits ${txMeta.id}:unapproved - */ +*/ addTx (txMeta) { this.txStateManager.addTx(txMeta) this.emit(`${txMeta.id}:unapproved`, txMeta) @@ -150,18 +148,18 @@ class TransactionController extends EventEmitter { } /** - * Add a new unapproved transaction to the pipeline - * - * @returns {Promise} the hash of the transaction after being submitted to the network - * @param txParams {object} - txParams for the transaction - * @param opts {object} - with the key origin to put the origin on the txMeta + add a new unapproved transaction to the pipeline + + @returns {Promise} the hash of the transaction after being submitted to the network + @param txParams {object} - txParams for the transaction + @param opts {object} - with the key origin to put the origin on the txMeta */ - async newUnapprovedTransaction (txParams, opts = {}) { + async newUnapprovedTransaction (txParams, opts = {}) { log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`) - - const initialTxMeta = await this.addUnapprovedTransaction(txParams, opts.origin) - + const initialTxMeta = await this.addUnapprovedTransaction(txParams) + initialTxMeta.origin = opts.origin + this.txStateManager.updateTx(initialTxMeta, '#newUnapprovedTransaction - adding the origin') // listen for tx completion (success, fail) return new Promise((resolve, reject) => { this.txStateManager.once(`${initialTxMeta.id}:finished`, (finishedTxMeta) => { @@ -169,64 +167,38 @@ class TransactionController extends EventEmitter { case 'submitted': return resolve(finishedTxMeta.hash) case 'rejected': - return reject(cleanErrorStack(ethErrors.provider.userRejectedRequest('MetaMask Tx Signature: User denied transaction signature.'))) + return reject(cleanErrorStack(rpcErrors.eth.userRejectedRequest('MetaMask Tx Signature: User denied transaction signature.'))) case 'failed': - return reject(cleanErrorStack(ethErrors.rpc.internal(finishedTxMeta.err.message))) + return reject(cleanErrorStack(rpcErrors.internal(finishedTxMeta.err.message))) default: - return reject(cleanErrorStack(ethErrors.rpc.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))) + return reject(cleanErrorStack(rpcErrors.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))) } }) }) } /** - * Validates and generates a txMeta with defaults and puts it in txStateManager - * store. - * - * @returns {txMeta} - */ - async addUnapprovedTransaction (txParams, origin) { + Validates and generates a txMeta with defaults and puts it in txStateManager + store + @returns {txMeta} + */ + + async addUnapprovedTransaction (txParams) { // validate const normalizedTxParams = txUtils.normalizeTxParams(txParams) - + // Assert the from address is the selected address + if (normalizedTxParams.from !== this.getSelectedAddress()) { + throw new Error(`Transaction from address isn't valid for this account`) + } txUtils.validateTxParams(normalizedTxParams) - /** - `generateTxMeta` adds the default txMeta properties to the passed object. - These include the tx's `id`. As we use the id for determining order of - txes in the tx-state-manager, it is necessary to call the asynchronous - method `this._determineTransactionCategory` after `generateTxMeta`. - */ + // construct txMeta + const { transactionCategory, getCodeResponse } = await this._determineTransactionCategory(txParams) let txMeta = this.txStateManager.generateTxMeta({ txParams: normalizedTxParams, type: TRANSACTION_TYPE_STANDARD, + transactionCategory, }) - - if (origin === 'metamask') { - // Assert the from address is the selected address - if (normalizedTxParams.from !== this.getSelectedAddress()) { - throw ethErrors.rpc.internal({ - message: `Internally initiated transaction is using invalid account.`, - data: { - origin, - fromAddress: normalizedTxParams.from, - selectedAddress: this.getSelectedAddress(), - }, - }) - } - } else { - // Assert that the origin has permissions to initiate transactions from - // the specified address - const permittedAddresses = await this.getPermittedAccounts(origin) - if (!permittedAddresses.includes(normalizedTxParams.from)) { - throw ethErrors.provider.unauthorized({ data: { origin }}) - } - } - - txMeta['origin'] = origin - - const { transactionCategory, getCodeResponse } = await this._determineTransactionCategory(txParams) - txMeta.transactionCategory = transactionCategory this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) @@ -245,16 +217,15 @@ class TransactionController extends EventEmitter { txMeta.loadingDefaults = false // save txMeta - this.txStateManager.updateTx(txMeta, 'Added new unapproved transaction.') + this.txStateManager.updateTx(txMeta) return txMeta } - /** - * Adds the tx gas defaults: gas && gasPrice - * @param txMeta {Object} - the txMeta object - * @returns {Promise} resolves with txMeta - */ + adds the tx gas defaults: gas && gasPrice + @param txMeta {Object} - the txMeta object + @returns {Promise} resolves with txMeta +*/ async addTxGasDefaults (txMeta, getCodeResponse) { const txParams = txMeta.txParams // ensure value @@ -431,16 +402,13 @@ class TransactionController extends EventEmitter { log.error(err) } // must set transaction to submitted/failed before releasing lock - if (nonceLock) { - nonceLock.releaseLock() - } + if (nonceLock) nonceLock.releaseLock() // continue with error chain throw err } finally { this.inProcessOfSigning.delete(txId) } } - /** adds the chain id and signs the transaction and set the status to signed @param txId {number} - the tx's Id @@ -635,9 +603,7 @@ class TransactionController extends EventEmitter { } }) this.pendingTxTracker.on('tx:retry', (txMeta) => { - if (!('retryCount' in txMeta)) { - txMeta.retryCount = 0 - } + if (!('retryCount' in txMeta)) txMeta.retryCount = 0 txMeta.retryCount++ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:retry') }) @@ -691,14 +657,10 @@ class TransactionController extends EventEmitter { const txMeta = this.txStateManager.getTx(txId) const { nonce, from } = txMeta.txParams const sameNonceTxs = this.txStateManager.getFilteredTxList({nonce, from}) - if (!sameNonceTxs.length) { - return - } + if (!sameNonceTxs.length) return // mark all same nonce transactions as dropped and give i a replacedBy hash sameNonceTxs.forEach((otherTxMeta) => { - if (otherTxMeta.id === txId) { - return - } + if (otherTxMeta.id === txId) return otherTxMeta.replacedBy = txMeta.hash this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce') this.txStateManager.setTxStatusDropped(otherTxMeta.id) diff --git a/app/scripts/controllers/transactions/lib/tx-state-history-helper.js b/app/scripts/controllers/transactions/lib/tx-state-history-helper.js index 3cc76e6179..76fc5c35b3 100644 --- a/app/scripts/controllers/transactions/lib/tx-state-history-helper.js +++ b/app/scripts/controllers/transactions/lib/tx-state-history-helper.js @@ -18,9 +18,7 @@ function migrateFromSnapshotsToDiffs (longHistory) { longHistory // convert non-initial history entries into diffs .map((entry, index) => { - if (index === 0) { - return entry - } + if (index === 0) return entry return generateHistoryEntry(longHistory[index - 1], entry) }) ) @@ -42,9 +40,7 @@ function generateHistoryEntry (previousState, newState, note) { const entry = jsonDiffer.compare(previousState, newState) // Add a note to the first op, since it breaks if we append it to the entry if (entry[0]) { - if (note) { - entry[0].note = note - } + if (note) entry[0].note = note entry[0].timestamp = Date.now() } diff --git a/app/scripts/controllers/transactions/lib/util.js b/app/scripts/controllers/transactions/lib/util.js index 86924e7faf..0d2ddddef9 100644 --- a/app/scripts/controllers/transactions/lib/util.js +++ b/app/scripts/controllers/transactions/lib/util.js @@ -35,9 +35,7 @@ function normalizeTxParams (txParams, LowerCase) { // apply only keys in the normalizers const normalizedTxParams = {} for (const key in normalizers) { - if (txParams[key]) { - normalizedTxParams[key] = normalizers[key](txParams[key], LowerCase) - } + if (txParams[key]) normalizedTxParams[key] = normalizers[key](txParams[key], LowerCase) } return normalizedTxParams } @@ -66,12 +64,8 @@ function validateTxParams (txParams) { @param txParams {object} */ function validateFrom (txParams) { - if (!(typeof txParams.from === 'string')) { - throw new Error(`Invalid from address ${txParams.from} not a string`) - } - if (!isValidAddress(txParams.from)) { - throw new Error('Invalid from address') - } + if (!(typeof txParams.from === 'string')) throw new Error(`Invalid from address ${txParams.from} not a string`) + if (!isValidAddress(txParams.from)) throw new Error('Invalid from address') } /** diff --git a/app/scripts/controllers/transactions/pending-tx-tracker.js b/app/scripts/controllers/transactions/pending-tx-tracker.js index 4e2db5ead7..8f4076f45c 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.js @@ -56,9 +56,7 @@ class PendingTransactionTracker extends EventEmitter { resubmitPendingTxs (blockNumber) { const pending = this.getPendingTransactions() // only try resubmitting if their are transactions to resubmit - if (!pending.length) { - return - } + if (!pending.length) return pending.forEach((txMeta) => this._resubmitTx(txMeta, blockNumber).catch((err) => { /* Dont marked as failed if the error is a "known" transaction warning @@ -81,9 +79,7 @@ class PendingTransactionTracker extends EventEmitter { errorMessage.includes('nonce too low') ) // ignore resubmit warnings, return early - if (isKnownTx) { - return - } + if (isKnownTx) return // encountered real error - transition to error state txMeta.warning = { error: errorMessage, @@ -111,14 +107,10 @@ class PendingTransactionTracker extends EventEmitter { const retryCount = txMeta.retryCount || 0 // Exponential backoff to limit retries at publishing - if (txBlockDistance <= Math.pow(2, retryCount) - 1) { - return - } + if (txBlockDistance <= Math.pow(2, retryCount) - 1) return // Only auto-submit already-signed txs: - if (!('rawTx' in txMeta)) { - return this.approveTransaction(txMeta.id) - } + if (!('rawTx' in txMeta)) return this.approveTransaction(txMeta.id) const rawTx = txMeta.rawTx const txHash = await this.publishTransaction(rawTx) @@ -140,9 +132,7 @@ class PendingTransactionTracker extends EventEmitter { const txId = txMeta.id // Only check submitted txs - if (txMeta.status !== 'submitted') { - return - } + if (txMeta.status !== 'submitted') return // extra check in case there was an uncaught error during the // signature and submission process diff --git a/app/scripts/controllers/transactions/tx-gas-utils.js b/app/scripts/controllers/transactions/tx-gas-utils.js index 517137f865..287fb6f44c 100644 --- a/app/scripts/controllers/transactions/tx-gas-utils.js +++ b/app/scripts/controllers/transactions/tx-gas-utils.js @@ -142,13 +142,9 @@ class TxGasUtil { const bufferedGasLimitBn = initialGasLimitBn.muln(1.5) // if initialGasLimit is above blockGasLimit, dont modify it - if (initialGasLimitBn.gt(upperGasLimitBn)) { - return bnToHex(initialGasLimitBn) - } + if (initialGasLimitBn.gt(upperGasLimitBn)) return bnToHex(initialGasLimitBn) // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit - if (bufferedGasLimitBn.lt(upperGasLimitBn)) { - return bnToHex(bufferedGasLimitBn) - } + if (bufferedGasLimitBn.lt(upperGasLimitBn)) return bnToHex(bufferedGasLimitBn) // otherwise use blockGasLimit return bnToHex(upperGasLimitBn) } diff --git a/app/scripts/controllers/transactions/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js index ffbe6f0107..6a92c06011 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.js +++ b/app/scripts/controllers/transactions/tx-state-manager.js @@ -45,9 +45,7 @@ class TransactionStateManager extends EventEmitter { */ generateTxMeta (opts) { const netId = this.getNetwork() - if (netId === 'loading') { - throw new Error('MetaMask is having trouble connecting to the network') - } + if (netId === 'loading') throw new Error('MetaMask is having trouble connecting to the network') return extend({ id: createId(), time: (new Date()).getTime(), @@ -91,9 +89,7 @@ class TransactionStateManager extends EventEmitter { */ getApprovedTransactions (address) { const opts = { status: 'approved' } - if (address) { - opts.from = address - } + if (address) opts.from = address return this.getFilteredTxList(opts) } @@ -104,9 +100,7 @@ class TransactionStateManager extends EventEmitter { */ getPendingTransactions (address) { const opts = { status: 'submitted' } - if (address) { - opts.from = address - } + if (address) opts.from = address return this.getFilteredTxList(opts) } @@ -117,9 +111,7 @@ class TransactionStateManager extends EventEmitter { */ getConfirmedTransactions (address) { const opts = { status: 'confirmed' } - if (address) { - opts.from = address - } + if (address) opts.from = address return this.getFilteredTxList(opts) } @@ -167,12 +159,7 @@ class TransactionStateManager extends EventEmitter { transactions.splice(index, 1) } } - const newTxIndex = transactions - .findIndex((currentTxMeta) => currentTxMeta.time > txMeta.time) - - newTxIndex === -1 - ? transactions.push(txMeta) - : transactions.splice(newTxIndex, 0, txMeta) + transactions.push(txMeta) this._saveTxList(transactions) return txMeta } @@ -249,14 +236,10 @@ class TransactionStateManager extends EventEmitter { // validate types switch (key) { case 'chainId': - if (typeof value !== 'number' && typeof value !== 'string') { - throw new Error(`${key} in txParams is not a Number or hex string. got: (${value})`) - } + if (typeof value !== 'number' && typeof value !== 'string') throw new Error(`${key} in txParams is not a Number or hex string. got: (${value})`) break default: - if (typeof value !== 'string') { - throw new Error(`${key} in txParams is not a string. got: (${value})`) - } + if (typeof value !== 'string') throw new Error(`${key} in txParams is not a string. got: (${value})`) break } }) diff --git a/app/scripts/createStandardProvider.js b/app/scripts/createStandardProvider.js new file mode 100644 index 0000000000..2059b9b3a7 --- /dev/null +++ b/app/scripts/createStandardProvider.js @@ -0,0 +1,73 @@ +class StandardProvider { + _isConnected + _provider + + constructor (provider) { + this._provider = provider + this._subscribe() + // indicate that we've connected, mostly just for standard compliance + setTimeout(() => { + this._onConnect() + }) + } + + _onClose () { + if (this._isConnected === undefined || this._isConnected) { + this._provider.emit('close', { + code: 1011, + reason: 'Network connection error', + }) + } + this._isConnected = false + } + + _onConnect () { + !this._isConnected && this._provider.emit('connect') + this._isConnected = true + } + + _subscribe () { + this._provider.on('data', (error, { method, params }) => { + if (!error && method === 'eth_subscription') { + this._provider.emit('notification', params.result) + } + }) + } + + /** + * Initiate an RPC method call + * + * @param {string} method - RPC method name to call + * @param {string[]} params - Array of RPC method parameters + * @returns {Promise<*>} Promise resolving to the result if successful + */ + send (method, params = []) { + return new Promise((resolve, reject) => { + try { + this._provider.sendAsync({ id: 1, jsonrpc: '2.0', method, params }, (error, response) => { + error = error || response.error + error ? reject(error) : resolve(response) + }) + } catch (error) { + reject(error) + } + }) + } +} + +/** + * Converts a legacy provider into an EIP-1193-compliant standard provider + * @param {Object} provider - Legacy provider to convert + * @returns {Object} Standard provider + */ +export default function createStandardProvider (provider) { + const standardProvider = new StandardProvider(provider) + const sendLegacy = provider.send + provider.send = (methodOrPayload, callbackOrArgs) => { + if (typeof methodOrPayload === 'string' && !callbackOrArgs || Array.isArray(callbackOrArgs)) { + return standardProvider.send(methodOrPayload, callbackOrArgs) + } + return sendLegacy.call(provider, methodOrPayload, callbackOrArgs) + } + return provider +} diff --git a/app/scripts/edge-encryptor.js b/app/scripts/edge-encryptor.js index d086a854de..012672ed23 100644 --- a/app/scripts/edge-encryptor.js +++ b/app/scripts/edge-encryptor.js @@ -14,17 +14,17 @@ class EdgeEncryptor { * @returns {Promise} Promise resolving to an object with ciphertext */ encrypt (password, dataObject) { - const salt = this._generateSalt() + var salt = this._generateSalt() return this._keyFromPassword(password, salt) .then(function (key) { - const data = JSON.stringify(dataObject) - const dataBuffer = Unibabel.utf8ToBuffer(data) - const vector = global.crypto.getRandomValues(new Uint8Array(16)) - const resultbuffer = asmcrypto.AES_GCM.encrypt(dataBuffer, key, vector) + var data = JSON.stringify(dataObject) + var dataBuffer = Unibabel.utf8ToBuffer(data) + var vector = global.crypto.getRandomValues(new Uint8Array(16)) + var resultbuffer = asmcrypto.AES_GCM.encrypt(dataBuffer, key, vector) - const buffer = new Uint8Array(resultbuffer) - const vectorStr = Unibabel.bufferToBase64(vector) - const vaultStr = Unibabel.bufferToBase64(buffer) + var buffer = new Uint8Array(resultbuffer) + var vectorStr = Unibabel.bufferToBase64(vector) + var vaultStr = Unibabel.bufferToBase64(buffer) return JSON.stringify({ data: vaultStr, iv: vectorStr, @@ -48,7 +48,7 @@ class EdgeEncryptor { const encryptedData = Unibabel.base64ToBuffer(payload.data) const vector = Unibabel.base64ToBuffer(payload.iv) return new Promise((resolve, reject) => { - let result + var result try { result = asmcrypto.AES_GCM.decrypt(encryptedData, key, vector) } catch (err) { @@ -72,12 +72,12 @@ class EdgeEncryptor { */ _keyFromPassword (password, salt) { - const passBuffer = Unibabel.utf8ToBuffer(password) - const saltBuffer = Unibabel.base64ToBuffer(salt) + var passBuffer = Unibabel.utf8ToBuffer(password) + var saltBuffer = Unibabel.base64ToBuffer(salt) const iterations = 10000 const length = 32 // SHA256 hash size return new Promise((resolve) => { - const key = asmcrypto.Pbkdf2HmacSha256(passBuffer, saltBuffer, iterations, length) + var key = asmcrypto.Pbkdf2HmacSha256(passBuffer, saltBuffer, iterations, length) resolve(key) }) } @@ -89,9 +89,9 @@ class EdgeEncryptor { * @returns {string} Randomized base64 encoded data */ _generateSalt (byteCount = 32) { - const view = new Uint8Array(byteCount) + var view = new Uint8Array(byteCount) global.crypto.getRandomValues(view) - const b64encoded = btoa(String.fromCharCode.apply(null, view)) + var b64encoded = btoa(String.fromCharCode.apply(null, view)) return b64encoded } } diff --git a/app/scripts/inpage.js b/app/scripts/inpage.js index d81d8587b9..ec88243a4e 100644 --- a/app/scripts/inpage.js +++ b/app/scripts/inpage.js @@ -1,5 +1,6 @@ /*global Web3*/ + // need to make sure we aren't affected by overlapping namespaces // and that we dont affect the app with our namespace // mostly a fix for web3's BigNumber if AMD's "define" is defined... @@ -31,14 +32,14 @@ const restoreContextAfterImports = () => { } cleanContextForImports() - +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('metamask-inpage-provider') +const createStandardProvider = require('./createStandardProvider').default -// TODO:deprecate:2020-01-13 -require('web3/dist/web3.min.js') -const setupDappAutoReload = require('./lib/auto-reload.js') +let warned = false restoreContextAfterImports() @@ -60,6 +61,89 @@ const inpageProvider = new MetamaskInpageProvider(metamaskStream) // set a high max listener count to avoid unnecesary warnings inpageProvider.setMaxListeners(100) +let warnedOfAutoRefreshDeprecation = false +// augment the provider with its enable method +inpageProvider.enable = function ({ force } = {}) { + if ( + !warnedOfAutoRefreshDeprecation && + inpageProvider.autoRefreshOnNetworkChange + ) { + console.warn(`MetaMask: MetaMask will soon stop reloading pages on network change. +If you rely upon this behavior, add a 'networkChanged' event handler to trigger the reload manually: https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider#ethereum.on(eventname%2C-callback) +Set 'ethereum.autoRefreshOnNetworkChange' to 'false' to silence this warning: https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider#ethereum.autorefreshonnetworkchange' +`) + warnedOfAutoRefreshDeprecation = true + } + return new Promise((resolve, reject) => { + inpageProvider.sendAsync({ method: 'eth_requestAccounts', params: [force] }, (error, response) => { + if (error || response.error) { + reject(error || response.error) + } else { + resolve(response.result) + } + }) + }) +} + +// give the dapps control of a refresh they can toggle this off on the window.ethereum +// this will be default true so it does not break any old apps. +inpageProvider.autoRefreshOnNetworkChange = true + + +// publicConfig isn't populated until we get a message from background. +// Using this getter will ensure the state is available +const getPublicConfigWhenReady = async () => { + const store = inpageProvider.publicConfigStore + let state = store.getState() + // if state is missing, wait for first update + if (!state.networkVersion) { + state = await new Promise(resolve => store.once('update', resolve)) + console.log('new state', state) + } + return state +} + +// add metamask-specific convenience methods +inpageProvider._metamask = new Proxy({ + /** + * Synchronously determines if this domain is currently enabled, with a potential false negative if called to soon + * + * @returns {boolean} - returns true if this domain is currently enabled + */ + isEnabled: function () { + const { isEnabled } = inpageProvider.publicConfigStore.getState() + return Boolean(isEnabled) + }, + + /** + * Asynchronously determines if this domain is currently enabled + * + * @returns {Promise} - Promise resolving to true if this domain is currently enabled + */ + isApproved: async function () { + const { isEnabled } = await getPublicConfigWhenReady() + return Boolean(isEnabled) + }, + + /** + * Determines if MetaMask is unlocked by the user + * + * @returns {Promise} - Promise resolving to true if MetaMask is currently unlocked + */ + isUnlocked: async function () { + const { isUnlocked } = await getPublicConfigWhenReady() + return Boolean(isUnlocked) + }, +}, { + get: function (obj, prop) { + !warned && console.warn('Heads up! ethereum._metamask exposes methods that have ' + + 'not been standardized yet. This means that these methods may not be implemented ' + + 'in other dapp browsers and may be removed from MetaMask in the future.') + warned = true + return obj[prop] + }, +}) + // Work around for web3@1.0 deleting the bound `sendAsync` but not the unbound // `sendAsync` method on the prototype, causing `this` reference issues const proxiedInpageProvider = new Proxy(inpageProvider, { @@ -68,11 +152,11 @@ const proxiedInpageProvider = new Proxy(inpageProvider, { deleteProperty: () => true, }) -// -// TODO:deprecate:2020-01-13 -// +window.ethereum = createStandardProvider(proxiedInpageProvider) +// // setup web3 +// if (typeof window.web3 !== 'undefined') { throw new Error(`MetaMask detected another web3. @@ -88,13 +172,15 @@ web3.setProvider = function () { } log.debug('MetaMask - injected web3') -proxiedInpageProvider._web3Ref = web3.eth +setupDappAutoReload(web3, inpageProvider.publicConfigStore) -// setup dapp auto reload AND proxy web3 -setupDappAutoReload(web3, inpageProvider._publicConfigStore) - -// -// end deprecate:2020-01-13 -// +// set web3 defaultAccount +inpageProvider.publicConfigStore.subscribe(function (state) { + web3.eth.defaultAccount = state.selectedAddress +}) -window.ethereum = proxiedInpageProvider +inpageProvider.publicConfigStore.subscribe(function (state) { + if (state.onboardingcomplete) { + window.postMessage('onboardingcomplete', '*') + } +}) diff --git a/app/scripts/lib/account-tracker.js b/app/scripts/lib/account-tracker.js index 8fef712fe6..3137ea8a36 100644 --- a/app/scripts/lib/account-tracker.js +++ b/app/scripts/lib/account-tracker.js @@ -124,9 +124,7 @@ class AccountTracker { // save accounts state this.store.updateState({ accounts }) // fetch balances for the accounts if there is block number ready - if (!this._currentBlockNumber) { - return - } + if (!this._currentBlockNumber) return this._updateAccounts() } @@ -160,9 +158,7 @@ class AccountTracker { // block gasLimit polling shouldn't be in account-tracker shouldn't be here... const currentBlock = await this._query.getBlockByNumber(blockNumber, false) - if (!currentBlock) { - return - } + if (!currentBlock) return const currentBlockGasLimit = currentBlock.gasLimit this.store.updateState({ currentBlockGasLimit }) @@ -222,9 +218,7 @@ class AccountTracker { // update accounts state const { accounts } = this.store.getState() // only populate if the entry is still present - if (!accounts[address]) { - return - } + if (!accounts[address]) return accounts[address] = result this.store.updateState({ accounts }) } diff --git a/app/scripts/lib/auto-reload.js b/app/scripts/lib/auto-reload.js index e2b9c17bd3..fd209c230a 100644 --- a/app/scripts/lib/auto-reload.js +++ b/app/scripts/lib/auto-reload.js @@ -1,6 +1,3 @@ - -// TODO:deprecate:2020-01-13 - module.exports = setupDappAutoReload function setupDappAutoReload (web3, observable) { @@ -16,7 +13,7 @@ function setupDappAutoReload (web3, observable) { lastTimeUsed = Date.now() // show warning once on web3 access if (!hasBeenWarned && key !== 'currentProvider') { - console.warn(`MetaMask: On 2020-01-13, MetaMask will no longer inject web3. For more information, see: https://medium.com/metamask/no-longer-injecting-web3-js-4a899ad6e59e`) + console.warn('MetaMask: web3 will be deprecated in the near future in favor of the ethereumProvider\nhttps://medium.com/metamask/4a899ad6e59e') hasBeenWarned = true } // return value normally @@ -31,14 +28,10 @@ function setupDappAutoReload (web3, observable) { observable.subscribe(function (state) { // if the auto refresh on network change is false do not // do anything - if (!window.ethereum.autoRefreshOnNetworkChange) { - return - } + if (!window.ethereum.autoRefreshOnNetworkChange) return // if reload in progress, no need to check reload logic - if (reloadInProgress) { - return - } + if (reloadInProgress) return const currentNetwork = state.networkVersion @@ -49,14 +42,10 @@ function setupDappAutoReload (web3, observable) { } // skip reload logic if web3 not used - if (!lastTimeUsed) { - return - } + if (!lastTimeUsed) return // if network did not change, exit - if (currentNetwork === lastSeenNetwork) { - return - } + if (currentNetwork === lastSeenNetwork) return // initiate page reload reloadInProgress = true diff --git a/app/scripts/lib/buy-eth-url.js b/app/scripts/lib/buy-eth-url.js index 6892364ca0..5cae83a9f4 100644 --- a/app/scripts/lib/buy-eth-url.js +++ b/app/scripts/lib/buy-eth-url.js @@ -13,13 +13,11 @@ module.exports = getBuyEthUrl */ function getBuyEthUrl ({ network, amount, address, service }) { // default service by network if not specified - if (!service) { - service = getDefaultServiceForNetwork(network) - } + if (!service) service = getDefaultServiceForNetwork(network) switch (service) { case 'wyre': - return `https://pay.sendwyre.com/?dest=ethereum:${address}&destCurrency=ETH&accountId=AC-7AG3W4XH4N2` + return `https://dash.sendwyre.com/sign-up` case 'coinswitch': return `https://metamask.coinswitch.co/?address=${address}&to=eth` case 'coinbase': @@ -32,9 +30,8 @@ function getBuyEthUrl ({ network, amount, address, service }) { return 'https://github.com/kovan-testnet/faucet' case 'goerli-faucet': return 'https://goerli-faucet.slock.it/' - default: - throw new Error(`Unknown cryptocurrency exchange or faucet: "${service}"`) } + throw new Error(`Unknown cryptocurrency exchange or faucet: "${service}"`) } function getDefaultServiceForNetwork (network) { @@ -49,7 +46,6 @@ function getDefaultServiceForNetwork (network) { return 'kovan-faucet' case '5': return 'goerli-faucet' - default: - throw new Error(`No default cryptocurrency exchange or faucet for networkId: "${network}"`) } + throw new Error(`No default cryptocurrency exchange or faucet for networkId: "${network}"`) } diff --git a/app/scripts/lib/cleanErrorStack.js b/app/scripts/lib/cleanErrorStack.js index 58f7ccfdf1..8adf55db70 100644 --- a/app/scripts/lib/cleanErrorStack.js +++ b/app/scripts/lib/cleanErrorStack.js @@ -4,10 +4,10 @@ * @returns {Error} Error with clean stack trace. */ function cleanErrorStack (err) { - let name = err.name + var name = err.name name = (name === undefined) ? 'Error' : String(name) - let msg = err.message + var msg = err.message msg = (msg === undefined) ? '' : String(msg) if (name === '') { diff --git a/app/scripts/lib/createDnodeRemoteGetter.js b/app/scripts/lib/createDnodeRemoteGetter.js index 60a7753831..b70d218f32 100644 --- a/app/scripts/lib/createDnodeRemoteGetter.js +++ b/app/scripts/lib/createDnodeRemoteGetter.js @@ -8,9 +8,7 @@ function createDnodeRemoteGetter (dnode) { }) async function getRemote () { - if (remote) { - return remote - } + if (remote) return remote return await new Promise(resolve => dnode.once('remote', resolve)) } diff --git a/app/scripts/lib/createLoggerMiddleware.js b/app/scripts/lib/createLoggerMiddleware.js index d95cdb465f..996c3477c6 100644 --- a/app/scripts/lib/createLoggerMiddleware.js +++ b/app/scripts/lib/createLoggerMiddleware.js @@ -13,9 +13,7 @@ function createLoggerMiddleware (opts) { if (res.error) { log.error('Error in RPC response:\n', res) } - if (req.isMetamaskInternal) { - return - } + if (req.isMetamaskInternal) return log.info(`RPC (${opts.origin}):`, req, '->', res) cb() }) diff --git a/app/scripts/lib/createOriginMiddleware.js b/app/scripts/lib/createOriginMiddleware.js index 4ff9a33862..98bb0e3b39 100644 --- a/app/scripts/lib/createOriginMiddleware.js +++ b/app/scripts/lib/createOriginMiddleware.js @@ -1,4 +1,3 @@ - module.exports = createOriginMiddleware /** diff --git a/app/scripts/lib/ens-ipfs/resolver.js b/app/scripts/lib/ens-ipfs/resolver.js index 34b1304c17..a0af263bc7 100644 --- a/app/scripts/lib/ens-ipfs/resolver.js +++ b/app/scripts/lib/ens-ipfs/resolver.js @@ -66,7 +66,5 @@ function getRegistryForChainId (chainId) { // goerli case 5: return '0x112234455c3a32fd11230c42e7bccd4a84e02010' - default: - return null } } diff --git a/app/scripts/lib/ens-ipfs/setup.js b/app/scripts/lib/ens-ipfs/setup.js index f12a22238b..a3711c5f94 100644 --- a/app/scripts/lib/ens-ipfs/setup.js +++ b/app/scripts/lib/ens-ipfs/setup.js @@ -23,18 +23,14 @@ function setupEnsIpfsResolver ({ provider }) { async function webRequestDidFail (details) { const { tabId, url } = details // ignore requests that are not associated with tabs - if (tabId === -1) { - return - } + if (tabId === -1) return // parse ens name const urlData = urlUtil.parse(url) const { hostname: name, path, search } = urlData const domainParts = name.split('.') const topLevelDomain = domainParts[domainParts.length - 1] // if unsupported TLD, abort - if (!supportedTopLevelDomains.includes(topLevelDomain)) { - return - } + if (!supportedTopLevelDomains.includes(topLevelDomain)) return // otherwise attempt resolve attemptResolve({ tabId, name, path, search }) } @@ -49,9 +45,7 @@ function setupEnsIpfsResolver ({ provider }) { try { // check if ipfs gateway has result const response = await fetch(resolvedUrl, { method: 'HEAD' }) - if (response.status === 200) { - url = resolvedUrl - } + if (response.status === 200) url = resolvedUrl } catch (err) { console.warn(err) } diff --git a/app/scripts/lib/local-store.js b/app/scripts/lib/local-store.js index b7212c9805..8fde2e9111 100644 --- a/app/scripts/lib/local-store.js +++ b/app/scripts/lib/local-store.js @@ -1,6 +1,5 @@ const extension = require('extensionizer') const log = require('loglevel') -const { checkForError } = require('./util') /** * A wrapper around the extension's storage local API @@ -21,9 +20,7 @@ module.exports = class ExtensionStore { * @return {Promise<*>} */ async get () { - if (!this.isSupported) { - return undefined - } + if (!this.isSupported) return undefined const result = await this._get() // extension.storage.local always returns an obj // if the object is empty, treat it as undefined @@ -91,3 +88,17 @@ module.exports = class ExtensionStore { function isEmpty (obj) { return Object.keys(obj).length === 0 } + +/** + * Returns an Error if extension.runtime.lastError is present + * this is a workaround for the non-standard error object thats used + * @returns {Error} + */ +function checkForError () { + const lastError = extension.runtime.lastError + if (!lastError) return + // if it quacks like an Error, its an Error + if (lastError.stack && lastError.message) return lastError + // repair incomplete error object (eg chromium v77) + return new Error(lastError.message) +} diff --git a/app/scripts/lib/message-manager.js b/app/scripts/lib/message-manager.js index a947188e53..8e1ff34b75 100644 --- a/app/scripts/lib/message-manager.js +++ b/app/scripts/lib/message-manager.js @@ -1,7 +1,7 @@ const EventEmitter = require('events') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') -const { ethErrors } = require('eth-json-rpc-errors') +const { errors: rpcErrors } = require('eth-json-rpc-errors') const createId = require('./random-id') /** @@ -62,9 +62,7 @@ module.exports = class MessageManager extends EventEmitter { */ getUnapprovedMsgs () { return this.messages.filter(msg => msg.status === 'unapproved') - .reduce((result, msg) => { - result[msg.id] = msg; return result - }, {}) + .reduce((result, msg) => { result[msg.id] = msg; return result }, {}) } /** @@ -85,7 +83,7 @@ module.exports = class MessageManager extends EventEmitter { case 'signed': return resolve(data.rawSig) case 'rejected': - return reject(ethErrors.provider.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) + return reject(rpcErrors.eth.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) default: return reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) } @@ -104,14 +102,12 @@ module.exports = class MessageManager extends EventEmitter { */ addUnapprovedMessage (msgParams, req) { // add origin from request - if (req) { - msgParams.origin = req.origin - } + if (req) msgParams.origin = req.origin msgParams.data = normalizeMsgData(msgParams.data) // create txData obj with parameters and meta data - const time = (new Date()).getTime() - const msgId = createId() - const msgData = { + var time = (new Date()).getTime() + var msgId = createId() + var msgData = { id: msgId, msgParams: msgParams, time: time, @@ -223,9 +219,7 @@ module.exports = class MessageManager extends EventEmitter { */ _setMsgStatus (msgId, status) { const msg = this.getMsg(msgId) - if (!msg) { - throw new Error('MessageManager - Message not found for id: "${msgId}".') - } + if (!msg) throw new Error('MessageManager - Message not found for id: "${msgId}".') msg.status = status this._updateMsg(msg) this.emit(`${msgId}:${status}`, msg) diff --git a/app/scripts/lib/migrator/index.js b/app/scripts/lib/migrator/index.js index c1c225fb39..345ca80016 100644 --- a/app/scripts/lib/migrator/index.js +++ b/app/scripts/lib/migrator/index.js @@ -40,12 +40,8 @@ class Migrator extends EventEmitter { try { // attempt migration and validate const migratedData = await migration.migrate(versionedData) - if (!migratedData.data) { - throw new Error('Migrator - migration returned empty data') - } - if (migratedData.version !== undefined && migratedData.meta.version !== migration.version) { - throw new Error('Migrator - Migration did not update version number correctly') - } + if (!migratedData.data) throw new Error('Migrator - migration returned empty data') + if (migratedData.version !== undefined && migratedData.meta.version !== migration.version) throw new Error('Migrator - Migration did not update version number correctly') // accept the migration as good versionedData = migratedData } catch (err) { diff --git a/app/scripts/lib/nodeify.js b/app/scripts/lib/nodeify.js index 99b96b3566..a813ae679c 100644 --- a/app/scripts/lib/nodeify.js +++ b/app/scripts/lib/nodeify.js @@ -1,9 +1,5 @@ const promiseToCallback = require('promise-to-callback') -const callbackNoop = function (err) { - if (err) { - throw err - } -} +const callbackNoop = function (err) { if (err) throw err } /** * A generator that returns a function which, when passed a promise, can treat that promise as a node style callback. diff --git a/app/scripts/lib/notification-manager.js b/app/scripts/lib/notification-manager.js index 85177cceb9..721d109a1a 100644 --- a/app/scripts/lib/notification-manager.js +++ b/app/scripts/lib/notification-manager.js @@ -18,9 +18,7 @@ class NotificationManager { */ showPopup () { this._getPopup((err, popup) => { - if (err) { - throw err - } + if (err) throw err // Bring focus to chrome popup if (popup) { @@ -30,9 +28,7 @@ class NotificationManager { const {screenX, screenY, outerWidth, outerHeight} = window const notificationTop = Math.round(screenY + (outerHeight / 2) - (NOTIFICATION_HEIGHT / 2)) const notificationLeft = Math.round(screenX + (outerWidth / 2) - (NOTIFICATION_WIDTH / 2)) - const cb = (currentPopup) => { - this._popupId = currentPopup.id - } + const cb = (currentPopup) => { this._popupId = currentPopup.id } // create new notification popup const creation = extension.windows.create({ url: 'notification.html', @@ -54,12 +50,8 @@ class NotificationManager { closePopup () { // closes notification popup this._getPopup((err, popup) => { - if (err) { - throw err - } - if (!popup) { - return - } + if (err) throw err + if (!popup) return extension.windows.remove(popup.id, console.error) }) } @@ -74,9 +66,7 @@ class NotificationManager { */ _getPopup (cb) { this._getWindows((err, windows) => { - if (err) { - throw err - } + if (err) throw err cb(null, this._getPopupIn(windows)) }) } diff --git a/app/scripts/lib/pending-balance-calculator.js b/app/scripts/lib/pending-balance-calculator.js index dd7fa6de46..0f1dc19a90 100644 --- a/app/scripts/lib/pending-balance-calculator.js +++ b/app/scripts/lib/pending-balance-calculator.js @@ -32,9 +32,7 @@ class PendingBalanceCalculator { ]) const [ balance, pending ] = results - if (!balance) { - return undefined - } + if (!balance) return undefined const pendingValue = pending.reduce((total, tx) => { return total.add(this.calculateMaxCost(tx)) diff --git a/app/scripts/lib/personal-message-manager.js b/app/scripts/lib/personal-message-manager.js index fb30cc03ce..2a2ab481ab 100644 --- a/app/scripts/lib/personal-message-manager.js +++ b/app/scripts/lib/personal-message-manager.js @@ -1,7 +1,7 @@ const EventEmitter = require('events') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') -const { ethErrors } = require('eth-json-rpc-errors') +const { errors: rpcErrors } = require('eth-json-rpc-errors') const createId = require('./random-id') const hexRe = /^[0-9A-Fa-f]+$/g const log = require('loglevel') @@ -65,9 +65,7 @@ module.exports = class PersonalMessageManager extends EventEmitter { */ getUnapprovedMsgs () { return this.messages.filter(msg => msg.status === 'unapproved') - .reduce((result, msg) => { - result[msg.id] = msg; return result - }, {}) + .reduce((result, msg) => { result[msg.id] = msg; return result }, {}) } /** @@ -91,7 +89,7 @@ module.exports = class PersonalMessageManager extends EventEmitter { case 'signed': return resolve(data.rawSig) case 'rejected': - return reject(ethErrors.provider.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) + return reject(rpcErrors.eth.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) default: return reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) } @@ -112,14 +110,12 @@ module.exports = class PersonalMessageManager extends EventEmitter { addUnapprovedMessage (msgParams, req) { log.debug(`PersonalMessageManager addUnapprovedMessage: ${JSON.stringify(msgParams)}`) // add origin from request - if (req) { - msgParams.origin = req.origin - } + if (req) msgParams.origin = req.origin msgParams.data = this.normalizeMsgData(msgParams.data) // create txData obj with parameters and meta data - const time = (new Date()).getTime() - const msgId = createId() - const msgData = { + var time = (new Date()).getTime() + var msgId = createId() + var msgData = { id: msgId, msgParams: msgParams, time: time, @@ -233,9 +229,7 @@ module.exports = class PersonalMessageManager extends EventEmitter { */ _setMsgStatus (msgId, status) { const msg = this.getMsg(msgId) - if (!msg) { - throw new Error(`PersonalMessageManager - Message not found for id: "${msgId}".`) - } + if (!msg) throw new Error(`PersonalMessageManager - Message not found for id: "${msgId}".`) msg.status = status this._updateMsg(msg) this.emit(`${msgId}:${status}`, msg) diff --git a/app/scripts/lib/select-chain-id.js b/app/scripts/lib/select-chain-id.js index d94b35898f..3171c98402 100644 --- a/app/scripts/lib/select-chain-id.js +++ b/app/scripts/lib/select-chain-id.js @@ -15,8 +15,8 @@ const standardNetworkId = { } function selectChainId (metamaskState) { - const { network, provider: { chainId } } = metamaskState - return standardNetworkId[network] || `0x${parseInt(chainId, 10).toString(16)}` + const { network, provider: { chaindId } } = metamaskState + return standardNetworkId[network] || `0x${parseInt(chaindId, 10).toString(16)}` } module.exports = selectChainId diff --git a/app/scripts/lib/setupFetchDebugging.js b/app/scripts/lib/setupFetchDebugging.js index d5c01b1f23..431340e2be 100644 --- a/app/scripts/lib/setupFetchDebugging.js +++ b/app/scripts/lib/setupFetchDebugging.js @@ -7,9 +7,7 @@ module.exports = setupFetchDebugging // function setupFetchDebugging () { - if (!global.fetch) { - return - } + if (!global.fetch) return const originalFetch = global.fetch global.fetch = wrappedFetch diff --git a/app/scripts/lib/setupMetamaskMeshMetrics.js b/app/scripts/lib/setupMetamaskMeshMetrics.js index b520ceaa7f..6f0d86b284 100644 --- a/app/scripts/lib/setupMetamaskMeshMetrics.js +++ b/app/scripts/lib/setupMetamaskMeshMetrics.js @@ -22,9 +22,7 @@ function setupMetamaskMeshMetrics () { function submitMeshMetricsEntry (message) { // ignore if we haven't loaded yet - if (!didLoad) { - return - } + if (!didLoad) return // submit the message testingContainer.contentWindow.postMessage(message, targetOrigin) } diff --git a/app/scripts/lib/setupSentry.js b/app/scripts/lib/setupSentry.js index 096bd34541..ba0e17df0d 100644 --- a/app/scripts/lib/setupSentry.js +++ b/app/scripts/lib/setupSentry.js @@ -67,15 +67,11 @@ function simplifyErrorMessages (report) { function rewriteErrorMessages (report, rewriteFn) { // rewrite top level message - if (typeof report.message === 'string') { - 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 => { - if (typeof item.value === 'string') { - item.value = rewriteFn(item.value) - } + if (typeof item.value === 'string') item.value = rewriteFn(item.value) }) } } @@ -95,9 +91,7 @@ function rewriteReportUrls (report) { function toMetamaskUrl (origUrl) { const filePath = origUrl.split(location.origin)[1] - if (!filePath) { - return origUrl - } + if (!filePath) return origUrl const metamaskUrl = `metamask${filePath}` return metamaskUrl } diff --git a/app/scripts/lib/stream-utils.js b/app/scripts/lib/stream-utils.js index 66b3107f4e..3dbc064b5e 100644 --- a/app/scripts/lib/stream-utils.js +++ b/app/scripts/lib/stream-utils.js @@ -43,9 +43,7 @@ function setupMultiplex (connectionStream) { mux, connectionStream, (err) => { - if (err) { - console.error(err) - } + if (err) console.error(err) } ) return mux diff --git a/app/scripts/lib/typed-message-manager.js b/app/scripts/lib/typed-message-manager.js index 5e3c480387..e4d3e842bb 100644 --- a/app/scripts/lib/typed-message-manager.js +++ b/app/scripts/lib/typed-message-manager.js @@ -2,7 +2,7 @@ const EventEmitter = require('events') const ObservableStore = require('obs-store') const createId = require('./random-id') const assert = require('assert') -const { ethErrors } = require('eth-json-rpc-errors') +const { errors: rpcErrors } = require('eth-json-rpc-errors') const sigUtil = require('eth-sig-util') const log = require('loglevel') const jsonschema = require('jsonschema') @@ -58,9 +58,7 @@ module.exports = class TypedMessageManager extends EventEmitter { */ getUnapprovedMsgs () { return this.messages.filter(msg => msg.status === 'unapproved') - .reduce((result, msg) => { - result[msg.id] = msg; return result - }, {}) + .reduce((result, msg) => { result[msg.id] = msg; return result }, {}) } /** @@ -81,7 +79,7 @@ module.exports = class TypedMessageManager extends EventEmitter { case 'signed': return resolve(data.rawSig) case 'rejected': - return reject(ethErrors.provider.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) + return reject(rpcErrors.eth.userRejectedRequest('MetaMask Message Signature: User denied message signature.')) case 'errored': return reject(new Error(`MetaMask Message Signature: ${data.error}`)) default: @@ -105,15 +103,13 @@ module.exports = class TypedMessageManager extends EventEmitter { msgParams.version = version this.validateParams(msgParams) // add origin from request - if (req) { - msgParams.origin = req.origin - } + if (req) msgParams.origin = req.origin log.debug(`TypedMessageManager addUnapprovedMessage: ${JSON.stringify(msgParams)}`) // create txData obj with parameters and meta data - const time = (new Date()).getTime() - const msgId = createId() - const msgData = { + var time = (new Date()).getTime() + var msgId = createId() + var msgData = { id: msgId, msgParams: msgParams, time: time, @@ -153,9 +149,7 @@ module.exports = class TypedMessageManager extends EventEmitter { 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.') + 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.') @@ -163,8 +157,6 @@ module.exports = class TypedMessageManager extends EventEmitter { const activeChainId = parseInt(this.networkController.getNetworkState()) chainId && assert.equal(chainId, activeChainId, `Provided chainId (${chainId}) must match the active chainId (${activeChainId})`) break - default: - assert.fail(`Unknown params.version ${params.version}`) } } @@ -286,9 +278,7 @@ module.exports = class TypedMessageManager extends EventEmitter { */ _setMsgStatus (msgId, status) { const msg = this.getMsg(msgId) - if (!msg) { - throw new Error('TypedMessageManager - Message not found for id: "${msgId}".') - } + if (!msg) throw new Error('TypedMessageManager - Message not found for id: "${msgId}".') msg.status = status this._updateMsg(msg) this.emit(`${msgId}:${status}`, msg) diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js index 36b836eb11..114203d7f8 100644 --- a/app/scripts/lib/util.js +++ b/app/scripts/lib/util.js @@ -1,4 +1,3 @@ -const extension = require('extensionizer') const ethUtil = require('ethereumjs-util') const assert = require('assert') const BN = require('bn.js') @@ -149,32 +148,6 @@ function getRandomArrayItem (array) { return array[Math.floor((Math.random() * array.length))] } -function mapObjectValues (object, cb) { - const mappedObject = {} - Object.keys(object).forEach(key => { - mappedObject[key] = cb(key, object[key]) - }) - return mappedObject -} - -/** - * Returns an Error if extension.runtime.lastError is present - * this is a workaround for the non-standard error object thats used - * @returns {Error} - */ -function checkForError () { - const lastError = extension.runtime.lastError - if (!lastError) { - return - } - // if it quacks like an Error, its an Error - if (lastError.stack && lastError.message) { - return lastError - } - // repair incomplete error object (eg chromium v77) - return new Error(lastError.message) -} - module.exports = { removeListeners, applyListeners, @@ -186,6 +159,4 @@ module.exports = { bnToHex, BnMultiplyByFraction, getRandomArrayItem, - mapObjectValues, - checkForError, } diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 246ae511d3..14caf07069 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -4,13 +4,13 @@ * @license MIT */ -const assert = require('assert').strict const EventEmitter = require('events') const pump = require('pump') const Dnode = require('dnode') -const extension = require('extensionizer') +const pify = require('pify') const ObservableStore = require('obs-store') const ComposableObservableStore = require('./lib/ComposableObservableStore') +const createDnodeRemoteGetter = require('./lib/createDnodeRemoteGetter') const asStream = require('obs-store/lib/asStream') const AccountTracker = require('./lib/account-tracker') const RpcEngine = require('json-rpc-engine') @@ -18,8 +18,8 @@ const debounce = require('debounce') const createEngineStream = require('json-rpc-middleware-stream/engineStream') const createFilterMiddleware = require('eth-json-rpc-filters') const createSubscriptionManager = require('eth-json-rpc-filters/subscriptionManager') -const createLoggerMiddleware = require('./lib/createLoggerMiddleware') const createOriginMiddleware = require('./lib/createOriginMiddleware') +const createLoggerMiddleware = require('./lib/createLoggerMiddleware') const providerAsMiddleware = require('eth-json-rpc-middleware/providerAsMiddleware') const {setupMultiplex} = require('./lib/stream-utils.js') const KeyringController = require('eth-keyring-controller') @@ -39,8 +39,8 @@ const TypedMessageManager = require('./lib/typed-message-manager') const TransactionController = require('./controllers/transactions') const TokenRatesController = require('./controllers/token-rates') const DetectTokensController = require('./controllers/detect-tokens') +const ProviderApprovalController = require('./controllers/provider-approval') const ABTestController = require('./controllers/ab-test') -const { PermissionsController } = require('./controllers/permissions/') const nodeify = require('./lib/nodeify') const accountImporter = require('./account-import-strategies') const getBuyEthUrl = require('./lib/buy-eth-url') @@ -56,7 +56,6 @@ const TrezorKeyring = require('eth-trezor-keyring') const LedgerBridgeKeyring = require('eth-ledger-bridge-keyring') const EthQuery = require('eth-query') const ethUtil = require('ethereumjs-util') -const nanoid = require('nanoid') const contractMap = require('eth-contract-metadata') const { AddressBookController, @@ -89,24 +88,16 @@ module.exports = class MetamaskController extends EventEmitter { // platform-specific api this.platform = opts.platform - this.getRequestAccountTabIds = opts.getRequestAccountTabIds - this.getOpenMetamaskTabsIds = opts.getOpenMetamaskTabsIds - // observable state store this.store = new ComposableObservableStore(initState) - // external connections by origin - // Do not modify directly. Use the associated methods. - this.connections = {} - // lock to ensure only one vault created at once this.createVaultMutex = new Mutex() - // next, we will initialize the controllers - // controller initializaiton order matters - + // network store this.networkController = new NetworkController(initState.NetworkController) + // preferences controller this.preferencesController = new PreferencesController({ initState: initState.PreferencesController, initLangCode: opts.initLangCode, @@ -114,14 +105,16 @@ module.exports = class MetamaskController extends EventEmitter { network: this.networkController, }) + // app-state controller this.appStateController = new AppStateController({ preferencesStore: this.preferencesController.store, onInactiveTimeout: () => this.setLocked(), - initState: initState.AppStateController, }) + // currency controller this.currencyRateController = new CurrencyRateController(undefined, initState.CurrencyController) + // infura controller this.infuraController = new InfuraController({ initState: initState.InfuraController, }) @@ -129,7 +122,7 @@ module.exports = class MetamaskController extends EventEmitter { this.phishingController = new PhishingController() - // now we can initialize the RPC provider, which other controllers require + // rpc provider this.initializeProvider() this.provider = this.networkController.getProviderAndBlockTracker().provider this.blockTracker = this.networkController.getProviderAndBlockTracker().blockTracker @@ -158,7 +151,7 @@ module.exports = class MetamaskController extends EventEmitter { initState: initState.IncomingTransactionsController, }) - // account tracker watches balances, nonces, and any code at their address + // account tracker watches balances, nonces, and any code at their address. this.accountTracker = new AccountTracker({ provider: this.provider, blockTracker: this.blockTracker, @@ -184,7 +177,6 @@ module.exports = class MetamaskController extends EventEmitter { this.onboardingController = new OnboardingController({ initState: initState.OnboardingController, - preferencesController: this.preferencesController, }) // ensure accountTracker updates balances after network change @@ -192,6 +184,7 @@ module.exports = class MetamaskController extends EventEmitter { this.accountTracker._updateAccounts() }) + // key mgmt const additionalKeyrings = [TrezorKeyring, LedgerBridgeKeyring] this.keyringController = new KeyringController({ keyringTypes: additionalKeyrings, @@ -199,25 +192,16 @@ module.exports = class MetamaskController extends EventEmitter { getNetwork: this.networkController.getNetworkState.bind(this.networkController), encryptor: opts.encryptor || undefined, }) - this.keyringController.memStore.subscribe((s) => this._onKeyringControllerUpdate(s)) - this.permissionsController = new PermissionsController({ - keyringController: this.keyringController, - platform: opts.platform, - notifyDomain: this.notifyConnections.bind(this), - notifyAllDomains: this.notifyAllConnections.bind(this), - }, initState.PermissionsController, initState.PermissionsMetadata) + this.keyringController.memStore.subscribe((s) => this._onKeyringControllerUpdate(s)) + // detect tokens controller this.detectTokensController = new DetectTokensController({ preferences: this.preferencesController, network: this.networkController, keyringMemStore: this.keyringController.memStore, }) - this.abTestController = new ABTestController({ - initState: initState.ABTestController, - }) - this.addressBookController = new AddressBookController(undefined, initState.AddressBookController) this.threeBoxController = new ThreeBoxController({ @@ -229,9 +213,9 @@ module.exports = class MetamaskController extends EventEmitter { version, }) + // tx mgmt this.txController = new TransactionController({ initState: initState.TransactionController || initState.TransactionManager, - getPermittedAccounts: this.permissionsController.getAccounts.bind(this.permissionsController), networkStore: this.networkController.networkStore, preferencesStore: this.preferencesController.store, txHistoryLimit: 40, @@ -282,6 +266,18 @@ module.exports = class MetamaskController extends EventEmitter { this.isClientOpenAndUnlocked = memState.isUnlocked && this._isClientOpen }) + this.providerApprovalController = new ProviderApprovalController({ + closePopup: opts.closePopup, + initState: initState.ProviderApprovalController, + keyringController: this.keyringController, + openPopup: opts.openPopup, + preferencesController: this.preferencesController, + }) + + this.abTestController = new ABTestController({ + initState: initState.ABTestController, + }) + this.store.updateStructure({ AppStateController: this.appStateController.store, TransactionController: this.txController.store, @@ -294,11 +290,10 @@ module.exports = class MetamaskController extends EventEmitter { InfuraController: this.infuraController.store, CachedBalancesController: this.cachedBalancesController.store, OnboardingController: this.onboardingController.store, + ProviderApprovalController: this.providerApprovalController.store, IncomingTransactionsController: this.incomingTransactionsController.store, - ABTestController: this.abTestController.store, - PermissionsController: this.permissionsController.permissions, - PermissionsMetadata: this.permissionsController.store, ThreeBoxController: this.threeBoxController.store, + ABTestController: this.abTestController.store, }) this.memStore = new ComposableObservableStore(null, { @@ -319,9 +314,11 @@ module.exports = class MetamaskController extends EventEmitter { ShapeshiftController: this.shapeshiftController, InfuraController: this.infuraController.store, OnboardingController: this.onboardingController.store, + // ProviderApprovalController + ProviderApprovalController: this.providerApprovalController.store, + ProviderApprovalControllerMemStore: this.providerApprovalController.memStore, IncomingTransactionsController: this.incomingTransactionsController.store, - PermissionsController: this.permissionsController.permissions, - PermissionsMetadata: this.permissionsController.store, + // ThreeBoxController ThreeBoxController: this.threeBoxController.store, ABTestController: this.abTestController.store, // ENS Controller @@ -342,15 +339,18 @@ module.exports = class MetamaskController extends EventEmitter { version, // account mgmt getAccounts: async ({ origin }) => { - if (origin === 'metamask') { - const selectedAddress = this.preferencesController.getSelectedAddress() - return selectedAddress ? [selectedAddress] : [] - } else if ( - this.keyringController.memStore.getState().isUnlocked - ) { - return await this.permissionsController.getAccounts(origin) + // Expose no accounts if this origin has not been approved, preventing + // account-requring RPC methods from completing successfully + const exposeAccounts = this.providerApprovalController.shouldExposeAccounts(origin) + if (origin !== 'metamask' && !exposeAccounts) { return [] } + const isUnlocked = this.keyringController.memStore.getState().isUnlocked + const selectedAddress = this.preferencesController.getSelectedAddress() + // only show address if account is unlocked + if (isUnlocked && selectedAddress) { + return [selectedAddress] + } else { + return [] } - return [] // changing this is a breaking change }, // tx signing processTransaction: this.newUnapprovedTransaction.bind(this), @@ -371,7 +371,7 @@ module.exports = class MetamaskController extends EventEmitter { * Constructor helper: initialize a public config store. * This store is used to make some config info available to Dapps synchronously. */ - createPublicConfigStore () { + createPublicConfigStore ({ checkIsEnabled }) { // subset of state for metamask inpage provider const publicConfigStore = new ObservableStore() @@ -384,16 +384,24 @@ module.exports = class MetamaskController extends EventEmitter { } function updatePublicConfigStore (memState) { - publicConfigStore.putState(selectPublicState(memState)) + const publicState = selectPublicState(memState) + publicConfigStore.putState(publicState) } - function selectPublicState ({ isUnlocked, network, provider }) { - return { + function selectPublicState ({ isUnlocked, selectedAddress, network, completedOnboarding, provider }) { + const isEnabled = checkIsEnabled() + const isReady = isUnlocked && isEnabled + const result = { isUnlocked, + isEnabled, + selectedAddress: isReady ? selectedAddress : null, networkVersion: network, + onboardingcomplete: completedOnboarding, chainId: selectChainId({ network, provider }), } + return result } + return publicConfigStore } @@ -425,13 +433,13 @@ module.exports = class MetamaskController extends EventEmitter { */ getApi () { const keyringController = this.keyringController + const preferencesController = this.preferencesController + const txController = this.txController const networkController = this.networkController + const providerApprovalController = this.providerApprovalController const onboardingController = this.onboardingController - const permissionsController = this.permissionsController - const preferencesController = this.preferencesController const threeBoxController = this.threeBoxController const abTestController = this.abTestController - const txController = this.txController return { // etc @@ -489,6 +497,7 @@ module.exports = class MetamaskController extends EventEmitter { setPreference: nodeify(preferencesController.setPreference, preferencesController), completeOnboarding: nodeify(preferencesController.completeOnboarding, preferencesController), addKnownMethodData: nodeify(preferencesController.addKnownMethodData, preferencesController), + unsetMigratedPrivacyMode: nodeify(preferencesController.unsetMigratedPrivacyMode, preferencesController), // BlacklistController whitelistPhishingDomain: this.whitelistPhishingDomain.bind(this), @@ -536,6 +545,11 @@ module.exports = class MetamaskController extends EventEmitter { signTypedMessage: nodeify(this.signTypedMessage, this), cancelTypedMessage: this.cancelTypedMessage.bind(this), + // provider approval + approveProviderRequestByOrigin: providerApprovalController.approveProviderRequestByOrigin.bind(providerApprovalController), + rejectProviderRequestByOrigin: providerApprovalController.rejectProviderRequestByOrigin.bind(providerApprovalController), + clearApprovedOrigins: providerApprovalController.clearApprovedOrigins.bind(providerApprovalController), + // onboarding controller setSeedPhraseBackedUp: nodeify(onboardingController.setSeedPhraseBackedUp, onboardingController), @@ -549,21 +563,10 @@ module.exports = class MetamaskController extends EventEmitter { // a/b test controller getAssignedABTestGroupName: nodeify(abTestController.getAssignedABTestGroupName, abTestController), - - // permissions - approvePermissionsRequest: nodeify(permissionsController.approvePermissionsRequest, permissionsController), - clearPermissions: permissionsController.clearPermissions.bind(permissionsController), - getApprovedAccounts: nodeify(permissionsController.getAccounts.bind(permissionsController)), - rejectPermissionsRequest: nodeify(permissionsController.rejectPermissionsRequest, permissionsController), - removePermissionsFor: permissionsController.removePermissionsFor.bind(permissionsController), - updateExposedAccounts: nodeify(permissionsController.updateExposedAccounts, permissionsController), - legacyExposeAccounts: nodeify(permissionsController.legacyExposeAccounts, permissionsController), - - getRequestAccountTabIds: (cb) => cb(null, this.getRequestAccountTabIds()), - getOpenMetamaskTabsIds: (cb) => cb(null, this.getOpenMetamaskTabsIds()), } } + //============================================================================= // VAULT / KEYRING RELATED METHODS //============================================================================= @@ -1343,10 +1346,10 @@ module.exports = class MetamaskController extends EventEmitter { // setup multiplexing const mux = setupMultiplex(connectionStream) - - // messages between inpage and background - this.setupProviderConnection(mux.createStream('provider'), senderUrl, extensionId) - this.setupPublicConfig(mux.createStream('publicConfig')) + // connect features + const publicApi = this.setupPublicApi(mux.createStream('publicApi')) + this.setupProviderConnection(mux.createStream('provider'), senderUrl, extensionId, publicApi) + this.setupPublicConfig(mux.createStream('publicConfig'), senderUrl) } /** @@ -1402,9 +1405,7 @@ module.exports = class MetamaskController extends EventEmitter { this.activeControllerConnections-- this.emit('controllerConnectionChanged', this.activeControllerConnections) // report any error - if (err) { - log.error(err) - } + if (err) log.error(err) } ) dnode.on('remote', (remote) => { @@ -1424,15 +1425,13 @@ module.exports = class MetamaskController extends EventEmitter { * resource is an extension. * @param {object} publicApi - The public API */ - setupProviderConnection (outStream, senderUrl, extensionId) { - const origin = senderUrl.hostname - const engine = this.setupProviderEngine(senderUrl, extensionId) + setupProviderConnection (outStream, senderUrl, extensionId, publicApi) { + const getSiteMetadata = publicApi && publicApi.getSiteMetadata + const engine = this.setupProviderEngine(senderUrl, extensionId, getSiteMetadata) // setup connection const providerStream = createEngineStream({ engine }) - const connectionId = this.addConnection(origin, { engine }) - pump( outStream, providerStream, @@ -1444,10 +1443,7 @@ module.exports = class MetamaskController extends EventEmitter { mid.destroy() } }) - connectionId && this.removeConnection(origin, connectionId) - if (err) { - log.error(err) - } + if (err) log.error(err) } ) } @@ -1455,8 +1451,7 @@ module.exports = class MetamaskController extends EventEmitter { /** * A method for creating a provider that is safely restricted for the requesting domain. **/ - setupProviderEngine (senderUrl, extensionId) { - + setupProviderEngine (senderUrl, extensionId, getSiteMetadata) { const origin = senderUrl.hostname // setup json rpc engine stack const engine = new RpcEngine() @@ -1470,17 +1465,20 @@ module.exports = class MetamaskController extends EventEmitter { const subscriptionManager = createSubscriptionManager({ provider, blockTracker }) subscriptionManager.events.on('notification', (message) => engine.emit('notification', message)) - // append origin to each request + // metadata engine.push(createOriginMiddleware({ origin })) - // logging engine.push(createLoggerMiddleware({ origin })) // filter and subscription polyfills engine.push(filterMiddleware) engine.push(subscriptionManager.middleware) - // permissions - engine.push(this.permissionsController.createMiddleware({ origin, extensionId })) // watch asset engine.push(this.preferencesController.requestWatchAsset.bind(this.preferencesController)) + // requestAccounts + engine.push(this.providerApprovalController.createMiddleware({ + senderUrl, + extensionId, + getSiteMetadata, + })) // forward to metamask primary provider engine.push(providerAsMiddleware(provider)) return engine @@ -1495,9 +1493,13 @@ module.exports = class MetamaskController extends EventEmitter { * this is a good candidate for deprecation. * * @param {*} outStream - The stream to provide public config over. + * @param {URL} senderUrl - The URL of requesting resource */ - setupPublicConfig (outStream) { - const configStore = this.createPublicConfigStore() + setupPublicConfig (outStream, senderUrl) { + const configStore = this.createPublicConfigStore({ + // check the providerApprovalController's approvedOrigins + checkIsEnabled: () => this.providerApprovalController.shouldExposeAccounts(senderUrl.hostname), + }) const configStream = asStream(configStore) pump( @@ -1506,145 +1508,43 @@ module.exports = class MetamaskController extends EventEmitter { (err) => { configStore.destroy() configStream.destroy() - if (err) { - log.error(err) - } + if (err) log.error(err) } ) } - // manage external connections - - onMessage (message, sender, sendResponse) { - if (!message || !message.type) { - log.debug(`Ignoring invalid message: '${JSON.stringify(message)}'`) - return - } - - let handleMessage - - try { - if (message.type === 'metamask:registerOnboarding') { - assert(sender.tab, 'Missing tab from sender') - assert(sender.tab.id && sender.tab.id !== extension.tabs.TAB_ID_NONE, 'Missing tab ID from sender') - assert(message.location, 'Missing location from message') - - handleMessage = this.onboardingController.registerOnboarding(message.location, sender.tab.id) - } else { - throw new Error(`Unrecognized message type: '${message.type}'`) - } - } catch (error) { - console.error(error) - sendResponse(error) - return true - } - - if (handleMessage) { - handleMessage - .then(() => { - sendResponse(null, true) - }) - .catch((error) => { - console.error(error) - sendResponse(error) - }) - return true - } - } - - /** - * Adds a reference to a connection by origin. Ignores the 'metamask' origin. - * Caller must ensure that the returned id is stored such that the reference - * can be deleted later. - * - * @param {string} origin - The connection's origin string. - * @param {Object} options - Data associated with the connection - * @param {Object} options.engine - The connection's JSON Rpc Engine - * @returns {string} - The connection's id (so that it can be deleted later) - */ - addConnection (origin, { engine }) { - - if (origin === 'metamask') { - return null - } - - if (!this.connections[origin]) { - this.connections[origin] = {} - } - - const id = nanoid() - this.connections[origin][id] = { - engine, - } - - return id - } - - /** - * Deletes a reference to a connection, by origin and id. - * Ignores unknown origins. - * - * @param {string} origin - The connection's origin string. - * @param {string} id - The connection's id, as returned from addConnection. - */ - removeConnection (origin, id) { - - const connections = this.connections[origin] - if (!connections) { - return - } - - delete connections[id] - - if (Object.keys(connections.length === 0)) { - delete this.connections[origin] - } - } - /** - * Causes the RPC engines associated with the connections to the given origin - * to emit a notification event with the given payload. - * Does nothing if the extension is locked or the origin is unknown. + * A method for providing our public api over a stream. + * This includes a method for setting site metadata like title and image * - * @param {string} origin - The connection's origin string. - * @param {any} payload - The event payload. + * @param {*} outStream - The stream to provide the api over. */ - notifyConnections (origin, payload) { - - const { isUnlocked } = this.getState() - const connections = this.connections[origin] - if (!isUnlocked || !connections) { - return - } - - Object.values(connections).forEach(conn => { - conn.engine && conn.engine.emit('notification', payload) - }) - } + setupPublicApi (outStream) { + const dnode = Dnode() + // connect dnode api to remote connection + pump( + outStream, + dnode, + outStream, + (err) => { + // report any error + if (err) log.error(err) + } + ) - /** - * Causes the RPC engines associated with all connections to emit a - * notification event with the given payload. - * Does nothing if the extension is locked. - * - * @param {any} payload - The event payload. - */ - notifyAllConnections (payload) { + const getRemote = createDnodeRemoteGetter(dnode) - const { isUnlocked } = this.getState() - if (!isUnlocked) { - return + const publicApi = { + // wrap with an await remote + getSiteMetadata: async () => { + const remote = await getRemote() + return await pify(remote.getSiteMetadata)() + }, } - Object.values(this.connections).forEach(origin => { - Object.values(origin).forEach(conn => { - conn.engine && conn.engine.emit('notification', payload) - }) - }) + return publicApi } - // handlers - /** * Handle a KeyringController update * @param {object} state the KC state @@ -1673,8 +1573,6 @@ module.exports = class MetamaskController extends EventEmitter { } } - // misc - /** * A method for emitting the full MetaMask state to all registered listeners. * @private @@ -1683,10 +1581,6 @@ module.exports = class MetamaskController extends EventEmitter { this.emit('update', this.getState()) } - //============================================================================= - // MISCELLANEOUS - //============================================================================= - /** * A method for estimating a good gas price at recent prices. * Returns the lowest price that would have been included in @@ -1783,14 +1677,10 @@ module.exports = class MetamaskController extends EventEmitter { * @param {string} amount - The amount of ether desired, as a base 10 string. */ buyEth (address, amount) { - if (!amount) { - amount = '5' - } + if (!amount) amount = '5' const network = this.networkController.getNetworkState() const url = getBuyEthUrl({ network, address, amount }) - if (url) { - this.platform.openWindow({ url }) - } + if (url) this.platform.openWindow({ url }) } /** diff --git a/app/scripts/migrations/004.js b/app/scripts/migrations/004.js index a1ae823cde..cd558300c3 100644 --- a/app/scripts/migrations/004.js +++ b/app/scripts/migrations/004.js @@ -9,9 +9,7 @@ module.exports = { const safeVersionedData = clone(versionedData) safeVersionedData.meta.version = version try { - if (safeVersionedData.data.config.provider.type !== 'rpc') { - return Promise.resolve(safeVersionedData) - } + if (safeVersionedData.data.config.provider.type !== 'rpc') return Promise.resolve(safeVersionedData) switch (safeVersionedData.data.config.provider.rpcTarget) { case 'https://testrpc.metamask.io/': safeVersionedData.data.config.provider = { @@ -23,7 +21,6 @@ module.exports = { type: 'mainnet', } break - // No default } } catch (_) {} return Promise.resolve(safeVersionedData) diff --git a/app/scripts/migrations/015.js b/app/scripts/migrations/015.js index 3d20b58db5..5e2f9e63bd 100644 --- a/app/scripts/migrations/015.js +++ b/app/scripts/migrations/015.js @@ -32,11 +32,8 @@ function transformState (state) { if (TransactionController && TransactionController.transactions) { const transactions = TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta) => { - if (!txMeta.err) { - return txMeta - } else if (txMeta.err.message === 'Gave up submitting tx.') { - txMeta.status = 'failed' - } + if (!txMeta.err) return txMeta + else if (txMeta.err.message === 'Gave up submitting tx.') txMeta.status = 'failed' return txMeta }) } diff --git a/app/scripts/migrations/016.js b/app/scripts/migrations/016.js index 76a106ca7e..048c7a40ec 100644 --- a/app/scripts/migrations/016.js +++ b/app/scripts/migrations/016.js @@ -33,9 +33,7 @@ function transformState (state) { const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta) => { - if (!txMeta.err) { - return txMeta - } + if (!txMeta.err) return txMeta if (txMeta.err === 'transaction with the same hash was already imported.') { txMeta.status = 'submitted' delete txMeta.err diff --git a/app/scripts/migrations/017.js b/app/scripts/migrations/017.js index 918df4ade1..5f6d906d67 100644 --- a/app/scripts/migrations/017.js +++ b/app/scripts/migrations/017.js @@ -31,9 +31,7 @@ function transformState (state) { if (TransactionController && TransactionController.transactions) { const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta) => { - if (!txMeta.status === 'failed') { - return txMeta - } + if (!txMeta.status === 'failed') return txMeta if (txMeta.retryCount > 0 && txMeta.retryCount < 2) { txMeta.status = 'submitted' delete txMeta.err diff --git a/app/scripts/migrations/019.js b/app/scripts/migrations/019.js index f560f5579d..7b726c3e85 100644 --- a/app/scripts/migrations/019.js +++ b/app/scripts/migrations/019.js @@ -35,9 +35,7 @@ function transformState (state) { const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta, _, txList) => { - if (txMeta.status !== 'submitted') { - return txMeta - } + if (txMeta.status !== 'submitted') return txMeta const confirmedTxs = txList.filter((tx) => tx.status === 'confirmed') .filter((tx) => tx.txParams.from === txMeta.txParams.from) diff --git a/app/scripts/migrations/022.js b/app/scripts/migrations/022.js index eeb142b7a9..1fbe241e6e 100644 --- a/app/scripts/migrations/022.js +++ b/app/scripts/migrations/022.js @@ -33,9 +33,7 @@ function transformState (state) { const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta) => { - if (txMeta.status !== 'submitted' || txMeta.submittedTime) { - return txMeta - } + if (txMeta.status !== 'submitted' || txMeta.submittedTime) return txMeta txMeta.submittedTime = (new Date()).getTime() return txMeta }) diff --git a/app/scripts/migrations/023.js b/app/scripts/migrations/023.js index 84532537ea..18493a7893 100644 --- a/app/scripts/migrations/023.js +++ b/app/scripts/migrations/023.js @@ -33,9 +33,7 @@ function transformState (state) { if (TransactionController && TransactionController.transactions) { const transactions = newState.TransactionController.transactions - if (transactions.length <= 40) { - return newState - } + if (transactions.length <= 40) return newState const reverseTxList = transactions.reverse() let stripping = true @@ -46,11 +44,8 @@ function transformState (state) { txMeta.status === 'confirmed' || txMeta.status === 'dropped') }) - if (txIndex < 0) { - stripping = false - } else { - reverseTxList.splice(txIndex, 1) - } + if (txIndex < 0) stripping = false + else reverseTxList.splice(txIndex, 1) } newState.TransactionController.transactions = reverseTxList.reverse() diff --git a/app/scripts/migrations/024.js b/app/scripts/migrations/024.js index fda463e1a1..5ffaea377e 100644 --- a/app/scripts/migrations/024.js +++ b/app/scripts/migrations/024.js @@ -25,9 +25,7 @@ module.exports = { function transformState (state) { const newState = state - if (!newState.TransactionController) { - return newState - } + if (!newState.TransactionController) return newState const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta, _) => { if ( diff --git a/app/scripts/migrations/025.js b/app/scripts/migrations/025.js index 48bff962de..fd4faa782c 100644 --- a/app/scripts/migrations/025.js +++ b/app/scripts/migrations/025.js @@ -29,9 +29,7 @@ function transformState (state) { if (newState.TransactionController.transactions) { const transactions = newState.TransactionController.transactions newState.TransactionController.transactions = transactions.map((txMeta) => { - if (txMeta.status !== 'unapproved') { - return txMeta - } + if (txMeta.status !== 'unapproved') return txMeta txMeta.txParams = normalizeTxParams(txMeta.txParams) return txMeta }) @@ -56,9 +54,7 @@ function normalizeTxParams (txParams) { // apply only keys in the whiteList const normalizedTxParams = {} Object.keys(whiteList).forEach((key) => { - if (txParams[key]) { - normalizedTxParams[key] = whiteList[key](txParams[key]) - } + if (txParams[key]) normalizedTxParams[key] = whiteList[key](txParams[key]) }) return normalizedTxParams diff --git a/app/scripts/migrations/029.js b/app/scripts/migrations/029.js index 59724c1545..e17479ccc2 100644 --- a/app/scripts/migrations/029.js +++ b/app/scripts/migrations/029.js @@ -24,3 +24,4 @@ module.exports = { return isApproved && now - createdTime > unacceptableDelay }), } + diff --git a/app/scripts/migrations/031.js b/app/scripts/migrations/031.js index 927de98c43..9c8cbeb09b 100644 --- a/app/scripts/migrations/031.js +++ b/app/scripts/migrations/031.js @@ -3,7 +3,7 @@ const version = 31 const clone = require('clone') /* - * The purpose of this migration is to properly set the completedOnboarding flag based on the state + * The purpose of this migration is to properly set the completedOnboarding flag baesd on the state * of the KeyringController. */ module.exports = { diff --git a/app/scripts/migrations/040.js b/app/scripts/migrations/040.js deleted file mode 100644 index 042f499b2c..0000000000 --- a/app/scripts/migrations/040.js +++ /dev/null @@ -1,23 +0,0 @@ -const version = 40 -const clone = require('clone') - -/** - * Site connections are now managed by the PermissionsController, and the - * ProviderApprovalController is removed. This migration deletes all - * ProviderApprovalController state. - */ -module.exports = { - version, - migrate: async function (originalVersionedData) { - const versionedData = clone(originalVersionedData) - versionedData.meta.version = version - const state = versionedData.data - versionedData.data = transformState(state) - return versionedData - }, -} - -function transformState (state) { - delete state.ProviderApprovalController - return state -} diff --git a/app/scripts/platforms/extension.js b/app/scripts/platforms/extension.js index 5ae05d2304..d54a8a7b32 100644 --- a/app/scripts/platforms/extension.js +++ b/app/scripts/platforms/extension.js @@ -1,7 +1,7 @@ const extension = require('extensionizer') const {createExplorerLink: explorerLink} = require('etherscan-link') -const { getEnvironmentType, checkForError } = require('../lib/util') +const {getEnvironmentType} = require('../lib/util') const {ENVIRONMENT_TYPE_BACKGROUND} = require('../lib/enums') class ExtensionPlatform { @@ -66,58 +66,6 @@ class ExtensionPlatform { } } - queryTabs () { - return new Promise((resolve, reject) => { - extension.tabs.query({}, tabs => { - const err = checkForError() - if (err) { - reject(err) - } else { - resolve(tabs) - } - }) - }) - } - - currentTab () { - return new Promise((resolve, reject) => { - extension.tabs.getCurrent(tab => { - const err = checkForError() - if (err) { - reject(err) - } else { - resolve(tab) - } - }) - }) - } - - switchToTab (tabId) { - return new Promise((resolve, reject) => { - extension.tabs.update(tabId, {highlighted: true}, (tab) => { - const err = checkForError() - if (err) { - reject(err) - } else { - resolve(tab) - } - }) - }) - } - - closeTab (tabId) { - return new Promise((resolve, reject) => { - extension.tabs.remove(tabId, () => { - const err = checkForError() - if (err) { - reject(err) - } else { - resolve() - } - }) - }) - } - _showConfirmedTransaction (txMeta) { this._subscribeToNotificationClicked() diff --git a/brave/ui/app/pages/home/home.container.js b/brave/ui/app/pages/home/home.container.js index 2a412372e9..435fc7e7d1 100644 --- a/brave/ui/app/pages/home/home.container.js +++ b/brave/ui/app/pages/home/home.container.js @@ -3,7 +3,7 @@ import { compose } from 'recompose' import { connect } from 'react-redux' import { withRouter } from 'react-router-dom' import { unconfirmedTransactionsCountSelector } from '../../../../../ui/app/selectors/confirm-transaction' -import { getCurrentEthBalance, getDaiV1Token, hasPermissionRequests } from '../../../../../ui/app/selectors/selectors' +import { getCurrentEthBalance, getDaiV1Token } from '../../../../../ui/app/selectors/selectors' import { addTokens, setHardwareConnect, @@ -11,6 +11,7 @@ import { turnThreeBoxSyncingOn, getThreeBoxLastUpdated, setShowRestorePromptToFalse, + unsetMigratedPrivacyMode, } from '../../store/actions' import batToken from '../../store/bat-token' import { setThreeBoxLastUpdated } from '../../../../../ui/app/ducks/app/app' @@ -28,6 +29,8 @@ const mapStateToProps = state => { selectedAddress, batTokenAdded, hardwareConnect, + providerRequests, + migratedPrivacyMode, } = metamask const accountBalance = getCurrentEthBalance(state) const { forgottenPassword, threeBoxLastUpdated } = appState @@ -46,13 +49,15 @@ const mapStateToProps = state => { selectedAddress, threeBoxLastUpdated, hasDaiV1Token: Boolean(getDaiV1Token(state)), - hasPermissionRequests: hasPermissionRequests(state), batTokenAdded, hardwareConnect, + providerRequests, + showPrivacyModeNotification: migratedPrivacyMode, } } const mapDispatchToProps = (dispatch) => ({ + unsetMigratedPrivacyMode: () => dispatch(unsetMigratedPrivacyMode()), turnThreeBoxSyncingOn: () => dispatch(turnThreeBoxSyncingOn()), setupThreeBox: () => { dispatch(getThreeBoxLastUpdated()) diff --git a/brave/ui/app/pages/routes/index.js b/brave/ui/app/pages/routes/index.js index 9df7e3f088..bcbd549d36 100644 --- a/brave/ui/app/pages/routes/index.js +++ b/brave/ui/app/pages/routes/index.js @@ -9,8 +9,6 @@ import { withRouter } from 'react-router-dom' import { getNetworkIdentifier, preferencesSelector, - hasPermissionRequests, - getAddressConnectedToCurrentTab, } from '../../../../../ui/app/selectors/selectors' import BraveHeader from '../../components/app/header' import { @@ -50,8 +48,6 @@ function mapStateToProps (state) { isMouseUser: state.appState.isMouseUser, providerId: getNetworkIdentifier(state), autoLogoutTimeLimit, - hasPermissionsRequests: hasPermissionRequests(state), - addressConnectedToCurrentTab: getAddressConnectedToCurrentTab(state), batTokenAdded: state.metamask.batTokenAdded, rewardsDisclosureAccepted: state.metamask.rewardsDisclosureAccepted, hardwareConnect: state.metamask.hardwareConnect, diff --git a/development/announcer.js b/development/announcer.js index 8b0c1de272..ea1bfdd366 100644 --- a/development/announcer.js +++ b/development/announcer.js @@ -1,11 +1,11 @@ -const manifest = require('../app/manifest.json') -const version = manifest.version +var manifest = require('../app/manifest.json') +var version = manifest.version -const fs = require('fs') -const path = require('path') -const changelog = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md')).toString() +var fs = require('fs') +var path = require('path') +var changelog = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md')).toString() -const log = changelog.split(version)[1].split('##')[0].trim() +var log = changelog.split(version)[1].split('##')[0].trim() const msg = `*MetaMask ${version}* now published! It should auto-update soon!\n${log}` diff --git a/development/auto-changelog.sh b/development/auto-changelog.sh index 26ab8e93f7..3ed059b3d7 100755 --- a/development/auto-changelog.sh +++ b/development/auto-changelog.sh @@ -10,7 +10,7 @@ git fetch --tags most_recent_tag="$(git describe --tags "$(git rev-list --tags --max-count=1)")" -git rev-list "${most_recent_tag}"..HEAD | while read -r commit +git rev-list "${most_recent_tag}"..HEAD | while read commit do subject="$(git show -s --format="%s" "$commit")" diff --git a/development/mock-3box.js b/development/mock-3box.js index a26e02a820..53f228f216 100644 --- a/development/mock-3box.js +++ b/development/mock-3box.js @@ -28,9 +28,7 @@ class Mock3Box { static openBox (address) { this.address = address return Promise.resolve({ - onSyncDone: cb => { - setTimeout(cb, 200) - }, + onSyncDone: cb => { setTimeout(cb, 200) }, openSpace: async (spaceName, config) => { const { onSyncDone } = config this.spaceName = spaceName diff --git a/development/mock-dev.js b/development/mock-dev.js index 51a8cde463..8da6251493 100644 --- a/development/mock-dev.js +++ b/development/mock-dev.js @@ -10,13 +10,13 @@ * without having to re-open the plugin or even re-build it. */ -import React from 'react' const render = require('react-dom').render +const h = require('react-hyperscript') const Root = require('../ui/app/pages') const configureStore = require('../ui/app/store/store') const actions = require('../ui/app/store/actions') const backGroundConnectionModifiers = require('./backGroundConnectionModifiers') -import Selector from './selector' +const Selector = require('./selector') const MetamaskController = require('../app/scripts/metamask-controller') const firstTimeState = require('../app/scripts/first-time-state') const ExtensionPlatform = require('../app/scripts/platforms/extension') @@ -94,7 +94,7 @@ function modifyBackgroundConnection (backgroundConnectionModifier) { } // parse opts -const store = configureStore(firstState) +var store = configureStore(firstState) // start app startApp() @@ -106,38 +106,40 @@ function startApp () { body.appendChild(container) render( - - { + h('.super-dev-container', [ + + h('button', { + onClick: (ev) => { ev.preventDefault() store.dispatch(actions.update('terms')) - }} - style={{ + }, + style: { margin: '19px 19px 0px 19px', - }} - > - Reset State - - - - - - , - container, - ) + }, + }, [ + h(Root, { + store: store, + }), + ]), + + ] + ), container) } diff --git a/development/rollback.sh b/development/rollback.sh index a3040e6f11..639d72a675 100755 --- a/development/rollback.sh +++ b/development/rollback.sh @@ -4,20 +4,20 @@ echo "Rolling back to version $1" # Checkout branch to increment version -git checkout -b "version-increment-$1" +git checkout -b version-increment-$1 yarn version:bump patch # Store the new version name -NEW_VERSION=$(jq -r .version < app/manifest.json) +NEW_VERSION=$(cat app/manifest.json | jq -r .version) # Make sure origin tags are loaded git fetch origin # check out the rollback branch -git checkout "origin/v$1" +git checkout origin/v$1 # Create the rollback branch. -git checkout -b "Version-$NEW_VERSION-Rollback-to-$1" +git checkout -b Version-$NEW_VERSION-Rollback-to-$1 # Set the version files to the next one. git checkout master CHANGELOG.md @@ -28,8 +28,8 @@ git commit -m "Version $NEW_VERSION (Rollback to $1)" git push -u origin HEAD # Create tag and push that up too -git tag "v${NEW_VERSION}" -git push origin "v${NEW_VERSION}" +git tag v${NEW_VERSION} +git push origin v${NEW_VERSION} # Cleanup version branch -git branch -D "version-increment-$1" +git branch -D version-increment-$1 diff --git a/development/selector.js b/development/selector.js index 01011c7107..2673d0fe3c 100644 --- a/development/selector.js +++ b/development/selector.js @@ -1,49 +1,42 @@ -import PropTypes from 'prop-types' -import React, {Component} from 'react' +const Component = require('react').Component +const h = require('react-hyperscript') +const inherits = require('util').inherits -export default class Selector extends Component { - state = {} +module.exports = NewComponent - render () { - const { - states, - selectedKey, - actions, - store, - modifyBackgroundConnection, - backGroundConnectionModifiers, - } = this.props - const selected = this.state.selected || selectedKey - - return ( - { - const selectedKey = event.target.value - const backgroundConnectionModifier = backGroundConnectionModifiers[selectedKey] - modifyBackgroundConnection(backgroundConnectionModifier || {}) - store.dispatch(actions.update(selectedKey)) - this.setState({ selected: selectedKey }) - }} - > - {Object.keys(states).map((stateName, index) => { - return ( - - {stateName} - - ) - })} - - ) - } +inherits(NewComponent, Component) +function NewComponent () { + Component.call(this) } -Selector.propTypes = { - states: PropTypes.object.isRequired, - selectedKey: PropTypes.string.isRequired, - actions: PropTypes.object.isRequired, - store: PropTypes.object.isRequired, - modifyBackgroundConnection: PropTypes.func.isRequired, - backGroundConnectionModifiers: PropTypes.object.isRequired, +NewComponent.prototype.render = function () { + const props = this.props + const { + states, + selectedKey, + actions, + store, + modifyBackgroundConnection, + backGroundConnectionModifiers, + } = props + + const state = this.state || {} + const selected = state.selected || selectedKey + + return h('select', { + style: { + margin: '20px 20px 0px', + }, + value: selected, + onChange: (event) => { + const selectedKey = event.target.value + const backgroundConnectionModifier = backGroundConnectionModifiers[selectedKey] + modifyBackgroundConnection(backgroundConnectionModifier || {}) + store.dispatch(actions.update(selectedKey)) + this.setState({ selected: selectedKey }) + }, + }, Object.keys(states).map((stateName) => { + return h('option', { value: stateName }, stateName) + })) + } diff --git a/development/show-deps-install-scripts.js b/development/show-deps-install-scripts.js index 419c9d25f2..03a9bb859b 100644 --- a/development/show-deps-install-scripts.js +++ b/development/show-deps-install-scripts.js @@ -5,9 +5,7 @@ const readInstalled = require('read-installed') const installScripts = ['preinstall', 'install', 'postinstall'] readInstalled('./', { dev: true }, function (err, data) { - if (err) { - throw err - } + if (err) throw err const deps = data.dependencies Object.entries(deps).forEach(([packageName, packageData]) => { @@ -15,20 +13,12 @@ readInstalled('./', { dev: true }, function (err, data) { const scriptKeys = Reflect.ownKeys(packageScripts) const hasInstallScript = installScripts.some(installKey => scriptKeys.includes(installKey)) - if (!hasInstallScript) { - return - } + if (!hasInstallScript) return const matchingScripts = {} - if (packageScripts.preinstall) { - matchingScripts.preinstall = packageScripts.preinstall - } - if (packageScripts.install) { - matchingScripts.install = packageScripts.install - } - if (packageScripts.postinstall) { - matchingScripts.postinstall = packageScripts.postinstall - } + if (packageScripts.preinstall) matchingScripts.preinstall = packageScripts.preinstall + if (packageScripts.install) matchingScripts.install = packageScripts.install + if (packageScripts.postinstall) matchingScripts.postinstall = packageScripts.postinstall const scriptNames = Reflect.ownKeys(matchingScripts) const relativePath = path.relative(process.cwd(), packageData.path) diff --git a/development/sourcemap-validator.js b/development/sourcemap-validator.js index 22c448862a..546745f166 100644 --- a/development/sourcemap-validator.js +++ b/development/sourcemap-validator.js @@ -52,9 +52,7 @@ async function validateSourcemapForFile ({ buildName }) { const consumer = await new SourceMapConsumer(rawSourceMap) const hasContentsOfAllSources = consumer.hasContentsOfAllSources() - if (!hasContentsOfAllSources) { - console.warn('SourcemapValidator - missing content of some sources...') - } + if (!hasContentsOfAllSources) console.warn('SourcemapValidator - missing content of some sources...') console.log(` sampling from ${consumer.sources.length} files`) let sampleCount = 0 @@ -96,10 +94,8 @@ async function validateSourcemapForFile ({ buildName }) { } function indicesOf (substring, string) { - const a = [] - let i = -1 - while ((i = string.indexOf(substring, i + 1)) >= 0) { - a.push(i) - } + var a = [] + var i = -1 + while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i) return a } diff --git a/development/static-server.js b/development/static-server.js deleted file mode 100644 index d8f22cabea..0000000000 --- a/development/static-server.js +++ /dev/null @@ -1,92 +0,0 @@ -const fs = require('fs') -const http = require('http') -const path = require('path') - -const chalk = require('chalk') -const pify = require('pify') -const serveHandler = require('serve-handler') - -const fsStat = pify(fs.stat) -const DEFAULT_PORT = 9080 - -const onResponse = (request, response) => { - if (response.statusCode >= 400) { - console.log(chalk`{gray '-->'} {red ${response.statusCode}} ${request.url}`) - } else if (response.statusCode >= 200 && response.statusCode < 300) { - console.log(chalk`{gray '-->'} {green ${response.statusCode}} ${request.url}`) - } else { - console.log(chalk`{gray '-->'} {green.dim ${response.statusCode}} ${request.url}`) - } -} -const onRequest = (request, response) => { - console.log(chalk`{gray '<--'} {blue [${request.method}]} ${request.url}`) - response.on('finish', () => onResponse(request, response)) -} - -const startServer = ({ port, rootDirectory }) => { - const server = http.createServer((request, response) => { - if (request.url.startsWith('/node_modules/')) { - request.url = request.url.substr(14) - return serveHandler(request, response, { - directoryListing: false, - public: path.resolve('./node_modules'), - }) - } - return serveHandler(request, response, { - directoryListing: false, - public: rootDirectory, - }) - }) - - server.on('request', onRequest) - - server.listen(port, () => { - console.log(`Running at http://localhost:${port}`) - }) -} - -const parsePort = (portString) => { - const port = Number(portString) - if (!Number.isInteger(port)) { - throw new Error(`Port '${portString}' is invalid; must be an integer`) - } else if (port < 0 || port > 65535) { - throw new Error(`Port '${portString}' is out of range; must be between 0 and 65535 inclusive`) - } - return port -} - -const parseDirectoryArgument = async (pathString) => { - const resolvedPath = path.resolve(pathString) - const directoryStats = await fsStat(resolvedPath) - if (!directoryStats.isDirectory()) { - throw new Error(`Invalid path '${pathString}'; must be a directory`) - } - return resolvedPath -} - -const main = async () => { - const args = process.argv.slice(2) - - const options = { - port: process.env.port || DEFAULT_PORT, - rootDirectory: path.resolve('.'), - } - - while (args.length) { - if (/^(--port|-p)$/i.test(args[0])) { - if (args[1] === undefined) { - throw new Error('Missing port argument') - } - options.port = parsePort(args[1]) - args.splice(0, 2) - } else { - options.rootDirectory = await parseDirectoryArgument(args[0]) - args.splice(0, 1) - } - } - - startServer(options) -} - -main() - .catch(console.error) diff --git a/development/verify-locale-strings.js b/development/verify-locale-strings.js index c6875b36c9..aa0c4503fd 100644 --- a/development/verify-locale-strings.js +++ b/development/verify-locale-strings.js @@ -161,11 +161,11 @@ async function verifyEnglishLocale (fix = false) { const englishLocale = await getLocale('en') const javascriptFiles = await findJavascriptFiles(path.resolve(__dirname, '..', 'ui')) - const regex = /'(\w+)'|"(\w+)"/g + const regex = /'(\w+)'/g const usedMessages = new Set() for await (const fileContents of getFileContents(javascriptFiles)) { for (const match of matchAll.call(fileContents, regex)) { - usedMessages.add(match[1] || match[2]) + usedMessages.add(match[1]) } } diff --git a/development/version-bump.js b/development/version-bump.js index 6ae21b782a..66b6baffee 100644 --- a/development/version-bump.js +++ b/development/version-bump.js @@ -40,8 +40,6 @@ function newVersionFrom (manifest, bumpType) { case 'patch': segments[2] += 1 break - default: - throw new Error(`invalid bumpType ${bumpType}`) } return segments.map(String).join('.') diff --git a/docs/porting_to_new_environment.md b/docs/porting_to_new_environment.md index 92f06f37db..9cb8e9c2dc 100644 --- a/docs/porting_to_new_environment.md +++ b/docs/porting_to_new_environment.md @@ -18,8 +18,8 @@ const providerFromEngine = require('eth-json-rpc-middleware/providerFromEngine') /** * returns a provider restricted to the requesting domain **/ -function incomingConnection (domain) { - const engine = metamaskController.setupProviderEngine(domain) +function incomingConnection (domain, getSiteMetadata) { + const engine = metamaskController.setupProviderEngine(domain, getSiteMetadata) const provider = providerFromEngine(engine) return provider } @@ -32,6 +32,15 @@ const filterMiddleware = engine._middleware.filter(mid => mid.name === 'filterMi filterMiddleware.destroy() ``` +### getSiteMetadata() + +This method is used to enhance our confirmation screens with images and text representing the requesting domain. + +It should return a promise that resolves with an object with the following properties: + +- `name`: The requesting site's name. +- `icon`: A URI representing the site's logo. + ### Using the Streams Interface Only use this if you intend to construct the [metamask-inpage-provider](https://github.com/MetaMask/metamask-inpage-provider) over a stream! diff --git a/gulpfile.js b/gulpfile.js index d5d74333af..3e4a3b7ff2 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -428,9 +428,7 @@ function createTasksForBuildJs ({ rootDir, taskPrefix, bundleTaskOpts, destinati // compose into larger task const subtasks = [] subtasks.push(gulp.parallel(buildPhase1.map(file => `${taskPrefix}:${file}`))) - if (buildPhase2.length) { - subtasks.push(gulp.parallel(buildPhase2.map(file => `${taskPrefix}:${file}`))) - } + if (buildPhase2.length) subtasks.push(gulp.parallel(buildPhase2.map(file => `${taskPrefix}:${file}`))) gulp.task(taskPrefix, gulp.series(subtasks)) } diff --git a/package.json b/package.json index 000a66d161..86acdd5071 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "dapp": "static-server test/e2e/contract-test --port 8080", "dapp-chain": "GANACHE_ARGS='-b 2' concurrently -k -n ganache,dapp -p '[{time}][{name}]' 'yarn ganache:start' 'sleep 5 && static-server test/e2e/contract-test --port 8080'", "watch:test:unit": "nodemon --exec \"yarn test:unit\" ./test ./app ./ui", - "sendwithprivatedapp": "node development/static-server.js test/e2e/send-eth-with-private-key-test --port 8080", + "sendwithprivatedapp": "static-server test/e2e/send-eth-with-private-key-test --port 8080", "test:unit": "cross-env METAMASK_ENV=test mocha --exit --require test/setup.js --recursive \"test/unit/**/*.js\" \"ui/app/**/*.test.js\"", "test:unit:global": "mocha test/unit-global/*", "test:single": "cross-env METAMASK_ENV=test mocha --require test/helper.js", diff --git a/test/e2e/contract-test/contract.js b/test/e2e/contract-test/contract.js index 6c3941b9de..ebfea34ecd 100644 --- a/test/e2e/contract-test/contract.js +++ b/test/e2e/contract-test/contract.js @@ -1,4 +1,4 @@ -/*global ethereum, MetamaskOnboarding */ +/*global ethereum*/ /* The `piggybankContract` is compiled from: @@ -30,14 +30,8 @@ The `piggybankContract` is compiled from: } */ -const forwarderOrigin = 'http://localhost:9010' - -const isMetaMaskInstalled = () => { - return Boolean(window.ethereum && window.ethereum.isMetaMask) -} - -const initialize = () => { - const onboardButton = document.getElementById('connectButton') +web3.currentProvider.enable().then(() => { + var piggybankContract = web3.eth.contract([{'constant': false, 'inputs': [{'name': 'withdrawAmount', 'type': 'uint256'}], 'name': 'withdraw', 'outputs': [{'name': 'remainingBal', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'owner', 'outputs': [{'name': '', 'type': 'address'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [], 'name': 'deposit', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': true, 'stateMutability': 'payable', 'type': 'function'}, {'inputs': [], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor'}]) const deployButton = document.getElementById('deployButton') const depositButton = document.getElementById('depositButton') const withdrawButton = document.getElementById('withdrawButton') @@ -48,307 +42,200 @@ const initialize = () => { const transferTokensWithoutGas = document.getElementById('transferTokensWithoutGas') const approveTokensWithoutGas = document.getElementById('approveTokensWithoutGas') const signTypedData = document.getElementById('signTypedData') - const signTypedDataResults = document.getElementById('signTypedDataResult') - const getAccountsButton = document.getElementById('getAccounts') - const getAccountsResults = document.getElementById('getAccountsResult') - - const contractStatus = document.getElementById('contractStatus') - const tokenAddress = document.getElementById('tokenAddress') - const networkDiv = document.getElementById('network') - const chainIdDiv = document.getElementById('chainId') - const accountsDiv = document.getElementById('accounts') - - let onboarding - try { - onboarding = new MetamaskOnboarding({ forwarderOrigin }) - } catch (error) { - console.error(error) - } - let accounts - let piggybankContract - const accountButtons = [ - deployButton, - depositButton, - withdrawButton, - sendButton, - createToken, - transferTokens, - approveTokens, - transferTokensWithoutGas, - approveTokensWithoutGas, - ] - - for (const button of accountButtons) { - button.disabled = true - } - - const isMetaMaskConnected = () => accounts && accounts.length > 0 - - const onClickInstall = () => { - onboardButton.innerText = 'Onboarding in progress' - onboardButton.disabled = true - onboarding.startOnboarding() - } - - const onClickConnect = async () => { - await window.ethereum.enable() - } - - const updateButtons = () => { - const accountButtonsDisabled = !isMetaMaskInstalled() || !isMetaMaskConnected() - if (accountButtonsDisabled) { - for (const button of accountButtons) { - button.disabled = true - } - } else { - deployButton.disabled = false - sendButton.disabled = false - createToken.disabled = false - } - - if (!isMetaMaskInstalled()) { - onboardButton.innerText = 'Click here to install MetaMask!' - onboardButton.onclick = onClickInstall - } else if (isMetaMaskConnected()) { - onboardButton.innerText = 'Connected' - onboardButton.disabled = true - if (onboarding) { - onboarding.stopOnboarding() - } - } else { - onboardButton.innerText = 'Connect' - onboardButton.onclick = onClickConnect - } - } - - const initializeAccountButtons = () => { - piggybankContract = web3.eth.contract([{'constant': false, 'inputs': [{'name': 'withdrawAmount', 'type': 'uint256'}], 'name': 'withdraw', 'outputs': [{'name': 'remainingBal', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'owner', 'outputs': [{'name': '', 'type': 'address'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [], 'name': 'deposit', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': true, 'stateMutability': 'payable', 'type': 'function'}, {'inputs': [], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor'}]) - deployButton.onclick = async () => { - contractStatus.innerHTML = 'Deploying' + deployButton.addEventListener('click', async function () { + document.getElementById('contractStatus').innerHTML = 'Deploying' + + var piggybank = await piggybankContract.new( + { + from: web3.eth.accounts[0], + data: '0x608060405234801561001057600080fd5b5033600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000808190555061023b806100686000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632e1a7d4d1461005c5780638da5cb5b1461009d578063d0e30db0146100f4575b600080fd5b34801561006857600080fd5b5061008760048036038101908080359060200190929190505050610112565b6040518082815260200191505060405180910390f35b3480156100a957600080fd5b506100b26101d0565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100fc6101f6565b6040518082815260200191505060405180910390f35b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561017057600080fd5b8160008082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f193505050501580156101c5573d6000803e3d6000fd5b506000549050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60003460008082825401925050819055506000549050905600a165627a7a72305820f237db3ec816a52589d82512117bc85bc08d3537683ffeff9059108caf3e5d400029', + gas: '4700000', + }, function (e, contract) { + if (e) { + throw e + } + if (typeof contract.address !== 'undefined') { + console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash) - const piggybank = await piggybankContract.new( - { - from: accounts[0], - data: '0x608060405234801561001057600080fd5b5033600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000808190555061023b806100686000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632e1a7d4d1461005c5780638da5cb5b1461009d578063d0e30db0146100f4575b600080fd5b34801561006857600080fd5b5061008760048036038101908080359060200190929190505050610112565b6040518082815260200191505060405180910390f35b3480156100a957600080fd5b506100b26101d0565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100fc6101f6565b6040518082815260200191505060405180910390f35b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561017057600080fd5b8160008082825403925050819055503373ffffffffffffffffffffffffffffffffffffffff166108fc839081150290604051600060405180830381858888f193505050501580156101c5573d6000803e3d6000fd5b506000549050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60003460008082825401925050819055506000549050905600a165627a7a72305820f237db3ec816a52589d82512117bc85bc08d3537683ffeff9059108caf3e5d400029', - gas: '4700000', - }, (error, contract) => { - if (error) { - contractStatus.innerHTML = 'Deployment Failed' - throw error - } else if (contract.address === undefined) { - return - } + document.getElementById('contractStatus').innerHTML = 'Deployed' - console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash) - contractStatus.innerHTML = 'Deployed' - depositButton.disabled = false - withdrawButton.disabled = false + depositButton.addEventListener('click', function () { + document.getElementById('contractStatus').innerHTML = 'Deposit initiated' + contract.deposit({ from: web3.eth.accounts[0], value: '0x3782dace9d900000' }, function (result) { + console.log(result) + document.getElementById('contractStatus').innerHTML = 'Deposit completed' + }) + }) - depositButton.onclick = () => { - contractStatus.innerHTML = 'Deposit initiated' - contract.deposit( - { - from: accounts[0], - value: '0x3782dace9d900000', - }, - (result) => { - console.log(result) - contractStatus.innerHTML = 'Deposit completed' - } - ) - } - withdrawButton.onclick = () => { - contract.withdraw( - '0xde0b6b3a7640000', - { from: accounts[0] }, - (result) => { - console.log(result) - contractStatus.innerHTML = 'Withdrawn' - } - ) - } + withdrawButton.addEventListener('click', function () { + contract.withdraw('0xde0b6b3a7640000', { from: web3.eth.accounts[0] }, function (result) { + console.log(result) + document.getElementById('contractStatus').innerHTML = 'Withdrawn' + }) + }) } - ) - console.log(piggybank) - } - - sendButton.onclick = () => { - web3.eth.sendTransaction({ - from: accounts[0], - to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970', - value: '0x29a2241af62c0000', - gas: 21000, - gasPrice: 20000000000, - }, (result) => { - console.log(result) }) - } - - createToken.onclick = async () => { - const _initialAmount = 100 - const _tokenName = 'TST' - const _decimalUnits = 0 - const _tokenSymbol = 'TST' - const humanstandardtokenContract = web3.eth.contract([{'constant': true, 'inputs': [], 'name': 'name', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_spender', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'approve', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'totalSupply', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_from', 'type': 'address'}, {'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'transferFrom', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'decimals', 'outputs': [{'name': '', 'type': 'uint8'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'version', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}], 'name': 'balanceOf', 'outputs': [{'name': 'balance', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'symbol', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'transfer', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_spender', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}, {'name': '_extraData', 'type': 'bytes'}], 'name': 'approveAndCall', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}, {'name': '_spender', 'type': 'address'}], 'name': 'allowance', 'outputs': [{'name': 'remaining', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'name': '_initialAmount', 'type': 'uint256'}, {'name': '_tokenName', 'type': 'string'}, {'name': '_decimalUnits', 'type': 'uint8'}, {'name': '_tokenSymbol', 'type': 'string'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'payable': false, 'stateMutability': 'nonpayable', 'type': 'fallback'}, {'anonymous': false, 'inputs': [{'indexed': true, 'name': '_from', 'type': 'address'}, {'indexed': true, 'name': '_to', 'type': 'address'}, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Transfer', 'type': 'event'}, {'anonymous': false, 'inputs': [{'indexed': true, 'name': '_owner', 'type': 'address'}, {'indexed': true, 'name': '_spender', 'type': 'address'}, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Approval', 'type': 'event'}]) - - return humanstandardtokenContract.new( - _initialAmount, - _tokenName, - _decimalUnits, - _tokenSymbol, - { - from: accounts[0], - data: '0x60806040523480156200001157600080fd5b506040516200156638038062001566833981018060405260808110156200003757600080fd5b8101908080516401000000008111156200005057600080fd5b828101905060208101848111156200006757600080fd5b81518560018202830111640100000000821117156200008557600080fd5b50509291906020018051640100000000811115620000a257600080fd5b82810190506020810184811115620000b957600080fd5b8151856001820283011164010000000082111715620000d757600080fd5b5050929190602001805190602001909291908051906020019092919050505083838382600390805190602001906200011192919062000305565b5081600490805190602001906200012a92919062000305565b5080600560006101000a81548160ff021916908360ff1602179055505050506200016433826200016e640100000000026401000000009004565b50505050620003b4565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515620001ab57600080fd5b620001d081600254620002e36401000000000262001155179091906401000000009004565b60028190555062000237816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054620002e36401000000000262001155179091906401000000009004565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b6000808284019050838110151515620002fb57600080fd5b8091505092915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200034857805160ff191683800117855562000379565b8280016001018555821562000379579182015b82811115620003785782518255916020019190600101906200035b565b5b5090506200038891906200038c565b5090565b620003b191905b80821115620003ad57600081600090555060010162000393565b5090565b90565b6111a280620003c46000396000f3fe6080604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014457806318160ddd146101b757806323b872dd146101e2578063313ce5671461027557806339509351146102a657806370a082311461031957806395d89b411461037e578063a457c2d71461040e578063a9059cbb14610481578063dd62ed3e146104f4575b600080fd5b3480156100c057600080fd5b506100c9610579565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101095780820151818401526020810190506100ee565b50505050905090810190601f1680156101365780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561015057600080fd5b5061019d6004803603604081101561016757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061061b565b604051808215151515815260200191505060405180910390f35b3480156101c357600080fd5b506101cc610748565b6040518082815260200191505060405180910390f35b3480156101ee57600080fd5b5061025b6004803603606081101561020557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610752565b604051808215151515815260200191505060405180910390f35b34801561028157600080fd5b5061028a61095a565b604051808260ff1660ff16815260200191505060405180910390f35b3480156102b257600080fd5b506102ff600480360360408110156102c957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610971565b604051808215151515815260200191505060405180910390f35b34801561032557600080fd5b506103686004803603602081101561033c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ba8565b6040518082815260200191505060405180910390f35b34801561038a57600080fd5b50610393610bf0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103d35780820151818401526020810190506103b8565b50505050905090810190601f1680156104005780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561041a57600080fd5b506104676004803603604081101561043157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c92565b604051808215151515815260200191505060405180910390f35b34801561048d57600080fd5b506104da600480360360408110156104a457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610ec9565b604051808215151515815260200191505060405180910390f35b34801561050057600080fd5b506105636004803603604081101561051757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ee0565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156106115780601f106105e657610100808354040283529160200191610611565b820191906000526020600020905b8154815290600101906020018083116105f457829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561065857600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600254905090565b60006107e382600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061086e848484610f89565b3373ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a3600190509392505050565b6000600560009054906101000a900460ff16905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141515156109ae57600080fd5b610a3d82600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461115590919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610c885780601f10610c5d57610100808354040283529160200191610c88565b820191906000526020600020905b815481529060010190602001808311610c6b57829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610ccf57600080fd5b610d5e82600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000610ed6338484610f89565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b6000828211151515610f7857600080fd5b600082840390508091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515610fc557600080fd5b611016816000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506110a9816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461115590919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b600080828401905083811015151561116c57600080fd5b809150509291505056fea165627a7a723058205fcdfea06f4d97b442bc9f444b1e92524bc66398eb4f37ed5a99f2093a8842640029000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000186a00000000000000000000000000000000000000000000000000000000000000003545354000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035453540000000000000000000000000000000000000000000000000000000000', - gas: '4700000', - gasPrice: '20000000000', - }, (error, contract) => { - if (error) { - tokenAddress.innerHTML = 'Creation Failed' - throw error - } else if (contract.address === undefined) { - return - } + console.log(piggybank) + }) + + sendButton.addEventListener('click', function () { + web3.eth.sendTransaction({ + from: web3.eth.accounts[0], + to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970', + value: '0x29a2241af62c0000', + gas: 21000, + gasPrice: 20000000000, + }, (result) => { + console.log(result) + }) + }) + + + createToken.addEventListener('click', async function () { + var _initialAmount = 100 + var _tokenName = 'TST' + var _decimalUnits = 0 + var _tokenSymbol = 'TST' + var humanstandardtokenContract = web3.eth.contract([{'constant': true, 'inputs': [], 'name': 'name', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_spender', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'approve', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'totalSupply', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_from', 'type': 'address'}, {'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'transferFrom', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'decimals', 'outputs': [{'name': '', 'type': 'uint8'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'version', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}], 'name': 'balanceOf', 'outputs': [{'name': 'balance', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': true, 'inputs': [], 'name': 'symbol', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'transfer', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': false, 'inputs': [{'name': '_spender', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}, {'name': '_extraData', 'type': 'bytes'}], 'name': 'approveAndCall', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}, {'name': '_spender', 'type': 'address'}], 'name': 'allowance', 'outputs': [{'name': 'remaining', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function'}, {'inputs': [{'name': '_initialAmount', 'type': 'uint256'}, {'name': '_tokenName', 'type': 'string'}, {'name': '_decimalUnits', 'type': 'uint8'}, {'name': '_tokenSymbol', 'type': 'string'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'payable': false, 'stateMutability': 'nonpayable', 'type': 'fallback'}, {'anonymous': false, 'inputs': [{'indexed': true, 'name': '_from', 'type': 'address'}, {'indexed': true, 'name': '_to', 'type': 'address'}, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Transfer', 'type': 'event'}, {'anonymous': false, 'inputs': [{'indexed': true, 'name': '_owner', 'type': 'address'}, {'indexed': true, 'name': '_spender', 'type': 'address'}, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Approval', 'type': 'event'}]) + return humanstandardtokenContract.new( + _initialAmount, + _tokenName, + _decimalUnits, + _tokenSymbol, + { + from: web3.eth.accounts[0], + data: '0x60806040523480156200001157600080fd5b506040516200156638038062001566833981018060405260808110156200003757600080fd5b8101908080516401000000008111156200005057600080fd5b828101905060208101848111156200006757600080fd5b81518560018202830111640100000000821117156200008557600080fd5b50509291906020018051640100000000811115620000a257600080fd5b82810190506020810184811115620000b957600080fd5b8151856001820283011164010000000082111715620000d757600080fd5b5050929190602001805190602001909291908051906020019092919050505083838382600390805190602001906200011192919062000305565b5081600490805190602001906200012a92919062000305565b5080600560006101000a81548160ff021916908360ff1602179055505050506200016433826200016e640100000000026401000000009004565b50505050620003b4565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515620001ab57600080fd5b620001d081600254620002e36401000000000262001155179091906401000000009004565b60028190555062000237816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054620002e36401000000000262001155179091906401000000009004565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b6000808284019050838110151515620002fb57600080fd5b8091505092915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200034857805160ff191683800117855562000379565b8280016001018555821562000379579182015b82811115620003785782518255916020019190600101906200035b565b5b5090506200038891906200038c565b5090565b620003b191905b80821115620003ad57600081600090555060010162000393565b5090565b90565b6111a280620003c46000396000f3fe6080604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014457806318160ddd146101b757806323b872dd146101e2578063313ce5671461027557806339509351146102a657806370a082311461031957806395d89b411461037e578063a457c2d71461040e578063a9059cbb14610481578063dd62ed3e146104f4575b600080fd5b3480156100c057600080fd5b506100c9610579565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101095780820151818401526020810190506100ee565b50505050905090810190601f1680156101365780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561015057600080fd5b5061019d6004803603604081101561016757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061061b565b604051808215151515815260200191505060405180910390f35b3480156101c357600080fd5b506101cc610748565b6040518082815260200191505060405180910390f35b3480156101ee57600080fd5b5061025b6004803603606081101561020557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610752565b604051808215151515815260200191505060405180910390f35b34801561028157600080fd5b5061028a61095a565b604051808260ff1660ff16815260200191505060405180910390f35b3480156102b257600080fd5b506102ff600480360360408110156102c957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610971565b604051808215151515815260200191505060405180910390f35b34801561032557600080fd5b506103686004803603602081101561033c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ba8565b6040518082815260200191505060405180910390f35b34801561038a57600080fd5b50610393610bf0565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103d35780820151818401526020810190506103b8565b50505050905090810190601f1680156104005780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561041a57600080fd5b506104676004803603604081101561043157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c92565b604051808215151515815260200191505060405180910390f35b34801561048d57600080fd5b506104da600480360360408110156104a457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610ec9565b604051808215151515815260200191505060405180910390f35b34801561050057600080fd5b506105636004803603604081101561051757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ee0565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156106115780601f106105e657610100808354040283529160200191610611565b820191906000526020600020905b8154815290600101906020018083116105f457829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561065857600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600254905090565b60006107e382600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061086e848484610f89565b3373ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a3600190509392505050565b6000600560009054906101000a900460ff16905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141515156109ae57600080fd5b610a3d82600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461115590919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610c885780601f10610c5d57610100808354040283529160200191610c88565b820191906000526020600020905b815481529060010190602001808311610c6b57829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610ccf57600080fd5b610d5e82600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000610ed6338484610f89565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b6000828211151515610f7857600080fd5b600082840390508091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515610fc557600080fd5b611016816000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f6790919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506110a9816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461115590919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b600080828401905083811015151561116c57600080fd5b809150509291505056fea165627a7a723058205fcdfea06f4d97b442bc9f444b1e92524bc66398eb4f37ed5a99f2093a8842640029000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000186a00000000000000000000000000000000000000000000000000000000000000003545354000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035453540000000000000000000000000000000000000000000000000000000000', + gas: '4700000', + gasPrice: '20000000000', + }, function (e, contract) { + console.log(e, contract) + if (typeof contract.address !== 'undefined') { console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash) - tokenAddress.innerHTML = contract.address - transferTokens.disabled = false - approveTokens.disabled = false - transferTokensWithoutGas.disabled = false - approveTokensWithoutGas.disabled = false - transferTokens.onclick = (event) => { + document.getElementById('tokenAddress').innerHTML = contract.address + + transferTokens.addEventListener('click', function (event) { console.log(`event`, event) contract.transfer('0x2f318C334780961FB129D2a6c30D0763d9a5C970', '15000', { - from: accounts[0], + from: web3.eth.accounts[0], to: contract.address, data: '0xa9059cbb0000000000000000000000002f318c334780961fb129d2a6c30d0763d9a5c9700000000000000000000000000000000000000000000000000000000000003a98', gas: 60000, gasPrice: '20000000000', - }, (result) => { + }, function (result) { console.log('result', result) }) - } + }) - approveTokens.onclick = () => { + approveTokens.addEventListener('click', function () { contract.approve('0x9bc5baF874d2DA8D216aE9f137804184EE5AfEF4', '70000', { - from: accounts[0], + from: web3.eth.accounts[0], to: contract.address, data: '0x095ea7b30000000000000000000000009bc5baF874d2DA8D216aE9f137804184EE5AfEF40000000000000000000000000000000000000000000000000000000000000005', gas: 60000, gasPrice: '20000000000', - }, (result) => { + }, function (result) { console.log(result) }) - } + }) - transferTokensWithoutGas.onclick = (event) => { + transferTokensWithoutGas.addEventListener('click', function (event) { console.log(`event`, event) contract.transfer('0x2f318C334780961FB129D2a6c30D0763d9a5C970', '15000', { - from: accounts[0], + from: web3.eth.accounts[0], to: contract.address, data: '0xa9059cbb0000000000000000000000002f318c334780961fb129d2a6c30d0763d9a5c9700000000000000000000000000000000000000000000000000000000000003a98', gasPrice: '20000000000', - }, (result) => { + }, function (result) { console.log('result', result) }) - } + }) - approveTokensWithoutGas.onclick = () => { + approveTokensWithoutGas.addEventListener('click', function () { contract.approve('0x2f318C334780961FB129D2a6c30D0763d9a5C970', '70000', { - from: accounts[0], + from: web3.eth.accounts[0], to: contract.address, data: '0x095ea7b30000000000000000000000002f318C334780961FB129D2a6c30D0763d9a5C9700000000000000000000000000000000000000000000000000000000000000005', gasPrice: '20000000000', - }, (result) => { + }, function (result) { console.log(result) }) - } - } - ) - } - - signTypedData.addEventListener('click', () => { - const typedData = { - types: { - EIP712Domain: [ - { name: 'name', type: 'string' }, - { name: 'version', type: 'string' }, - { name: 'chainId', type: 'uint256' }, - { name: 'verifyingContract', type: 'address' }, - ], - Person: [ - { name: 'name', type: 'string' }, - { name: 'wallet', type: 'address' }, - ], - Mail: [ - { name: 'from', type: 'Person' }, - { name: 'to', type: 'Person' }, - { name: 'contents', type: 'string' }, - ], - }, - primaryType: 'Mail', - domain: { - name: 'Ether Mail', - version: '1', - chainId: 3, - verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', - }, - message: { - sender: { - name: 'Cow', - wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', - }, - recipient: { - name: 'Bob', - wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', - }, - contents: 'Hello, Bob!', - }, - } - web3.currentProvider.sendAsync({ - method: 'eth_signTypedData_v3', - params: [ethereum.selectedAddress, JSON.stringify(typedData)], - from: ethereum.selectedAddress, - }, (err, result) => { - if (err) { - console.log(err) - } else { - signTypedDataResults.innerHTML = result + }) } }) - }) - getAccountsButton.addEventListener('click', async () => { - try { - const accounts = await ethereum.send({ method: 'eth_accounts' }) - getAccountsResults.innerHTML = accounts[0] || 'Not able to get accounts' - } catch (error) { - console.error(error) - getAccountsResults.innerHTML = `Error: ${error}` - } - }) + }) - } + ethereum.autoRefreshOnNetworkChange = false - updateButtons() - if (isMetaMaskInstalled()) { - ethereum.autoRefreshOnNetworkChange = false - ethereum.on('networkChanged', (networkId) => { - networkDiv.innerHTML = networkId - }) - ethereum.on('chainIdChanged', (chainId) => { - chainIdDiv.innerHTML = chainId - }) - ethereum.on('accountsChanged', (newAccounts) => { - const connecting = Boolean((!accounts || !accounts.length) && newAccounts && newAccounts.length) - accounts = newAccounts - accountsDiv.innerHTML = accounts - if (connecting) { - initializeAccountButtons() + const networkDiv = document.getElementById('network') + const chainIdDiv = document.getElementById('chainId') + const accountsDiv = document.getElementById('accounts') + + ethereum.on('networkChanged', (networkId) => { + networkDiv.innerHTML = networkId + }) + + ethereum.on('chainIdChanged', (chainId) => { + chainIdDiv.innerHTML = chainId + }) + + ethereum.on('accountsChanged', (accounts) => { + accountsDiv.innerHTML = accounts + }) + + const signTypedDataResultsDiv = document.getElementById('signTypedDataResult') + signTypedData.addEventListener('click', function () { + + const typedData = { + types: { + EIP712Domain: [ + { name: 'name', type: 'string' }, + { name: 'version', type: 'string' }, + { name: 'chainId', type: 'uint256' }, + { name: 'verifyingContract', type: 'address' }, + ], + Person: [ + { name: 'name', type: 'string' }, + { name: 'wallet', type: 'address' }, + ], + Mail: [ + { name: 'from', type: 'Person' }, + { name: 'to', type: 'Person' }, + { name: 'contents', type: 'string' }, + ], + }, + primaryType: 'Mail', + domain: { + name: 'Ether Mail', + version: '1', + chainId: 3, + verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', + }, + message: { + sender: { + name: 'Cow', + wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', + }, + recipient: { + name: 'Bob', + wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', + }, + contents: 'Hello, Bob!', + }, + } + web3.currentProvider.sendAsync({ + method: 'eth_signTypedData_v3', + params: [ethereum.selectedAddress, JSON.stringify(typedData)], + from: ethereum.selectedAddress, + }, function (err, result) { + if (err) { + console.log(err) + } else { + signTypedDataResultsDiv.innerHTML = result } - updateButtons() }) - } -} -window.addEventListener('DOMContentLoaded', initialize) + }) +}) diff --git a/test/e2e/contract-test/index.html b/test/e2e/contract-test/index.html index 7655b87866..9689654ee0 100644 --- a/test/e2e/contract-test/index.html +++ b/test/e2e/contract-test/index.html @@ -1,69 +1,51 @@ - E2E Test Dapp - - - - E2E Test Dapp - - - - Connect - Connect - - - Contract - - Deploy Contract - Deposit - Withdraw - - - Contract Status: Not clicked - - - - Send Eth + + Contract + + Deploy Contract + Deposit + Withdraw + + + Not clicked + + + + Send eth + Send - - - Send Tokens - - Token: - - - Create Token - Transfer Tokens - Approve Tokens - Transfer Tokens Without Gas - Approve Tokens Without Gas - - - - Get Accounts - eth_accounts - - - - Status - - Network: - - - ChainId: - - - Accounts: - - - - Sign Typed Data + + + + Send tokens + + + Create Token + Transfer Tokens + Approve Tokens + Transfer Tokens Without Gas + Approve Tokens Without Gas + + + + Network: + ChainId: + Accounts: + + + + Sign Typed Data + Sign - Sign Typed Data Result: - - + Sign Typed Data Result: + + + + - + +