From aa41057628a812cfa3d330fd36684ca17ab2852d Mon Sep 17 00:00:00 2001 From: Whymarrh Whitby Date: Tue, 19 Nov 2019 20:33:20 -0330 Subject: [PATCH] Update ESLint rules for curly braces style (#7477) * eslint: Enable curly and brace-style * yarn lint --fix --- .eslintrc | 4 +- app/scripts/background.js | 4 +- app/scripts/contentscript.js | 12 +++-- app/scripts/controllers/detect-tokens.js | 42 ++++++++++++---- .../controllers/incoming-transactions.js | 4 +- .../controllers/network/middleware/pending.js | 16 +++++-- app/scripts/controllers/network/network.js | 4 +- app/scripts/controllers/preferences.js | 48 ++++++++++++++----- app/scripts/controllers/provider-approval.js | 4 +- app/scripts/controllers/recent-blocks.js | 8 +++- app/scripts/controllers/threebox.js | 4 +- app/scripts/controllers/token-rates.js | 20 ++++++-- app/scripts/controllers/transactions/index.js | 16 +++++-- .../lib/tx-state-history-helper.js | 8 +++- .../controllers/transactions/lib/util.js | 12 +++-- .../transactions/pending-tx-tracker.js | 20 ++++++-- .../controllers/transactions/tx-gas-utils.js | 8 +++- .../transactions/tx-state-manager.js | 24 +++++++--- app/scripts/lib/account-tracker.js | 12 +++-- app/scripts/lib/auto-reload.js | 16 +++++-- app/scripts/lib/buy-eth-url.js | 4 +- app/scripts/lib/createDnodeRemoteGetter.js | 4 +- app/scripts/lib/createLoggerMiddleware.js | 4 +- app/scripts/lib/ens-ipfs/setup.js | 12 +++-- app/scripts/lib/local-store.js | 12 +++-- app/scripts/lib/message-manager.js | 12 +++-- app/scripts/lib/migrator/index.js | 8 +++- app/scripts/lib/nodeify.js | 6 ++- app/scripts/lib/notification-manager.js | 20 ++++++-- app/scripts/lib/pending-balance-calculator.js | 4 +- app/scripts/lib/personal-message-manager.js | 12 +++-- app/scripts/lib/setupFetchDebugging.js | 4 +- app/scripts/lib/setupMetamaskMeshMetrics.js | 4 +- app/scripts/lib/setupSentry.js | 12 +++-- app/scripts/lib/stream-utils.js | 4 +- app/scripts/lib/typed-message-manager.js | 16 +++++-- app/scripts/metamask-controller.js | 28 ++++++++--- app/scripts/migrations/004.js | 4 +- app/scripts/migrations/015.js | 7 ++- app/scripts/migrations/016.js | 4 +- app/scripts/migrations/017.js | 4 +- app/scripts/migrations/019.js | 4 +- app/scripts/migrations/022.js | 4 +- app/scripts/migrations/023.js | 11 +++-- app/scripts/migrations/024.js | 4 +- app/scripts/migrations/025.js | 8 +++- development/mock-3box.js | 4 +- development/show-deps-install-scripts.js | 20 ++++++-- development/sourcemap-validator.js | 8 +++- gulpfile.js | 4 +- test/helper.js | 12 +++-- test/integration/index.js | 4 +- test/lib/mock-simple-keychain.js | 4 +- test/lib/util.js | 8 +++- test/setup.js | 8 +++- test/unit/actions/tx_test.js | 12 +++-- .../controllers/metamask-controller-test.js | 24 +++++++--- .../network/pending-middleware-test.js | 8 +++- .../preferences-controller-test.js | 32 +++++++++---- .../transactions/pending-tx-test.js | 36 ++++++++++---- .../transactions/tx-controller-test.js | 41 +++++++++++----- .../tx-state-history-helper-test.js | 4 +- .../controllers/transactions/tx-utils-test.js | 20 ++++++-- test/unit/app/nodeify-test.js | 16 +++++-- test/unit/migrations/023-test.js | 4 +- test/unit/migrations/024-test.js | 7 ++- test/unit/migrations/025-test.js | 8 +++- test/unit/migrations/027-test.js | 4 +- test/unit/migrations/029-test.js | 4 +- test/unit/migrations/migrator-test.js | 4 +- test/unit/test-utils.js | 4 +- test/unit/util_test.js | 4 +- .../app/dropdowns/components/menu.js | 16 +++++-- .../app/dropdowns/network-dropdown.js | 4 +- .../gas-price-chart/gas-price-chart.utils.js | 4 +- ui/app/components/app/input-number.js | 4 +- ui/app/components/app/token-list.js | 12 +++-- ui/app/components/ui/eth-balance.js | 8 +++- ui/app/components/ui/fiat-value.js | 4 +- ui/app/components/ui/mascot.js | 4 +- .../ui/unit-input/unit-input.component.js | 4 +- ui/app/ducks/index.js | 4 +- ui/app/helpers/utils/util.js | 40 ++++++++++++---- .../confirm-transaction.component.js | 4 +- .../connect-hardware/connect-screen.js | 8 +++- ui/app/pages/mobile-sync/index.js | 4 +- ui/app/pages/routes/index.js | 4 +- .../add-recipient/ens-input.component.js | 12 +++-- ui/app/pages/send/send.component.js | 4 +- ui/app/pages/send/send.utils.js | 12 +++-- ui/app/pages/send/tests/send-utils.test.js | 8 +++- .../add-contact/add-contact.component.js | 4 +- ui/app/store/actions.js | 20 ++++++-- ui/index.js | 8 +++- 94 files changed, 747 insertions(+), 251 deletions(-) diff --git a/.eslintrc b/.eslintrc index 08d8aeb9d..159fee387 100644 --- a/.eslintrc +++ b/.eslintrc @@ -49,13 +49,13 @@ "accessor-pairs": 2, "arrow-spacing": [2, { "before": true, "after": true }], "block-spacing": [2, "always"], - "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "brace-style": 2, "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, "multi-line"], + "curly": 2, "dot-location": [2, "property"], "eol-last": 2, "eqeqeq": [2, "allow-null"], diff --git a/app/scripts/background.js b/app/scripts/background.js index 2639d7703..b26a87ba2 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -260,7 +260,9 @@ 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 }) diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index db4d5fd63..4a84cb64b 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -123,7 +123,9 @@ async function setupPublicApi (outStream) { outStream, (err) => { // report any error - if (err) log.error(err) + if (err) { + log.error(err) + } } ) const background = await new Promise(resolve => dnode.once('remote', resolve)) @@ -151,7 +153,9 @@ function getSiteMetadata () { */ 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) } @@ -302,7 +306,9 @@ function getSiteIcon (window) { */ async function domIsReady () { // already loaded - if (['interactive', 'complete'].includes(document.readyState)) return + if (['interactive', 'complete'].includes(document.readyState)) { + return + } // wait for load await new Promise(resolve => window.addEventListener('DOMContentLoaded', resolve, { once: true })) } diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js index e6e993073..923aa2d15 100644 --- a/app/scripts/controllers/detect-tokens.js +++ b/app/scripts/controllers/detect-tokens.js @@ -29,8 +29,12 @@ 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) { @@ -80,7 +84,9 @@ class DetectTokensController { * */ restartTokenDetection () { - if (!(this.isActive && this.selectedAddress)) { return } + if (!(this.isActive && this.selectedAddress)) { + return + } this.detectNewTokens() this.interval = DEFAULT_INTERVAL } @@ -90,8 +96,12 @@ 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) } /** @@ -99,9 +109,15 @@ 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 @@ -114,7 +130,9 @@ class DetectTokensController { * @type {Object} */ set network (network) { - if (!network) { return } + if (!network) { + return + } this._network = network this.web3 = new Web3(network._provider) } @@ -124,12 +142,16 @@ 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 029bf47aa..10735b3f9 100644 --- a/app/scripts/controllers/incoming-transactions.js +++ b/app/scripts/controllers/incoming-transactions.js @@ -163,7 +163,9 @@ 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 542d8bde6..96a5d40be 100644 --- a/app/scripts/controllers/network/middleware/pending.js +++ b/app/scripts/controllers/network/middleware/pending.js @@ -4,9 +4,13 @@ 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) }) } @@ -14,10 +18,14 @@ 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 7b5d8ef38..f1be914bb 100644 --- a/app/scripts/controllers/network/network.js +++ b/app/scripts/controllers/network/network.js @@ -81,7 +81,9 @@ module.exports = class NetworkController extends EventEmitter { verifyNetwork () { // Check network when restoring connectivity: - if (this.isNetworkLoading()) this.lookupNetwork() + if (this.isNetworkLoading()) { + this.lookupNetwork() + } } getNetworkState () { diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 1cfbb4d4c..22c6e999d 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -303,7 +303,9 @@ 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 @@ -335,7 +337,9 @@ 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) { @@ -463,7 +467,9 @@ 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] || {} @@ -500,7 +506,9 @@ 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) @@ -524,7 +532,9 @@ 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) } @@ -548,7 +558,9 @@ 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) } @@ -687,10 +699,16 @@ 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 } } @@ -727,13 +745,19 @@ 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 index 00ff626f7..e54c7196f 100644 --- a/app/scripts/controllers/provider-approval.js +++ b/app/scripts/controllers/provider-approval.js @@ -34,7 +34,9 @@ class ProviderApprovalController extends SafeEventEmitter { createMiddleware ({ senderUrl, extensionId, getSiteMetadata }) { return createAsyncMiddleware(async (req, res, next) => { // only handle requestAccounts - if (req.method !== 'eth_requestAccounts') return next() + 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 diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js index a2b5d1bae..9e5a384a9 100644 --- a/app/scripts/controllers/recent-blocks.js +++ b/app/scripts/controllers/recent-blocks.js @@ -90,7 +90,9 @@ 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) @@ -162,7 +164,9 @@ 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 5bcab29ed..8226fb6b1 100644 --- a/app/scripts/controllers/threebox.js +++ b/app/scripts/controllers/threebox.js @@ -28,7 +28,9 @@ 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 9b86a9ebf..7c8526c34 100644 --- a/app/scripts/controllers/token-rates.js +++ b/app/scripts/controllers/token-rates.js @@ -28,7 +28,9 @@ 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(',') @@ -53,8 +55,12 @@ 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) } /** @@ -62,10 +68,14 @@ 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 df9fb6502..f19dd53f7 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -402,7 +402,9 @@ 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 { @@ -603,7 +605,9 @@ 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') }) @@ -657,10 +661,14 @@ 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 76fc5c35b..3cc76e617 100644 --- a/app/scripts/controllers/transactions/lib/tx-state-history-helper.js +++ b/app/scripts/controllers/transactions/lib/tx-state-history-helper.js @@ -18,7 +18,9 @@ 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) }) ) @@ -40,7 +42,9 @@ 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 0d2ddddef..86924e7fa 100644 --- a/app/scripts/controllers/transactions/lib/util.js +++ b/app/scripts/controllers/transactions/lib/util.js @@ -35,7 +35,9 @@ 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 } @@ -64,8 +66,12 @@ 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 8f4076f45..4e2db5ead 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.js @@ -56,7 +56,9 @@ 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 @@ -79,7 +81,9 @@ 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, @@ -107,10 +111,14 @@ 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) @@ -132,7 +140,9 @@ 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 287fb6f44..517137f86 100644 --- a/app/scripts/controllers/transactions/tx-gas-utils.js +++ b/app/scripts/controllers/transactions/tx-gas-utils.js @@ -142,9 +142,13 @@ 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 6a92c0601..fb9359c79 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.js +++ b/app/scripts/controllers/transactions/tx-state-manager.js @@ -45,7 +45,9 @@ 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(), @@ -89,7 +91,9 @@ class TransactionStateManager extends EventEmitter { */ getApprovedTransactions (address) { const opts = { status: 'approved' } - if (address) opts.from = address + if (address) { + opts.from = address + } return this.getFilteredTxList(opts) } @@ -100,7 +104,9 @@ class TransactionStateManager extends EventEmitter { */ getPendingTransactions (address) { const opts = { status: 'submitted' } - if (address) opts.from = address + if (address) { + opts.from = address + } return this.getFilteredTxList(opts) } @@ -111,7 +117,9 @@ class TransactionStateManager extends EventEmitter { */ getConfirmedTransactions (address) { const opts = { status: 'confirmed' } - if (address) opts.from = address + if (address) { + opts.from = address + } return this.getFilteredTxList(opts) } @@ -236,10 +244,14 @@ 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/lib/account-tracker.js b/app/scripts/lib/account-tracker.js index 3137ea8a3..8fef712fe 100644 --- a/app/scripts/lib/account-tracker.js +++ b/app/scripts/lib/account-tracker.js @@ -124,7 +124,9 @@ 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() } @@ -158,7 +160,9 @@ 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 }) @@ -218,7 +222,9 @@ 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 fd209c230..343191f4c 100644 --- a/app/scripts/lib/auto-reload.js +++ b/app/scripts/lib/auto-reload.js @@ -28,10 +28,14 @@ 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 @@ -42,10 +46,14 @@ 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 5cae83a9f..6728fde7c 100644 --- a/app/scripts/lib/buy-eth-url.js +++ b/app/scripts/lib/buy-eth-url.js @@ -13,7 +13,9 @@ 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': diff --git a/app/scripts/lib/createDnodeRemoteGetter.js b/app/scripts/lib/createDnodeRemoteGetter.js index b70d218f3..60a775383 100644 --- a/app/scripts/lib/createDnodeRemoteGetter.js +++ b/app/scripts/lib/createDnodeRemoteGetter.js @@ -8,7 +8,9 @@ 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 996c3477c..d95cdb465 100644 --- a/app/scripts/lib/createLoggerMiddleware.js +++ b/app/scripts/lib/createLoggerMiddleware.js @@ -13,7 +13,9 @@ 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/ens-ipfs/setup.js b/app/scripts/lib/ens-ipfs/setup.js index a3711c5f9..f12a22238 100644 --- a/app/scripts/lib/ens-ipfs/setup.js +++ b/app/scripts/lib/ens-ipfs/setup.js @@ -23,14 +23,18 @@ 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 }) } @@ -45,7 +49,9 @@ 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 8fde2e911..49294c84d 100644 --- a/app/scripts/lib/local-store.js +++ b/app/scripts/lib/local-store.js @@ -20,7 +20,9 @@ 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 @@ -96,9 +98,13 @@ function isEmpty (obj) { */ function checkForError () { const lastError = extension.runtime.lastError - if (!lastError) return + if (!lastError) { + return + } // if it quacks like an Error, its an Error - if (lastError.stack && lastError.message) return lastError + 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 8e1ff34b7..9f087abad 100644 --- a/app/scripts/lib/message-manager.js +++ b/app/scripts/lib/message-manager.js @@ -62,7 +62,9 @@ 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 + }, {}) } /** @@ -102,7 +104,9 @@ 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 var time = (new Date()).getTime() @@ -219,7 +223,9 @@ 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 345ca8001..c1c225fb3 100644 --- a/app/scripts/lib/migrator/index.js +++ b/app/scripts/lib/migrator/index.js @@ -40,8 +40,12 @@ 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 a813ae679..99b96b356 100644 --- a/app/scripts/lib/nodeify.js +++ b/app/scripts/lib/nodeify.js @@ -1,5 +1,9 @@ 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 721d109a1..85177cceb 100644 --- a/app/scripts/lib/notification-manager.js +++ b/app/scripts/lib/notification-manager.js @@ -18,7 +18,9 @@ class NotificationManager { */ showPopup () { this._getPopup((err, popup) => { - if (err) throw err + if (err) { + throw err + } // Bring focus to chrome popup if (popup) { @@ -28,7 +30,9 @@ 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', @@ -50,8 +54,12 @@ 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) }) } @@ -66,7 +74,9 @@ 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 0f1dc19a9..dd7fa6de4 100644 --- a/app/scripts/lib/pending-balance-calculator.js +++ b/app/scripts/lib/pending-balance-calculator.js @@ -32,7 +32,9 @@ 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 2a2ab481a..eea8e286d 100644 --- a/app/scripts/lib/personal-message-manager.js +++ b/app/scripts/lib/personal-message-manager.js @@ -65,7 +65,9 @@ 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 + }, {}) } /** @@ -110,7 +112,9 @@ 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 var time = (new Date()).getTime() @@ -229,7 +233,9 @@ 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/setupFetchDebugging.js b/app/scripts/lib/setupFetchDebugging.js index 431340e2b..d5c01b1f2 100644 --- a/app/scripts/lib/setupFetchDebugging.js +++ b/app/scripts/lib/setupFetchDebugging.js @@ -7,7 +7,9 @@ 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 6f0d86b28..b520ceaa7 100644 --- a/app/scripts/lib/setupMetamaskMeshMetrics.js +++ b/app/scripts/lib/setupMetamaskMeshMetrics.js @@ -22,7 +22,9 @@ 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 ba0e17df0..096bd3454 100644 --- a/app/scripts/lib/setupSentry.js +++ b/app/scripts/lib/setupSentry.js @@ -67,11 +67,15 @@ 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) + } }) } } @@ -91,7 +95,9 @@ 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 3dbc064b5..66b3107f4 100644 --- a/app/scripts/lib/stream-utils.js +++ b/app/scripts/lib/stream-utils.js @@ -43,7 +43,9 @@ 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 e4d3e842b..3f5934299 100644 --- a/app/scripts/lib/typed-message-manager.js +++ b/app/scripts/lib/typed-message-manager.js @@ -58,7 +58,9 @@ 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 + }, {}) } /** @@ -103,7 +105,9 @@ 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 @@ -149,7 +153,9 @@ 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.') @@ -278,7 +284,9 @@ 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/metamask-controller.js b/app/scripts/metamask-controller.js index 1c607a4c6..c8182b6bd 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -342,7 +342,9 @@ module.exports = class MetamaskController extends EventEmitter { // 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 [] } + if (origin !== 'metamask' && !exposeAccounts) { + return [] + } const isUnlocked = this.keyringController.memStore.getState().isUnlocked const selectedAddress = this.preferencesController.getSelectedAddress() // only show address if account is unlocked @@ -1404,7 +1406,9 @@ 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) => { @@ -1442,7 +1446,9 @@ module.exports = class MetamaskController extends EventEmitter { mid.destroy() } }) - if (err) log.error(err) + if (err) { + log.error(err) + } } ) } @@ -1507,7 +1513,9 @@ module.exports = class MetamaskController extends EventEmitter { (err) => { configStore.destroy() configStream.destroy() - if (err) log.error(err) + if (err) { + log.error(err) + } } ) } @@ -1527,7 +1535,9 @@ module.exports = class MetamaskController extends EventEmitter { outStream, (err) => { // report any error - if (err) log.error(err) + if (err) { + log.error(err) + } } ) @@ -1676,10 +1686,14 @@ 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 cd558300c..c0cf600c9 100644 --- a/app/scripts/migrations/004.js +++ b/app/scripts/migrations/004.js @@ -9,7 +9,9 @@ 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 = { diff --git a/app/scripts/migrations/015.js b/app/scripts/migrations/015.js index 5e2f9e63b..3d20b58db 100644 --- a/app/scripts/migrations/015.js +++ b/app/scripts/migrations/015.js @@ -32,8 +32,11 @@ 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 048c7a40e..76a106ca7 100644 --- a/app/scripts/migrations/016.js +++ b/app/scripts/migrations/016.js @@ -33,7 +33,9 @@ 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 5f6d906d6..918df4ade 100644 --- a/app/scripts/migrations/017.js +++ b/app/scripts/migrations/017.js @@ -31,7 +31,9 @@ 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 7b726c3e8..f560f5579 100644 --- a/app/scripts/migrations/019.js +++ b/app/scripts/migrations/019.js @@ -35,7 +35,9 @@ 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 1fbe241e6..eeb142b7a 100644 --- a/app/scripts/migrations/022.js +++ b/app/scripts/migrations/022.js @@ -33,7 +33,9 @@ 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 18493a789..84532537e 100644 --- a/app/scripts/migrations/023.js +++ b/app/scripts/migrations/023.js @@ -33,7 +33,9 @@ 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 @@ -44,8 +46,11 @@ 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 5ffaea377..fda463e1a 100644 --- a/app/scripts/migrations/024.js +++ b/app/scripts/migrations/024.js @@ -25,7 +25,9 @@ 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 fd4faa782..48bff962d 100644 --- a/app/scripts/migrations/025.js +++ b/app/scripts/migrations/025.js @@ -29,7 +29,9 @@ 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 }) @@ -54,7 +56,9 @@ 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/development/mock-3box.js b/development/mock-3box.js index 53f228f21..a26e02a82 100644 --- a/development/mock-3box.js +++ b/development/mock-3box.js @@ -28,7 +28,9 @@ 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/show-deps-install-scripts.js b/development/show-deps-install-scripts.js index 03a9bb859..419c9d25f 100644 --- a/development/show-deps-install-scripts.js +++ b/development/show-deps-install-scripts.js @@ -5,7 +5,9 @@ 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]) => { @@ -13,12 +15,20 @@ 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 546745f16..44336df9e 100644 --- a/development/sourcemap-validator.js +++ b/development/sourcemap-validator.js @@ -52,7 +52,9 @@ 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,6 +98,8 @@ async function validateSourcemapForFile ({ buildName }) { function indicesOf (substring, string) { var a = [] var i = -1 - while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i) + while ((i = string.indexOf(substring, i + 1)) >= 0) { + a.push(i) + } return a } diff --git a/gulpfile.js b/gulpfile.js index 3e4a3b7ff..d5d74333a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -428,7 +428,9 @@ 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/test/helper.js b/test/helper.js index ddc2aba40..a49249062 100644 --- a/test/helper.js +++ b/test/helper.js @@ -36,8 +36,12 @@ require('jsdom-global')() window.localStorage = {} // crypto.getRandomValues -if (!window.crypto) window.crypto = {} -if (!window.crypto.getRandomValues) window.crypto.getRandomValues = require('polyfill-crypto.getrandomvalues') +if (!window.crypto) { + window.crypto = {} +} +if (!window.crypto.getRandomValues) { + window.crypto.getRandomValues = require('polyfill-crypto.getrandomvalues') +} function enableFailureOnUnhandledPromiseRejection () { // overwrite node's promise with the stricter Bluebird promise @@ -60,7 +64,9 @@ function enableFailureOnUnhandledPromiseRejection () { } else { var oldOHR = window.onunhandledrejection window.onunhandledrejection = function (evt) { - if (typeof oldOHR === 'function') oldOHR.apply(this, arguments) + if (typeof oldOHR === 'function') { + oldOHR.apply(this, arguments) + } throw evt.detail.reason } } diff --git a/test/integration/index.js b/test/integration/index.js index b266ddf37..1c4523e1e 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -19,7 +19,9 @@ pump( b.bundle(), writeStream, (err) => { - if (err) throw err + if (err) { + throw err + } console.log(`Integration test build completed: "${bundlePath}"`) process.exit(0) } diff --git a/test/lib/mock-simple-keychain.js b/test/lib/mock-simple-keychain.js index d3addc3e8..daf6001c4 100644 --- a/test/lib/mock-simple-keychain.js +++ b/test/lib/mock-simple-keychain.js @@ -6,7 +6,9 @@ const type = 'Simple Key Pair' module.exports = class MockSimpleKeychain { - static type () { return type } + static type () { + return type + } constructor (opts) { this.type = type diff --git a/test/lib/util.js b/test/lib/util.js index 4c5d789d1..be7e240a4 100644 --- a/test/lib/util.js +++ b/test/lib/util.js @@ -15,7 +15,9 @@ async function findAsync (container, selector, opts) { try { return await pollUntilTruthy(() => { const result = container.find(selector) - if (result.length > 0) return result + if (result.length > 0) { + return result + } }, opts) } catch (err) { throw new Error(`Failed to find element within interval: "${selector}"`) @@ -26,7 +28,9 @@ async function queryAsync (jQuery, selector, opts) { try { return await pollUntilTruthy(() => { const result = jQuery(selector) - if (result.length > 0) return result + if (result.length > 0) { + return result + } }, opts) } catch (err) { throw new Error(`Failed to find element within interval: "${selector}"`) diff --git a/test/setup.js b/test/setup.js index bccb4d58e..5aa6e59dd 100644 --- a/test/setup.js +++ b/test/setup.js @@ -5,6 +5,10 @@ require('@babel/register')({ require('./helper') window.SVGPathElement = window.SVGPathElement || { prototype: {} } -window.fetch = window.fetch || function fetch () { return Promise.resolve() } +window.fetch = window.fetch || function fetch () { + return Promise.resolve() +} global.indexedDB = {} -global.fetch = global.fetch || function fetch () { return Promise.resolve() } +global.fetch = global.fetch || function fetch () { + return Promise.resolve() +} diff --git a/test/unit/actions/tx_test.js b/test/unit/actions/tx_test.js index 66378b594..ca1225113 100644 --- a/test/unit/actions/tx_test.js +++ b/test/unit/actions/tx_test.js @@ -33,9 +33,15 @@ describe('tx confirmation screen', function () { describe('cancelTx', function () { before(function (done) { actions._setBackgroundConnection({ - approveTransaction (_, cb) { cb('An error!') }, - cancelTransaction (_, cb) { cb() }, - getState (cb) { cb() }, + approveTransaction (_, cb) { + cb('An error!') + }, + cancelTransaction (_, cb) { + cb() + }, + getState (cb) { + cb() + }, }) done() }) diff --git a/test/unit/app/controllers/metamask-controller-test.js b/test/unit/app/controllers/metamask-controller-test.js index 7eac91a9b..a904dec08 100644 --- a/test/unit/app/controllers/metamask-controller-test.js +++ b/test/unit/app/controllers/metamask-controller-test.js @@ -227,7 +227,9 @@ describe('MetaMaskController', function () { it('should be able to call newVaultAndRestore despite a mistake.', async function () { const password = 'what-what-what' sandbox.stub(metamaskController, 'getBalance') - metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + metamaskController.getBalance.callsFake(() => { + return Promise.resolve('0x0') + }) await metamaskController.createNewVaultAndRestore(password, TEST_SEED.slice(0, -1)).catch(() => null) await metamaskController.createNewVaultAndRestore(password, TEST_SEED) @@ -237,7 +239,9 @@ describe('MetaMaskController', function () { it('should clear previous identities after vault restoration', async () => { sandbox.stub(metamaskController, 'getBalance') - metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + metamaskController.getBalance.callsFake(() => { + return Promise.resolve('0x0') + }) await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED) assert.deepEqual(metamaskController.getState().identities, { @@ -676,7 +680,9 @@ describe('MetaMaskController', function () { beforeEach(async () => { sandbox.stub(metamaskController, 'getBalance') - metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + metamaskController.getBalance.callsFake(() => { + return Promise.resolve('0x0') + }) await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) @@ -734,7 +740,9 @@ describe('MetaMaskController', function () { beforeEach(async function () { sandbox.stub(metamaskController, 'getBalance') - metamaskController.getBalance.callsFake(() => { return Promise.resolve('0x0') }) + metamaskController.getBalance.callsFake(() => { + return Promise.resolve('0x0') + }) await metamaskController.createNewVaultAndRestore('foobar1337', TEST_SEED_ALT) @@ -809,7 +817,9 @@ describe('MetaMaskController', function () { const { promise, resolve } = deferredPromise() streamTest = createThoughStream((chunk, _, cb) => { - if (chunk.name !== 'phishing') return cb() + if (chunk.name !== 'phishing') { + return cb() + } assert.equal(chunk.data.hostname, phishingUrl.hostname) resolve() cb() @@ -929,6 +939,8 @@ describe('MetaMaskController', function () { function deferredPromise () { let resolve - const promise = new Promise(_resolve => { resolve = _resolve }) + const promise = new Promise(_resolve => { + resolve = _resolve + }) return { promise, resolve } } diff --git a/test/unit/app/controllers/network/pending-middleware-test.js b/test/unit/app/controllers/network/pending-middleware-test.js index 838395b0b..ac6f8ad9a 100644 --- a/test/unit/app/controllers/network/pending-middleware-test.js +++ b/test/unit/app/controllers/network/pending-middleware-test.js @@ -19,7 +19,9 @@ describe('#createPendingNonceMiddleware', function () { it('should fill the result with a the "pending" nonce', (done) => { const req = { method: 'eth_getTransactionCount', params: [address, 'pending'] } const res = {} - pendingNonceMiddleware(req, res, () => { done(new Error('should not have called next')) }, () => { + pendingNonceMiddleware(req, res, () => { + done(new Error('should not have called next')) + }, () => { assert(res.result === '0x2') done() }) @@ -63,7 +65,9 @@ describe('#createPendingTxMiddleware', function () { returnUndefined = false const req = { method: 'eth_getTransactionByHash', params: [address, 'pending'] } const res = {} - pendingTxMiddleware(req, res, () => { done(new Error('should not have called next')) }, () => { + pendingTxMiddleware(req, res, () => { + done(new Error('should not have called next')) + }, () => { /* // uncomment this section for debugging help with non matching keys const coppy = {...res.result} diff --git a/test/unit/app/controllers/preferences-controller-test.js b/test/unit/app/controllers/preferences-controller-test.js index 7e047a2a8..f9dc9c099 100644 --- a/test/unit/app/controllers/preferences-controller-test.js +++ b/test/unit/app/controllers/preferences-controller-test.js @@ -455,28 +455,44 @@ describe('preferences controller', function () { }) it('should validate ERC20 asset correctly', async function () { const validateSpy = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpy({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABC', decimals: 0}) } catch (e) {} + try { + validateSpy({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABC', decimals: 0}) + } catch (e) {} assert.equal(validateSpy.threw(), false, 'correct options object') const validateSpyAddress = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyAddress({symbol: 'ABC', decimals: 0}) } catch (e) {} + try { + validateSpyAddress({symbol: 'ABC', decimals: 0}) + } catch (e) {} assert.equal(validateSpyAddress.threw(), true, 'options object with no address') const validateSpySymbol = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpySymbol({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', decimals: 0}) } catch (e) {} + try { + validateSpySymbol({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', decimals: 0}) + } catch (e) {} assert.equal(validateSpySymbol.threw(), true, 'options object with no symbol') const validateSpyDecimals = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyDecimals({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABC'}) } catch (e) {} + try { + validateSpyDecimals({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABC'}) + } catch (e) {} assert.equal(validateSpyDecimals.threw(), true, 'options object with no decimals') const validateSpyInvalidSymbol = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyInvalidSymbol({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: 0}) } catch (e) {} + try { + validateSpyInvalidSymbol({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: 0}) + } catch (e) {} assert.equal(validateSpyInvalidSymbol.threw(), true, 'options object with invalid symbol') const validateSpyInvalidDecimals1 = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyInvalidDecimals1({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: -1}) } catch (e) {} + try { + validateSpyInvalidDecimals1({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: -1}) + } catch (e) {} assert.equal(validateSpyInvalidDecimals1.threw(), true, 'options object with decimals less than zero') const validateSpyInvalidDecimals2 = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyInvalidDecimals2({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: 38}) } catch (e) {} + try { + validateSpyInvalidDecimals2({rawAddress: '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07', symbol: 'ABCDEFGHI', decimals: 38}) + } catch (e) {} assert.equal(validateSpyInvalidDecimals2.threw(), true, 'options object with decimals more than 36') const validateSpyInvalidAddress = sandbox.spy(preferencesController._validateERC20AssetParams) - try { validateSpyInvalidAddress({rawAddress: '0x123', symbol: 'ABC', decimals: 0}) } catch (e) {} + try { + validateSpyInvalidAddress({rawAddress: '0x123', symbol: 'ABC', decimals: 0}) + } catch (e) {} assert.equal(validateSpyInvalidAddress.threw(), true, 'options object with address invalid') }) }) diff --git a/test/unit/app/controllers/transactions/pending-tx-test.js b/test/unit/app/controllers/transactions/pending-tx-test.js index e1de5731b..622a53b18 100644 --- a/test/unit/app/controllers/transactions/pending-tx-test.js +++ b/test/unit/app/controllers/transactions/pending-tx-test.js @@ -40,13 +40,19 @@ describe('PendingTransactionTracker', function () { return { releaseLock: () => {} } }, }, - getPendingTransactions: () => { return [] }, - getCompletedTransactions: () => { return [] }, + getPendingTransactions: () => { + return [] + }, + getCompletedTransactions: () => { + return [] + }, publishTransaction: () => {}, confirmTransaction: () => {}, }) - pendingTxTracker._getBlock = (blockNumber) => { return {number: blockNumber, transactions: []} } + pendingTxTracker._getBlock = (blockNumber) => { + return {number: blockNumber, transactions: []} + } }) describe('_checkPendingTx state management', function () { @@ -150,14 +156,18 @@ describe('PendingTransactionTracker', function () { txMeta2.id = 2 txMeta3.id = 3 txList = [txMeta, txMeta2, txMeta3].map((tx) => { - tx.processed = new Promise((resolve) => { tx.resolve = resolve }) + tx.processed = new Promise((resolve) => { + tx.resolve = resolve + }) return tx }) }) it('should warp all txMeta\'s in #updatePendingTxs', function (done) { pendingTxTracker.getPendingTransactions = () => txList - pendingTxTracker._checkPendingTx = (tx) => { tx.resolve(tx) } + pendingTxTracker._checkPendingTx = (tx) => { + tx.resolve(tx) + } Promise.all(txList.map((tx) => tx.processed)) .then(() => done()) .catch(done) @@ -171,7 +181,9 @@ describe('PendingTransactionTracker', function () { beforeEach(function () { const txMeta2 = txMeta3 = txMeta txList = [txMeta, txMeta2, txMeta3].map((tx) => { - tx.processed = new Promise((resolve) => { tx.resolve = resolve }) + tx.processed = new Promise((resolve) => { + tx.resolve = resolve + }) return tx }) }) @@ -181,7 +193,9 @@ describe('PendingTransactionTracker', function () { }) it('should call #_resubmitTx for all pending tx\'s', function (done) { pendingTxTracker.getPendingTransactions = () => txList - pendingTxTracker._resubmitTx = async (tx) => { tx.resolve(tx) } + pendingTxTracker._resubmitTx = async (tx) => { + tx.resolve(tx) + } Promise.all(txList.map((tx) => tx.processed)) .then(() => done()) .catch(done) @@ -225,7 +239,9 @@ describe('PendingTransactionTracker', function () { }) pendingTxTracker.getPendingTransactions = () => txList - pendingTxTracker._resubmitTx = async () => { throw new TypeError('im some real error') } + pendingTxTracker._resubmitTx = async () => { + throw new TypeError('im some real error') + } Promise.all(txList.map((tx) => tx.processed)) .then(() => done()) .catch(done) @@ -369,7 +385,9 @@ describe('PendingTransactionTracker', function () { rawTx: '0xf86c808504a817c800827b0d940c62bb85faa3311a998d3aba8098c1235c564966880de0b6b3a7640000802aa08ff665feb887a25d4099e40e11f0fef93ee9608f404bd3f853dd9e84ed3317a6a02ec9d3d1d6e176d4d2593dd760e74ccac753e6a0ea0d00cc9789d0d7ff1f471d', }] pendingTxTracker.getCompletedTransactions = (address) => { - if (!address) throw new Error('unless behavior has changed #_checkIfNonceIsTaken needs a filtered list of transactions to see if the nonce is taken') + if (!address) { + throw new Error('unless behavior has changed #_checkIfNonceIsTaken needs a filtered list of transactions to see if the nonce is taken') + } return confirmedTxList } }) diff --git a/test/unit/app/controllers/transactions/tx-controller-test.js b/test/unit/app/controllers/transactions/tx-controller-test.js index 76b8e5025..d0a989e71 100644 --- a/test/unit/app/controllers/transactions/tx-controller-test.js +++ b/test/unit/app/controllers/transactions/tx-controller-test.js @@ -38,7 +38,9 @@ describe('Transaction Controller', function () { blockTrackerStub.getLatestBlock = noop txController = new TransactionController({ provider, - getGasPrice: function () { return '0xee6b2800' }, + getGasPrice: function () { + return '0xee6b2800' + }, networkStore: netStore, txHistoryLimit: 10, blockTracker: blockTrackerStub, @@ -162,8 +164,11 @@ describe('Transaction Controller', function () { txController.newUnapprovedTransaction(txParams) .catch((err) => { - if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') done() - else done(err) + if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') { + done() + } else { + done(err) + } }) }) }) @@ -209,8 +214,11 @@ describe('Transaction Controller', function () { txController.networkStore = new ObservableStore(1) txController.addUnapprovedTransaction({ from: selectedAddress, to: '0x0d1d4e623D10F9FBA5Db95830F7d3839406C6AF2' }) .catch((err) => { - if (err.message === 'Recipient is a public account') done() - else done(err) + if (err.message === 'Recipient is a public account') { + done() + } else { + done(err) + } }) }) @@ -239,8 +247,11 @@ describe('Transaction Controller', function () { txController.networkStore = new ObservableStore('loading') txController.addUnapprovedTransaction({ from: selectedAddress, to: '0x0d1d4e623D10F9FBA5Db95830F7d3839406C6AF2' }) .catch((err) => { - if (err.message === 'MetaMask is having trouble connecting to the network') done() - else done(err) + if (err.message === 'MetaMask is having trouble connecting to the network') { + done() + } else { + done(err) + } }) }) }) @@ -403,7 +414,9 @@ describe('Transaction Controller', function () { assert.equal(status, 'rejected', 'status should e rejected') assert.equal(txId, 0, 'id should e 0') done() - } catch (e) { done(e) } + } catch (e) { + done(e) + } }) txController.cancelTransaction(0) @@ -498,7 +511,9 @@ describe('Transaction Controller', function () { }) it('should ignore the error "Transaction Failed: known transaction" and be as usual', async function () { - providerResultStub['eth_sendRawTransaction'] = async (_, __, ___, end) => { end('Transaction Failed: known transaction') } + providerResultStub['eth_sendRawTransaction'] = async (_, __, ___, end) => { + end('Transaction Failed: known transaction') + } const rawTx = '0xf86204831e848082520894f231d46dd78806e1dd93442cf33c7671f853874880802ca05f973e540f2d3c2f06d3725a626b75247593cb36477187ae07ecfe0a4db3cf57a00259b52ee8c58baaa385fb05c3f96116e58de89bcc165cb3bfdfc708672fed8a' txController.txStateManager.addTx(txMeta) await txController.publishTransaction(txMeta.id, rawTx) @@ -617,7 +632,9 @@ describe('Transaction Controller', function () { _blockTrackerStub.getLatestBlock = noop const _txController = new TransactionController({ provider: _provider, - getGasPrice: function () { return '0xee6b2800' }, + getGasPrice: function () { + return '0xee6b2800' + }, networkStore: new ObservableStore(currentNetworkId), txHistoryLimit: 10, blockTracker: _blockTrackerStub, @@ -647,7 +664,9 @@ describe('Transaction Controller', function () { _blockTrackerStub.getLatestBlock = noop const _txController = new TransactionController({ provider: _provider, - getGasPrice: function () { return '0xee6b2800' }, + getGasPrice: function () { + return '0xee6b2800' + }, networkStore: new ObservableStore(currentNetworkId), txHistoryLimit: 10, blockTracker: _blockTrackerStub, diff --git a/test/unit/app/controllers/transactions/tx-state-history-helper-test.js b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js index 328c2ac6f..6136de66e 100644 --- a/test/unit/app/controllers/transactions/tx-state-history-helper-test.js +++ b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js @@ -106,7 +106,9 @@ describe('Transaction state history helper', function () { assert.equal(result[0].path, expectedEntry1.path) assert.equal(result[0].value, expectedEntry1.value) assert.equal(result[0].value, expectedEntry1.value) - if (note) { assert.equal(result[0].note, note) } + if (note) { + assert.equal(result[0].note, note) + } assert.ok(result[0].timestamp >= before && result[0].timestamp <= after) diff --git a/test/unit/app/controllers/transactions/tx-utils-test.js b/test/unit/app/controllers/transactions/tx-utils-test.js index 65c8d35b0..1c5d20b09 100644 --- a/test/unit/app/controllers/transactions/tx-utils-test.js +++ b/test/unit/app/controllers/transactions/tx-utils-test.js @@ -66,7 +66,9 @@ describe('txUtils', function () { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', to: '0x', } - assert.throws(() => { txUtils.validateRecipient(zeroRecipientTxParams) }, Error, 'Invalid recipient address') + assert.throws(() => { + txUtils.validateRecipient(zeroRecipientTxParams) + }, Error, 'Invalid recipient address') }) }) @@ -76,19 +78,27 @@ describe('txUtils', function () { // where from is undefined const txParams = {} - assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`) + assert.throws(() => { + txUtils.validateFrom(txParams) + }, Error, `Invalid from address ${txParams.from} not a string`) // where from is array txParams.from = [] - assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`) + assert.throws(() => { + txUtils.validateFrom(txParams) + }, Error, `Invalid from address ${txParams.from} not a string`) // where from is a object txParams.from = {} - assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address ${txParams.from} not a string`) + assert.throws(() => { + txUtils.validateFrom(txParams) + }, Error, `Invalid from address ${txParams.from} not a string`) // where from is a invalid address txParams.from = 'im going to fail' - assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address`) + assert.throws(() => { + txUtils.validateFrom(txParams) + }, Error, `Invalid from address`) // should run txParams.from = '0x1678a085c290ebd122dc42cba69373b5953b831d' diff --git a/test/unit/app/nodeify-test.js b/test/unit/app/nodeify-test.js index fa5e49fb2..fc06803db 100644 --- a/test/unit/app/nodeify-test.js +++ b/test/unit/app/nodeify-test.js @@ -33,7 +33,9 @@ describe('nodeify', function () { }) it('no callback - should asyncly throw an error if underlying function does', function (done) { - const nodified = nodeify(async () => { throw new Error('boom!') }, obj) + const nodified = nodeify(async () => { + throw new Error('boom!') + }, obj) process.prependOnceListener('uncaughtException', function (err) { assert.ok(err, 'got expected error') assert.ok(err.message.includes('boom!'), 'got expected error message') @@ -50,7 +52,9 @@ describe('nodeify', function () { const nodified = nodeify(() => 42) try { nodified((err, result) => { - if (err) return done(new Error(`should not have thrown any error: ${err.message}`)) + if (err) { + return done(new Error(`should not have thrown any error: ${err.message}`)) + } assert.equal(42, result, 'got expected result') }) done() @@ -60,10 +64,14 @@ describe('nodeify', function () { }) it('sync functions - handles errors', function (done) { - const nodified = nodeify(() => { throw new Error('boom!') }) + const nodified = nodeify(() => { + throw new Error('boom!') + }) try { nodified((err, result) => { - if (result) return done(new Error('should not have returned any result')) + if (result) { + return done(new Error('should not have returned any result')) + } assert.ok(err, 'got expected error') assert.ok(err.message.includes('boom!'), 'got expected error message') }) diff --git a/test/unit/migrations/023-test.js b/test/unit/migrations/023-test.js index 1b47dea92..7c93feefe 100644 --- a/test/unit/migrations/023-test.js +++ b/test/unit/migrations/023-test.js @@ -37,7 +37,9 @@ let nonDeletableCount = 0 let status while (transactions.length <= 100) { status = txStates[Math.floor(Math.random() * Math.floor(txStates.length - 1))] - if (!deletableTxStates.find((s) => s === status)) nonDeletableCount++ + if (!deletableTxStates.find((s) => s === status)) { + nonDeletableCount++ + } transactions.push({status}) } diff --git a/test/unit/migrations/024-test.js b/test/unit/migrations/024-test.js index 671c7f832..9a6a6661a 100644 --- a/test/unit/migrations/024-test.js +++ b/test/unit/migrations/024-test.js @@ -31,8 +31,11 @@ describe('storage is migrated successfully and the txParams.from are lowercase', .then((migratedData) => { const migratedTransactions = migratedData.data.TransactionController.transactions migratedTransactions.forEach((tx) => { - if (tx.status === 'unapproved') assert.equal(tx.txParams.from, '0x8acce2391c0d510a6c5e5d8f819a678f79b7e675') - else assert.equal(tx.txParams.from, '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675') + if (tx.status === 'unapproved') { + assert.equal(tx.txParams.from, '0x8acce2391c0d510a6c5e5d8f819a678f79b7e675') + } else { + assert.equal(tx.txParams.from, '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675') + } }) done() }).catch(done) diff --git a/test/unit/migrations/025-test.js b/test/unit/migrations/025-test.js index fa89bc54f..cabaecd41 100644 --- a/test/unit/migrations/025-test.js +++ b/test/unit/migrations/025-test.js @@ -32,8 +32,12 @@ describe('storage is migrated successfully and the txParams.from are lowercase', .then((migratedData) => { const migratedTransactions = migratedData.data.TransactionController.transactions migratedTransactions.forEach((tx) => { - if (tx.status === 'unapproved') assert(!tx.txParams.random) - if (tx.status === 'unapproved') assert(!tx.txParams.chainId) + if (tx.status === 'unapproved') { + assert(!tx.txParams.random) + } + if (tx.status === 'unapproved') { + assert(!tx.txParams.chainId) + } }) done() }).catch(done) diff --git a/test/unit/migrations/027-test.js b/test/unit/migrations/027-test.js index 3ec9f0c0e..767243a25 100644 --- a/test/unit/migrations/027-test.js +++ b/test/unit/migrations/027-test.js @@ -30,7 +30,9 @@ describe('migration #27', () => { const newTransactions = newStorage.data.TransactionController.transactions assert.equal(newTransactions.length, 6, 'transactions is expected to have the length of 6') newTransactions.forEach((txMeta) => { - if (txMeta.status === 'rejected') done(new Error('transaction was found with a status of rejected')) + if (txMeta.status === 'rejected') { + done(new Error('transaction was found with a status of rejected')) + } }) done() }) diff --git a/test/unit/migrations/029-test.js b/test/unit/migrations/029-test.js index 7f9b8a005..ca0996389 100644 --- a/test/unit/migrations/029-test.js +++ b/test/unit/migrations/029-test.js @@ -28,7 +28,9 @@ describe('storage is migrated successfully where transactions that are submitted assert(txMeta1.err.message.includes('too long'), 'error message assigned') txs.forEach((tx) => { - if (tx.id === 1) return + if (tx.id === 1) { + return + } assert.notEqual(tx.status, 'failed', 'other tx is not auto failed') }) diff --git a/test/unit/migrations/migrator-test.js b/test/unit/migrations/migrator-test.js index 3dcc5aff7..9a949def4 100644 --- a/test/unit/migrations/migrator-test.js +++ b/test/unit/migrations/migrator-test.js @@ -58,7 +58,9 @@ describe('Migrator', () => { it('should emit an error', function (done) { this.timeout(15000) - const migrator = new Migrator({ migrations: [{ version: 1, migrate: async () => { throw new Error('test') } } ] }) + const migrator = new Migrator({ migrations: [{ version: 1, migrate: async () => { + throw new Error('test') + } } ] }) migrator.on('error', () => done()) migrator.migrateData({ meta: {version: 0} }) .then(() => { diff --git a/test/unit/test-utils.js b/test/unit/test-utils.js index 7d0ae4d91..de508c504 100644 --- a/test/unit/test-utils.js +++ b/test/unit/test-utils.js @@ -10,7 +10,9 @@ async function assertRejects (asyncFn, regExp) { try { await asyncFn() } catch (error) { - f = () => { throw error } + f = () => { + throw error + } } finally { assert.throws(f, regExp) } diff --git a/test/unit/util_test.js b/test/unit/util_test.js index 87f57b218..768288ce7 100644 --- a/test/unit/util_test.js +++ b/test/unit/util_test.js @@ -7,7 +7,9 @@ var util = require(path.join(__dirname, '..', '..', 'ui', 'app', 'helpers', 'uti describe('util', function () { var ethInWei = '1' - for (var i = 0; i < 18; i++) { ethInWei += '0' } + for (var i = 0; i < 18; i++) { + ethInWei += '0' + } beforeEach(function () { this.sinon = sinon.createSandbox() diff --git a/ui/app/components/app/dropdowns/components/menu.js b/ui/app/components/app/dropdowns/components/menu.js index 63501eaa9..950ccccb7 100644 --- a/ui/app/components/app/dropdowns/components/menu.js +++ b/ui/app/components/app/dropdowns/components/menu.js @@ -3,7 +3,9 @@ const Component = require('react').Component const h = require('react-hyperscript') inherits(Menu, Component) -function Menu () { Component.call(this) } +function Menu () { + Component.call(this) +} Menu.prototype.render = function () { const { className = '', children, isShowing } = this.props @@ -13,7 +15,9 @@ Menu.prototype.render = function () { } inherits(Item, Component) -function Item () { Component.call(this) } +function Item () { + Component.call(this) +} Item.prototype.render = function () { const { @@ -37,14 +41,18 @@ Item.prototype.render = function () { } inherits(Divider, Component) -function Divider () { Component.call(this) } +function Divider () { + Component.call(this) +} Divider.prototype.render = function () { return h('div.menu__divider') } inherits(CloseArea, Component) -function CloseArea () { Component.call(this) } +function CloseArea () { + Component.call(this) +} CloseArea.prototype.render = function () { return h('div.menu__close-area', { onClick: this.props.onClick }) diff --git a/ui/app/components/app/dropdowns/network-dropdown.js b/ui/app/components/app/dropdowns/network-dropdown.js index e6a24ef11..d36f10d40 100644 --- a/ui/app/components/app/dropdowns/network-dropdown.js +++ b/ui/app/components/app/dropdowns/network-dropdown.js @@ -370,7 +370,9 @@ NetworkDropdown.prototype.renderCustomOption = function (provider) { const props = this.props const network = props.network - if (type !== 'rpc') return null + if (type !== 'rpc') { + return null + } switch (rpcTarget) { diff --git a/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js b/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js index 419cae0cd..452544abe 100644 --- a/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js +++ b/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js @@ -214,7 +214,9 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate tick: { values: [Math.floor(gasPrices[0]), Math.ceil(gasPricesMax)], outer: false, - format: function (val) { return val + ' GWEI' }, + format: function (val) { + return val + ' GWEI' + }, }, padding: {left: gasPricesMax / 50, right: gasPricesMax / 50}, label: { diff --git a/ui/app/components/app/input-number.js b/ui/app/components/app/input-number.js index 8a6ec725c..ed678755f 100644 --- a/ui/app/components/app/input-number.js +++ b/ui/app/components/app/input-number.js @@ -28,7 +28,9 @@ function removeLeadingZeroes (str) { InputNumber.prototype.setValue = function (newValue) { newValue = removeLeadingZeroes(newValue) - if (newValue && !isValidInput(newValue)) return + if (newValue && !isValidInput(newValue)) { + return + } const { fixed, min = -1, max = Infinity, onChange } = this.props newValue = fixed ? newValue.toFixed(4) : newValue diff --git a/ui/app/components/app/token-list.js b/ui/app/components/app/token-list.js index 000ca6b3f..c15e86e1d 100644 --- a/ui/app/components/app/token-list.js +++ b/ui/app/components/app/token-list.js @@ -105,7 +105,9 @@ TokenList.prototype.createFreshTokenTracker = function () { this.tracker.removeListener('error', this.showError) } - if (!global.ethereumProvider) return + if (!global.ethereumProvider) { + return + } const { userAddress } = this.props this.tracker = new TokenTracker({ @@ -154,7 +156,9 @@ TokenList.prototype.componentDidUpdate = function (prevProps) { const oldTokensLength = tokens ? tokens.length : 0 const tokensLengthUnchanged = oldTokensLength === newTokens.length - if (tokensLengthUnchanged && shouldUpdateTokens) return + if (tokensLengthUnchanged && shouldUpdateTokens) { + return + } this.setState({ isLoading: true }) this.createFreshTokenTracker() @@ -168,7 +172,9 @@ TokenList.prototype.updateBalances = function (tokens) { } TokenList.prototype.componentWillUnmount = function () { - if (!this.tracker) return + if (!this.tracker) { + return + } this.tracker.stop() this.tracker.removeListener('update', this.balanceUpdater) this.tracker.removeListener('error', this.showError) diff --git a/ui/app/components/ui/eth-balance.js b/ui/app/components/ui/eth-balance.js index 7d577b716..63d0057c5 100644 --- a/ui/app/components/ui/eth-balance.js +++ b/ui/app/components/ui/eth-balance.js @@ -43,8 +43,12 @@ EthBalanceComponent.prototype.render = function () { ) } EthBalanceComponent.prototype.renderBalance = function (value) { - if (value === 'None') return value - if (value === '...') return value + if (value === 'None') { + return value + } + if (value === '...') { + return value + } const { conversionRate, diff --git a/ui/app/components/ui/fiat-value.js b/ui/app/components/ui/fiat-value.js index 02111ba49..cabdd479d 100644 --- a/ui/app/components/ui/fiat-value.js +++ b/ui/app/components/ui/fiat-value.js @@ -17,7 +17,9 @@ FiatValue.prototype.render = function () { const value = formatBalance(props.value, 6) - if (value === 'None') return value + if (value === 'None') { + return value + } var fiatDisplayNumber, fiatTooltipNumber var splitBalance = value.split(' ') diff --git a/ui/app/components/ui/mascot.js b/ui/app/components/ui/mascot.js index 3b0d3e31b..e54a464db 100644 --- a/ui/app/components/ui/mascot.js +++ b/ui/app/components/ui/mascot.js @@ -46,7 +46,9 @@ Mascot.prototype.componentWillUnmount = function () { Mascot.prototype.handleAnimationEvents = function () { // only setup listeners once - if (this.animations) return + if (this.animations) { + return + } this.animations = this.props.animationEventEmitter this.animations.on('point', this.lookAt.bind(this)) this.animations.on('setFollowMouse', this.logo.setFollowMouse.bind(this.logo)) diff --git a/ui/app/components/ui/unit-input/unit-input.component.js b/ui/app/components/ui/unit-input/unit-input.component.js index 01a2e7cf1..55797440f 100644 --- a/ui/app/components/ui/unit-input/unit-input.component.js +++ b/ui/app/components/ui/unit-input/unit-input.component.js @@ -91,7 +91,9 @@ export default class UnitInput extends PureComponent { onChange={this.handleChange} onBlur={this.handleBlur} style={{ width: this.getInputWidth(value) }} - ref={ref => { this.unitInput = ref }} + ref={ref => { + this.unitInput = ref + }} disabled={maxModeOn} /> { diff --git a/ui/app/ducks/index.js b/ui/app/ducks/index.js index 6808252ef..f9c8821b0 100644 --- a/ui/app/ducks/index.js +++ b/ui/app/ducks/index.js @@ -67,7 +67,9 @@ window.getCleanAppState = function () { window.logStateString = function (cb) { const state = window.getCleanAppState() global.platform.getPlatformInfo((err, platform) => { - if (err) return cb(err) + if (err) { + return cb(err) + } state.platform = platform const stateString = JSON.stringify(state, null, 2) cb(null, stateString) diff --git a/ui/app/helpers/utils/util.js b/ui/app/helpers/utils/util.js index 19aabb770..96557c62e 100644 --- a/ui/app/helpers/utils/util.js +++ b/ui/app/helpers/utils/util.js @@ -73,13 +73,19 @@ function isEthNetwork (netId) { } function valuesFor (obj) { - if (!obj) return [] + if (!obj) { + return [] + } return Object.keys(obj) - .map(function (key) { return obj[key] }) + .map(function (key) { + return obj[key] + }) } function addressSummary (address, firstSegLength = 10, lastSegLength = 4, includeHex = true) { - if (!address) return '' + if (!address) { + return '' + } let checked = checksumAddress(address) if (!includeHex) { checked = ethUtil.stripHexPrefix(checked) @@ -88,14 +94,18 @@ function addressSummary (address, firstSegLength = 10, lastSegLength = 4, includ } function miniAddressSummary (address) { - if (!address) return '' + if (!address) { + return '' + } var checked = checksumAddress(address) return checked ? checked.slice(0, 4) + '...' + checked.slice(-4) : '...' } function isValidAddress (address) { var prefixed = ethUtil.addHexPrefix(address) - if (address === '0x0000000000000000000000000000000000000000') return false + if (address === '0x0000000000000000000000000000000000000000') { + return false + } return (isAllOneCase(prefixed) && ethUtil.isValidAddress(prefixed)) || ethUtil.isValidChecksumAddress(prefixed) } @@ -105,12 +115,16 @@ function isValidENSAddress (address) { function isInvalidChecksumAddress (address) { var prefixed = ethUtil.addHexPrefix(address) - if (address === '0x0000000000000000000000000000000000000000') return false + if (address === '0x0000000000000000000000000000000000000000') { + return false + } return !isAllOneCase(prefixed) && !ethUtil.isValidChecksumAddress(prefixed) && ethUtil.isValidAddress(prefixed) } function isAllOneCase (address) { - if (!address) return true + if (!address) { + return true + } var lower = address.toLowerCase() var upper = address.toUpperCase() return address === lower || address === upper @@ -118,7 +132,9 @@ function isAllOneCase (address) { // Takes wei Hex, returns wei BN, even if input is null function numericBalance (balance) { - if (!balance) return new ethUtil.BN(0, 16) + if (!balance) { + return new ethUtil.BN(0, 16) + } var stripped = ethUtil.stripHexPrefix(balance) return new ethUtil.BN(stripped, 16) } @@ -132,7 +148,9 @@ function parseBalance (balance) { beforeDecimal = weiString.length > 18 ? weiString.slice(0, weiString.length - 18) : '0' afterDecimal = ('000000000000000000' + wei).slice(-18).replace(trailingZeros, '') - if (afterDecimal === '') { afterDecimal = '0' } + if (afterDecimal === '') { + afterDecimal = '0' + } return [beforeDecimal, afterDecimal] } @@ -147,7 +165,9 @@ function formatBalance (balance, decimalsToKeep, needsParse = true, ticker = 'ET if (beforeDecimal === '0') { if (afterDecimal !== '0') { var sigFigs = afterDecimal.match(/^0*(.{2})/) // default: grabs 2 most significant digits - if (sigFigs) { afterDecimal = sigFigs[0] } + if (sigFigs) { + afterDecimal = sigFigs[0] + } formatted = '0.' + afterDecimal + ` ${ticker}` } } else { diff --git a/ui/app/pages/confirm-transaction/confirm-transaction.component.js b/ui/app/pages/confirm-transaction/confirm-transaction.component.js index 9cb69e0da..eb87c57ba 100644 --- a/ui/app/pages/confirm-transaction/confirm-transaction.component.js +++ b/ui/app/pages/confirm-transaction/confirm-transaction.component.js @@ -75,7 +75,9 @@ export default class ConfirmTransaction extends Component { getTokenParams(to) } const txId = transactionId || paramsTransactionId - if (txId) this.props.setTransactionToConfirm(txId) + if (txId) { + this.props.setTransactionToConfirm(txId) + } if (trackABTest) { this.context.metricsEvent({ diff --git a/ui/app/pages/create-account/connect-hardware/connect-screen.js b/ui/app/pages/create-account/connect-hardware/connect-screen.js index 3b45e7293..b1323b467 100644 --- a/ui/app/pages/create-account/connect-hardware/connect-screen.js +++ b/ui/app/pages/create-account/connect-hardware/connect-screen.js @@ -104,7 +104,9 @@ class ConnectScreen extends Component { scrollToTutorial = () => { - if (this.referenceNode) this.referenceNode.scrollIntoView({behavior: 'smooth'}) + if (this.referenceNode) { + this.referenceNode.scrollIntoView({behavior: 'smooth'}) + } } renderLearnMore () { @@ -141,7 +143,9 @@ class ConnectScreen extends Component { ] return h('.hw-tutorial', { - ref: node => { this.referenceNode = node }, + ref: node => { + this.referenceNode = node + }, }, steps.map((step) => ( h('div.hw-connect', {}, [ diff --git a/ui/app/pages/mobile-sync/index.js b/ui/app/pages/mobile-sync/index.js index bd2385808..078d2a5f6 100644 --- a/ui/app/pages/mobile-sync/index.js +++ b/ui/app/pages/mobile-sync/index.js @@ -170,7 +170,9 @@ class MobileSyncPage extends Component { } async startSyncing () { - if (this.syncing) return false + if (this.syncing) { + return false + } this.syncing = true this.setState({syncing: true}) diff --git a/ui/app/pages/routes/index.js b/ui/app/pages/routes/index.js index 01e61b1b4..45da4d097 100644 --- a/ui/app/pages/routes/index.js +++ b/ui/app/pages/routes/index.js @@ -261,7 +261,9 @@ class Routes extends Component { if (!this.props.isUnlocked) { // currently inactive: redirect to password box var passwordBox = document.querySelector('input[type=password]') - if (!passwordBox) return + if (!passwordBox) { + return + } passwordBox.focus() } else { // currently active: deactivate diff --git a/ui/app/pages/send/send-content/add-recipient/ens-input.component.js b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js index 8f8023fd0..5294388ac 100644 --- a/ui/app/pages/send/send-content/add-recipient/ens-input.component.js +++ b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js @@ -86,8 +86,12 @@ export default class EnsInput extends Component { log.info(`ENS attempting to resolve name: ${recipient}`) this.ens.lookup(recipient) .then((address) => { - if (address === ZERO_ADDRESS) throw new Error(this.context.t('noAddressForName')) - if (address === ZERO_X_ERROR_ADDRESS) throw new Error(this.context.t('ensRegistrationError')) + if (address === ZERO_ADDRESS) { + throw new Error(this.context.t('noAddressForName')) + } + if (address === ZERO_X_ERROR_ADDRESS) { + throw new Error(this.context.t('ensRegistrationError')) + } this.props.updateEnsResolution(address) }) .catch((reason) => { @@ -232,7 +236,9 @@ export default class EnsInput extends Component { ensIconContents () { const { loadingEns, ensFailure, ensResolution, toError } = this.state || { ensResolution: ZERO_ADDRESS } - if (toError) return + if (toError) { + return + } if (loadingEns) { return ( diff --git a/ui/app/pages/send/send.component.js b/ui/app/pages/send/send.component.js index d699e27a7..e348e283b 100644 --- a/ui/app/pages/send/send.component.js +++ b/ui/app/pages/send/send.component.js @@ -304,7 +304,9 @@ export default class SendTransactionScreen extends PersistentForm { }} onChange={this.onRecipientInputChange} onValidAddressTyped={(address) => this.props.updateSendTo(address, '')} - onPaste={text => { this.props.updateSendTo(text) && this.updateGas() }} + onPaste={text => { + this.props.updateSendTo(text) && this.updateGas() + }} onReset={() => this.props.updateSendTo('', '')} updateEnsResolution={this.props.updateSendEnsResolution} updateEnsResolutionError={this.props.updateSendEnsResolutionError} diff --git a/ui/app/pages/send/send.utils.js b/ui/app/pages/send/send.utils.js index 89513bfc1..aef9c7e78 100644 --- a/ui/app/pages/send/send.utils.js +++ b/ui/app/pages/send/send.utils.js @@ -293,18 +293,24 @@ function addGasBuffer (initialGasLimitHex, blockGasLimitHex, bufferMultiplier = if (conversionGreaterThan( { value: initialGasLimitHex, fromNumericBase: 'hex' }, { value: upperGasLimit, fromNumericBase: 'hex' }, - )) return initialGasLimitHex + )) { + return initialGasLimitHex + } // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit if (conversionLessThan( { value: bufferedGasLimit, fromNumericBase: 'hex' }, { value: upperGasLimit, fromNumericBase: 'hex' }, - )) return bufferedGasLimit + )) { + return bufferedGasLimit + } // otherwise use blockGasLimit return upperGasLimit } function generateTokenTransferData ({ toAddress = '0x0', amount = '0x0', selectedToken }) { - if (!selectedToken) return + if (!selectedToken) { + return + } return TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call( abi.rawEncode(['address', 'uint256'], [toAddress, ethUtil.addHexPrefix(amount)]), x => ('00' + x.toString(16)).slice(-2) diff --git a/ui/app/pages/send/tests/send-utils.test.js b/ui/app/pages/send/tests/send-utils.test.js index 4930b7ee1..9f6a01ad5 100644 --- a/ui/app/pages/send/tests/send-utils.test.js +++ b/ui/app/pages/send/tests/send-utils.test.js @@ -18,8 +18,12 @@ const { const stubs = { addCurrencies: sinon.stub().callsFake((a, b) => { - if (String(a).match(/^0x.+/)) a = Number(String(a).slice(2)) - if (String(b).match(/^0x.+/)) b = Number(String(b).slice(2)) + if (String(a).match(/^0x.+/)) { + a = Number(String(a).slice(2)) + } + if (String(b).match(/^0x.+/)) { + b = Number(String(b).slice(2)) + } return a + b }), conversionUtil: sinon.stub().callsFake((val) => parseInt(val, 16)), diff --git a/ui/app/pages/settings/contact-list-tab/add-contact/add-contact.component.js b/ui/app/pages/settings/contact-list-tab/add-contact/add-contact.component.js index 56d4415cf..9e3bc791b 100644 --- a/ui/app/pages/settings/contact-list-tab/add-contact/add-contact.component.js +++ b/ui/app/pages/settings/contact-list-tab/add-contact/add-contact.component.js @@ -63,7 +63,9 @@ export default class AddContact extends PureComponent { return ( { this.props.scanQrCode() }} + scanQrCode={_ => { + this.props.scanQrCode() + }} onChange={this.dValidate} onPaste={text => this.setState({ ethAddress: text })} onReset={() => this.setState({ ethAddress: '', ensAddress: '' })} diff --git a/ui/app/store/actions.js b/ui/app/store/actions.js index f76024590..e694cfeff 100644 --- a/ui/app/store/actions.js +++ b/ui/app/store/actions.js @@ -675,7 +675,9 @@ function addNewKeyring (type, opts) { log.debug(`background.addNewKeyring`) background.addNewKeyring(type, opts, (err) => { dispatch(actions.hideLoadingIndication()) - if (err) return dispatch(actions.displayWarning(err.message)) + if (err) { + return dispatch(actions.displayWarning(err.message)) + } dispatch(actions.showAccountsPage()) }) } @@ -2288,7 +2290,9 @@ function pairUpdate (coin) { dispatch(actions.hideWarning()) shapeShiftRequest('marketinfo', {pair: `${coin.toLowerCase()}_eth`}, (mktResponse) => { dispatch(actions.hideSubLoadingIndication()) - if (mktResponse.error) return dispatch(actions.displayWarning(mktResponse.error)) + if (mktResponse.error) { + return dispatch(actions.displayWarning(mktResponse.error)) + } dispatch({ type: actions.PAIR_UPDATE, value: { @@ -2306,7 +2310,9 @@ function shapeShiftSubview () { shapeShiftRequest('marketinfo', {pair}, (mktResponse) => { shapeShiftRequest('getcoins', {}, (response) => { dispatch(actions.hideSubLoadingIndication()) - if (mktResponse.error) return dispatch(actions.displayWarning(mktResponse.error)) + if (mktResponse.error) { + return dispatch(actions.displayWarning(mktResponse.error)) + } dispatch({ type: actions.SHAPESHIFT_SUBVIEW, value: { @@ -2324,7 +2330,9 @@ function coinShiftRquest (data, marketData) { dispatch(actions.showLoadingIndication()) shapeShiftRequest('shift', { method: 'POST', data}, (response) => { dispatch(actions.hideLoadingIndication()) - if (response.error) return dispatch(actions.displayWarning(response.error)) + if (response.error) { + return dispatch(actions.displayWarning(response.error)) + } var message = ` Deposit your ${response.depositType} to the address below:` log.debug(`background.createShapeShiftTx`) @@ -2359,7 +2367,9 @@ function reshowQrCode (data, coin) { return (dispatch) => { dispatch(actions.showLoadingIndication()) shapeShiftRequest('marketinfo', {pair: `${coin.toLowerCase()}_eth`}, (mktResponse) => { - if (mktResponse.error) return dispatch(actions.displayWarning(mktResponse.error)) + if (mktResponse.error) { + return dispatch(actions.displayWarning(mktResponse.error)) + } var message = [ `Deposit your ${coin} to the address below:`, diff --git a/ui/index.js b/ui/index.js index 058c09be0..5b268b7b0 100644 --- a/ui/index.js +++ b/ui/index.js @@ -17,7 +17,9 @@ function launchMetamaskUi (opts, cb) { actions._setBackgroundConnection(backgroundConnection) // check if we are unlocked first backgroundConnection.getState(function (err, metamaskState) { - if (err) return cb(err) + if (err) { + return cb(err) + } startApp(metamaskState, backgroundConnection, opts) .then((store) => { cb(null, store) @@ -27,7 +29,9 @@ function launchMetamaskUi (opts, cb) { async function startApp (metamaskState, backgroundConnection, opts) { // parse opts - if (!metamaskState.featureFlags) metamaskState.featureFlags = {} + if (!metamaskState.featureFlags) { + metamaskState.featureFlags = {} + } const currentLocaleMessages = metamaskState.currentLocale ? await fetchLocale(metamaskState.currentLocale)