mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 09:52:26 +01:00
Update ESLint rules for curly braces style (#7477)
* eslint: Enable curly and brace-style * yarn lint --fix
This commit is contained in:
parent
476274474f
commit
aa41057628
@ -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"],
|
||||
|
@ -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 })
|
||||
|
@ -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 }))
|
||||
}
|
||||
|
@ -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()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -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: {
|
||||
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
@ -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 () {
|
||||
|
@ -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<string>}
|
||||
*/
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
@ -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) {
|
||||
|
@ -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()
|
||||
|
@ -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
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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)
|
||||
|
@ -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()
|
||||
}
|
||||
|
@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
})
|
||||
|
@ -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 })
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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':
|
||||
|
@ -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))
|
||||
}
|
||||
|
||||
|
@ -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()
|
||||
})
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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) {
|
||||
|
@ -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.
|
||||
|
@ -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))
|
||||
})
|
||||
}
|
||||
|
@ -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))
|
||||
|
@ -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)
|
||||
|
@ -7,7 +7,9 @@ module.exports = setupFetchDebugging
|
||||
//
|
||||
|
||||
function setupFetchDebugging () {
|
||||
if (!global.fetch) return
|
||||
if (!global.fetch) {
|
||||
return
|
||||
}
|
||||
const originalFetch = global.fetch
|
||||
|
||||
global.fetch = wrappedFetch
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -43,7 +43,9 @@ function setupMultiplex (connectionStream) {
|
||||
mux,
|
||||
connectionStream,
|
||||
(err) => {
|
||||
if (err) console.error(err)
|
||||
if (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
return mux
|
||||
|
@ -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)
|
||||
|
@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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 = {
|
||||
|
@ -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
|
||||
})
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
})
|
||||
|
@ -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()
|
||||
|
@ -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 (
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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))
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -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}"`)
|
||||
|
@ -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()
|
||||
}
|
||||
|
@ -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()
|
||||
})
|
||||
|
@ -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 }
|
||||
}
|
||||
|
@ -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}
|
||||
|
@ -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')
|
||||
})
|
||||
})
|
||||
|
@ -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
|
||||
}
|
||||
})
|
||||
|
@ -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,
|
||||
|
@ -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)
|
||||
|
||||
|
@ -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'
|
||||
|
@ -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')
|
||||
})
|
||||
|
@ -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})
|
||||
}
|
||||
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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()
|
||||
})
|
||||
|
@ -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')
|
||||
})
|
||||
|
||||
|
@ -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(() => {
|
||||
|
@ -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)
|
||||
}
|
||||
|
@ -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()
|
||||
|
@ -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 })
|
||||
|
@ -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) {
|
||||
|
||||
|
@ -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: {
|
||||
|
@ -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
|
||||
|
@ -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)
|
||||
|
@ -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,
|
||||
|
@ -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(' ')
|
||||
|
||||
|
@ -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))
|
||||
|
@ -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}
|
||||
/>
|
||||
{
|
||||
|
@ -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)
|
||||
|
@ -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 {
|
||||
|
@ -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({
|
||||
|
@ -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', {}, [
|
||||
|
@ -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})
|
||||
|
||||
|
@ -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
|
||||
|
@ -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 (
|
||||
|
@ -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}
|
||||
|
@ -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)
|
||||
|
@ -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)),
|
||||
|
@ -63,7 +63,9 @@ export default class AddContact extends PureComponent {
|
||||
return (
|
||||
<EnsInput
|
||||
className="send__to-row"
|
||||
scanQrCode={_ => { this.props.scanQrCode() }}
|
||||
scanQrCode={_ => {
|
||||
this.props.scanQrCode()
|
||||
}}
|
||||
onChange={this.dValidate}
|
||||
onPaste={text => this.setState({ ethAddress: text })}
|
||||
onReset={() => this.setState({ ethAddress: '', ensAddress: '' })}
|
||||
|
@ -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:`,
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user