From ad7d38c0dc206074379c813b307ed9350c7efeb0 Mon Sep 17 00:00:00 2001 From: Jakub Stasiak Date: Wed, 11 Apr 2018 18:32:27 +0200 Subject: Update: allow other extension to connect --- app/scripts/background.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/background.js b/app/scripts/background.js index 6550e8944..6296eaa21 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -197,6 +197,7 @@ function setupController (initState, initLangCode) { // connect to other contexts // extension.runtime.onConnect.addListener(connectRemote) + extension.runtime.onConnectExternal.addListener(connectExternal) const metamaskInternalProcessHash = { [ENVIRONMENT_TYPE_POPUP]: true, @@ -211,9 +212,9 @@ function setupController (initState, initLangCode) { function connectRemote (remotePort) { const processName = remotePort.name const isMetaMaskInternalProcess = metamaskInternalProcessHash[processName] - const portStream = new PortStream(remotePort) if (isMetaMaskInternalProcess) { + const portStream = new PortStream(remotePort) // communication with popup controller.isClientOpen = true controller.setupTrustedCommunication(portStream, 'MetaMask') @@ -246,12 +247,17 @@ function setupController (initState, initLangCode) { }) } } else { - // communication with page - const originDomain = urlUtil.parse(remotePort.sender.url).hostname - controller.setupUntrustedCommunication(portStream, originDomain) + connectExternal(remotePort) } } + // communication with page or other extension + function connectExternal(remotePort) { + const originDomain = urlUtil.parse(remotePort.sender.url).hostname + const portStream = new PortStream(remotePort) + controller.setupUntrustedCommunication(portStream, originDomain) + } + // // User Interface setup // -- cgit From ce2834400ca202d5767c3d896407ac565fadfc14 Mon Sep 17 00:00:00 2001 From: bitpshr Date: Mon, 14 May 2018 08:33:47 -0400 Subject: Add new json-rpc-engine middleware for improved error handling --- app/scripts/lib/createErrorMiddleware.js | 66 ++++++++++++++++++++++++++++++++ app/scripts/lib/inpage-provider.js | 2 + 2 files changed, 68 insertions(+) create mode 100644 app/scripts/lib/createErrorMiddleware.js (limited to 'app/scripts') diff --git a/app/scripts/lib/createErrorMiddleware.js b/app/scripts/lib/createErrorMiddleware.js new file mode 100644 index 000000000..baed99e45 --- /dev/null +++ b/app/scripts/lib/createErrorMiddleware.js @@ -0,0 +1,66 @@ +const log = require('loglevel') + +/** + * JSON-RPC error object + * + * @typedef {Object} RpcError + * @property {number} code - Indicates the error type that occurred + * @property {Object} [data] - Contains additional information about the error + * @property {string} [message] - Short description of the error + */ + +/** + * Middleware configuration object + * + * @typedef {Object} MiddlewareConfig + * @property {boolean} [override] - Use RPC_ERRORS message in place of provider message + */ + +/** + * Map of standard and non-standard RPC error codes to messages + */ +const RPC_ERRORS = { + 1: 'An unauthorized action was attempted.', + 2: 'A disallowed action was attempted.', + 3: 'An execution error occurred.', + [-32600]: 'The JSON sent is not a valid Request object.', + [-32601]: 'The method does not exist / is not available.', + [-32602]: 'Invalid method parameter(s).', + [-32603]: 'Internal JSON-RPC error.', + [-32700]: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.', + internal: 'Internal server error.', + unknown: 'Unknown JSON-RPC error.', +} + +/** + * Modifies a JSON-RPC error object in-place to add a human-readable message, + * optionally overriding any provider-supplied message + * + * @param {RpcError} error - JSON-RPC error object + * @param {boolean} override - Use RPC_ERRORS message in place of provider message + */ +function sanitizeRPCError (error, override) { + if (error.message && !override) { return error } + const message = error.code > -31099 && error.code < -32100 ? RPC_ERRORS.internal : RPC_ERRORS[error.code] + error.message = message || RPC_ERRORS.unknown +} + +/** + * json-rpc-engine middleware that both logs standard and non-standard error + * messages and ends middleware stack traversal if an error is encountered + * + * @param {MiddlewareConfig} [config={override:true}] - Middleware configuration + * @returns {Function} json-rpc-engine middleware function + */ +function createErrorMiddleware ({ override = true } = {}) { + return (req, res, next) => { + next(done => { + const { error } = res + if (!error) { return done() } + sanitizeRPCError(error) + log.error(`MetaMask - RPC Error: ${error.message}`, error) + }) + } +} + +module.exports = createErrorMiddleware \ No newline at end of file diff --git a/app/scripts/lib/inpage-provider.js b/app/scripts/lib/inpage-provider.js index 99cc5d2cf..4e65f0a23 100644 --- a/app/scripts/lib/inpage-provider.js +++ b/app/scripts/lib/inpage-provider.js @@ -1,5 +1,6 @@ const pump = require('pump') const RpcEngine = require('json-rpc-engine') +const createErrorMiddleware = require('./createErrorMiddleware') const createIdRemapMiddleware = require('json-rpc-engine/src/idRemapMiddleware') const createStreamMiddleware = require('json-rpc-middleware-stream') const LocalStorageStore = require('obs-store') @@ -44,6 +45,7 @@ function MetamaskInpageProvider (connectionStream) { // handle sendAsync requests via dapp-side rpc engine const rpcEngine = new RpcEngine() rpcEngine.push(createIdRemapMiddleware()) + rpcEngine.push(createErrorMiddleware()) rpcEngine.push(streamMiddleware) self.rpcEngine = rpcEngine } -- cgit From 924cc1fcf7de1896ac09bbe7a400d5ff5df0b50d Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Thu, 19 Apr 2018 01:03:51 -0230 Subject: Move setAccountLabel into PreferencesController --- app/scripts/controllers/preferences.js | 20 ++++++++++++++++++-- app/scripts/metamask-controller.js | 2 +- 2 files changed, 19 insertions(+), 3 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 1d3308d36..55416d15f 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -27,6 +27,7 @@ class PreferencesController { useBlockie: false, featureFlags: {}, currentLocale: opts.initLangCode, + identities: {}, }, opts.initState) this.store = new ObservableStore(initState) } @@ -155,6 +156,21 @@ class PreferencesController { return this.store.getState().tokens } + /** + * Sets a custom label for an account + * @param {string} account the account to set a label for + * @param {string} label the custom label for the account + * @return {Promise} + */ + setAccountLabel (account, label) { + const address = normalizeAddress(account) + const {identities} = this.store.getState() + identities[address] = identities[address] || {} + identities[address].name = label + this.store.updateState({ identities }) + return Promise.resolve(label) + } + /** * Gets an updated rpc list from this.addToFrequentRpcList() and sets the `frequentRpcList` to this update list. * @@ -189,8 +205,8 @@ class PreferencesController { * The returned list will have a max length of 2. If the _url currently exists it the list, it will be moved to the * end of the list. The current list is modified and returned as a promise. * - * @param {string} _url The rpc url to add to the frequentRpcList. - * @returns {Promise} The updated frequentRpcList. + * @param {string} _url The rpc url to add to the frequentRpcList. + * @returns {Promise} The updated frequentRpcList. * */ addToFrequentRpcList (_url) { diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index a6b5d3453..4dcec8ef7 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -363,6 +363,7 @@ module.exports = class MetamaskController extends EventEmitter { addToken: nodeify(preferencesController.addToken, preferencesController), removeToken: nodeify(preferencesController.removeToken, preferencesController), setCurrentAccountTab: nodeify(preferencesController.setCurrentAccountTab, preferencesController), + setAccountLabel: nodeify(preferencesController.setAccountLabel, preferencesController), setFeatureFlag: nodeify(preferencesController.setFeatureFlag, preferencesController), // AddressController @@ -373,7 +374,6 @@ module.exports = class MetamaskController extends EventEmitter { createNewVaultAndKeychain: nodeify(this.createNewVaultAndKeychain, this), createNewVaultAndRestore: nodeify(this.createNewVaultAndRestore, this), addNewKeyring: nodeify(keyringController.addNewKeyring, keyringController), - saveAccountLabel: nodeify(keyringController.saveAccountLabel, keyringController), exportAccount: nodeify(keyringController.exportAccount, keyringController), // txController -- cgit From cbe4d0d88c83ee1d8dd8efde537ee753bf19596a Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Thu, 19 Apr 2018 01:03:51 -0230 Subject: Update AddressBookController to read from preferences store --- app/scripts/controllers/address-book.js | 27 ++++++--------------------- app/scripts/metamask-controller.js | 3 ++- 2 files changed, 8 insertions(+), 22 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/address-book.js b/app/scripts/controllers/address-book.js index c91e6b2e4..4697e074c 100644 --- a/app/scripts/controllers/address-book.js +++ b/app/scripts/controllers/address-book.js @@ -13,19 +13,17 @@ class AddressBookController { * @param {object} opts Overrides the defaults for the initial state of this.store * @property {array} opts.initState initializes the the state of the AddressBookController. Can contain an * addressBook property to initialize the addressBook array - * @param {KeyringController} keyringController (Soon to be deprecated) The keyringController used in the current - * MetamaskController. Contains the identities used in this AddressBookController. + * @property {object} opts.preferencesStore the {@code PreferencesController} store * @property {object} store The the store of the current users address book * @property {array} store.addressBook An array of addresses and nicknames. These are set by the user when sending * to a new address. * */ - constructor (opts = {}, keyringController) { - const initState = extend({ + constructor ({initState, preferencesStore}) { + this.store = new ObservableStore(extend({ addressBook: [], - }, opts.initState) - this.store = new ObservableStore(initState) - this.keyringController = keyringController + }, initState)) + this._preferencesStore = preferencesStore } // @@ -62,7 +60,7 @@ class AddressBookController { */ _addToAddressBook (address, name) { const addressBook = this._getAddressBook() - const identities = this._getIdentities() + const {identities} = this._preferencesStore.getState() const addressBookIndex = addressBook.findIndex((element) => { return element.address.toLowerCase() === address.toLowerCase() || element.name === name }) const identitiesIndex = Object.keys(identities).findIndex((element) => { return element.toLowerCase() === address.toLowerCase() }) @@ -95,19 +93,6 @@ class AddressBookController { _getAddressBook () { return this.store.getState().addressBook } - - /** - * Retrieves identities from the keyring controller in order to avoid - * duplication - * - * @deprecated - * @returns {array} Returns the identies array from the keyringContoller's state - * - */ - _getIdentities () { - return this.keyringController.memStore.getState().identities - } - } module.exports = AddressBookController diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 4dcec8ef7..06ee6c47a 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -144,7 +144,8 @@ module.exports = class MetamaskController extends EventEmitter { // address book controller this.addressBookController = new AddressBookController({ initState: initState.AddressBookController, - }, this.keyringController) + preferencesStore: this.preferencesController.store, + }) // tx mgmt this.txController = new TransactionController({ -- cgit From c54e4c719110c2033b7cc3757676f97ad3329d42 Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Thu, 19 Apr 2018 01:03:51 -0230 Subject: Add PreferencesController#setAddresses to update ids --- app/scripts/controllers/preferences.js | 10 ++++++++++ app/scripts/metamask-controller.js | 20 ++++++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 55416d15f..a4ff1207e 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -63,6 +63,16 @@ class PreferencesController { this.store.updateState({ currentLocale: key }) } + setAddresses (addresses) { + const oldIdentities = this.store.getState().identities + const identities = addresses.reduce((ids, address, index) => { + const oldId = oldIdentities[address] || {} + ids[address] = {name: `Account ${index + 1}`, address, ...oldId} + return ids + }, {}) + this.store.updateState({ identities }) + } + /** * Setter for the `selectedAddress` property * diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 06ee6c47a..807c9a0b9 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -434,7 +434,9 @@ module.exports = class MetamaskController extends EventEmitter { } else { vault = await this.keyringController.createNewVaultAndKeychain(password) - this.selectFirstIdentity(vault) + const accounts = await this.keyringController.getAccounts() + this.preferencesController.setAddresses(accounts) + this.selectFirstIdentity() } release() } catch (err) { @@ -454,7 +456,9 @@ module.exports = class MetamaskController extends EventEmitter { const release = await this.createVaultMutex.acquire() try { const vault = await this.keyringController.createNewVaultAndRestore(password, seed) - this.selectFirstIdentity(vault) + const accounts = await this.keyringController.getAccounts() + this.preferencesController.setAddresses(accounts) + this.selectFirstIdentity() release() return vault } catch (err) { @@ -472,12 +476,10 @@ module.exports = class MetamaskController extends EventEmitter { */ /** - * Retrieves the first Identiy from the passed Vault and selects the related address - * - * @param {} vault + * Sets the first address in the state to the selected address */ - selectFirstIdentity (vault) { - const { identities } = vault + selectFirstIdentity () { + const { identities } = this.preferencesController.store.getState() const address = Object.keys(identities)[0] this.preferencesController.setSelectedAddress(address) } @@ -503,13 +505,15 @@ module.exports = class MetamaskController extends EventEmitter { await this.verifySeedPhrase() + this.preferencesController.setAddresses(newAccounts) newAccounts.forEach((address) => { if (!oldAccounts.includes(address)) { this.preferencesController.setSelectedAddress(address) } }) - return keyState + const {identities} = this.preferencesController.store.getState() + return {...keyState, identities} } /** -- cgit From 2d13fac476cfbb7b0140611dca00fa95ee8d91ab Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Thu, 19 Apr 2018 01:03:51 -0230 Subject: Add migration to move identities from KeyringController --- app/scripts/migrations/026.js | 40 ++++++++++++++++++++++++++++++++++++++++ app/scripts/migrations/index.js | 1 + 2 files changed, 41 insertions(+) create mode 100644 app/scripts/migrations/026.js (limited to 'app/scripts') diff --git a/app/scripts/migrations/026.js b/app/scripts/migrations/026.js new file mode 100644 index 000000000..ef0ed0542 --- /dev/null +++ b/app/scripts/migrations/026.js @@ -0,0 +1,40 @@ +const version = 26 + +/* + +This migration moves the identities stored in the KeyringController + into the PreferencesController + +*/ + +const clone = require('clone') + +module.exports = { + version, + migrate (originalVersionedData) { + const versionedData = clone(originalVersionedData) + versionedData.meta.version = version + try { + const state = versionedData.data + versionedData.data = transformState(state) + } catch (err) { + console.warn(`MetaMask Migration #${version}` + err.stack) + return Promise.reject(err) + } + return Promise.resolve(versionedData) + }, +} + +function transformState (state) { + if (!state.KeyringController || !state.PreferencesController) { + return + } + + if (!state.KeyringController.walletNicknames) { + return state + } + + state.PreferencesController.identities = state.KeyringController.walletNicknames + delete state.KeyringController.walletNicknames + return state +} diff --git a/app/scripts/migrations/index.js b/app/scripts/migrations/index.js index 6c4a51b32..04d90bfff 100644 --- a/app/scripts/migrations/index.js +++ b/app/scripts/migrations/index.js @@ -36,4 +36,5 @@ module.exports = [ require('./023'), require('./024'), require('./025'), + require('./026'), ] -- cgit From 67310e151ea75c7aa4fc00bfd63bf41cd4f2db51 Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Thu, 17 May 2018 13:35:38 -0230 Subject: Fix migration 026 to produce the correct shape for state.identities --- app/scripts/migrations/026.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/migrations/026.js b/app/scripts/migrations/026.js index ef0ed0542..1b8a91a45 100644 --- a/app/scripts/migrations/026.js +++ b/app/scripts/migrations/026.js @@ -34,7 +34,14 @@ function transformState (state) { return state } - state.PreferencesController.identities = state.KeyringController.walletNicknames + state.PreferencesController.identities = Object.keys(state.KeyringController.walletNicknames) + .reduce((identities, address) => { + identities[address] = { + name: state.KeyringController.walletNicknames[address], + address, + } + return identities + }, {}) delete state.KeyringController.walletNicknames return state } -- cgit From 41502cb38495125bd99efa042f0759a45ac16e6b Mon Sep 17 00:00:00 2001 From: simon Date: Fri, 18 May 2018 15:43:27 +0200 Subject: Added adyen.com to blacklisted domains because postMessages are blocking card encryption --- app/scripts/contentscript.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index ddf1a9432..bf82205c1 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -166,7 +166,7 @@ function documentElementCheck () { /** * Checks if the current domain is blacklisted - * + * * @returns {boolean} {@code true} if the current domain is blacklisted */ function blacklistedDomainCheck () { @@ -175,6 +175,7 @@ function blacklistedDomainCheck () { 'dropbox.com', 'webbyawards.com', 'cdn.shopify.com/s/javascripts/tricorder/xtld-read-only-frame.html', + 'adyen.com' ] var currentUrl = window.location.href var currentRegex -- cgit From 22753d96fd87b7bef8f30c1f778935e7ae39b492 Mon Sep 17 00:00:00 2001 From: simon Date: Fri, 18 May 2018 16:11:46 +0200 Subject: Added trailing comma for eslint --- app/scripts/contentscript.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index bf82205c1..555902ddf 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -175,7 +175,7 @@ function blacklistedDomainCheck () { 'dropbox.com', 'webbyawards.com', 'cdn.shopify.com/s/javascripts/tricorder/xtld-read-only-frame.html', - 'adyen.com' + 'adyen.com', ] var currentUrl = window.location.href var currentRegex -- cgit From 2d4d77b17d0494182c3dc70c3d5bf9a866d384a9 Mon Sep 17 00:00:00 2001 From: kumavis Date: Fri, 18 May 2018 11:52:28 -0700 Subject: docs - jsdoc - fix syntax --- app/scripts/background.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/background.js b/app/scripts/background.js index 69d549c85..686296329 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -322,7 +322,7 @@ function setupController (initState, initLangCode) { /** * A runtime.Port object, as provided by the browser: - * @link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port + * @see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port * @typedef Port * @type Object */ -- cgit From e8b2e11c5624d80f535c1344d9c9be48627b1319 Mon Sep 17 00:00:00 2001 From: Frankie Date: Mon, 21 May 2018 16:00:44 -0700 Subject: Reveal get filtered tx list (#4332) * add getFilteredTxList from txController to getApi * transactions - remove dead code (isNonceTaken) --- app/scripts/controllers/transactions/index.js | 15 --------------- app/scripts/metamask-controller.js | 2 +- 2 files changed, 1 insertion(+), 16 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 3886db104..541f1db73 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -111,21 +111,6 @@ class TransactionController extends EventEmitter { this.txStateManager.wipeTransactions(address) } - /** - Check if a txMeta in the list with the same nonce has been confirmed in a block - if the txParams dont have a nonce will return false - @returns {boolean} whether the nonce has been used in a transaction confirmed in a block - @param {object} txMeta - the txMeta object - */ - async isNonceTaken (txMeta) { - const { from, nonce } = txMeta.txParams - if ('nonce' in txMeta.txParams) { - const sameNonceTxList = this.txStateManager.getFilteredTxList({from, nonce, status: 'confirmed'}) - return (sameNonceTxList.length >= 1) - } - return false - } - /** add a new unapproved transaction to the pipeline diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 807c9a0b9..1b1d26886 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -382,7 +382,7 @@ module.exports = class MetamaskController extends EventEmitter { updateTransaction: nodeify(txController.updateTransaction, txController), updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController), retryTransaction: nodeify(this.retryTransaction, this), - isNonceTaken: nodeify(txController.isNonceTaken, txController), + getFilteredTxList: nodeify(txController.getFilteredTxList, txController), // messageManager signMessage: nodeify(this.signMessage, this), -- cgit From fa37ba39927e5e8a28a98f72a9208170ff0f2900 Mon Sep 17 00:00:00 2001 From: kumavis Date: Tue, 22 May 2018 01:58:36 -0700 Subject: controllers - recent-blocks - pull first historical blocks in parallel --- app/scripts/controllers/recent-blocks.js | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js index 1377c1ba9..033ef1d7e 100644 --- a/app/scripts/controllers/recent-blocks.js +++ b/app/scripts/controllers/recent-blocks.js @@ -119,29 +119,21 @@ class RecentBlocksController { */ async backfill() { this.blockTracker.once('block', async (block) => { - let blockNum = block.number - let recentBlocks - let state = this.store.getState() - recentBlocks = state.recentBlocks - - while (recentBlocks.length < this.historyLength) { + const currentBlockNumber = Number.parseInt(block.number, 16) + const blocksToFetch = Math.min(currentBlockNumber, this.historyLength) + const prevBlockNumber = currentBlockNumber - 1 + const targetBlockNumbers = Array(blocksToFetch).fill().map((_, index) => prevBlockNumber - index) + await Promise.all(targetBlockNumbers.map(async (targetBlockNumber) => { try { - let blockNumBn = new BN(blockNum.substr(2), 16) - const newNum = blockNumBn.subn(1).toString(10) - const newBlock = await this.getBlockByNumber(newNum) + const newBlock = await this.getBlockByNumber(targetBlockNumber) if (newBlock) { this.backfillBlock(newBlock) - blockNum = newBlock.number } - - state = this.store.getState() - recentBlocks = state.recentBlocks } catch (e) { log.error(e) } - await this.wait() - } + })) }) } -- cgit From 62dc6e20eb1f7188c6452519782e8ebe54c1c540 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 28 May 2018 17:57:45 +0200 Subject: Clean up user rejection error message --- app/scripts/controllers/transactions/index.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 541f1db73..586a80baf 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -111,6 +111,15 @@ class TransactionController extends EventEmitter { this.txStateManager.wipeTransactions(address) } + /** + Returns error without stack trace for better UI display + @param {Error} err - error which stack will be cleaned + */ + cleanErrorStack(err){ + err.stack = err.name + ': ' + err.message + return err + } + /** add a new unapproved transaction to the pipeline @@ -118,6 +127,8 @@ class TransactionController extends EventEmitter { @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 = {}) { log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`) const initialTxMeta = await this.addUnapprovedTransaction(txParams) @@ -130,11 +141,11 @@ class TransactionController extends EventEmitter { case 'submitted': return resolve(finishedTxMeta.hash) case 'rejected': - return reject(new Error('MetaMask Tx Signature: User denied transaction signature.')) + return reject(this.cleanErrorStack(new Error('MetaMask Tx Signature: User denied transaction signature.'))) case 'failed': - return reject(new Error(finishedTxMeta.err.message)) + return reject(this.cleanErrorStack(new Error(finishedTxMeta.err.message))) default: - return reject(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`)) + return reject(this.cleanErrorStack(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`)) } }) }) -- cgit From 1d23a5c81b03b8b52225e942603c84b237d4e63c Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 28 May 2018 18:08:33 +0200 Subject: error message fix --- app/scripts/controllers/transactions/index.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 586a80baf..6609b80b0 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -128,7 +128,6 @@ class TransactionController extends EventEmitter { @param opts {object} - with the key origin to put the origin on the txMeta */ - async newUnapprovedTransaction (txParams, opts = {}) { log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`) const initialTxMeta = await this.addUnapprovedTransaction(txParams) @@ -145,7 +144,7 @@ class TransactionController extends EventEmitter { case 'failed': return reject(this.cleanErrorStack(new Error(finishedTxMeta.err.message))) default: - return reject(this.cleanErrorStack(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`)) + return reject(this.cleanErrorStack(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))) } }) }) -- cgit From 71a6e97327a4c759942784ee81505e3bc5ed545e Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 28 May 2018 22:57:08 +0200 Subject: cleanErrorStack moved to separate library module more errors traces cleaned up --- app/scripts/controllers/transactions/index.js | 16 ++++------------ app/scripts/lib/cleanErrorStack.js | 24 ++++++++++++++++++++++++ app/scripts/metamask-controller.js | 15 ++++++++------- 3 files changed, 36 insertions(+), 19 deletions(-) create mode 100644 app/scripts/lib/cleanErrorStack.js (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 6609b80b0..aff5db984 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -8,6 +8,7 @@ const TxGasUtil = require('./tx-gas-utils') const PendingTransactionTracker = require('./pending-tx-tracker') const NonceTracker = require('./nonce-tracker') const txUtils = require('./lib/util') +const cleanErrorStack = require('../../lib/cleanErrorStack') const log = require('loglevel') /** @@ -111,15 +112,6 @@ class TransactionController extends EventEmitter { this.txStateManager.wipeTransactions(address) } - /** - Returns error without stack trace for better UI display - @param {Error} err - error which stack will be cleaned - */ - cleanErrorStack(err){ - err.stack = err.name + ': ' + err.message - return err - } - /** add a new unapproved transaction to the pipeline @@ -140,11 +132,11 @@ class TransactionController extends EventEmitter { case 'submitted': return resolve(finishedTxMeta.hash) case 'rejected': - return reject(this.cleanErrorStack(new Error('MetaMask Tx Signature: User denied transaction signature.'))) + return reject(cleanErrorStack(new Error('MetaMask Tx Signature: User denied transaction signature.'))) case 'failed': - return reject(this.cleanErrorStack(new Error(finishedTxMeta.err.message))) + return reject(cleanErrorStack(new Error(finishedTxMeta.err.message))) default: - return reject(this.cleanErrorStack(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))) + return reject(cleanErrorStack(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finishedTxMeta.txParams)}`))) } }) }) diff --git a/app/scripts/lib/cleanErrorStack.js b/app/scripts/lib/cleanErrorStack.js new file mode 100644 index 000000000..fe1bfb0ce --- /dev/null +++ b/app/scripts/lib/cleanErrorStack.js @@ -0,0 +1,24 @@ +/** + * Returns error without stack trace for better UI display + * @param {Error} err - error + * @returns {Error} Error with clean stack trace. + */ +function cleanErrorStack(err){ + var name = err.name + name = (name === undefined) ? 'Error' : String(name) + + var msg = err.message + msg = (msg === undefined) ? '' : String(msg) + + if (name === '') { + err.stack = err.message + } else if (msg === '') { + err.stack = err.name + } else { + err.stack = err.name + ': ' + err.message + } + + return err +} + +module.exports = cleanErrorStack diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index c4a73d8ea..b0666d9f9 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -45,6 +45,7 @@ const BN = require('ethereumjs-util').BN const GWEI_BN = new BN('1000000000') const percentile = require('percentile') const seedPhraseVerifier = require('./lib/seed-phrase-verifier') +const cleanErrorStack = require('./lib/cleanErrorStack') const log = require('loglevel') module.exports = class MetamaskController extends EventEmitter { @@ -637,9 +638,9 @@ module.exports = class MetamaskController extends EventEmitter { case 'signed': return cb(null, data.rawSig) case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) + return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.'))) default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) } }) } @@ -697,7 +698,7 @@ module.exports = class MetamaskController extends EventEmitter { */ newUnsignedPersonalMessage (msgParams, cb) { if (!msgParams.from) { - return cb(new Error('MetaMask Message Signature: from field is required.')) + return cb(cleanErrorStack(new Error('MetaMask Message Signature: from field is required.'))) } const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams) @@ -708,9 +709,9 @@ module.exports = class MetamaskController extends EventEmitter { case 'signed': return cb(null, data.rawSig) case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) + return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.'))) default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) } }) } @@ -776,9 +777,9 @@ module.exports = class MetamaskController extends EventEmitter { case 'signed': return cb(null, data.rawSig) case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) + return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.'))) default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))) } }) } -- cgit From e3ecc94a521b040d8937bd7aaed2ecc7f029c586 Mon Sep 17 00:00:00 2001 From: kumavis Date: Mon, 28 May 2018 21:50:23 -0700 Subject: i18n - getFirstPreferredLangCode - guard against missing i18n api fix for brave --- app/scripts/lib/get-first-preferred-lang-code.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/lib/get-first-preferred-lang-code.js b/app/scripts/lib/get-first-preferred-lang-code.js index 5473fccf0..1e6a83ba6 100644 --- a/app/scripts/lib/get-first-preferred-lang-code.js +++ b/app/scripts/lib/get-first-preferred-lang-code.js @@ -2,6 +2,12 @@ const extension = require('extensionizer') const promisify = require('pify') const allLocales = require('../../_locales/index.json') +const isSupported = extension.i18n && extension.i18n.getAcceptLanguages +const getPreferredLocales = isSupported ? promisify( + extension.i18n.getAcceptLanguages, + { errorFirst: false } +) : async () => [] + const existingLocaleCodes = allLocales.map(locale => locale.code.toLowerCase().replace('_', '-')) /** @@ -12,10 +18,7 @@ const existingLocaleCodes = allLocales.map(locale => locale.code.toLowerCase().r * */ async function getFirstPreferredLangCode () { - const userPreferredLocaleCodes = await promisify( - extension.i18n.getAcceptLanguages, - { errorFirst: false } - )() + const userPreferredLocaleCodes = await getPreferredLocales() const firstPreferredLangCode = userPreferredLocaleCodes .map(code => code.toLowerCase()) .find(code => existingLocaleCodes.includes(code)) -- cgit From 09601439e38e2681c434f23bc77c3b7665f8c98a Mon Sep 17 00:00:00 2001 From: kumavis Date: Mon, 28 May 2018 22:58:14 -0700 Subject: metamask-controller - update preferences controller addresses after import account --- app/scripts/metamask-controller.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 1b1d26886..01adc3596 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -350,7 +350,7 @@ module.exports = class MetamaskController extends EventEmitter { verifySeedPhrase: nodeify(this.verifySeedPhrase, this), clearSeedWordCache: this.clearSeedWordCache.bind(this), resetAccount: nodeify(this.resetAccount, this), - importAccountWithStrategy: this.importAccountWithStrategy.bind(this), + importAccountWithStrategy: nodeify(this.importAccountWithStrategy, this), // vault management submitPassword: nodeify(keyringController.submitPassword, keyringController), @@ -608,15 +608,15 @@ module.exports = class MetamaskController extends EventEmitter { * @param {any} args - The data required by that strategy to import an account. * @param {Function} cb - A callback function called with a state update on success. */ - importAccountWithStrategy (strategy, args, cb) { - accountImporter.importAccount(strategy, args) - .then((privateKey) => { - return this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ]) - }) - .then(keyring => keyring.getAccounts()) - .then((accounts) => this.preferencesController.setSelectedAddress(accounts[0])) - .then(() => { cb(null, this.keyringController.fullUpdate()) }) - .catch((reason) => { cb(reason) }) + async importAccountWithStrategy (strategy, args) { + const privateKey = await accountImporter.importAccount(strategy, args) + const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ]) + const accounts = await keyring.getAccounts() + // update accounts in preferences controller + const allAccounts = await keyringController.getAccounts() + this.preferencesController.setAddresses(allAccounts) + // set new account as selected + await this.preferencesController.setSelectedAddress(accounts[0]) } // --------------------------------------------------------------------------- -- cgit From 7e87600042805727a9e99e62c8bf23819f6d0b0f Mon Sep 17 00:00:00 2001 From: kumavis Date: Mon, 28 May 2018 23:14:38 -0700 Subject: metamask-controller - lint fix --- app/scripts/metamask-controller.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 01adc3596..0457b4476 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -613,7 +613,7 @@ module.exports = class MetamaskController extends EventEmitter { const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ]) const accounts = await keyring.getAccounts() // update accounts in preferences controller - const allAccounts = await keyringController.getAccounts() + const allAccounts = await this.keyringController.getAccounts() this.preferencesController.setAddresses(allAccounts) // set new account as selected await this.preferencesController.setSelectedAddress(accounts[0]) -- cgit