1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Fix prefer-destructuring issues (#9263)

See [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring) for more information.

This change enables `prefer-destructuring` and fixes the issues raised by the rule.
This commit is contained in:
Whymarrh Whitby 2020-08-18 17:36:58 -02:30 committed by GitHub
parent 8b0a308449
commit 6ab12001e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 105 additions and 99 deletions

View File

@ -71,6 +71,18 @@ module.exports = {
'no-template-curly-in-string': 'error', 'no-template-curly-in-string': 'error',
'no-useless-catch': 'error', 'no-useless-catch': 'error',
'no-useless-concat': 'error', 'no-useless-concat': 'error',
'prefer-destructuring': ['error', {
'VariableDeclarator': {
'array': false,
'object': true,
},
'AssignmentExpression': {
'array': false,
'object': false,
},
}, {
'enforceForRenamedProperties': false,
}],
'prefer-rest-params': 'error', 'prefer-rest-params': 'error',
'prefer-spread': 'error', 'prefer-spread': 'error',
'radix': 'error', 'radix': 'error',

View File

@ -406,11 +406,11 @@ function setupController (initState, initLangCode) {
function updateBadge () { function updateBadge () {
let label = '' let label = ''
const unapprovedTxCount = controller.txController.getUnapprovedTxCount() const unapprovedTxCount = controller.txController.getUnapprovedTxCount()
const unapprovedMsgCount = controller.messageManager.unapprovedMsgCount const { unapprovedMsgCount } = controller.messageManager
const unapprovedPersonalMsgCount = controller.personalMessageManager.unapprovedPersonalMsgCount const { unapprovedPersonalMsgCount } = controller.personalMessageManager
const unapprovedDecryptMsgCount = controller.decryptMessageManager.unapprovedDecryptMsgCount const { unapprovedDecryptMsgCount } = controller.decryptMessageManager
const unapprovedEncryptionPublicKeyMsgCount = controller.encryptionPublicKeyManager.unapprovedEncryptionPublicKeyMsgCount const { unapprovedEncryptionPublicKeyMsgCount } = controller.encryptionPublicKeyManager
const unapprovedTypedMessagesCount = controller.typedMessageManager.unapprovedTypedMessagesCount const { unapprovedTypedMessagesCount } = controller.typedMessageManager
const pendingPermissionRequests = Object.keys(controller.permissionsController.permissions.state.permissionsRequests).length const pendingPermissionRequests = Object.keys(controller.permissionsController.permissions.state.permissionsRequests).length
const waitingForUnlockCount = controller.appStateController.waitingForUnlock.length const waitingForUnlockCount = controller.appStateController.waitingForUnlock.length
const count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgCount + unapprovedDecryptMsgCount + unapprovedEncryptionPublicKeyMsgCount + const count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgCount + unapprovedDecryptMsgCount + unapprovedEncryptionPublicKeyMsgCount +

View File

@ -136,7 +136,7 @@ function shouldInjectProvider () {
* @returns {boolean} {@code true} - if the doctype is html or if none exists * @returns {boolean} {@code true} - if the doctype is html or if none exists
*/ */
function doctypeCheck () { function doctypeCheck () {
const doctype = window.document.doctype const { doctype } = window.document
if (doctype) { if (doctype) {
return doctype.name === 'html' return doctype.name === 'html'
} else { } else {

View File

@ -22,7 +22,7 @@ import {
} from './enums' } from './enums'
const env = process.env.METAMASK_ENV const env = process.env.METAMASK_ENV
const METAMASK_DEBUG = process.env.METAMASK_DEBUG const { METAMASK_DEBUG } = process.env
let defaultProviderConfigType let defaultProviderConfigType
if (process.env.IN_TEST === 'true') { if (process.env.IN_TEST === 'true') {

View File

@ -178,7 +178,7 @@ export default class PreferencesController {
* @param {string} methodData - Corresponding data method * @param {string} methodData - Corresponding data method
*/ */
addKnownMethodData (fourBytePrefix, methodData) { addKnownMethodData (fourBytePrefix, methodData) {
const knownMethodData = this.store.getState().knownMethodData const { knownMethodData } = this.store.getState()
knownMethodData[fourBytePrefix] = methodData knownMethodData[fourBytePrefix] = methodData
this.store.updateState({ knownMethodData }) this.store.updateState({ knownMethodData })
} }
@ -264,8 +264,8 @@ export default class PreferencesController {
* @returns {string} - the address that was removed * @returns {string} - the address that was removed
*/ */
removeAddress (address) { removeAddress (address) {
const identities = this.store.getState().identities const { identities } = this.store.getState()
const accountTokens = this.store.getState().accountTokens const { accountTokens } = this.store.getState()
if (!identities[address]) { if (!identities[address]) {
throw new Error(`${address} can't be deleted cause it was not found`) throw new Error(`${address} can't be deleted cause it was not found`)
} }
@ -290,8 +290,7 @@ export default class PreferencesController {
* *
*/ */
addAddresses (addresses) { addAddresses (addresses) {
const identities = this.store.getState().identities const { identities, accountTokens } = this.store.getState()
const accountTokens = this.store.getState().accountTokens
addresses.forEach((address) => { addresses.forEach((address) => {
// skip if already exists // skip if already exists
if (identities[address]) { if (identities[address]) {
@ -420,7 +419,7 @@ export default class PreferencesController {
async addToken (rawAddress, symbol, decimals, image) { async addToken (rawAddress, symbol, decimals, image) {
const address = normalizeAddress(rawAddress) const address = normalizeAddress(rawAddress)
const newEntry = { address, symbol, decimals } const newEntry = { address, symbol, decimals }
const tokens = this.store.getState().tokens const { tokens } = this.store.getState()
const assetImages = this.getAssetImages() const assetImages = this.getAssetImages()
const previousEntry = tokens.find((token) => { const previousEntry = tokens.find((token) => {
return token.address === address return token.address === address
@ -445,7 +444,7 @@ export default class PreferencesController {
* *
*/ */
removeToken (rawAddress) { removeToken (rawAddress) {
const tokens = this.store.getState().tokens const { tokens } = this.store.getState()
const assetImages = this.getAssetImages() const assetImages = this.getAssetImages()
const updatedTokens = tokens.filter((token) => token.address !== rawAddress) const updatedTokens = tokens.filter((token) => token.address !== rawAddress)
delete assetImages[rawAddress] delete assetImages[rawAddress]
@ -688,7 +687,7 @@ export default class PreferencesController {
* *
*/ */
_getTokenRelatedStates (selectedAddress) { _getTokenRelatedStates (selectedAddress) {
const accountTokens = this.store.getState().accountTokens const { accountTokens } = this.store.getState()
if (!selectedAddress) { if (!selectedAddress) {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
selectedAddress = this.store.getState().selectedAddress selectedAddress = this.store.getState().selectedAddress

View File

@ -35,7 +35,7 @@ export default class ThreeBoxController {
if (origin !== '3Box') { if (origin !== '3Box') {
return [] return []
} }
const isUnlocked = getKeyringControllerState().isUnlocked const { isUnlocked } = getKeyringControllerState()
const accounts = await this.keyringController.getAccounts() const accounts = await this.keyringController.getAccounts()

View File

@ -756,8 +756,7 @@ export default class TransactionController extends EventEmitter {
_setupBlockTrackerListener () { _setupBlockTrackerListener () {
let listenersAreActive = false let listenersAreActive = false
const latestBlockHandler = this._onLatestBlock.bind(this) const latestBlockHandler = this._onLatestBlock.bind(this)
const blockTracker = this.blockTracker const { blockTracker, txStateManager } = this
const txStateManager = this.txStateManager
txStateManager.on('tx:status-update', updateSubscription) txStateManager.on('tx:status-update', updateSubscription)
updateSubscription() updateSubscription()

View File

@ -137,7 +137,7 @@ export default class PendingTransactionTracker extends EventEmitter {
return this.approveTransaction(txMeta.id) return this.approveTransaction(txMeta.id)
} }
const rawTx = txMeta.rawTx const { rawTx } = txMeta
const txHash = await this.publishTransaction(rawTx) const txHash = await this.publishTransaction(rawTx)
// Increment successful tries: // Increment successful tries:

View File

@ -56,7 +56,7 @@ export default class TxGasUtil {
@returns {string} - the estimated gas limit as a hex string @returns {string} - the estimated gas limit as a hex string
*/ */
async estimateTxGas (txMeta) { async estimateTxGas (txMeta) {
const txParams = txMeta.txParams const { txParams } = txMeta
// estimate tx gas requirements // estimate tx gas requirements
return await this.query.estimateGas(txParams) return await this.query.estimateGas(txParams)

View File

@ -178,7 +178,7 @@ export default class TransactionStateManager extends EventEmitter {
const transactions = this.getFullTxList() const transactions = this.getFullTxList()
const txCount = transactions.length const txCount = transactions.length
const txHistoryLimit = this.txHistoryLimit const { txHistoryLimit } = this
// checks if the length of the tx history is // checks if the length of the tx history is
// longer then desired persistence limit // longer then desired persistence limit

View File

@ -92,7 +92,7 @@ export default class AccountTracker {
* *
*/ */
syncWithAddresses (addresses) { syncWithAddresses (addresses) {
const accounts = this.store.getState().accounts const { accounts } = this.store.getState()
const locals = Object.keys(accounts) const locals = Object.keys(accounts)
const accountsToAdd = [] const accountsToAdd = []
@ -121,7 +121,7 @@ export default class AccountTracker {
* *
*/ */
addAccounts (addresses) { addAccounts (addresses) {
const accounts = this.store.getState().accounts const { accounts } = this.store.getState()
// add initial state for addresses // add initial state for addresses
addresses.forEach((address) => { addresses.forEach((address) => {
accounts[address] = {} accounts[address] = {}
@ -142,7 +142,7 @@ export default class AccountTracker {
* *
*/ */
removeAccount (addresses) { removeAccount (addresses) {
const accounts = this.store.getState().accounts const { accounts } = this.store.getState()
// remove each state object // remove each state object
addresses.forEach((address) => { addresses.forEach((address) => {
delete accounts[address] delete accounts[address]
@ -194,7 +194,7 @@ export default class AccountTracker {
* *
*/ */
async _updateAccounts () { async _updateAccounts () {
const accounts = this.store.getState().accounts const { accounts } = this.store.getState()
const addresses = Object.keys(accounts) const addresses = Object.keys(accounts)
const currentNetwork = this.network.getNetworkState() const currentNetwork = this.network.getNetworkState()
@ -248,7 +248,7 @@ export default class AccountTracker {
* @param {*} deployedContractAddress * @param {*} deployedContractAddress
*/ */
async _updateAccountsViaBalanceChecker (addresses, deployedContractAddress) { async _updateAccountsViaBalanceChecker (addresses, deployedContractAddress) {
const accounts = this.store.getState().accounts const { accounts } = this.store.getState()
this.web3.setProvider(this._provider) this.web3.setProvider(this._provider)
const ethContract = this.web3.eth.contract(SINGLE_CALL_BALANCES_ABI).at(deployedContractAddress) const ethContract = this.web3.eth.contract(SINGLE_CALL_BALANCES_ABI).at(deployedContractAddress)
const ethBalance = ['0x0'] const ethBalance = ['0x0']

View File

@ -4,7 +4,7 @@
* @returns {Error} - Error with clean stack trace. * @returns {Error} - Error with clean stack trace.
*/ */
export default function cleanErrorStack (err) { export default function cleanErrorStack (err) {
let name = err.name let { name } = err
name = (name === undefined) ? 'Error' : String(name) name = (name === undefined) ? 'Error' : String(name)
let msg = err.message let msg = err.message

View File

@ -49,7 +49,7 @@ export default class ExtensionStore {
* @returns {Object} - the key-value map from local storage * @returns {Object} - the key-value map from local storage
*/ */
_get () { _get () {
const local = extension.storage.local const { local } = extension.storage
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
local.get(null, (/** @type {any} */ result) => { local.get(null, (/** @type {any} */ result) => {
const err = checkForError() const err = checkForError()
@ -69,7 +69,7 @@ export default class ExtensionStore {
* @private * @private
*/ */
_set (obj) { _set (obj) {
const local = extension.storage.local const { local } = extension.storage
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
local.set(obj, () => { local.set(obj, () => {
const err = checkForError() const err = checkForError()

View File

@ -3,8 +3,7 @@ import { Dedupe, ExtraErrorData } from '@sentry/integrations'
import extractEthjsErrorMessage from './extractEthjsErrorMessage' import extractEthjsErrorMessage from './extractEthjsErrorMessage'
const METAMASK_DEBUG = process.env.METAMASK_DEBUG const { METAMASK_DEBUG, METAMASK_ENVIRONMENT } = process.env
const METAMASK_ENVIRONMENT = process.env.METAMASK_ENVIRONMENT
const SENTRY_DSN_DEV = 'https://f59f3dd640d2429d9d0e2445a87ea8e1@sentry.io/273496' const SENTRY_DSN_DEV = 'https://f59f3dd640d2429d9d0e2445a87ea8e1@sentry.io/273496'
// This describes the subset of Redux state attached to errors sent to Sentry // This describes the subset of Redux state attached to errors sent to Sentry

View File

@ -164,7 +164,7 @@ export default class TypedMessageManager extends EventEmitter {
const validation = jsonschema.validate(data, sigUtil.TYPED_MESSAGE_SCHEMA) 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.ok(data.primaryType in data.types, `Primary type of "${data.primaryType}" has no type definition.`)
assert.equal(validation.errors.length, 0, 'Signing data must conform to EIP-712 schema. See https://git.io/fNtcx.') assert.equal(validation.errors.length, 0, 'Signing data must conform to EIP-712 schema. See https://git.io/fNtcx.')
const chainId = data.domain.chainId const { chainId } = data.domain
// eslint-disable-next-line radix // eslint-disable-next-line radix
const activeChainId = parseInt(this.networkController.getNetworkState()) const activeChainId = parseInt(this.networkController.getNetworkState())
chainId && assert.equal(chainId, activeChainId, `Provided chainId "${chainId}" must match the active chainId "${activeChainId}"`) chainId && assert.equal(chainId, activeChainId, `Provided chainId "${chainId}" must match the active chainId "${activeChainId}"`)

View File

@ -138,7 +138,7 @@ function BnMultiplyByFraction (targetBN, numerator, denominator) {
* @returns {Error|undefined} * @returns {Error|undefined}
*/ */
function checkForError () { function checkForError () {
const lastError = extension.runtime.lastError const { lastError } = extension.runtime
if (!lastError) { if (!lastError) {
return undefined return undefined
} }

View File

@ -406,7 +406,7 @@ export default class MetamaskController extends EventEmitter {
* @returns {Object} - status * @returns {Object} - status
*/ */
getState () { getState () {
const vault = this.keyringController.store.getState().vault const { vault } = this.keyringController.store.getState()
const isInitialized = !!vault const isInitialized = !!vault
return { return {
@ -423,14 +423,16 @@ export default class MetamaskController extends EventEmitter {
* @returns {Object} - Object containing API functions. * @returns {Object} - Object containing API functions.
*/ */
getApi () { getApi () {
const keyringController = this.keyringController const {
const networkController = this.networkController keyringController,
const onboardingController = this.onboardingController networkController,
const alertController = this.alertController onboardingController,
const permissionsController = this.permissionsController alertController,
const preferencesController = this.preferencesController permissionsController,
const threeBoxController = this.threeBoxController preferencesController,
const txController = this.txController threeBoxController,
txController,
} = this
return { return {
// etc // etc
@ -612,7 +614,7 @@ export default class MetamaskController extends EventEmitter {
try { try {
let accounts, lastBalance let accounts, lastBalance
const keyringController = this.keyringController const { keyringController } = this
// clear known identities // clear known identities
this.preferencesController.setAddresses([]) this.preferencesController.setAddresses([])
@ -744,7 +746,7 @@ export default class MetamaskController extends EventEmitter {
// transactions // transactions
let transactions = this.txController.store.getState().transactions let { transactions } = this.txController.store.getState()
// delete tx for other accounts that we're not importing // delete tx for other accounts that we're not importing
transactions = transactions.filter((tx) => { transactions = transactions.filter((tx) => {
const checksummedTxFrom = ethUtil.toChecksumAddress(tx.txParams.from) const checksummedTxFrom = ethUtil.toChecksumAddress(tx.txParams.from)
@ -942,7 +944,7 @@ export default class MetamaskController extends EventEmitter {
if (!primaryKeyring) { if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found') throw new Error('MetamaskController - No HD Key Tree found')
} }
const keyringController = this.keyringController const { keyringController } = this
const oldAccounts = await keyringController.getAccounts() const oldAccounts = await keyringController.getAccounts()
const keyState = await keyringController.addNewAccount(primaryKeyring) const keyState = await keyringController.addNewAccount(primaryKeyring)
const newAccounts = await keyringController.getAccounts() const newAccounts = await keyringController.getAccounts()
@ -1112,7 +1114,7 @@ export default class MetamaskController extends EventEmitter {
* @param {string} msgId - The id of the message to cancel. * @param {string} msgId - The id of the message to cancel.
*/ */
cancelMessage (msgId, cb) { cancelMessage (msgId, cb) {
const messageManager = this.messageManager const { messageManager } = this
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (cb && typeof cb === 'function') {
cb(null, this.getState()) cb(null, this.getState())
@ -1347,7 +1349,7 @@ export default class MetamaskController extends EventEmitter {
async signTypedMessage (msgParams) { async signTypedMessage (msgParams) {
log.info('MetaMaskController - eth_signTypedData') log.info('MetaMaskController - eth_signTypedData')
const msgId = msgParams.metamaskId const msgId = msgParams.metamaskId
const version = msgParams.version const { version } = msgParams
try { try {
const cleanMsgParams = await this.typedMessageManager.approveMessage(msgParams) const cleanMsgParams = await this.typedMessageManager.approveMessage(msgParams)
@ -1460,7 +1462,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
setupUntrustedCommunication (connectionStream, sender) { setupUntrustedCommunication (connectionStream, sender) {
const { usePhishDetect } = this.preferencesController.store.getState() const { usePhishDetect } = this.preferencesController.store.getState()
const hostname = (new URL(sender.url)).hostname const { hostname } = new URL(sender.url)
// Check if new connection is blocked if phishing detection is on // Check if new connection is blocked if phishing detection is on
if (usePhishDetect && this.phishingController.test(hostname)) { if (usePhishDetect && this.phishingController.test(hostname)) {
log.debug('MetaMask - sending phishing warning for', hostname) log.debug('MetaMask - sending phishing warning for', hostname)
@ -1599,8 +1601,7 @@ export default class MetamaskController extends EventEmitter {
setupProviderEngine ({ origin, location, extensionId, tabId, isInternal = false }) { setupProviderEngine ({ origin, location, extensionId, tabId, isInternal = false }) {
// setup json rpc engine stack // setup json rpc engine stack
const engine = new RpcEngine() const engine = new RpcEngine()
const provider = this.provider const { provider, blockTracker } = this
const blockTracker = this.blockTracker
// create filter polyfill middleware // create filter polyfill middleware
const filterMiddleware = createFilterMiddleware({ provider, blockTracker }) const filterMiddleware = createFilterMiddleware({ provider, blockTracker })

View File

@ -27,7 +27,7 @@ export default {
} }
function selectSubstateForKeyringController (state) { function selectSubstateForKeyringController (state) {
const config = state.config const { config } = state
const newState = { const newState = {
...state, ...state,
KeyringController: { KeyringController: {

View File

@ -30,7 +30,7 @@ function transformState (state) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = TransactionController.transactions const { transactions } = TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (!txMeta.err) { if (!txMeta.err) {
return txMeta return txMeta

View File

@ -30,7 +30,7 @@ function transformState (state) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (!txMeta.err) { if (!txMeta.err) {

View File

@ -29,7 +29,7 @@ function transformState (state) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (!txMeta.status === 'failed') { if (!txMeta.status === 'failed') {
return txMeta return txMeta

View File

@ -34,7 +34,7 @@ function transformState (state) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
// no history: initialize // no history: initialize
if (!txMeta.history || txMeta.history.length === 0) { if (!txMeta.history || txMeta.history.length === 0) {

View File

@ -32,7 +32,7 @@ function transformState (state) {
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta, _, txList) => { newState.TransactionController.transactions = transactions.map((txMeta, _, txList) => {
if (txMeta.status !== 'submitted') { if (txMeta.status !== 'submitted') {
@ -66,7 +66,7 @@ function transformState (state) {
function getHighestContinuousFrom (txList, startPoint) { function getHighestContinuousFrom (txList, startPoint) {
const nonces = txList.map((txMeta) => { const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce const { nonce } = txMeta.txParams
return parseInt(nonce, 16) return parseInt(nonce, 16)
}) })
@ -80,7 +80,7 @@ function getHighestContinuousFrom (txList, startPoint) {
function getHighestNonce (txList) { function getHighestNonce (txList) {
const nonces = txList.map((txMeta) => { const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce const { nonce } = txMeta.txParams
return parseInt(nonce || '0x0', 16) return parseInt(nonce || '0x0', 16)
}) })
const highestNonce = Math.max.apply(null, nonces) const highestNonce = Math.max.apply(null, nonces)

View File

@ -30,7 +30,7 @@ function transformState (state) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (txMeta.status !== 'submitted' || txMeta.submittedTime) { if (txMeta.status !== 'submitted' || txMeta.submittedTime) {

View File

@ -31,7 +31,7 @@ function transformState (state) {
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
if (transactions.length <= 40) { if (transactions.length <= 40) {
return newState return newState

View File

@ -28,7 +28,7 @@ function transformState (state) {
if (!newState.TransactionController) { if (!newState.TransactionController) {
return newState return newState
} }
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta, _) => { newState.TransactionController.transactions = transactions.map((txMeta, _) => {
if ( if (
txMeta.status === 'unapproved' && txMeta.status === 'unapproved' &&

View File

@ -28,7 +28,7 @@ function transformState (state) {
if (newState.TransactionController) { if (newState.TransactionController) {
if (newState.TransactionController.transactions) { if (newState.TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (txMeta.status !== 'unapproved') { if (txMeta.status !== 'unapproved') {
return txMeta return txMeta

View File

@ -26,7 +26,7 @@ function transformState (state) {
if (newState.TransactionController) { if (newState.TransactionController) {
if (newState.TransactionController.transactions) { if (newState.TransactionController.transactions) {
const transactions = newState.TransactionController.transactions const { transactions } = newState.TransactionController
newState.TransactionController.transactions = transactions.filter((txMeta) => txMeta.status !== 'rejected') newState.TransactionController.transactions = transactions.filter((txMeta) => txMeta.status !== 'rejected')
} }
} }

View File

@ -26,8 +26,7 @@ function transformState (state) {
if (newState.PreferencesController) { if (newState.PreferencesController) {
if (newState.PreferencesController.tokens && newState.PreferencesController.identities) { if (newState.PreferencesController.tokens && newState.PreferencesController.identities) {
const identities = newState.PreferencesController.identities const { identities, tokens } = newState.PreferencesController
const tokens = newState.PreferencesController.tokens
newState.PreferencesController.accountTokens = {} newState.PreferencesController.accountTokens = {}
Object.keys(identities).forEach((identity) => { Object.keys(identities).forEach((identity) => {
newState.PreferencesController.accountTokens[identity] = { 'mainnet': tokens } newState.PreferencesController.accountTokens[identity] = { 'mainnet': tokens }

View File

@ -25,7 +25,7 @@ export default {
function transformState (state) { function transformState (state) {
const newState = state const newState = state
if (state.PreferencesController) { if (state.PreferencesController) {
const frequentRpcListDetail = newState.PreferencesController.frequentRpcListDetail const { frequentRpcListDetail } = newState.PreferencesController
if (frequentRpcListDetail) { if (frequentRpcListDetail) {
frequentRpcListDetail.forEach((rpc, index) => { frequentRpcListDetail.forEach((rpc, index) => {
// eslint-disable-next-line radix // eslint-disable-next-line radix

View File

@ -20,7 +20,7 @@ function transformState (state, condition, reason) {
const newState = state const newState = state
const { TransactionController } = newState const { TransactionController } = newState
if (TransactionController && TransactionController.transactions) { if (TransactionController && TransactionController.transactions) {
const transactions = TransactionController.transactions const { transactions } = TransactionController
newState.TransactionController.transactions = transactions.map((txMeta) => { newState.TransactionController.transactions = transactions.map((txMeta) => {
if (!condition(txMeta)) { if (!condition(txMeta)) {

View File

@ -62,8 +62,7 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
core.prod, core.prod,
) )
const dev = core.dev const { dev, testDev } = core
const testDev = core.testDev
const test = composeParallel( const test = composeParallel(
deps.background, deps.background,

View File

@ -12,12 +12,11 @@ function capitalizeFirstLetter (string) {
async function start () { async function start () {
const GITHUB_COMMENT_TOKEN = process.env.GITHUB_COMMENT_TOKEN const { GITHUB_COMMENT_TOKEN, CIRCLE_PULL_REQUEST } = process.env
const CIRCLE_PULL_REQUEST = process.env.CIRCLE_PULL_REQUEST
console.log('CIRCLE_PULL_REQUEST', CIRCLE_PULL_REQUEST) console.log('CIRCLE_PULL_REQUEST', CIRCLE_PULL_REQUEST)
const CIRCLE_SHA1 = process.env.CIRCLE_SHA1 const { CIRCLE_SHA1 } = process.env
console.log('CIRCLE_SHA1', CIRCLE_SHA1) console.log('CIRCLE_SHA1', CIRCLE_SHA1)
const CIRCLE_BUILD_NUM = process.env.CIRCLE_BUILD_NUM const { CIRCLE_BUILD_NUM } = process.env
console.log('CIRCLE_BUILD_NUM', CIRCLE_BUILD_NUM) console.log('CIRCLE_BUILD_NUM', CIRCLE_BUILD_NUM)
if (!CIRCLE_PULL_REQUEST) { if (!CIRCLE_PULL_REQUEST) {

View File

@ -12,7 +12,7 @@ const defaultOptions = {
class Ganache { class Ganache {
async start (opts) { async start (opts) {
const options = { ...defaultOptions, ...opts } const options = { ...defaultOptions, ...opts }
const port = options.port const { port } = options
this._server = ganache.server(options) this._server = ganache.server(options)
const listen = promisify(this._server.listen).bind(this._server) const listen = promisify(this._server.listen).bind(this._server)

View File

@ -53,7 +53,7 @@ describe('NetworkController', function () {
it('should update provider.type', function () { it('should update provider.type', function () {
networkController.initializeProvider(networkControllerProviderConfig) networkController.initializeProvider(networkControllerProviderConfig)
networkController.setProviderType('mainnet') networkController.setProviderType('mainnet')
const type = networkController.getProviderConfig().type const { type } = networkController.getProviderConfig()
assert.equal(type, 'mainnet', 'provider type is updated') assert.equal(type, 'mainnet', 'provider type is updated')
}) })
it('should set the network to loading', function () { it('should set the network to loading', function () {

View File

@ -39,7 +39,7 @@ describe('preferences controller', function () {
'0x7e57e2', '0x7e57e2',
]) ])
const accountTokens = preferencesController.store.getState().accountTokens const { accountTokens } = preferencesController.store.getState()
assert.deepEqual(accountTokens, { assert.deepEqual(accountTokens, {
'0xda22le': {}, '0xda22le': {},

View File

@ -19,7 +19,7 @@ describe('migration #26', function () {
it('should move the identities from KeyringController', function (done) { it('should move the identities from KeyringController', function (done) {
migration26.migrate(oldStorage) migration26.migrate(oldStorage)
.then((newStorage) => { .then((newStorage) => {
const identities = newStorage.data.PreferencesController.identities const { identities } = newStorage.data.PreferencesController
assert.deepEqual(identities, { assert.deepEqual(identities, {
'0x1e77e2': { name: 'Test Account 1', address: '0x1e77e2' }, '0x1e77e2': { name: 'Test Account 1', address: '0x1e77e2' },
'0x7e57e2': { name: 'Test Account 2', address: '0x7e57e2' }, '0x7e57e2': { name: 'Test Account 2', address: '0x7e57e2' },

View File

@ -12,7 +12,7 @@ import * as actions from '../../../../ui/app/store/actions'
import MetaMaskController from '../../../../app/scripts/metamask-controller' import MetaMaskController from '../../../../app/scripts/metamask-controller'
import firstTimeState from '../../localhostState' import firstTimeState from '../../localhostState'
const provider = createTestProviderTools({ scaffold: {} }).provider const { provider } = createTestProviderTools({ scaffold: {} })
const middleware = [thunk] const middleware = [thunk]
const defaultState = { metamask: {} } const defaultState = { metamask: {} }
const mockStore = (state = defaultState) => configureStore(middleware)(state) const mockStore = (state = defaultState) => configureStore(middleware)(state)

View File

@ -86,7 +86,7 @@ class NetworkDropdown extends Component {
renderCustomOption (provider) { renderCustomOption (provider) {
const { rpcTarget, type, ticker, nickname } = provider const { rpcTarget, type, ticker, nickname } = provider
const network = this.props.network const { network } = this.props
if (type !== 'rpc') { if (type !== 'rpc') {
return null return null
@ -136,7 +136,7 @@ class NetworkDropdown extends Component {
if ((rpc === 'http://localhost:8545') || currentRpcTarget) { if ((rpc === 'http://localhost:8545') || currentRpcTarget) {
return null return null
} else { } else {
const chainId = entry.chainId const { chainId } = entry
return ( return (
<DropdownMenuItem <DropdownMenuItem
key={`common${rpc}`} key={`common${rpc}`}

View File

@ -98,7 +98,7 @@ const mapStateToProps = (state, ownProps) => {
const newTotalFiat = addHexWEIsToRenderableFiat(value, customGasTotal, currentCurrency, conversionRate) const newTotalFiat = addHexWEIsToRenderableFiat(value, customGasTotal, currentCurrency, conversionRate)
const hideBasic = state.appState.modal.modalState.props.hideBasic const { hideBasic } = state.appState.modal.modalState.props
const customGasPrice = calcCustomGasPrice(customModalGasPriceInHex) const customGasPrice = calcCustomGasPrice(customModalGasPriceInHex)

View File

@ -51,7 +51,7 @@ export default function AccountOptionsMenu ({ anchorElement, onClose }) {
const rpcPrefs = useSelector(getRpcPrefsForCurrentProvider) const rpcPrefs = useSelector(getRpcPrefsForCurrentProvider)
const selectedIdentity = useSelector(getSelectedIdentity) const selectedIdentity = useSelector(getSelectedIdentity)
const address = selectedIdentity.address const { address } = selectedIdentity
const isRemovable = keyring.type !== 'HD Key Tree' const isRemovable = keyring.type !== 'HD Key Tree'
return ( return (

View File

@ -17,7 +17,7 @@ export default class MenuDroppoComponent extends Component {
} }
renderPrimary () { renderPrimary () {
const isOpen = this.props.isOpen const { isOpen } = this.props
if (!isOpen) { if (!isOpen) {
return null return null
} }
@ -32,8 +32,7 @@ export default class MenuDroppoComponent extends Component {
} }
manageListeners () { manageListeners () {
const isOpen = this.props.isOpen const { isOpen, onClickOutside } = this.props
const onClickOutside = this.props.onClickOutside
if (isOpen) { if (isOpen) {
this.outsideClickHandler = onClickOutside this.outsideClickHandler = onClickOutside
@ -41,7 +40,7 @@ export default class MenuDroppoComponent extends Component {
} }
globalClickOccurred = (event) => { globalClickOccurred = (event) => {
const target = event.target const { target } = event
// eslint-disable-next-line react/no-find-dom-node // eslint-disable-next-line react/no-find-dom-node
const container = findDOMNode(this) const container = findDOMNode(this)
@ -70,7 +69,7 @@ export default class MenuDroppoComponent extends Component {
render () { render () {
const { containerClassName = '', style } = this.props const { containerClassName = '', style } = this.props
const speed = this.props.speed || '300ms' const speed = this.props.speed || '300ms'
const useCssTransition = this.props.useCssTransition const { useCssTransition } = this.props
const zIndex = ('zIndex' in this.props) ? this.props.zIndex : 0 const zIndex = ('zIndex' in this.props) ? this.props.zIndex : 0
this.manageListeners() this.manageListeners()

View File

@ -85,7 +85,7 @@ export default function reduceMetamask (state = {}, action) {
} }
case actionConstants.SET_ACCOUNT_LABEL: { case actionConstants.SET_ACCOUNT_LABEL: {
const account = action.value.account const { account } = action.value
const name = action.value.label const name = action.value.label
const id = {} const id = {}
id[account] = Object.assign({}, metamaskState.identities[account], { name }) id[account] = Object.assign({}, metamaskState.identities[account], { name })

View File

@ -25,7 +25,7 @@ import BigNumber from 'bignumber.js'
import ethUtil, { stripHexPrefix } from 'ethereumjs-util' import ethUtil, { stripHexPrefix } from 'ethereumjs-util'
const BN = ethUtil.BN const { BN } = ethUtil
// Big Number Constants // Big Number Constants
const BIG_NUMBER_WEI_MULTIPLIER = new BigNumber('1000000000000000000') const BIG_NUMBER_WEI_MULTIPLIER = new BigNumber('1000000000000000000')

View File

@ -19,7 +19,7 @@ import { getConversionRate, getSelectedAccount } from '../selectors'
export function useCancelTransaction (transactionGroup) { export function useCancelTransaction (transactionGroup) {
const { primaryTransaction, initialTransaction } = transactionGroup const { primaryTransaction, initialTransaction } = transactionGroup
const gasPrice = primaryTransaction.txParams?.gasPrice const gasPrice = primaryTransaction.txParams?.gasPrice
const id = initialTransaction.id const { id } = initialTransaction
const dispatch = useDispatch() const dispatch = useDispatch()
const selectedAccount = useSelector(getSelectedAccount) const selectedAccount = useSelector(getSelectedAccount)
const conversionRate = useSelector(getConversionRate) const conversionRate = useSelector(getConversionRate)

View File

@ -42,7 +42,7 @@ export default class EnsInput extends Component {
} }
componentDidMount () { componentDidMount () {
const network = this.props.network const { network } = this.props
const networkHasEnsSupport = getNetworkEnsSupport(network) const networkHasEnsSupport = getNetworkEnsSupport(network)
this.setState({ ensResolution: ZERO_ADDRESS }) this.setState({ ensResolution: ZERO_ADDRESS })

View File

@ -422,7 +422,7 @@ export default class AdvancedTab extends PureComponent {
handleIpfsGatewaySave () { handleIpfsGatewaySave () {
const url = new URL(addUrlProtocolPrefix(this.state.ipfsGateway)) const url = new URL(addUrlProtocolPrefix(this.state.ipfsGateway))
const host = url.host const { host } = url
this.props.setIpfsGateway(host) this.props.setIpfsGateway(host)
} }

View File

@ -200,7 +200,7 @@ export function getRenderableBasicEstimateData (state, gasLimit) {
const { showFiatInTestnets } = getPreferences(state) const { showFiatInTestnets } = getPreferences(state)
const isMainnet = getIsMainnet(state) const isMainnet = getIsMainnet(state)
const showFiat = (isMainnet || !!showFiatInTestnets) const showFiat = (isMainnet || !!showFiatInTestnets)
const conversionRate = state.metamask.conversionRate const { conversionRate } = state.metamask
const currentCurrency = getCurrentCurrency(state) const currentCurrency = getCurrentCurrency(state)
const { const {
gas: { gas: {
@ -255,7 +255,7 @@ export function getRenderableEstimateDataForSmallButtonsFromGWEI (state) {
const isMainnet = getIsMainnet(state) const isMainnet = getIsMainnet(state)
const showFiat = (isMainnet || !!showFiatInTestnets) const showFiat = (isMainnet || !!showFiatInTestnets)
const gasLimit = state.metamask.send.gasLimit || getCustomGasLimit(state) || '0x5208' const gasLimit = state.metamask.send.gasLimit || getCustomGasLimit(state) || '0x5208'
const conversionRate = state.metamask.conversionRate const { conversionRate } = state.metamask
const currentCurrency = getCurrentCurrency(state) const currentCurrency = getCurrentCurrency(state)
const { const {
gas: { gas: {

View File

@ -78,7 +78,7 @@ export function getSelectedAddress (state) {
export function getSelectedIdentity (state) { export function getSelectedIdentity (state) {
const selectedAddress = getSelectedAddress(state) const selectedAddress = getSelectedAddress(state)
const identities = state.metamask.identities const { identities } = state.metamask
return identities[selectedAddress] return identities[selectedAddress]
} }
@ -88,7 +88,7 @@ export function getNumberOfAccounts (state) {
} }
export function getNumberOfTokens (state) { export function getNumberOfTokens (state) {
const tokens = state.metamask.tokens const { tokens } = state.metamask
return tokens ? tokens.length : 0 return tokens ? tokens.length : 0
} }
@ -157,7 +157,7 @@ export function getAssetImages (state) {
} }
export function getAddressBook (state) { export function getAddressBook (state) {
const network = state.metamask.network const { network } = state.metamask
if (!state.metamask.addressBook[network]) { if (!state.metamask.addressBook[network]) {
return [] return []
} }

View File

@ -21,7 +21,7 @@ export const incomingTxListSelector = (state) => {
return [] return []
} }
const network = state.metamask.network const { network } = state.metamask
const selectedAddress = getSelectedAddress(state) const selectedAddress = getSelectedAddress(state)
return Object.values(state.metamask.incomingTransactions) return Object.values(state.metamask.incomingTransactions)
.filter(({ metamaskNetworkId, txParams }) => ( .filter(({ metamaskNetworkId, txParams }) => (

View File

@ -75,7 +75,7 @@ async function startApp (metamaskState, backgroundConnection, opts) {
} }
if (getEnvironmentType() === ENVIRONMENT_TYPE_POPUP) { if (getEnvironmentType() === ENVIRONMENT_TYPE_POPUP) {
const origin = draftInitialState.activeTab.origin const { origin } = draftInitialState.activeTab
const permittedAccountsForCurrentTab = getPermittedAccountsForCurrentTab(draftInitialState) const permittedAccountsForCurrentTab = getPermittedAccountsForCurrentTab(draftInitialState)
const selectedAddress = getSelectedAddress(draftInitialState) const selectedAddress = getSelectedAddress(draftInitialState)
const unconnectedAccountAlertShownOrigins = getUnconnectedAccountAlertShown(draftInitialState) const unconnectedAccountAlertShownOrigins = getUnconnectedAccountAlertShown(draftInitialState)