Enable indent linting via ESLint (#6936)

* Enable indent linting via ESLint

* yarn run lint:fix
feature/default_network_editable
Whymarrh Whitby 5 years ago committed by Frankie
parent e9c7df28ed
commit 4d88e1cf86
  1. 2
      .eslintrc
  2. 2
      app/scripts/controllers/computed-balances.js
  3. 2
      app/scripts/controllers/detect-tokens.js
  4. 8
      app/scripts/controllers/network/contract-addresses.js
  5. 36
      app/scripts/controllers/preferences.js
  6. 26
      app/scripts/controllers/transactions/index.js
  7. 8
      app/scripts/controllers/transactions/lib/tx-state-history-helper.js
  8. 10
      app/scripts/controllers/transactions/lib/util.js
  9. 4
      app/scripts/controllers/transactions/pending-tx-tracker.js
  10. 10
      app/scripts/controllers/transactions/tx-state-manager.js
  11. 94
      app/scripts/edge-encryptor.js
  12. 18
      app/scripts/lib/account-tracker.js
  13. 10
      app/scripts/lib/backend-metametrics.js
  14. 2
      app/scripts/lib/message-manager.js
  15. 2
      app/scripts/lib/personal-message-manager.js
  16. 102
      app/scripts/metamask-controller.js
  17. 6
      app/scripts/migrations/018.js
  18. 10
      app/scripts/migrations/019.js
  19. 2
      app/scripts/migrations/024.js
  20. 10
      app/scripts/migrations/031.js
  21. 8
      app/scripts/platforms/extension.js
  22. 14
      development/metamaskbot-build-announce.js
  23. 4
      development/mock-dev.js
  24. 2
      development/sentry-publish.js
  25. 120
      development/verify-locale-strings.js
  26. 6
      gentests.js
  27. 72
      gulpfile.js
  28. 4
      test/e2e/contract-test/contract.js
  29. 2
      test/e2e/helpers.js
  30. 168
      test/e2e/metamask-responsive-ui.spec.js
  31. 246
      test/e2e/web3.spec.js
  32. 16
      test/unit/app/controllers/detect-tokens-test.js
  33. 90
      test/unit/app/controllers/transactions/pending-tx-test.js
  34. 4
      test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js
  35. 100
      test/unit/app/controllers/transactions/tx-controller-test.js
  36. 12
      test/unit/app/controllers/transactions/tx-state-manager-test.js
  37. 2
      test/unit/app/controllers/transactions/tx-utils-test.js
  38. 32
      test/unit/app/edge-encryptor-test.js
  39. 10
      test/unit/localhostState.js
  40. 12
      test/unit/migrations/021-test.js
  41. 22
      test/unit/migrations/022-test.js
  42. 44
      test/unit/migrations/023-test.js
  43. 24
      test/unit/migrations/024-test.js
  44. 24
      test/unit/migrations/025-test.js
  45. 24
      test/unit/migrations/029-test.js
  46. 16
      test/unit/migrations/030-test.js
  47. 8
      test/unit/migrations/031-test.js
  48. 154
      test/unit/migrations/migrations-test.js
  49. 22
      test/unit/migrations/migrator-test.js
  50. 8
      test/unit/migrations/template-test.js
  51. 2
      test/unit/ui/app/actions.spec.js
  52. 2
      test/web3/schema.js
  53. 4
      test/web3/web3.js
  54. 4
      ui/app/components/app/confirm-page-container/confirm-detail-row/tests/confirm-detail-row.component.test.js
  55. 6
      ui/app/components/app/confirm-page-container/confirm-page-container-navigation/confirm-page-container-navigation.component.js
  56. 20
      ui/app/components/app/confirm-page-container/confirm-page-container.component.js
  57. 2
      ui/app/components/app/dropdowns/account-details-dropdown.js
  58. 12
      ui/app/components/app/dropdowns/network-dropdown.js
  59. 4
      ui/app/components/app/gas-customization/advanced-gas-inputs/advanced-gas-inputs.component.js
  60. 4
      ui/app/components/app/gas-customization/gas-modal-page-container/advanced-tab-content/advanced-tab-content.component.js
  61. 12
      ui/app/components/app/gas-customization/gas-modal-page-container/basic-tab-content/basic-tab-content.component.js
  62. 12
      ui/app/components/app/gas-customization/gas-modal-page-container/gas-modal-page-container.component.js
  63. 74
      ui/app/components/app/gas-customization/gas-modal-page-container/tests/gas-modal-page-container-container.test.js
  64. 36
      ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js
  65. 16
      ui/app/components/app/modals/account-details-modal/account-details-modal.component.js
  66. 28
      ui/app/components/app/modals/deposit-ether-modal.js
  67. 46
      ui/app/components/app/modals/export-private-key-modal.js
  68. 2
      ui/app/components/app/modals/new-account-modal.js
  69. 2
      ui/app/components/app/modals/notification-modal.js
  70. 34
      ui/app/components/app/modals/qr-scanner/qr-scanner.component.js
  71. 24
      ui/app/components/app/network-display/network-display.component.js
  72. 24
      ui/app/components/app/network.js
  73. 2
      ui/app/components/app/sidebars/sidebar.component.js
  74. 2
      ui/app/components/app/signature-request.js
  75. 18
      ui/app/components/app/token-list.js
  76. 18
      ui/app/components/app/transaction-activity-log/transaction-activity-log-icon/transaction-activity-log-icon.component.js
  77. 2
      ui/app/components/app/transaction-list-item-details/transaction-list-item-details.component.js
  78. 4
      ui/app/components/app/transaction-list/transaction-list.component.js
  79. 62
      ui/app/components/app/transaction-view-balance/transaction-view-balance.component.js
  80. 90
      ui/app/components/ui/alert/index.js
  81. 50
      ui/app/components/ui/button-group/tests/button-group-component.test.js
  82. 32
      ui/app/components/ui/currency-input/currency-input.component.js
  83. 8
      ui/app/components/ui/sender-to-recipient/sender-to-recipient.component.js
  84. 10
      ui/app/ducks/app/app.js
  85. 10
      ui/app/ducks/gas/gas-duck.test.js
  86. 30
      ui/app/ducks/gas/gas.duck.js
  87. 2
      ui/app/ducks/metamask/metamask.js
  88. 2
      ui/app/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js
  89. 2
      ui/app/pages/confirm-add-token/confirm-add-token.component.js
  90. 228
      ui/app/pages/create-account/connect-hardware/account-list.js
  91. 214
      ui/app/pages/create-account/connect-hardware/connect-screen.js
  92. 60
      ui/app/pages/create-account/connect-hardware/index.js
  93. 2
      ui/app/pages/first-time-flow/create-password/import-with-seed-phrase/import-with-seed-phrase.component.js
  94. 4
      ui/app/pages/first-time-flow/metametrics-opt-in/metametrics-opt-in.component.js
  95. 4
      ui/app/pages/first-time-flow/select-action/select-action.component.js
  96. 2
      ui/app/pages/home/home.component.js
  97. 74
      ui/app/pages/mobile-sync/index.js
  98. 20
      ui/app/pages/routes/index.js
  99. 6
      ui/app/pages/send/account-list-item/account-list-item.container.js
  100. 2
      ui/app/pages/send/send-content/add-recipient/add-recipient.selectors.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -59,7 +59,7 @@
"eqeqeq": [2, "allow-null"],
"generator-star-spacing": [2, { "before": true, "after": true }],
"handle-callback-err": [2, "^(err|error)$" ],
"indent": "off",
"indent": [2, 2,{ "SwitchCase": 1 }],
"jsx-quotes": [2, "prefer-double"],
"key-spacing": 2,
"keyword-spacing": [2, { "before": true, "after": true }],

@ -65,7 +65,7 @@ class ComputedbalancesController {
syncAllAccountsFromStore (store) {
const upstream = Object.keys(store.accounts)
const balances = Object.keys(this.balances)
.map(address => this.balances[address])
.map(address => this.balances[address])
// Follow new addresses
for (const address in balances) {

@ -54,7 +54,7 @@ class DetectTokensController {
})
}
/**
/**
* Find if selectedAddress has tokens with contract in contractAddress.
*
* @param {string} contractAddress Hex address of the token contract to explore.

@ -4,8 +4,8 @@ const SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN = '0xb8e671734ce5c8d7dfbbea5574fa4cf3
const SINGLE_CALL_BALANCES_ADDRESS_KOVAN = '0xb1d3fbb2f83aecd196f474c16ca5d9cffa0d0ffc'
module.exports = {
SINGLE_CALL_BALANCES_ADDRESS,
SINGLE_CALL_BALANCES_ADDRESS_RINKEBY,
SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN,
SINGLE_CALL_BALANCES_ADDRESS_KOVAN,
SINGLE_CALL_BALANCES_ADDRESS,
SINGLE_CALL_BALANCES_ADDRESS_RINKEBY,
SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN,
SINGLE_CALL_BALANCES_ADDRESS_KOVAN,
}

@ -68,7 +68,7 @@ class PreferencesController {
return this.setFeatureFlag(key, value)
}
}
// PUBLIC METHODS
// PUBLIC METHODS
/**
* Sets the {@code forgottenPassword} state property
@ -129,9 +129,9 @@ class PreferencesController {
* @param {String} type Indicates the type of first time flow - create or import - the user wishes to follow
*
*/
setFirstTimeFlowType (type) {
this.store.updateState({ firstTimeFlowType: type })
}
setFirstTimeFlowType (type) {
this.store.updateState({ firstTimeFlowType: type })
}
getSuggestedTokens () {
@ -493,22 +493,22 @@ class PreferencesController {
* @returns {Promise<array>} Promise resolving to updated frequentRpcList.
*
*/
addToFrequentRpcList (url, chainId, ticker = 'ETH', nickname = '', rpcPrefs = {}) {
const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => { return element.rpcUrl === url })
if (index !== -1) {
rpcList.splice(index, 1)
}
if (url !== 'http://localhost:8545') {
let checkedChainId
if (!!chainId && !Number.isNaN(parseInt(chainId))) {
checkedChainId = chainId
}
rpcList.push({ rpcUrl: url, chainId: checkedChainId, ticker, nickname, rpcPrefs })
addToFrequentRpcList (url, chainId, ticker = 'ETH', nickname = '', rpcPrefs = {}) {
const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => { return element.rpcUrl === url })
if (index !== -1) {
rpcList.splice(index, 1)
}
if (url !== 'http://localhost:8545') {
let checkedChainId
if (!!chainId && !Number.isNaN(parseInt(chainId))) {
checkedChainId = chainId
}
this.store.updateState({ frequentRpcListDetail: rpcList })
return Promise.resolve(rpcList)
rpcList.push({ rpcUrl: url, chainId: checkedChainId, ticker, nickname, rpcPrefs })
}
this.store.updateState({ frequentRpcListDetail: rpcList })
return Promise.resolve(rpcList)
}
/**
* Removes custom RPC url from state.

@ -129,7 +129,7 @@ class TransactionController extends EventEmitter {
}
}
/**
/**
Adds a tx to the txlist
@emits ${txMeta.id}:unapproved
*/
@ -220,7 +220,7 @@ class TransactionController extends EventEmitter {
return txMeta
}
/**
/**
adds the tx gas defaults: gas && gasPrice
@param txMeta {Object} - the txMeta object
@returns {Promise<object>} resolves with txMeta
@ -495,9 +495,9 @@ class TransactionController extends EventEmitter {
this.txStateManager.updateTx(txMeta, 'transactions#setTxHash')
}
//
// PRIVATE METHODS
//
//
// PRIVATE METHODS
//
/** maps methods for convenience*/
_mapMethods () {
/** @returns the state in transaction controller */
@ -537,14 +537,14 @@ class TransactionController extends EventEmitter {
loadingDefaults: true,
}).forEach((tx) => {
this.addTxGasDefaults(tx)
.then((txMeta) => {
txMeta.loadingDefaults = false
this.txStateManager.updateTx(txMeta, 'transactions: gas estimation for tx on boot')
}).catch((error) => {
tx.loadingDefaults = false
this.txStateManager.updateTx(tx, 'failed to estimate gas during boot cleanup.')
this.txStateManager.setTxStatusFailed(tx.id, error)
})
.then((txMeta) => {
txMeta.loadingDefaults = false
this.txStateManager.updateTx(txMeta, 'transactions: gas estimation for tx on boot')
}).catch((error) => {
tx.loadingDefaults = false
this.txStateManager.updateTx(tx, 'failed to estimate gas during boot cleanup.')
this.txStateManager.setTxStatusFailed(tx.id, error)
})
})
this.txStateManager.getFilteredTxList({

@ -17,10 +17,10 @@ function migrateFromSnapshotsToDiffs (longHistory) {
return (
longHistory
// convert non-initial history entries into diffs
.map((entry, index) => {
if (index === 0) return entry
return generateHistoryEntry(longHistory[index - 1], entry)
})
.map((entry, index) => {
if (index === 0) return entry
return generateHistoryEntry(longHistory[index - 1], entry)
})
)
}

@ -26,7 +26,7 @@ const normalizers = {
gasPrice: gasPrice => addHexPrefix(gasPrice),
}
/**
/**
normalizes txParams
@param txParams {object}
@returns {object} normalized txParams
@ -40,7 +40,7 @@ function normalizeTxParams (txParams, LowerCase) {
return normalizedTxParams
}
/**
/**
validates txParams
@param txParams {object}
*/
@ -59,7 +59,7 @@ function validateTxParams (txParams) {
}
}
/**
/**
validates the from field in txParams
@param txParams {object}
*/
@ -68,7 +68,7 @@ function validateFrom (txParams) {
if (!isValidAddress(txParams.from)) throw new Error('Invalid from address')
}
/**
/**
validates the to field in txParams
@param txParams {object}
*/
@ -85,7 +85,7 @@ function validateRecipient (txParams) {
return txParams
}
/**
/**
@returns an {array} of states that can be considered final
*/
function getFinalStates () {

@ -186,7 +186,7 @@ class PendingTransactionTracker extends EventEmitter {
this.emit('tx:warning', txMeta, err)
}
}
/**
/**
checks to see if if the tx's nonce has been used by another transaction
@param txMeta {Object} - txMeta object
@emits tx:dropped
@ -198,7 +198,7 @@ class PendingTransactionTracker extends EventEmitter {
const nextNonce = await this.query.getTransactionCount(from)
const { blockNumber } = await this.query.getTransactionByHash(hash) || {}
if (!blockNumber && parseInt(nextNonce) > parseInt(nonce)) {
return true
return true
}
return false
}

@ -34,7 +34,7 @@ class TransactionStateManager extends EventEmitter {
this.store = new ObservableStore(
extend({
transactions: [],
}, initState))
}, initState))
this.txHistoryLimit = txHistoryLimit
this.getNetwork = getNetwork
}
@ -245,7 +245,7 @@ class TransactionStateManager extends EventEmitter {
})
}
/**
/**
@param opts {object} - an object of fields to search for eg:<br>
let <code>thingsToLookFor = {<br>
to: '0x0..',<br>
@ -403,9 +403,9 @@ class TransactionStateManager extends EventEmitter {
// Update state
this._saveTxList(otherAccountTxs)
}
//
// PRIVATE METHODS
//
//
// PRIVATE METHODS
//
// STATUS METHODS
// statuses:

@ -14,23 +14,23 @@ class EdgeEncryptor {
* @returns {Promise<string>} Promise resolving to an object with ciphertext
*/
encrypt (password, dataObject) {
var salt = this._generateSalt()
return this._keyFromPassword(password, salt)
.then(function (key) {
var data = JSON.stringify(dataObject)
var dataBuffer = Unibabel.utf8ToBuffer(data)
var vector = global.crypto.getRandomValues(new Uint8Array(16))
var resultbuffer = asmcrypto.AES_GCM.encrypt(dataBuffer, key, vector)
var salt = this._generateSalt()
return this._keyFromPassword(password, salt)
.then(function (key) {
var data = JSON.stringify(dataObject)
var dataBuffer = Unibabel.utf8ToBuffer(data)
var vector = global.crypto.getRandomValues(new Uint8Array(16))
var resultbuffer = asmcrypto.AES_GCM.encrypt(dataBuffer, key, vector)
var buffer = new Uint8Array(resultbuffer)
var vectorStr = Unibabel.bufferToBase64(vector)
var vaultStr = Unibabel.bufferToBase64(buffer)
return JSON.stringify({
data: vaultStr,
iv: vectorStr,
salt: salt,
})
})
var buffer = new Uint8Array(resultbuffer)
var vectorStr = Unibabel.bufferToBase64(vector)
var vaultStr = Unibabel.bufferToBase64(buffer)
return JSON.stringify({
data: vaultStr,
iv: vectorStr,
salt: salt,
})
})
}
/**
@ -41,25 +41,25 @@ class EdgeEncryptor {
* @returns {Promise<Object>} Promise resolving to copy of decrypted object
*/
decrypt (password, text) {
const payload = JSON.parse(text)
const salt = payload.salt
return this._keyFromPassword(password, salt)
.then(function (key) {
const encryptedData = Unibabel.base64ToBuffer(payload.data)
const vector = Unibabel.base64ToBuffer(payload.iv)
return new Promise((resolve, reject) => {
var result
try {
result = asmcrypto.AES_GCM.decrypt(encryptedData, key, vector)
} catch (err) {
return reject(new Error('Incorrect password'))
}
const decryptedData = new Uint8Array(result)
const decryptedStr = Unibabel.bufferToUtf8(decryptedData)
const decryptedObj = JSON.parse(decryptedStr)
resolve(decryptedObj)
})
})
const payload = JSON.parse(text)
const salt = payload.salt
return this._keyFromPassword(password, salt)
.then(function (key) {
const encryptedData = Unibabel.base64ToBuffer(payload.data)
const vector = Unibabel.base64ToBuffer(payload.iv)
return new Promise((resolve, reject) => {
var result
try {
result = asmcrypto.AES_GCM.decrypt(encryptedData, key, vector)
} catch (err) {
return reject(new Error('Incorrect password'))
}
const decryptedData = new Uint8Array(result)
const decryptedStr = Unibabel.bufferToUtf8(decryptedData)
const decryptedObj = JSON.parse(decryptedStr)
resolve(decryptedObj)
})
})
}
/**
@ -72,14 +72,14 @@ class EdgeEncryptor {
*/
_keyFromPassword (password, salt) {
var passBuffer = Unibabel.utf8ToBuffer(password)
var saltBuffer = Unibabel.base64ToBuffer(salt)
const iterations = 10000
const length = 32 // SHA256 hash size
return new Promise((resolve) => {
var key = asmcrypto.Pbkdf2HmacSha256(passBuffer, saltBuffer, iterations, length)
resolve(key)
})
var passBuffer = Unibabel.utf8ToBuffer(password)
var saltBuffer = Unibabel.base64ToBuffer(salt)
const iterations = 10000
const length = 32 // SHA256 hash size
return new Promise((resolve) => {
var key = asmcrypto.Pbkdf2HmacSha256(passBuffer, saltBuffer, iterations, length)
resolve(key)
})
}
/**
@ -89,10 +89,10 @@ class EdgeEncryptor {
* @returns {string} Randomized base64 encoded data
*/
_generateSalt (byteCount = 32) {
var view = new Uint8Array(byteCount)
global.crypto.getRandomValues(view)
var b64encoded = btoa(String.fromCharCode.apply(null, view))
return b64encoded
var view = new Uint8Array(byteCount)
global.crypto.getRandomValues(view)
var b64encoded = btoa(String.fromCharCode.apply(null, view))
return b64encoded
}
}

@ -183,23 +183,23 @@ class AccountTracker {
switch (currentNetwork) {
case MAINNET_CODE:
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS)
break
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS)
break
case RINKEYBY_CODE:
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_RINKEBY)
break
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_RINKEBY)
break
case ROPSTEN_CODE:
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN)
break
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN)
break
case KOVAN_CODE:
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_KOVAN)
break
await this._updateAccountsViaBalanceChecker(addresses, SINGLE_CALL_BALANCES_ADDRESS_KOVAN)
break
default:
await Promise.all(addresses.map(this._updateAccount.bind(this)))
await Promise.all(addresses.map(this._updateAccount.bind(this)))
}
}

@ -15,11 +15,11 @@ function backEndMetaMetricsEvent (metaMaskState, eventData) {
const stateEventData = getMetaMetricState({ metamask: metaMaskState })
if (stateEventData.participateInMetaMetrics) {
sendMetaMetricsEvent({
...stateEventData,
...eventData,
url: METAMETRICS_TRACKING_URL + '/backend',
})
sendMetaMetricsEvent({
...stateEventData,
...eventData,
url: METAMETRICS_TRACKING_URL + '/backend',
})
}
}

@ -61,7 +61,7 @@ module.exports = class MessageManager extends EventEmitter {
*/
getUnapprovedMsgs () {
return this.messages.filter(msg => msg.status === 'unapproved')
.reduce((result, msg) => { result[msg.id] = msg; return result }, {})
.reduce((result, msg) => { result[msg.id] = msg; return result }, {})
}
/**

@ -64,7 +64,7 @@ module.exports = class PersonalMessageManager extends EventEmitter {
*/
getUnapprovedMsgs () {
return this.messages.filter(msg => msg.status === 'unapproved')
.reduce((result, msg) => { result[msg.id] = msg; return result }, {})
.reduce((result, msg) => { result[msg.id] = msg; return result }, {})
}
/**

@ -68,7 +68,7 @@ module.exports = class MetamaskController extends EventEmitter {
* @constructor
* @param {Object} opts
*/
constructor (opts) {
constructor (opts) {
super()
this.defaultMaxListeners = 20
@ -362,9 +362,9 @@ module.exports = class MetamaskController extends EventEmitter {
return publicConfigStore
}
//=============================================================================
// EXPOSED TO THE UI SUBSYSTEM
//=============================================================================
//=============================================================================
// EXPOSED TO THE UI SUBSYSTEM
//=============================================================================
/**
* The metamask-state of the various controllers, made available to the UI
@ -503,9 +503,9 @@ module.exports = class MetamaskController extends EventEmitter {
}
//=============================================================================
// VAULT / KEYRING RELATED METHODS
//=============================================================================
//=============================================================================
// VAULT / KEYRING RELATED METHODS
//=============================================================================
/**
* Creates a new Vault and create a new keychain.
@ -615,7 +615,7 @@ module.exports = class MetamaskController extends EventEmitter {
* with the mobile client for syncing purposes
* @returns Promise<Object> Parts of the state that we want to syncx
*/
async fetchInfoToSync () {
async fetchInfoToSync () {
// Preferences
const {
accountTokens,
@ -744,14 +744,14 @@ module.exports = class MetamaskController extends EventEmitter {
const keyring = await this.getKeyringForDevice(deviceName, hdPath)
let accounts = []
switch (page) {
case -1:
accounts = await keyring.getPreviousPage()
break
case 1:
accounts = await keyring.getNextPage()
break
default:
accounts = await keyring.getFirstPage()
case -1:
accounts = await keyring.getPreviousPage()
break
case 1:
accounts = await keyring.getNextPage()
break
default:
accounts = await keyring.getFirstPage()
}
// Merge with existing accounts
@ -808,7 +808,7 @@ module.exports = class MetamaskController extends EventEmitter {
const { identities } = this.preferencesController.store.getState()
return { ...keyState, identities }
}
}
//
@ -975,16 +975,16 @@ module.exports = class MetamaskController extends EventEmitter {
// sets the status op the message to 'approved'
// and removes the metamaskId for signing
return this.messageManager.approveMessage(msgParams)
.then((cleanMsgParams) => {
.then((cleanMsgParams) => {
// signs the message
return this.keyringController.signMessage(cleanMsgParams)
})
.then((rawSig) => {
return this.keyringController.signMessage(cleanMsgParams)
})
.then((rawSig) => {
// tells the listener that the message has been signed
// and can be returned to the dapp
this.messageManager.setMsgStatusSigned(msgId, rawSig)
return this.getState()
})
this.messageManager.setMsgStatusSigned(msgId, rawSig)
return this.getState()
})
}
/**
@ -1033,16 +1033,16 @@ module.exports = class MetamaskController extends EventEmitter {
// sets the status op the message to 'approved'
// and removes the metamaskId for signing
return this.personalMessageManager.approveMessage(msgParams)
.then((cleanMsgParams) => {
.then((cleanMsgParams) => {
// signs the message
return this.keyringController.signPersonalMessage(cleanMsgParams)
})
.then((rawSig) => {
return this.keyringController.signPersonalMessage(cleanMsgParams)
})
.then((rawSig) => {
// tells the listener that the message has been signed
// and can be returned to the dapp
this.personalMessageManager.setMsgStatusSigned(msgId, rawSig)
return this.getState()
})
this.personalMessageManager.setMsgStatusSigned(msgId, rawSig)
return this.getState()
})
}
/**
@ -1142,7 +1142,7 @@ module.exports = class MetamaskController extends EventEmitter {
restoreOldVaultAccounts (migratorOutput) {
const { serialized } = migratorOutput
return this.keyringController.restoreKeyring(serialized)
.then(() => migratorOutput)
.then(() => migratorOutput)
}
/**
@ -1185,9 +1185,9 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
//=============================================================================
// END (VAULT / KEYRING RELATED METHODS)
//=============================================================================
//=============================================================================
// END (VAULT / KEYRING RELATED METHODS)
//=============================================================================
/**
* Allows a user to try to speed up a transaction by retrying it
@ -1236,9 +1236,9 @@ module.exports = class MetamaskController extends EventEmitter {
})
}
//=============================================================================
// PASSWORD MANAGEMENT
//=============================================================================
//=============================================================================
// PASSWORD MANAGEMENT
//=============================================================================
/**
* Allows a user to begin the seed phrase recovery process.
@ -1260,9 +1260,9 @@ module.exports = class MetamaskController extends EventEmitter {
cb()
}
//=============================================================================
// SETUP
//=============================================================================
//=============================================================================
// SETUP
//=============================================================================
/**
* Used to create a multiplexed stream for connecting to an untrusted context
@ -1531,13 +1531,13 @@ module.exports = class MetamaskController extends EventEmitter {
return GWEI_BN
}
return block.gasPrices
.map(hexPrefix => hexPrefix.substr(2))
.map(hex => new BN(hex, 16))
.sort((a, b) => {
return a.gt(b) ? 1 : -1
})[0]
.map(hexPrefix => hexPrefix.substr(2))
.map(hex => new BN(hex, 16))
.sort((a, b) => {
return a.gt(b) ? 1 : -1
})[0]
})
.map(number => number.div(GWEI_BN).toNumber())
.map(number => number.div(GWEI_BN).toNumber())
const percentileNum = percentile(65, lowestPrices)
const percentileNumBn = new BN(percentileNum)
@ -1557,9 +1557,9 @@ module.exports = class MetamaskController extends EventEmitter {
return pendingNonce
}
//=============================================================================
// CONFIG
//=============================================================================
//=============================================================================
// CONFIG
//=============================================================================
// Log blocks
@ -1754,7 +1754,7 @@ module.exports = class MetamaskController extends EventEmitter {
this.tokenRatesController.isActive = active
}
/**
/**
* Creates RPC engine middleware for processing eth_signTypedData requests
*
* @param {Object} req - request object

@ -43,9 +43,9 @@ function transformState (state) {
const newHistory = (
txStateHistoryHelper.migrateFromSnapshotsToDiffs(txMeta.history)
// remove empty diffs
.filter((entry) => {
return !Array.isArray(entry) || entry.length > 0
})
.filter((entry) => {
return !Array.isArray(entry) || entry.length > 0
})
)
txMeta.history = newHistory
return txMeta

@ -38,13 +38,13 @@ function transformState (state) {
if (txMeta.status !== 'submitted') return txMeta
const confirmedTxs = txList.filter((tx) => tx.status === 'confirmed')
.filter((tx) => tx.txParams.from === txMeta.txParams.from)
.filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
.filter((tx) => tx.txParams.from === txMeta.txParams.from)
.filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
const highestConfirmedNonce = getHighestNonce(confirmedTxs)
const pendingTxs = txList.filter((tx) => tx.status === 'submitted')
.filter((tx) => tx.txParams.from === txMeta.txParams.from)
.filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
.filter((tx) => tx.txParams.from === txMeta.txParams.from)
.filter((tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from)
const highestContinuousNonce = getHighestContinuousFrom(pendingTxs, highestConfirmedNonce)
const maxNonce = Math.max(highestContinuousNonce, highestConfirmedNonce)
@ -78,7 +78,7 @@ function getHighestContinuousFrom (txList, startPoint) {
function getHighestNonce (txList) {
const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce
const nonce = txMeta.txParams.nonce
return parseInt(nonce || '0x0', 16)
})
const highestNonce = Math.max.apply(null, nonces)

@ -32,7 +32,7 @@ function transformState (state) {
txMeta.status === 'unapproved' &&
txMeta.txParams &&
txMeta.txParams.from
) {
) {
txMeta.txParams.from = txMeta.txParams.from.toLowerCase()
}
return txMeta

@ -2,14 +2,14 @@
const version = 31
const clone = require('clone')
/*
/*
* The purpose of this migration is to properly set the completedOnboarding flag baesd on the state
* of the KeyringController.
*/
module.exports = {
version,
migrate: async function (originalVersionedData) {
migrate: async function (originalVersionedData) {
const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
const state = versionedData.data
@ -19,13 +19,13 @@ module.exports = {
},
}
function transformState (state) {
function transformState (state) {
const { KeyringController, PreferencesController } = state
if (KeyringController && PreferencesController) {
if (KeyringController && PreferencesController) {
const { vault } = KeyringController
PreferencesController.completedOnboarding = Boolean(vault)
}
return state
return state
}

@ -84,10 +84,10 @@ class ExtensionPlatform {
extension.notifications.create(
url,
{
'type': 'basic',
'title': title,
'iconUrl': extension.extension.getURL('../../images/icon-64.png'),
'message': message,
'type': 'basic',
'title': title,
'iconUrl': extension.extension.getURL('../../images/icon-64.png'),
'message': message,
})
}

@ -36,13 +36,13 @@ async function start () {
console.log(`Posting to: ${POST_COMMENT_URI}`)
await request({
method: 'POST',
uri: POST_COMMENT_URI,
body: JSON_PAYLOAD,
headers: {
'User-Agent': 'metamaskbot',
'Authorization': `token ${GITHUB_COMMENT_TOKEN}`,
},
method: 'POST',
uri: POST_COMMENT_URI,
body: JSON_PAYLOAD,
headers: {
'User-Agent': 'metamaskbot',
'Authorization': `token ${GITHUB_COMMENT_TOKEN}`,
},
})
}

@ -134,10 +134,10 @@ function startApp () {
},
}, [
h(Root, {
store: store,
store: store,
}),
]),
]
), container)
), container)
}

@ -16,7 +16,7 @@ async function start () {
if (versionAlreadyExists) {
console.log(`Version "${VERSION}" already exists on Sentry, skipping version creation`)
} else {
// create sentry release
// create sentry release
console.log(`creating Sentry release for "${VERSION}"...`)
await exec(`sentry-cli releases --org 'metamask' --project 'metamask' new ${VERSION}`)
console.log(`removing any existing files from Sentry release "${VERSION}"...`)

@ -18,79 +18,79 @@ console.log('Locale Verification')
const specifiedLocale = process.argv[2]
if (specifiedLocale) {
console.log(`Verifying selected locale "${specifiedLocale}":\n\n`)
const locale = localeIndex.find(localeMeta => localeMeta.code === specifiedLocale)
verifyLocale(locale)
console.log(`Verifying selected locale "${specifiedLocale}":\n\n`)
const locale = localeIndex.find(localeMeta => localeMeta.code === specifiedLocale)
verifyLocale(locale)
} else {
console.log('Verifying all locales:\n\n')
localeIndex.forEach(localeMeta => {
verifyLocale({ localeMeta })
console.log('\n')
})
console.log('Verifying all locales:\n\n')
localeIndex.forEach(localeMeta => {
verifyLocale({ localeMeta })
console.log('\n')
})
}
function verifyLocale ({ localeMeta }) {
const localeCode = localeMeta.code
const localeName = localeMeta.name
let targetLocale, englishLocale
try {
const localeFilePath = path.join(process.cwd(), 'app', '_locales', localeCode, 'messages.json')
targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8'))
} catch (e) {
if (e.code === 'ENOENT') {
console.log('Locale file not found')
} else {
console.log(`Error opening your locale ("${localeCode}") file: `, e)
}
process.exit(1)
}
const localeCode = localeMeta.code
const localeName = localeMeta.name
let targetLocale, englishLocale
try {
const localeFilePath = path.join(process.cwd(), 'app', '_locales', localeCode, 'messages.json')
targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8'))
} catch (e) {
if (e.code === 'ENOENT') {
console.log('Locale file not found')
} else {
console.log(`Error opening your locale ("${localeCode}") file: `, e)
}
process.exit(1)
}
try {
const englishFilePath = path.join(process.cwd(), 'app', '_locales', 'en', 'messages.json')
englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8'))
} catch (e) {
if (e.code === 'ENOENT') {
console.log('English File not found')
} else {
console.log('Error opening english locale file: ', e)
}
process.exit(1)
}
try {
const englishFilePath = path.join(process.cwd(), 'app', '_locales', 'en', 'messages.json')
englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8'))
} catch (e) {
if (e.code === 'ENOENT') {
console.log('English File not found')
} else {
console.log('Error opening english locale file: ', e)
}
process.exit(1)
}
// console.log(' verifying whether all your locale ("${localeCode}") strings are contained in the english one')
const extraItems = compareLocalesForMissingItems({ base: targetLocale, subject: englishLocale })
// console.log('\n verifying whether your locale ("${localeCode}") contains all english strings')
const missingItems = compareLocalesForMissingItems({ base: englishLocale, subject: targetLocale })
// console.log(' verifying whether all your locale ("${localeCode}") strings are contained in the english one')
const extraItems = compareLocalesForMissingItems({ base: targetLocale, subject: englishLocale })
// console.log('\n verifying whether your locale ("${localeCode}") contains all english strings')
const missingItems = compareLocalesForMissingItems({ base: englishLocale, subject: targetLocale })
const englishEntryCount = Object.keys(englishLocale).length
const coveragePercent = 100 * (englishEntryCount - missingItems.length) / englishEntryCount
const englishEntryCount = Object.keys(englishLocale).length
const coveragePercent = 100 * (englishEntryCount - missingItems.length) / englishEntryCount
console.log(`Status of **${localeName} (${localeCode})** ${coveragePercent.toFixed(2)}% coverage:`)
console.log(`Status of **${localeName} (${localeCode})** ${coveragePercent.toFixed(2)}% coverage:`)
if (extraItems.length) {
console.log('\nMissing from english locale:')
extraItems.forEach(function (key) {
console.log(` - [ ] ${key}`)
})
} else {
// console.log(` all ${counter} strings declared in your locale ("${localeCode}") were found in the english one`)
}
if (extraItems.length) {
console.log('\nMissing from english locale:')
extraItems.forEach(function (key) {
console.log(` - [ ] ${key}`)
})
} else {
// console.log(` all ${counter} strings declared in your locale ("${localeCode}") were found in the english one`)
}
if (missingItems.length) {
console.log(`\nMissing:`)
missingItems.forEach(function (key) {
console.log(` - [ ] ${key}`)
})
} else {
// console.log(` all ${counter} english strings were found in your locale ("${localeCode}")!`)
}
if (missingItems.length) {
console.log(`\nMissing:`)
missingItems.forEach(function (key) {
console.log(` - [ ] ${key}`)
})
} else {
// console.log(` all ${counter} english strings were found in your locale ("${localeCode}")!`)
}
if (!extraItems.length && !missingItems.length) {
console.log('Full coverage : )')
}
if (!extraItems.length && !missingItems.length) {
console.log('Full coverage : )')
}
}
function compareLocalesForMissingItems ({ base, subject }) {
return Object.keys(base).filter((key) => !subject[key])
return Object.keys(base).filter((key) => !subject[key])
}

@ -94,8 +94,8 @@ async function startContainer (fileRegEx) {
.map((s) => {
const proxyKeys = s.match(/{.+}/)[0].match(/\w+/g)
return '\'' + s.match(/'(.+)'/)[1] + '\': { ' + (proxyKeys.length > 1
? '\n ' + proxyKeys.join(': () => {},\n ') + ': () => {},\n '
: proxyKeys[0] + ': () => {},') + ' }'
? '\n ' + proxyKeys.join(': () => {},\n ') + ': () => {},\n '
: proxyKeys[0] + ': () => {},') + ' }'
})
.join(',\n ') + '\n}')
.replace('{ connect: () => {}, },', `{
@ -205,7 +205,7 @@ function generateContainerTest (sPath, {
mapDispatchToPropsMethodNames,
proxyquireObject,
}) {
return `import assert from 'assert'
return `import assert from 'assert'
import proxyquire from 'proxyquire'
import sinon from 'sinon'

@ -155,27 +155,27 @@ function copyTask (taskName, opts) {
gulp.task('manifest:chrome', function () {
return gulp.src('./dist/chrome/manifest.json')
.pipe(jsoneditor(function (json) {
delete json.applications
json.minimum_chrome_version = '58'
return json
}))
.pipe(gulp.dest('./dist/chrome', { overwrite: true }))
.pipe(jsoneditor(function (json) {
delete json.applications
json.minimum_chrome_version = '58'
return json
}))
.pipe(gulp.dest('./dist/chrome', { overwrite: true }))
})
gulp.task('manifest:opera', function () {
return gulp.src('./dist/opera/manifest.json')
.pipe(jsoneditor(function (json) {
json.permissions = [
'storage',
'tabs',
'clipboardWrite',
'clipboardRead',
'http://localhost:8545/',
]
return json
}))
.pipe(gulp.dest('./dist/opera', { overwrite: true }))
.pipe(jsoneditor(function (json) {
json.permissions = [
'storage',
'tabs',
'clipboardWrite',
'clipboardRead',
'http://localhost:8545/',
]
return json
}))
.pipe(gulp.dest('./dist/opera', { overwrite: true }))
})
gulp.task('manifest:production', function () {
@ -188,14 +188,14 @@ gulp.task('manifest:production', function () {
], {base: './dist/'})
// Exclude chromereload script in production:
.pipe(jsoneditor(function (json) {
json.background.scripts = json.background.scripts.filter((script) => {
return !script.includes('chromereload')
})
return json
}))
.pipe(jsoneditor(function (json) {
json.background.scripts = json.background.scripts.filter((script) => {
return !script.includes('chromereload')
})
return json
}))
.pipe(gulp.dest('./dist/', { overwrite: true }))
.pipe(gulp.dest('./dist/', { overwrite: true }))
})
gulp.task('manifest:testing', function () {
@ -205,12 +205,12 @@ gulp.task('manifest:testing', function () {
], {base: './dist/'})
// Exclude chromereload script in production:
.pipe(jsoneditor(function (json) {
json.permissions = [...json.permissions, 'webRequestBlocking']
return json
}))
.pipe(jsoneditor(function (json) {
json.permissions = [...json.permissions, 'webRequestBlocking']
return json
}))
.pipe(gulp.dest('./dist/', { overwrite: true }))
.pipe(gulp.dest('./dist/', { overwrite: true }))
})
gulp.task('copy',
@ -477,8 +477,8 @@ gulp.task('dist',
function zipTask (target) {
return () => {
return gulp.src(`dist/${target}/**`)
.pipe(zip(`metamask-${target}-${manifest.version}.zip`))
.pipe(gulp.dest('builds'))
.pipe(zip(`metamask-${target}-${manifest.version}.zip`))
.pipe(gulp.dest('builds'))
}
}
@ -570,11 +570,11 @@ function bundleTask (opts) {
// Minification
if (opts.minifyBuild) {
buildStream = buildStream
.pipe(uglify({
mangle: {
reserved: [ 'MetamaskInpageProvider' ],
},
}))
.pipe(uglify({
mangle: {
reserved: [ 'MetamaskInpageProvider' ],
},
}))
}
// Finalize Source Maps

@ -72,7 +72,7 @@ web3.currentProvider.enable().then(() => {
})
})
}
})
})
console.log(piggybank)
})
@ -161,7 +161,7 @@ web3.currentProvider.enable().then(() => {
})
})
}
})
})
})
})

@ -162,6 +162,6 @@ async function switchToWindowWithUrlThatMatches (driver, regexp, windowHandles)
if (windowUrl.match(regexp)) {
return firstHandle
} else {
return await switchToWindowWithUrlThatMatches(driver, regexp, windowHandles.slice(1))
return await switchToWindowWithUrlThatMatches(driver, regexp, windowHandles.slice(1))
}
}

@ -109,110 +109,110 @@ describe('MetaMask', function () {
})
describe('Going through the first time flow', () => {
it('clicks the continue button on the welcome screen', async () => {
await findElement(driver, By.css('.welcome-page__header'))
const welcomeScreenBtn = await findElement(driver, By.css('.first-time-flow__button'))
welcomeScreenBtn.click()
await delay(largeDelayMs)
})
it('clicks the continue button on the welcome screen', async () => {
await findElement(driver, By.css('.welcome-page__header'))
const welcomeScreenBtn = await findElement(driver, By.css('.first-time-flow__button'))
welcomeScreenBtn.click()
await delay(largeDelayMs)
})
it('clicks the "Create New Wallet" option', async () => {
const customRpcButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Create a Wallet')]`))
customRpcButton.click()
await delay(largeDelayMs)
})
it('clicks the "Create New Wallet" option', async () => {
const customRpcButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Create a Wallet')]`))
customRpcButton.click()
await delay(largeDelayMs)
})
it('clicks the "I agree" option on the metametrics opt-in screen', async () => {
const optOutButton = await findElement(driver, By.css('.btn-primary'))
optOutButton.click()
await delay(largeDelayMs)
})
it('clicks the "I agree" option on the metametrics opt-in screen', async () => {
const optOutButton = await findElement(driver, By.css('.btn-primary'))
optOutButton.click()
await delay(largeDelayMs)
})
it('accepts a secure password', async () => {
const passwordBox = await findElement(driver, By.css('.first-time-flow__form #create-password'))
const passwordBoxConfirm = await findElement(driver, By.css('.first-time-flow__form #confirm-password'))
const button = await findElement(driver, By.css('.first-time-flow__form button'))
it('accepts a secure password', async () => {
const passwordBox = await findElement(driver, By.css('.first-time-flow__form #create-password'))
const passwordBoxConfirm = await findElement(driver, By.css('.first-time-flow__form #confirm-password'))
const button = await findElement(driver, By.css('.first-time-flow__form button'))
await passwordBox.sendKeys('correct horse battery staple')
await passwordBoxConfirm.sendKeys('correct horse battery staple')
await passwordBox.sendKeys('correct horse battery staple')
await passwordBoxConfirm.sendKeys('correct horse battery staple')
const tosCheckBox = await findElement(driver, By.css('.first-time-flow__checkbox'))
await tosCheckBox.click()
const tosCheckBox = await findElement(driver, By.css('.first-time-flow__checkbox'))
await tosCheckBox.click()
await button.click()
await delay(regularDelayMs)
})
await button.click()
await delay(regularDelayMs)
})
let seedPhrase
let seedPhrase
it('reveals the seed phrase', async () => {
const byRevealButton = By.css('.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button')
await driver.wait(until.elementLocated(byRevealButton, 10000))
const revealSeedPhraseButton = await findElement(driver, byRevealButton, 10000)
await revealSeedPhraseButton.click()
await delay(regularDelayMs)
it('reveals the seed phrase', async () => {
const byRevealButton = By.css('.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button')
await driver.wait(until.elementLocated(byRevealButton, 10000))
const revealSeedPhraseButton = await findElement(driver, byRevealButton, 10000)
await revealSeedPhraseButton.click()
await delay(regularDelayMs)
seedPhrase = await driver.findElement(By.css('.reveal-seed-phrase__secret-words')).getText()
assert.equal(seedPhrase.split(' ').length, 12)
await delay(regularDelayMs)
seedPhrase = await driver.findElement(By.css('.reveal-seed-phrase__secret-words')).getText()
assert.equal(seedPhrase.split(' ').length, 12)
await delay(regularDelayMs)
const nextScreen = await findElement(driver, By.css('button.first-time-flow__button'))
await nextScreen.click()
await delay(regularDelayMs)
})
const nextScreen = await findElement(driver, By.css('button.first-time-flow__button'))
await nextScreen.click()
await delay(regularDelayMs)
})
async function clickWordAndWait (word) {
const xpath = `//div[contains(@class, 'confirm-seed-phrase__seed-word--shuffled') and not(contains(@class, 'confirm-seed-phrase__seed-word--selected')) and contains(text(), '${word}')]`
const word0 = await findElement(driver, By.xpath(xpath), 10000)
async function clickWordAndWait (word) {
const xpath = `//div[contains(@class, 'confirm-seed-phrase__seed-word--shuffled') and not(contains(@class, 'confirm-seed-phrase__seed-word--selected')) and contains(text(), '${word}')]`
const word0 = await findElement(driver, By.xpath(xpath), 10000)
await word0.click()
await delay(tinyDelayMs)
}
await word0.click()
await delay(tinyDelayMs)
}
async function retypeSeedPhrase (words, wasReloaded, count = 0) {
try {
if (wasReloaded) {
const byRevealButton = By.css('.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button')
await driver.wait(until.elementLocated(byRevealButton, 10000))
const revealSeedPhraseButton = await findElement(driver, byRevealButton, 10000)
await revealSeedPhraseButton.click()
await delay(regularDelayMs)
const nextScreen = await findElement(driver, By.css('button.first-time-flow__button'))
await nextScreen.click()
await delay(regularDelayMs)
}
async function retypeSeedPhrase (words, wasReloaded, count = 0) {
try {
if (wasReloaded) {
const byRevealButton = By.css('.reveal-seed-phrase__secret-blocker .reveal-seed-phrase__reveal-button')
await driver.wait(until.elementLocated(byRevealButton, 10000))
const revealSeedPhraseButton = await findElement(driver, byRevealButton, 10000)
await revealSeedPhraseButton.click()
await delay(regularDelayMs)
const nextScreen = await findElement(driver, By.css('button.first-time-flow__button'))
await nextScreen.click()
await delay(regularDelayMs)
}
for (let i = 0; i < 12; i++) {
await clickWordAndWait(words[i])
}
} catch (e) {
if (count > 2) {
throw e
} else {
await loadExtension(driver, extensionId)
await retypeSeedPhrase(words, true, count + 1)
}
for (let i = 0; i < 12; i++) {
await clickWordAndWait(words[i])
}
} catch (e) {
if (count > 2) {
throw e
} else {
await loadExtension(driver, extensionId)
await retypeSeedPhrase(words, true, count + 1)
}
}
}
it('can retype the seed phrase', async () => {
const words = seedPhrase.split(' ')
it('can retype the seed phrase', async () => {
const words = seedPhrase.split(' ')
await retypeSeedPhrase(words)
await retypeSeedPhrase(words)
const confirm = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirm.click()
await delay(regularDelayMs)
})
const confirm = await findElement(driver, By.xpath(`//button[contains(text(), 'Confirm')]`))
await confirm.click()
await delay(regularDelayMs)
})
it('clicks through the success screen', async () => {
await findElement(driver, By.xpath(`//div[contains(text(), 'Congratulations')]`))
const doneButton = await findElement(driver, By.css('button.first-time-flow__button'))
await doneButton.click()
await delay(regularDelayMs)
})
it('clicks through the success screen', async () => {
await findElement(driver, By.xpath(`//div[contains(text(), 'Congratulations')]`))
const doneButton = await findElement(driver, By.css('button.first-time-flow__button'))
await doneButton.click()
await delay(regularDelayMs)
})
})
describe('Show account information', () => {
it('show account details dropdown menu', async () => {

@ -34,9 +34,9 @@ describe('Using MetaMask with an existing account', function () {
const button = async (x) => {
const buttoncheck = x
await buttoncheck.click()
await delay(largeDelayMs)
const [results] = await findElements(driver, By.css('#results'))
const resulttext = await results.getText()
await delay(largeDelayMs)
const [results] = await findElements(driver, By.css('#results'))
const resulttext = await results.getText()
var parsedData = JSON.parse(resulttext)
return (parsedData)
@ -169,197 +169,197 @@ describe('Using MetaMask with an existing account', function () {
})
describe('opens dapp', () => {
describe('opens dapp', () => {
it('switches to mainnet', async () => {
const networkDropdown = await findElement(driver, By.css('.network-name'))
await networkDropdown.click()
await delay(regularDelayMs)
it('switches to mainnet', async () => {
const networkDropdown = await findElement(driver, By.css('.network-name'))
await networkDropdown.click()
await delay(regularDelayMs)
const [mainnet] = await findElements(driver, By.xpath(`//span[contains(text(), 'Main Ethereum Network')]`))
await mainnet.click()
await delay(largeDelayMs * 2)
})
const [mainnet] = await findElements(driver, By.xpath(`//span[contains(text(), 'Main Ethereum Network')]`))
await mainnet.click()
await delay(largeDelayMs * 2)
})
it('', async () => {
await openNewPage(driver, 'http://127.0.0.1:8080/')
await delay(regularDelayMs)
it('', async () => {
await openNewPage(driver, 'http://127.0.0.1:8080/')
await delay(regularDelayMs)
await waitUntilXWindowHandles(driver, 3)
const windowHandles = await driver.getAllWindowHandles()
await waitUntilXWindowHandles(driver, 3)
const windowHandles = await driver.getAllWindowHandles()
const extension = windowHandles[0]
const popup = await switchToWindowWithTitle(driver, 'MetaMask Notification', windowHandles)
const dapp = windowHandles.find(handle => handle !== extension && handle !== popup)
const extension = windowHandles[0]
const popup = await switchToWindowWithTitle(driver, 'MetaMask Notification', windowHandles)
const dapp = windowHandles.find(handle => handle !== extension && handle !== popup)
await delay(regularDelayMs)
const approveButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Connect')]`))
await approveButton.click()
await delay(regularDelayMs)
const approveButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Connect')]`))
await approveButton.click()
await driver.switchTo().window(dapp)
await delay(regularDelayMs)
await driver.switchTo().window(dapp)
await delay(regularDelayMs)
})
})
})
describe('testing web3 methods', async () => {
describe('testing web3 methods', async () => {
it('testing hexa methods', async () => {
it('testing hexa methods', async () => {
var List = await driver.findElements(By.className('hexaNumberMethods'))
var List = await driver.findElements(By.className('hexaNumberMethods'))
for (let i = 0; i < List.length; i++) {
try {
for (let i = 0; i < List.length; i++) {
try {
var parsedData = await button(List[i])
console.log(parsedData)
var result = parseInt(parsedData.result, 16)
var parsedData = await button(List[i])
console.log(parsedData)
var result = parseInt(parsedData.result, 16)
assert.equal((typeof result === 'number'), true)
await delay(regularDelayMs)
} catch (err) {
console.log(err)
assert(false)
assert.equal((typeof result === 'number'), true)
await delay(regularDelayMs)
} catch (err) {
console.log(err)
assert(false)
}
}
})
}
})
it('testing booleanMethods', async () => {
it('testing booleanMethods', async () => {
var List = await driver.findElements(By.className('booleanMethods'))
var List = await driver.findElements(By.className('booleanMethods'))
for (let i = 0; i < List.length; i++) {
try {
for (let i = 0; i < List.length; i++) {
try {
var parsedData = await button(List[i])
console.log(parsedData)
var result = parsedData.result
var parsedData = await button(List[i])
console.log(parsedData)
var result = parsedData.result
assert.equal(result, false)
await delay(regularDelayMs)
} catch (err) {
console.log(err)
assert(false)
assert.equal(result, false)
await delay(regularDelayMs)
} catch (err) {
console.log(err)
assert(false)
}
}
}
})
})
it('testing transactionMethods', async () => {
it('testing transactionMethods', async () => {
var List = await driver.findElements(By.className('transactionMethods'))
var List = await driver.findElements(By.className('transactionMethods'))
for (let i = 0; i < List.length; i++) {
try {
for (let i = 0; i < List.length; i++) {
try {
var parsedData = await button(List[i])
var parsedData = await button(List[i])
console.log(parsedData.result.blockHash)
console.log(parsedData.result.blockHash)
var result = []
result.push(parseInt(parsedData.result.blockHash, 16))
result.push(parseInt(parsedData.result.blockNumber, 16))
result.push(parseInt(parsedData.result.gas, 16))
result.push(parseInt(parsedData.result.gasPrice, 16))
result.push(parseInt(parsedData.result.hash, 16))
result.push(parseInt(parsedData.result.input, 16))
result.push(parseInt(parsedData.result.nonce, 16))
result.push(parseInt(parsedData.result.r, 16))
result.push(parseInt(parsedData.result.s, 16))
result.push(parseInt(parsedData.result.v, 16))
result.push(parseInt(parsedData.result.to, 16))
result.push(parseInt(parsedData.result.value, 16))
var result = []
result.push(parseInt(parsedData.result.blockHash, 16))
result.push(parseInt(parsedData.result.blockNumber, 16))
result.push(parseInt(parsedData.result.gas, 16))
result.push(parseInt(parsedData.result.gasPrice, 16))
result.push(parseInt(parsedData.result.hash, 16))
result.push(parseInt(parsedData.result.input, 16))
result.push(parseInt(parsedData.result.nonce, 16))
result.push(parseInt(parsedData.result.r, 16))
result.push(parseInt(parsedData.result.s, 16))
result.push(parseInt(parsedData.result.v, 16))
result.push(parseInt(parsedData.result.to, 16))
result.push(parseInt(parsedData.result.value, 16))
result.forEach((value) => {
assert.equal((typeof value === 'number'), true)
})
result.forEach((value) => {
assert.equal((typeof value === 'number'), true)
})
} catch (err) {
} catch (err) {
console.log(err)
assert(false)
console.log(err)
assert(false)
}
}
}
})
})
it('testing blockMethods', async () => {
it('testing blockMethods', async () => {
var List = await driver.findElements(By.className('blockMethods'))
var List = await driver.findElements(By.className('blockMethods'))
for (let i = 0; i < List.length; i++) {
try {
for (let i = 0; i < List.length; i++) {
try {
var parsedData = await button(List[i])
console.log(JSON.stringify(parsedData) + i)
var parsedData = await button(List[i])
console.log(JSON.stringify(parsedData) + i)
console.log(parsedData.result.parentHash)
console.log(parsedData.result.parentHash)
var result = parseInt(parsedData.result.parentHash, 16)
var result = parseInt(parsedData.result.parentHash, 16)
assert.equal((typeof result === 'number'), true)
await delay(regularDelayMs)
} catch (err) {
assert.equal((typeof result === 'number'), true)
await delay(regularDelayMs)
} catch (err) {
console.log(err)
assert(false)
console.log(err)
assert(false)
}
}
})
}
})
it('testing methods', async () => {
it('testing methods', async () => {
var List = await driver.findElements(By.className('methods'))
var parsedData
var result
var List = await driver.findElements(By.className('methods'))
var parsedData
var result
for (let i = 0; i < List.length; i++) {
try {
for (let i = 0; i < List.length; i++) {
try {
if (i === 2) {
if (i === 2) {
parsedData = await button(List[i])
console.log(parsedData.result.blockHash)
parsedData = await button(List[i])
console.log(parsedData.result.blockHash)
result = parseInt(parsedData.result.blockHash, 16)
result = parseInt(parsedData.result.blockHash, 16)
assert.equal((typeof result === 'number' || (result === 0)), true)
await delay(regularDelayMs)
} else {
parsedData = await button(List[i])
console.log(parsedData.result)
assert.equal((typeof result === 'number' || (result === 0)), true)
await delay(regularDelayMs)
} else {
parsedData = await button(List[i])
console.log(parsedData.result)
result = parseInt(parsedData.result, 16)
result = parseInt(parsedData.result, 16)
assert.equal((typeof result === 'number' || (result === 0)), true)
await delay(regularDelayMs)
}
assert.equal((typeof result === 'number' || (result === 0)), true)
await delay(regularDelayMs)
}
} catch (err) {
} catch (err) {
console.log(err)
assert(false)
console.log(err)
assert(false)
}
}
})
}
})
})
})
})
})

@ -71,8 +71,8 @@ describe('DetectTokensController', () => {
controller.isUnlocked = true
var stub = sandbox.stub(controller, 'detectTokenBalance')
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4').returns(true)
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388').returns(true)
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4').returns(true)
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388').returns(true)
await controller.detectNewTokens()
sandbox.assert.notCalled(stub)
@ -84,14 +84,14 @@ describe('DetectTokensController', () => {
controller.isUnlocked = true
sandbox.stub(controller, 'detectTokenBalance')
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4')
.returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8))
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388')
.returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18))
.withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4')
.returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8))
.withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388')
.returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18))
await controller.detectNewTokens()
assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'},
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
})
it('should not detect same token while in main network', async () => {
@ -108,7 +108,7 @@ describe('DetectTokensController', () => {
await controller.detectNewTokens()
assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'},
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
{address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
})
it('should trigger detect new tokens when change address', async () => {

@ -7,7 +7,7 @@ const sinon = require('sinon')
describe('PendingTransactionTracker', function () {
let pendingTxTracker, txMeta, txMetaNoHash, providerResultStub,
provider, txMeta3, txList, knownErrors
provider, txMeta3, txList, knownErrors
this.timeout(10000)
beforeEach(function () {
@ -80,7 +80,7 @@ describe('PendingTransactionTracker', function () {
}, { count: 1 })[0]
stub = sinon.stub(pendingTxTracker, 'getCompletedTransactions')
.returns(txGen.txs)
.returns(txGen.txs)
// THE EXPECTATION
const spy = sinon.spy()
@ -107,18 +107,18 @@ describe('PendingTransactionTracker', function () {
})
it('should emit tx:dropped with the txMetas id only after the second call', function (done) {
txMeta = {
id: 1,
hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb',
status: 'submitted',
txParams: {
from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
nonce: '0x1',
value: '0xfffff',
},
history: [{}],
rawTx: '0xf86c808504a817c800827b0d940c62bb85faa3311a998d3aba8098c1235c564966880de0b6b3a7640000802aa08ff665feb887a25d4099e40e11f0fef93ee9608f404bd3f853dd9e84ed3317a6a02ec9d3d1d6e176d4d2593dd760e74ccac753e6a0ea0d00cc9789d0d7ff1f471d',
}
txMeta = {
id: 1,
hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb',
status: 'submitted',
txParams: {
from: '0x1678a085c290ebd122dc42cba69373b5953b831d',
nonce: '0x1',
value: '0xfffff',
},
history: [{}],
rawTx: '0xf86c808504a817c800827b0d940c62bb85faa3311a998d3aba8098c1235c564966880de0b6b3a7640000802aa08ff665feb887a25d4099e40e11f0fef93ee9608f404bd3f853dd9e84ed3317a6a02ec9d3d1d6e176d4d2593dd760e74ccac753e6a0ea0d00cc9789d0d7ff1f471d',
}
providerResultStub['eth_getTransactionCount'] = '0x02'
providerResultStub['eth_getTransactionByHash'] = {}
@ -159,8 +159,8 @@ describe('PendingTransactionTracker', function () {
pendingTxTracker.getPendingTransactions = () => txList
pendingTxTracker._checkPendingTx = (tx) => { tx.resolve(tx) }
Promise.all(txList.map((tx) => tx.processed))
.then(() => done())
.catch(done)
.then(() => done())
.catch(done)
pendingTxTracker.updatePendingTxs()
})
@ -169,8 +169,8 @@ describe('PendingTransactionTracker', function () {
describe('#resubmitPendingTxs', function () {
const blockNumberStub = '0x0'
beforeEach(function () {
const txMeta2 = txMeta3 = txMeta
txList = [txMeta, txMeta2, txMeta3].map((tx) => {
const txMeta2 = txMeta3 = txMeta
txList = [txMeta, txMeta2, txMeta3].map((tx) => {
tx.processed = new Promise((resolve) => { tx.resolve = resolve })
return tx
})
@ -183,8 +183,8 @@ describe('PendingTransactionTracker', function () {
pendingTxTracker.getPendingTransactions = () => txList
pendingTxTracker._resubmitTx = async (tx) => { tx.resolve(tx) }
Promise.all(txList.map((tx) => tx.processed))
.then(() => done())
.catch(done)
.then(() => done())
.catch(done)
pendingTxTracker.resubmitPendingTxs(blockNumberStub)
})
it('should not emit \'tx:failed\' if the txMeta throws a known txError', function (done) {
@ -209,8 +209,8 @@ describe('PendingTransactionTracker', function () {
throw new Error(knownErrors.pop())
}
Promise.all(txList.map((tx) => tx.processed))
.then(() => done())
.catch(done)
.then(() => done())
.catch(done)
pendingTxTracker.resubmitPendingTxs(blockNumberStub)
})
@ -227,8 +227,8 @@ describe('PendingTransactionTracker', function () {
pendingTxTracker.getPendingTransactions = () => txList
pendingTxTracker._resubmitTx = async () => { throw new TypeError('im some real error') }
Promise.all(txList.map((tx) => tx.processed))
.then(() => done())
.catch(done)
.then(() => done())
.catch(done)
pendingTxTracker.resubmitPendingTxs(blockNumberStub)
})
@ -264,11 +264,11 @@ describe('PendingTransactionTracker', function () {
// Stubbing out current account state:
// Adding the fake tx:
pendingTxTracker._resubmitTx(txMeta)
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
assert.equal(pendingTxTracker.publishTransaction.callCount, 1, 'Should call publish transaction')
})
@ -278,11 +278,11 @@ describe('PendingTransactionTracker', function () {
const mockLatestBlockNumber = '0x5'
pendingTxTracker._resubmitTx(txMetaToTestExponentialBackoff, mockLatestBlockNumber)
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
assert.equal(pendingTxTracker.publishTransaction.callCount, 0, 'Should NOT call publish transaction')
})
@ -292,11 +292,11 @@ describe('PendingTransactionTracker', function () {
const mockLatestBlockNumber = '0x11'
pendingTxTracker._resubmitTx(txMetaToTestExponentialBackoff, mockLatestBlockNumber)
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
.then(() => done())
.catch((err) => {
assert.ifError(err, 'should not throw an error')
done(err)
})
assert.equal(pendingTxTracker.publishTransaction.callCount, 1, 'Should call publish transaction')
})
@ -382,11 +382,11 @@ describe('PendingTransactionTracker', function () {
value: '0xfffff',
},
})
.then((taken) => {
assert.ok(!taken)
done()
})
.catch(done)
.then((taken) => {
assert.ok(!taken)
done()
})
.catch(done)
})
it('should return true if nonce has been taken', function (done) {
@ -400,7 +400,7 @@ describe('PendingTransactionTracker', function () {
assert.ok(taken)
done()
})
.catch(done)
.catch(done)
})
})
})

@ -31,8 +31,8 @@ describe('Recipient Blacklist Checker', function () {
const networks = [ROPSTEN_CODE, RINKEYBY_CODE, KOVAN_CODE, GOERLI_CODE]
for (const networkId in networks) {
publicAccounts.forEach((account) => {
recipientBlackListChecker.checkAccount(networkId, account)
callCount++
recipientBlackListChecker.checkAccount(networkId, account)
callCount++
})
}
assert.equal(callCount, 40)

@ -129,13 +129,13 @@ describe('Transaction Controller', function () {
stub = sinon.stub(txController, 'addUnapprovedTransaction').callsFake(() => {
txController.emit('newUnapprovedTx', txMeta)
return Promise.resolve(txController.txStateManager.addTx(txMeta))
})
})
afterEach(function () {
txController.txStateManager._saveTxList([])
stub.restore()
afterEach(function () {
txController.txStateManager._saveTxList([])
stub.restore()
})
})
})
it('should resolve when finished and status is submitted and resolve with the hash', function (done) {
txController.once('newUnapprovedTx', (txMetaFromEmit) => {
@ -146,11 +146,11 @@ describe('Transaction Controller', function () {
})
txController.newUnapprovedTransaction(txParams)
.then((hash) => {
assert(hash, 'newUnapprovedTransaction needs to return the hash')
done()
})
.catch(done)
.then((hash) => {
assert(hash, 'newUnapprovedTransaction needs to return the hash')
done()
})
.catch(done)
})
it('should reject when finished and status is rejected', function (done) {
@ -161,10 +161,10 @@ describe('Transaction Controller', function () {
})
txController.newUnapprovedTransaction(txParams)
.catch((err) => {
if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') done()
else done(err)
})
.catch((err) => {
if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') done()
else done(err)
})
})
})
@ -182,17 +182,17 @@ describe('Transaction Controller', function () {
it('should add an unapproved transaction and return a valid txMeta', function (done) {
txController.addUnapprovedTransaction({ from: selectedAddress })
.then((txMeta) => {
assert(('id' in txMeta), 'should have a id')
assert(('time' in txMeta), 'should have a time stamp')
assert(('metamaskNetworkId' in txMeta), 'should have a metamaskNetworkId')
assert(('txParams' in txMeta), 'should have a txParams')
assert(('history' in txMeta), 'should have a history')
const memTxMeta = txController.txStateManager.getTx(txMeta.id)
assert.deepEqual(txMeta, memTxMeta, `txMeta should be stored in txController after adding it\n expected: ${txMeta} \n got: ${memTxMeta}`)
done()
}).catch(done)
.then((txMeta) => {
assert(('id' in txMeta), 'should have a id')
assert(('time' in txMeta), 'should have a time stamp')
assert(('metamaskNetworkId' in txMeta), 'should have a metamaskNetworkId')
assert(('txParams' in txMeta), 'should have a txParams')
assert(('history' in txMeta), 'should have a history')
const memTxMeta = txController.txStateManager.getTx(txMeta.id)
assert.deepEqual(txMeta, memTxMeta, `txMeta should be stored in txController after adding it\n expected: ${txMeta} \n got: ${memTxMeta}`)
done()
}).catch(done)
})
it('should emit newUnapprovedTx event and pass txMeta as the first argument', function (done) {
@ -202,16 +202,16 @@ describe('Transaction Controller', function () {
done()
})
txController.addUnapprovedTransaction({ from: selectedAddress })
.catch(done)
.catch(done)
})
it('should fail if recipient is public', function (done) {
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)
})
.catch((err) => {
if (err.message === 'Recipient is a public account') done()
else done(err)
})
})
it('should fail if the from address isn\'t the selected address', function (done) {
@ -232,16 +232,16 @@ describe('Transaction Controller', function () {
done()
})
txController.addUnapprovedTransaction({ from: selectedAddress, to: '0x0d1d4e623D10F9FBA5Db95830F7d3839406C6AF2' })
.catch(done)
.catch(done)
})
it('should fail if netId is loading', function (done) {
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)
})
.catch((err) => {
if (err.message === 'MetaMask is having trouble connecting to the network') done()
else done(err)
})
})
})
@ -284,11 +284,11 @@ describe('Transaction Controller', function () {
}))
})
Promise.all(listeners)
.then((returnValues) => {
assert.deepEqual(returnValues.pop(), txMeta, 'last event 1:unapproved should return txMeta')
done()
})
.catch(done)
.then((returnValues) => {
assert.deepEqual(returnValues.pop(), txMeta, 'last event 1:unapproved should return txMeta')
done()
})
.catch(done)
txController.addTx(txMeta)
})
})
@ -511,16 +511,16 @@ describe('Transaction Controller', function () {
{ id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams, history: [{}] },
])
txController.retryTransaction(1)
.then((txMeta) => {
assert.equal(txMeta.txParams.gasPrice, '0x10642ac00', 'gasPrice should have a %10 gasPrice bump')
assert.equal(txMeta.txParams.nonce, txParams.nonce, 'nonce should be the same')
assert.equal(txMeta.txParams.from, txParams.from, 'from should be the same')
assert.equal(txMeta.txParams.to, txParams.to, 'to should be the same')
assert.equal(txMeta.txParams.data, txParams.data, 'data should be the same')
assert.ok(('lastGasPrice' in txMeta), 'should have the key `lastGasPrice`')
assert.equal(txController.txStateManager.getTxList().length, 2)
done()
}).catch(done)
.then((txMeta) => {
assert.equal(txMeta.txParams.gasPrice, '0x10642ac00', 'gasPrice should have a %10 gasPrice bump')
assert.equal(txMeta.txParams.nonce, txParams.nonce, 'nonce should be the same')
assert.equal(txMeta.txParams.from, txParams.from, 'from should be the same')
assert.equal(txMeta.txParams.to, txParams.to, 'to should be the same')
assert.equal(txMeta.txParams.data, txParams.data, 'data should be the same')
assert.ok(('lastGasPrice' in txMeta), 'should have the key `lastGasPrice`')
assert.equal(txController.txStateManager.getTxList().length, 2)
done()
}).catch(done)
})
})

@ -43,7 +43,7 @@ describe('TransactionStateManager', function () {
})
describe('#setTxStatusRejected', function () {
it('sets the tx status to rejected and removes it from history', function () {
it('sets the tx status to rejected and removes it from history', function () {
const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx)
txStateManager.setTxStatusRejected(1)
@ -56,11 +56,11 @@ describe('TransactionStateManager', function () {
const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx)
const noop = function (err) {
if (err) {
console.log('Error: ', err)
}
assert(true, 'event listener has been triggered and noop executed')
done()
if (err) {
console.log('Error: ', err)
}
assert(true, 'event listener has been triggered and noop executed')
done()
}
txStateManager.on('1:rejected', noop)
txStateManager.setTxStatusRejected(1)

@ -93,6 +93,6 @@ describe('txUtils', function () {
// should run
txParams.from = '0x1678a085c290ebd122dc42cba69373b5953b831d'
txUtils.validateFrom(txParams)
})
})
})
})

@ -65,13 +65,13 @@ describe('EdgeEncryptor', function () {
edgeEncryptor.encrypt(password, data)
.then(function (encryptedData) {
edgeEncryptor.decrypt(password, encryptedData)
.then(function (decryptedData) {
assert.equal(decryptedData, data)
done()
})
.catch(function (err) {
done(err)
})
.then(function (decryptedData) {
assert.equal(decryptedData, data)
done()
})
.catch(function (err) {
done(err)
})
})
.catch(function (err) {
done(err)
@ -83,15 +83,15 @@ describe('EdgeEncryptor', function () {
edgeEncryptor.encrypt(password, data)
.then(function (encryptedData) {
edgeEncryptor.decrypt('wrong password', encryptedData)
.then(function () {
assert.fail('could decrypt with wrong password')
done()
})
.catch(function (err) {
assert.ok(err instanceof Error)
assert.equal(err.message, 'Incorrect password')
done()
})
.then(function () {
assert.fail('could decrypt with wrong password')
done()
})
.catch(function (err) {
assert.ok(err instanceof Error)
assert.equal(err.message, 'Incorrect password')
done()
})
})
.catch(function (err) {
done(err)

@ -10,12 +10,12 @@
*/
const initialState = {
config: {},
NetworkController: {
provider: {
type: 'rpc',
rpcTarget: 'http://localhost:8545',
},
NetworkController: {
provider: {
type: 'rpc',
rpcTarget: 'http://localhost:8545',
},
},
}
module.exports = initialState

@ -6,11 +6,11 @@ const migration21 = require('../../../app/scripts/migrations/021')
describe('wallet2 is migrated successfully with out the BlacklistController', () => {
it('should delete BlacklistController key', (done) => {
migration21.migrate(wallet2)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 21)
assert(!migratedData.data.BlacklistController)
assert(!migratedData.data.RecentBlocks)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 21)
assert(!migratedData.data.BlacklistController)
assert(!migratedData.data.RecentBlocks)
done()
}).catch(done)
})
})

@ -17,16 +17,16 @@ const storage = {
describe('storage is migrated successfully where transactions that are submitted have submittedTimes', () => {
it('should add submittedTime key on the txMeta if appropriate', (done) => {
migration22.migrate(storage)
.then((migratedData) => {
const [txMeta1, txMeta2, txMeta3] = migratedData.data.TransactionController.transactions
assert.equal(migratedData.meta.version, 22)
// should have written a submitted time
assert(txMeta1.submittedTime)
// should not have written a submitted time because it already has one
assert.equal(txMeta2.submittedTime, properTime)
// should not have written a submitted time
assert(!txMeta3.submittedTime)
done()
}).catch(done)
.then((migratedData) => {
const [txMeta1, txMeta2, txMeta3] = migratedData.data.TransactionController.transactions
assert.equal(migratedData.meta.version, 22)
// should have written a submitted time
assert(txMeta1.submittedTime)
// should not have written a submitted time because it already has one
assert.equal(txMeta2.submittedTime, properTime)
// should not have written a submitted time
assert(!txMeta3.submittedTime)
done()
}).catch(done)
})
})

@ -57,41 +57,41 @@ storage.data.TransactionController.transactions = transactions
describe('storage is migrated successfully and the proper transactions are remove from state', () => {
it('should remove transactions that are unneeded', (done) => {
migration23.migrate(storage)
.then((migratedData) => {
let leftoverNonDeletableTxCount = 0
const migratedTransactions = migratedData.data.TransactionController.transactions
migratedTransactions.forEach((tx) => {
if (!deletableTxStates.find((s) => s === tx.status)) {
leftoverNonDeletableTxCount++
}
})
assert.equal(leftoverNonDeletableTxCount, nonDeletableCount, 'migration shouldnt delete transactions we want to keep')
assert((migratedTransactions.length >= 40), `should be equal or greater to 40 if they are non deletable states got ${migratedTransactions.length} transactions`)
done()
}).catch(done)
.then((migratedData) => {
let leftoverNonDeletableTxCount = 0
const migratedTransactions = migratedData.data.TransactionController.transactions
migratedTransactions.forEach((tx) => {
if (!deletableTxStates.find((s) => s === tx.status)) {
leftoverNonDeletableTxCount++
}
})
assert.equal(leftoverNonDeletableTxCount, nonDeletableCount, 'migration shouldnt delete transactions we want to keep')
assert((migratedTransactions.length >= 40), `should be equal or greater to 40 if they are non deletable states got ${migratedTransactions.length} transactions`)
done()
}).catch(done)
})
it('should not remove any transactions because 40 is the expectable limit', (done) => {
storage.meta.version = 22
storage.data.TransactionController.transactions = transactions40
migration23.migrate(storage)
.then((migratedData) => {
const migratedTransactions = migratedData.data.TransactionController.transactions
.then((migratedData) => {
const migratedTransactions = migratedData.data.TransactionController.transactions
assert.equal(migratedTransactions.length, 40, 'migration shouldnt delete when at limit')
done()
}).catch(done)
assert.equal(migratedTransactions.length, 40, 'migration shouldnt delete when at limit')
done()
}).catch(done)
})
it('should not remove any transactions because 20 txs is under the expectable limit', (done) => {
storage.meta.version = 22
storage.data.TransactionController.transactions = transactions20
migration23.migrate(storage)
.then((migratedData) => {
const migratedTransactions = migratedData.data.TransactionController.transactions
assert.equal(migratedTransactions.length, 20, 'migration shouldnt delete when under limit')
done()
}).catch(done)
.then((migratedData) => {
const migratedTransactions = migratedData.data.TransactionController.transactions
assert.equal(migratedTransactions.length, 20, 'migration shouldnt delete when under limit')
done()
}).catch(done)
})
})

@ -28,21 +28,21 @@ storage.data.TransactionController.transactions = transactions
describe('storage is migrated successfully and the txParams.from are lowercase', () => {
it('should lowercase the from for unapproved txs', (done) => {
migration24.migrate(storage)
.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')
})
done()
}).catch(done)
.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')
})
done()
}).catch(done)
})
it('should migrate first time state', (done) => {
migration24.migrate(firstTimeState)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 24)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 24)
done()
}).catch(done)
})
})

@ -29,21 +29,21 @@ storage.data.TransactionController.transactions = transactions
describe('storage is migrated successfully and the txParams.from are lowercase', () => {
it('should lowercase the from for unapproved txs', (done) => {
migration25.migrate(storage)
.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)
})
done()
}).catch(done)
.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)
})
done()
}).catch(done)
})
it('should migrate first time state', (done) => {
migration25.migrate(firstTimeState)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 25)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 25)
done()
}).catch(done)
})
})

@ -19,20 +19,20 @@ const storage = {
describe('storage is migrated successfully where transactions that are submitted have submittedTimes', () => {
it('should auto fail transactions more than 12 hours old', (done) => {
migration29.migrate(storage)
.then((migratedData) => {
const txs = migratedData.data.TransactionController.transactions
const [ txMeta1 ] = txs
assert.equal(migratedData.meta.version, 29)
.then((migratedData) => {
const txs = migratedData.data.TransactionController.transactions
const [ txMeta1 ] = txs
assert.equal(migratedData.meta.version, 29)
assert.equal(txMeta1.status, 'failed', 'old tx is auto failed')
assert(txMeta1.err.message.includes('too long'), 'error message assigned')
assert.equal(txMeta1.status, 'failed', 'old tx is auto failed')
assert(txMeta1.err.message.includes('too long'), 'error message assigned')
txs.forEach((tx) => {
if (tx.id === 1) return
assert.notEqual(tx.status, 'failed', 'other tx is not auto failed')
})
txs.forEach((tx) => {
if (tx.id === 1) return
assert.notEqual(tx.status, 'failed', 'other tx is not auto failed')
})
done()
}).catch(done)
done()
}).catch(done)
})
})

@ -25,13 +25,13 @@ const storage = {
describe('storage is migrated successfully', () => {
it('should work', (done) => {
migrationTemplate.migrate(storage)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 30)
assert.equal(migratedData.data.PreferencesController.frequentRpcListDetail[0].chainId, undefined)
assert.equal(migratedData.data.PreferencesController.frequentRpcListDetail[1].chainId, '1')
assert.equal(migratedData.data.NetworkController.provider.chainId, undefined)
assert.equal(migratedData.data.NetworkController.network, undefined)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 30)
assert.equal(migratedData.data.PreferencesController.frequentRpcListDetail[0].chainId, undefined)
assert.equal(migratedData.data.PreferencesController.frequentRpcListDetail[1].chainId, '1')
assert.equal(migratedData.data.NetworkController.provider.chainId, undefined)
assert.equal(migratedData.data.NetworkController.network, undefined)
done()
}).catch(done)
})
})

@ -1,7 +1,7 @@
const assert = require('assert')
const migration31 = require('../../../app/scripts/migrations/031')
describe('migration #31', () => {
describe('migration #31', () => {
it('should set completedOnboarding to true if vault exists', done => {
const oldStorage = {
'meta': {},
@ -23,7 +23,7 @@ const migration31 = require('../../../app/scripts/migrations/031')
},
}
migration31.migrate(oldStorage)
migration31.migrate(oldStorage)
.then(newStorage => {
assert.equal(newStorage.data.PreferencesController.completedOnboarding, true)
done()
@ -31,7 +31,7 @@ const migration31 = require('../../../app/scripts/migrations/031')
.catch(done)
})
it('should set completedOnboarding to false if vault does not exist', done => {
it('should set completedOnboarding to false if vault does not exist', done => {
const oldStorage = {
'meta': {},
'data': {
@ -46,7 +46,7 @@ const migration31 = require('../../../app/scripts/migrations/031')
},
}
migration31.migrate(oldStorage)
migration31.migrate(oldStorage)
.then(newStorage => {
assert.equal(newStorage.data.PreferencesController.completedOnboarding, false)
done()

@ -27,82 +27,82 @@ describe('wallet1 is migrated successfully', () => {
wallet1.data.config.provider = { type: 'etherscan', rpcTarget: null }
return migration2.migrate(wallet1)
.then((secondResult) => {
const secondData = secondResult.data
assert.equal(secondData.config.provider.type, 'rpc', 'provider should be rpc')
assert.equal(secondData.config.provider.rpcTarget, 'https://rpc.metamask.io/', 'main provider should be our rpc')
secondResult.data.config.provider.rpcTarget = oldTestRpc
return migration3.migrate(secondResult)
}).then((thirdResult) => {
assert.equal(thirdResult.data.config.provider.rpcTarget, newTestRpc, 'config.provider.rpcTarget should be set to the proper testrpc url.')
return migration4.migrate(thirdResult)
}).then((fourthResult) => {
const fourthData = fourthResult.data
assert.equal(fourthData.config.provider.rpcTarget, null, 'old rpcTarget should not exist.')
assert.equal(fourthData.config.provider.type, 'testnet', 'config.provider should be set to testnet.')
return migration5.migrate(vault4)
}).then((fifthResult) => {
const fifthData = fifthResult.data
assert.equal(fifthData.vault, null, 'old vault should not exist')
assert.equal(fifthData.walletNicknames, null, 'old walletNicknames should not exist')
assert.equal(fifthData.config.selectedAccount, null, 'old config.selectedAccount should not exist')
assert.equal(fifthData.KeyringController.vault, vault4.data.vault, 'KeyringController.vault should exist')
assert.equal(fifthData.KeyringController.selectedAccount, vault4.data.config.selectedAccount, 'KeyringController.selectedAccount should have moved')
assert.equal(fifthData.KeyringController.walletNicknames['0x0beb674745816b125fbc07285d39fd373e64895c'], vault4.data.walletNicknames['0x0beb674745816b125fbc07285d39fd373e64895c'], 'KeyringController.walletNicknames should have moved')
vault5 = fifthResult
return migration6.migrate(fifthResult)
}).then((sixthResult) => {
assert.equal(sixthResult.data.KeyringController.selectedAccount, null, 'old selectedAccount should not exist')
assert.equal(sixthResult.data.PreferencesController.selectedAddress, vault5.data.KeyringController.selectedAccount, 'selectedAccount should have moved')
vault6 = sixthResult
return migration7.migrate(sixthResult)
}).then((seventhResult) => {
assert.equal(seventhResult.data.transactions, null, 'old transactions should not exist')
assert.equal(seventhResult.data.gasMultiplier, null, 'old gasMultiplier should not exist')
assert.equal(seventhResult.data.TransactionManager.transactions[0].id, vault6.data.transactions[0].id, 'transactions should have moved')
assert.equal(seventhResult.data.TransactionManager.gasMultiplier, vault6.data.gasMultiplier, 'gasMultiplier should have moved')
vault7 = seventhResult
return migration8.migrate(seventhResult)
}).then((eighthResult) => {
assert.equal(eighthResult.data.noticesList, null, 'old noticesList should not exist')
assert.equal(eighthResult.data.NoticeController.noticesList[0].title, vault7.data.noticesList[0].title, 'noticesList should have moved')
vault8 = eighthResult
return migration9.migrate(eighthResult)
}).then((ninthResult) => {
assert.equal(ninthResult.data.currentFiat, null, 'old currentFiat should not exist')
assert.equal(ninthResult.data.fiatCurrency, null, 'old fiatCurrency should not exist')
assert.equal(ninthResult.data.conversionRate, null, 'old conversionRate should not exist')
assert.equal(ninthResult.data.conversionDate, null, 'old conversionDate should not exist')
assert.equal(ninthResult.data.CurrencyController.currentCurrency, vault8.data.fiatCurrency, 'currentFiat should have moved')
assert.equal(ninthResult.data.CurrencyController.conversionRate, vault8.data.conversionRate, 'conversionRate should have moved')
assert.equal(ninthResult.data.CurrencyController.conversionDate, vault8.data.conversionDate, 'conversionDate should have moved')
vault9 = ninthResult
return migration10.migrate(ninthResult)
}).then((tenthResult) => {
assert.equal(tenthResult.data.shapeShiftTxList, null, 'old shapeShiftTxList should not exist')
assert.equal(tenthResult.data.ShapeShiftController.shapeShiftTxList[0].transaction, vault9.data.shapeShiftTxList[0].transaction)
return migration11.migrate(tenthResult)
}).then((eleventhResult) => {
assert.equal(eleventhResult.data.isDisclaimerConfirmed, null, 'isDisclaimerConfirmed should not exist')
assert.equal(eleventhResult.data.TOSHash, null, 'TOSHash should not exist')
return migration12.migrate(eleventhResult)
}).then((twelfthResult) => {
assert.equal(twelfthResult.data.NoticeController.noticesList[0].body, '', 'notices that have been read should have an empty body.')
assert.equal(twelfthResult.data.NoticeController.noticesList[1].body, 'nonempty', 'notices that have not been read should not have an empty body.')
assert.equal(twelfthResult.data.config.provider.type, 'testnet', 'network is originally testnet.')
return migration13.migrate(twelfthResult)
}).then((thirteenthResult) => {
assert.equal(thirteenthResult.data.config.provider.type, 'ropsten', 'network has been changed to ropsten.')
})
.then((secondResult) => {
const secondData = secondResult.data
assert.equal(secondData.config.provider.type, 'rpc', 'provider should be rpc')
assert.equal(secondData.config.provider.rpcTarget, 'https://rpc.metamask.io/', 'main provider should be our rpc')
secondResult.data.config.provider.rpcTarget = oldTestRpc
return migration3.migrate(secondResult)
}).then((thirdResult) => {
assert.equal(thirdResult.data.config.provider.rpcTarget, newTestRpc, 'config.provider.rpcTarget should be set to the proper testrpc url.')
return migration4.migrate(thirdResult)
}).then((fourthResult) => {
const fourthData = fourthResult.data
assert.equal(fourthData.config.provider.rpcTarget, null, 'old rpcTarget should not exist.')
assert.equal(fourthData.config.provider.type, 'testnet', 'config.provider should be set to testnet.')
return migration5.migrate(vault4)
}).then((fifthResult) => {
const fifthData = fifthResult.data
assert.equal(fifthData.vault, null, 'old vault should not exist')
assert.equal(fifthData.walletNicknames, null, 'old walletNicknames should not exist')
assert.equal(fifthData.config.selectedAccount, null, 'old config.selectedAccount should not exist')
assert.equal(fifthData.KeyringController.vault, vault4.data.vault, 'KeyringController.vault should exist')
assert.equal(fifthData.KeyringController.selectedAccount, vault4.data.config.selectedAccount, 'KeyringController.selectedAccount should have moved')
assert.equal(fifthData.KeyringController.walletNicknames['0x0beb674745816b125fbc07285d39fd373e64895c'], vault4.data.walletNicknames['0x0beb674745816b125fbc07285d39fd373e64895c'], 'KeyringController.walletNicknames should have moved')
vault5 = fifthResult
return migration6.migrate(fifthResult)
}).then((sixthResult) => {
assert.equal(sixthResult.data.KeyringController.selectedAccount, null, 'old selectedAccount should not exist')
assert.equal(sixthResult.data.PreferencesController.selectedAddress, vault5.data.KeyringController.selectedAccount, 'selectedAccount should have moved')
vault6 = sixthResult
return migration7.migrate(sixthResult)
}).then((seventhResult) => {
assert.equal(seventhResult.data.transactions, null, 'old transactions should not exist')
assert.equal(seventhResult.data.gasMultiplier, null, 'old gasMultiplier should not exist')
assert.equal(seventhResult.data.TransactionManager.transactions[0].id, vault6.data.transactions[0].id, 'transactions should have moved')
assert.equal(seventhResult.data.TransactionManager.gasMultiplier, vault6.data.gasMultiplier, 'gasMultiplier should have moved')
vault7 = seventhResult
return migration8.migrate(seventhResult)
}).then((eighthResult) => {
assert.equal(eighthResult.data.noticesList, null, 'old noticesList should not exist')
assert.equal(eighthResult.data.NoticeController.noticesList[0].title, vault7.data.noticesList[0].title, 'noticesList should have moved')
vault8 = eighthResult
return migration9.migrate(eighthResult)
}).then((ninthResult) => {
assert.equal(ninthResult.data.currentFiat, null, 'old currentFiat should not exist')
assert.equal(ninthResult.data.fiatCurrency, null, 'old fiatCurrency should not exist')
assert.equal(ninthResult.data.conversionRate, null, 'old conversionRate should not exist')
assert.equal(ninthResult.data.conversionDate, null, 'old conversionDate should not exist')
assert.equal(ninthResult.data.CurrencyController.currentCurrency, vault8.data.fiatCurrency, 'currentFiat should have moved')
assert.equal(ninthResult.data.CurrencyController.conversionRate, vault8.data.conversionRate, 'conversionRate should have moved')
assert.equal(ninthResult.data.CurrencyController.conversionDate, vault8.data.conversionDate, 'conversionDate should have moved')
vault9 = ninthResult
return migration10.migrate(ninthResult)
}).then((tenthResult) => {
assert.equal(tenthResult.data.shapeShiftTxList, null, 'old shapeShiftTxList should not exist')
assert.equal(tenthResult.data.ShapeShiftController.shapeShiftTxList[0].transaction, vault9.data.shapeShiftTxList[0].transaction)
return migration11.migrate(tenthResult)
}).then((eleventhResult) => {
assert.equal(eleventhResult.data.isDisclaimerConfirmed, null, 'isDisclaimerConfirmed should not exist')
assert.equal(eleventhResult.data.TOSHash, null, 'TOSHash should not exist')
return migration12.migrate(eleventhResult)
}).then((twelfthResult) => {
assert.equal(twelfthResult.data.NoticeController.noticesList[0].body, '', 'notices that have been read should have an empty body.')
assert.equal(twelfthResult.data.NoticeController.noticesList[1].body, 'nonempty', 'notices that have not been read should not have an empty body.')
assert.equal(twelfthResult.data.config.provider.type, 'testnet', 'network is originally testnet.')
return migration13.migrate(twelfthResult)
}).then((thirteenthResult) => {
assert.equal(thirteenthResult.data.config.provider.type, 'ropsten', 'network has been changed to ropsten.')
})
})
})

@ -40,20 +40,20 @@ describe('Migrator', () => {
const migrator = new Migrator({ migrations: stubMigrations })
it('migratedData version should be version 3', (done) => {
migrator.migrateData(versionedData)
.then((migratedData) => {
assert.equal(migratedData.meta.version, stubMigrations[2].version)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, stubMigrations[2].version)
done()
}).catch(done)
})
it('should match the last version in live migrations', (done) => {
const migrator = new Migrator({ migrations: liveMigrations })
migrator.migrateData(firstTimeState)
.then((migratedData) => {
const last = liveMigrations.length - 1
assert.equal(migratedData.meta.version, liveMigrations[last].version)
done()
}).catch(done)
.then((migratedData) => {
const last = liveMigrations.length - 1
assert.equal(migratedData.meta.version, liveMigrations[last].version)
done()
}).catch(done)
})
it('should emit an error', function (done) {
@ -61,8 +61,8 @@ describe('Migrator', () => {
const migrator = new Migrator({ migrations: [{ version: 1, migrate: async () => { throw new Error('test') } } ] })
migrator.on('error', () => done())
migrator.migrateData({ meta: {version: 0} })
.then(() => {
}).catch(done)
.then(() => {
}).catch(done)
})
})

@ -8,9 +8,9 @@ const storage = {
describe('storage is migrated successfully', () => {
it('should work', (done) => {
migrationTemplate.migrate(storage)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 0)
done()
}).catch(done)
.then((migratedData) => {
assert.equal(migratedData.meta.version, 0)
done()
}).catch(done)
})
})

@ -628,7 +628,7 @@ describe('Actions', () => {
{ type: 'DISPLAY_WARNING', value: 'error' },
{ type: 'HIDE_LOADING_INDICATION' },
{ type: 'LOCK_METAMASK' },
]
]
backgroundSetLockedSpy = sinon.stub(background, 'setLocked')
backgroundSetLockedSpy.callsFake(callback => {
callback(new Error('error'))

@ -173,7 +173,7 @@ var methods = {
eth_getUncleByBlockNumberAndIndex: [
'eth_getUncleByBlockNumberAndIndex',
params.uncleByBlockNumberAndIndexParams,
params.uncleByBlockNumberAndIndexParams,
params.block,
2,
],

@ -27,8 +27,8 @@ web3.currentProvider.enable().then(() => {
})
})
})
})
})
})

@ -27,7 +27,7 @@ describe('Confirm Detail Row Component', function () {
)
})
describe('render', () => {
describe('render', () => {
it('should render a div with a confirm-detail-row class', () => {
assert.equal(wrapper.find('div.confirm-detail-row').length, 1)
})
@ -60,5 +60,5 @@ describe('Confirm Detail Row Component', function () {
wrapper.find('.confirm-detail-row__header-text').props().onClick()
assert.equal(assert.equal(propsMethodSpies.onHeaderClick.callCount, 1))
})
})
})
})

@ -6,9 +6,9 @@ const ConfirmPageContainerNavigation = props => {
return (
<div className="confirm-page-container-navigation"
style={{
display: showNavigation ? 'flex' : 'none',
}}
style={{
display: showNavigation ? 'flex' : 'none',
}}
>
<div className="confirm-page-container-navigation__container"
style={{

@ -106,16 +106,16 @@ export default class ConfirmPageContainer extends Component {
return (
<div className="page-container">
<ConfirmPageContainerNavigation
totalTx={totalTx}
positionOfCurrentTx={positionOfCurrentTx}
nextTxId={nextTxId}
prevTxId={prevTxId}
showNavigation={showNavigation}
onNextTx={(txId) => onNextTx(txId)}
firstTx={firstTx}
lastTx={lastTx}
ofText={ofText}
requestsWaitingText={requestsWaitingText}
totalTx={totalTx}
positionOfCurrentTx={positionOfCurrentTx}
nextTxId={nextTxId}
prevTxId={prevTxId}
showNavigation={showNavigation}
onNextTx={(txId) => onNextTx(txId)}
firstTx={firstTx}
lastTx={lastTx}
ofText={ofText}
requestsWaitingText={requestsWaitingText}
/>
<ConfirmPageContainerHeader
showEdit={showEdit}

@ -59,7 +59,7 @@ AccountDetailsDropdown.prototype.render = function () {
viewOnEtherscan,
showRemoveAccountConfirmationModal,
rpcPrefs,
} = this.props
} = this.props
const address = selectedIdentity.address

@ -353,12 +353,12 @@ NetworkDropdown.prototype.renderCommonRpc = function (rpcListDetail, provider) {
},
}, nickname || rpc),
h('i.fa.fa-times.delete',
{
onClick: (e) => {
e.stopPropagation()
props.delRpcTarget(rpc)
},
}),
{
onClick: (e) => {
e.stopPropagation()
props.delRpcTarget(rpc)
},
}),
]
)
}

@ -131,8 +131,8 @@ export default class AdvancedTabContent extends Component {
</div>
{ isInError
? <div className={`advanced-gas-inputs__gas-edit-row__${errorType}-text`}>
{ errorText }
</div>
{ errorText }
</div>
: null }
</div>
)

@ -104,8 +104,8 @@ export default class AdvancedTabContent extends Component {
</div>
{ isInError
? <div className={`advanced-tab__gas-edit-row__${errorType}-text`}>
{ errorText }
</div>
{ errorText }
</div>
: null }
</div>
)

@ -21,12 +21,12 @@ export default class BasicTabContent extends Component {
<div className="basic-tab-content__title">{ t('estimatedProcessingTimes') }</div>
<div className="basic-tab-content__blurb">{ t('selectAHigherGasFee') }</div>
{!gasPriceButtonGroupProps.loading
? <GasPriceButtonGroup
className="gas-price-button-group--alt"
showCheck={true}
{...gasPriceButtonGroupProps}
/>
: <Loading />
? <GasPriceButtonGroup
className="gas-price-button-group--alt"
showCheck={true}
{...gasPriceButtonGroupProps}
/>
: <Loading />
}
<div className="basic-tab-content__footer-blurb">{ t('acceleratingATransaction') }</div>
</div>

@ -47,7 +47,7 @@ export default class GasModalPageContainer extends Component {
const promise = this.props.hideBasic
? Promise.resolve(this.props.blockTime)
: this.props.fetchBasicGasAndTimeEstimates()
.then(basicEstimates => basicEstimates.blockTime)
.then(basicEstimates => basicEstimates.blockTime)
promise
.then(blockTime => {
@ -144,11 +144,11 @@ export default class GasModalPageContainer extends Component {
return (
<Tabs>
{tabsToRender.map(({ name, content }, i) => <Tab name={this.context.t(name)} key={`gas-modal-tab-${i}`}>
<div className="gas-modal-content">
{ content }
{ this.renderInfoRows(newTotalFiat, newTotalEth, sendAmount, transactionFee) }
</div>
</Tab>
<div className="gas-modal-content">
{ content }
{ this.renderInfoRows(newTotalFiat, newTotalEth, sendAmount, transactionFee) }
</div>
</Tab>
)}
</Tabs>
)

@ -341,44 +341,44 @@ describe('gas-modal-page-container container', () => {
})
describe('mergeProps', () => {
let stateProps
let dispatchProps
let ownProps
beforeEach(() => {
stateProps = {
gasPriceButtonGroupProps: {
someGasPriceButtonGroupProp: 'foo',
anotherGasPriceButtonGroupProp: 'bar',
},
isConfirm: true,
someOtherStateProp: 'baz',
transaction: {},
}
dispatchProps = {
updateCustomGasPrice: sinon.spy(),
hideGasButtonGroup: sinon.spy(),
setGasData: sinon.spy(),
updateConfirmTxGasAndCalculate: sinon.spy(),
someOtherDispatchProp: sinon.spy(),
createSpeedUpTransaction: sinon.spy(),
hideSidebar: sinon.spy(),
hideModal: sinon.spy(),
cancelAndClose: sinon.spy(),
}
ownProps = { someOwnProp: 123 }
})
let stateProps
let dispatchProps
let ownProps
afterEach(() => {
dispatchProps.updateCustomGasPrice.resetHistory()
dispatchProps.hideGasButtonGroup.resetHistory()
dispatchProps.setGasData.resetHistory()
dispatchProps.updateConfirmTxGasAndCalculate.resetHistory()
dispatchProps.someOtherDispatchProp.resetHistory()
dispatchProps.createSpeedUpTransaction.resetHistory()
dispatchProps.hideSidebar.resetHistory()
dispatchProps.hideModal.resetHistory()
})
beforeEach(() => {
stateProps = {
gasPriceButtonGroupProps: {
someGasPriceButtonGroupProp: 'foo',
anotherGasPriceButtonGroupProp: 'bar',
},
isConfirm: true,
someOtherStateProp: 'baz',
transaction: {},
}
dispatchProps = {
updateCustomGasPrice: sinon.spy(),
hideGasButtonGroup: sinon.spy(),
setGasData: sinon.spy(),
updateConfirmTxGasAndCalculate: sinon.spy(),
someOtherDispatchProp: sinon.spy(),
createSpeedUpTransaction: sinon.spy(),
hideSidebar: sinon.spy(),
hideModal: sinon.spy(),
cancelAndClose: sinon.spy(),
}
ownProps = { someOwnProp: 123 }
})
afterEach(() => {
dispatchProps.updateCustomGasPrice.resetHistory()
dispatchProps.hideGasButtonGroup.resetHistory()
dispatchProps.setGasData.resetHistory()
dispatchProps.updateConfirmTxGasAndCalculate.resetHistory()
dispatchProps.someOtherDispatchProp.resetHistory()
dispatchProps.createSpeedUpTransaction.resetHistory()
dispatchProps.hideSidebar.resetHistory()
dispatchProps.hideModal.resetHistory()
})
it('should return the expected props when isConfirm is true', () => {
const result = mergeProps(stateProps, dispatchProps, ownProps)

@ -210,17 +210,17 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate
},
padding: {left: 20, right: 15, top: 6, bottom: 10},
data: {
x: 'x',
columns: [
['x', ...gasPrices],
['data1', ...estimatedTimes],
],
types: {
data1: 'area',
},
selection: {
enabled: false,
},
x: 'x',
columns: [
['x', ...gasPrices],
['data1', ...estimatedTimes],
],
types: {
data1: 'area',
},
selection: {
enabled: false,
},
},
color: {
data1: '#259de5',
@ -254,13 +254,13 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate
},
},
legend: {
show: false,
show: false,
},
grid: {
x: {},
lines: {
front: false,
},
x: {},
lines: {
front: false,
},
},
point: {
focus: {
@ -296,8 +296,8 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate
const flipTooltip = circleY - circleWidth < chartYStart + 5
d3
.select('.tooltip-arrow')
.style('margin-top', flipTooltip ? '-16px' : '4px')
.select('.tooltip-arrow')
.style('margin-top', flipTooltip ? '-16px' : '4px')
return {
top: bigNumMinus(circleY, chartYStart).minus(19).plus(flipTooltip ? circleWidth + 38 : 0).toNumber(),

@ -72,14 +72,14 @@ export default class AccountDetailsModal extends Component {
</Button>
{exportPrivateKeyFeatureEnabled
? <Button
type="secondary"
className="account-modal__button"
onClick={() => showExportPrivateKeyModal()}
>
{this.context.t('exportPrivateKey')}
</Button>
: null
? <Button
type="secondary"
className="account-modal__button"
onClick={() => showExportPrivateKeyModal()}
>
{this.context.t('exportPrivateKey')}
</Button>
: null
}
</AccountModalContainer>
)

@ -87,8 +87,8 @@ DepositEtherModal.prototype.renderRow = function ({
}
return h('div', {
className: className || 'deposit-ether-modal__buy-row',
}, [
className: className || 'deposit-ether-modal__buy-row',
}, [
onBackClick && showBackButton && h('div.deposit-ether-modal__buy-row__back', {
onClick: onBackClick,
@ -100,22 +100,22 @@ DepositEtherModal.prototype.renderRow = function ({
h('div.deposit-ether-modal__buy-row__logo-container', [logo]),
h('div.deposit-ether-modal__buy-row__description', [
h('div.deposit-ether-modal__buy-row__description', [
!hideTitle && h('div.deposit-ether-modal__buy-row__description__title', [title]),
!hideTitle && h('div.deposit-ether-modal__buy-row__description__title', [title]),
h('div.deposit-ether-modal__buy-row__description__text', [text]),
h('div.deposit-ether-modal__buy-row__description__text', [text]),
]),
]),
!hideButton && h('div.deposit-ether-modal__buy-row__button', [
h(Button, {
type: 'secondary',
className: 'deposit-ether-modal__deposit-button',
large: true,
onClick: onButtonClick,
}, [buttonLabel]),
]),
!hideButton && h('div.deposit-ether-modal__buy-row__button', [
h(Button, {
type: 'secondary',
className: 'deposit-ether-modal__deposit-button',
large: true,
onClick: onButtonClick,
}, [buttonLabel]),
]),
])
}

@ -86,12 +86,12 @@ ExportPrivateKeyModal.prototype.renderPasswordInput = function (privateKey) {
return privateKey
? h(ReadOnlyInput, {
wrapperClass: 'private-key-password-display-wrapper',
inputClass: 'private-key-password-display-textarea',
textarea: true,
value: plainKey,
onClick: () => copyToClipboard(plainKey),
})
wrapperClass: 'private-key-password-display-wrapper',
inputClass: 'private-key-password-display-textarea',
textarea: true,
value: plainKey,
onClick: () => copyToClipboard(plainKey),
})
: h('input.private-key-password-input', {
type: 'password',
onChange: event => this.setState({ password: event.target.value }),
@ -109,14 +109,14 @@ ExportPrivateKeyModal.prototype.renderButtons = function (privateKey, address, h
(privateKey
? (
h(Button, {
h(Button, {
type: 'secondary',
large: true,
className: 'export-private-key__button',
onClick: () => hideModal(),
}, this.context.t('done'))
) : (
h(Button, {
h(Button, {
type: 'secondary',
large: true,
className: 'export-private-key__button',
@ -149,29 +149,29 @@ ExportPrivateKeyModal.prototype.render = function () {
backButtonAction: () => showAccountDetailModal(),
}, [
h('span.account-name', name),
h('span.account-name', name),
h(ReadOnlyInput, {
wrapperClass: 'ellip-address-wrapper',
inputClass: 'qr-ellip-address ellip-address',
value: checksumAddress(address),
}),
h(ReadOnlyInput, {
wrapperClass: 'ellip-address-wrapper',
inputClass: 'qr-ellip-address ellip-address',
value: checksumAddress(address),
}),
h('div.account-modal-divider'),
h('div.account-modal-divider'),
h('span.modal-body-title', this.context.t('showPrivateKeys')),
h('span.modal-body-title', this.context.t('showPrivateKeys')),
h('div.private-key-password', {}, [
this.renderPasswordLabel(privateKey),
h('div.private-key-password', {}, [
this.renderPasswordLabel(privateKey),
this.renderPasswordInput(privateKey),
this.renderPasswordInput(privateKey),
showWarning && warning ? h('span.private-key-password-error', warning) : null,
]),
showWarning && warning ? h('span.private-key-password-error', warning) : null,
]),
h('div.private-key-password-warning', this.context.t('privateKeyWarning')),
h('div.private-key-password-warning', this.context.t('privateKeyWarning')),
this.renderButtons(privateKey, address, hideModal),
this.renderButtons(privateKey, address, hideModal),
])
}

@ -69,7 +69,7 @@ NewAccountModal.propTypes = {
showImportPage: PropTypes.func,
createAccount: PropTypes.func,
numberOfExistingAccounts: PropTypes.number,
t: PropTypes.func,
t: PropTypes.func,
}
const mapStateToProps = state => {

@ -62,7 +62,7 @@ NotificationModal.propTypes = {
showCancelButton: PropTypes.bool,
showConfirmButton: PropTypes.bool,
onConfirm: PropTypes.func,
t: PropTypes.func,
t: PropTypes.func,
}
const mapDispatchToProps = dispatch => {

@ -75,23 +75,23 @@ export default class QrScanner extends Component {
clearTimeout(this.permissionChecker)
this.checkPermisisions()
this.codeReader.decodeFromInputVideoDevice(undefined, 'video')
.then(content => {
const result = this.parseContent(content.text)
if (result.type !== 'unknown') {
this.props.qrCodeDetected(result)
this.stopAndClose()
} else {
this.setState({msg: this.context.t('unknownQrCode')})
}
})
.catch(err => {
if (err && err.name === 'NotAllowedError') {
this.setState({msg: this.context.t('youNeedToAllowCameraAccess')})
clearTimeout(this.permissionChecker)
this.needsToReinit = true
this.checkPermisisions()
}
})
.then(content => {
const result = this.parseContent(content.text)
if (result.type !== 'unknown') {
this.props.qrCodeDetected(result)
this.stopAndClose()
} else {
this.setState({msg: this.context.t('unknownQrCode')})
}
})
.catch(err => {
if (err && err.name === 'NotAllowedError') {
this.setState({msg: this.context.t('youNeedToAllowCameraAccess')})
clearTimeout(this.permissionChecker)
this.needsToReinit = true
this.checkPermisisions()
}
})
}).catch(err => {
console.error('[QR-SCANNER]: getVideoInputDevices threw an exception: ', err)
})

@ -39,12 +39,12 @@ export default class NetworkDisplay extends Component {
return networkClass
? <div className={`network-display__icon network-display__icon--${networkClass}`} />
: <div
className="i fa fa-question-circle fa-med"
style={{
margin: '0 4px',
color: 'rgb(125, 128, 130)',
}}
/>
className="i fa fa-question-circle fa-med"
style={{
margin: '0 4px',
color: 'rgb(125, 128, 130)',
}}
/>
}
render () {
@ -62,12 +62,12 @@ export default class NetworkDisplay extends Component {
networkClass
? <div className={`network-display__icon network-display__icon--${networkClass}`} />
: <div
className="i fa fa-question-circle fa-med"
style={{
margin: '0 4px',
color: 'rgb(125, 128, 130)',
}}
/>
className="i fa fa-question-circle fa-med"
style={{
margin: '0 4px',
color: 'rgb(125, 128, 130)',
}}
/>
}
<div className="network-display__name">
{ type === 'rpc' && nickname ? nickname : this.context.t(type) }

@ -127,19 +127,19 @@ Network.prototype.render = function () {
default:
return h('.network-indicator', [
networkNumber === 'loading'
? h('span.pointer.network-loading-spinner', {
onClick: (event) => this.props.onClick(event),
}, [
h('img', {
title: context.t('attemptingConnect'),
src: 'images/loading.svg',
? h('span.pointer.network-loading-spinner', {
onClick: (event) => this.props.onClick(event),
}, [
h('img', {
title: context.t('attemptingConnect'),
src: 'images/loading.svg',
}),
])
: h('i.fa.fa-question-circle.fa-lg', {
style: {
color: 'rgb(125, 128, 130)',
},
}),
])
: h('i.fa.fa-question-circle.fa-lg', {
style: {
color: 'rgb(125, 128, 130)',
},
}),
h('.network-name', providerName === 'localhost' ? context.t('localhost') : providerNick || context.t('privateNetwork')),
h('.network-indicator__down-arrow'),

@ -26,7 +26,7 @@ export default class Sidebar extends Component {
onOverlayClose && onOverlayClose()
this.props.hideSidebar()
}
} />
} />
}
renderSidebarContent () {

@ -251,7 +251,7 @@ SignatureRequest.prototype.renderBody = function () {
url: 'https://metamask.zendesk.com/hc/en-us/articles/360015488751',
})
},
}, this.context.t('learnMore'))]
}, this.context.t('learnMore'))]
}
return h('div.request-signature__body', {}, [

@ -67,8 +67,8 @@ TokenList.prototype.render = function () {
},
onClick: () => {
global.platform.openWindow({
url: `https://ethplorer.io/address/${userAddress}`,
})
url: `https://ethplorer.io/address/${userAddress}`,
})
},
}, this.context.t('here')),
])
@ -125,13 +125,13 @@ TokenList.prototype.createFreshTokenTracker = function () {
this.tracker.on('error', this.showError)
this.tracker.updateBalances()
.then(() => {
this.updateBalances(this.tracker.serialize())
})
.catch((reason) => {
log.error(`Problem updating balances`, reason)
this.setState({ isLoading: false })
})
.then(() => {
this.updateBalances(this.tracker.serialize())
})
.catch((reason) => {
log.error(`Problem updating balances`, reason)
this.setState({ isLoading: false })
})
}
TokenList.prototype.componentDidUpdate = function (prevProps) {

@ -40,15 +40,15 @@ export default class TransactionActivityLogIcon extends PureComponent {
return (
<div className={classnames('transaction-activity-log-icon', className)}>
{
imagePath && (
<img
src={imagePath}
height={9}
width={9}
/>
)
}
{
imagePath && (
<img
src={imagePath}
height={9}
width={9}
/>
)
}
</div>
)
}

@ -166,7 +166,7 @@ export default class TransactionListItemDetails extends PureComponent {
onClick={this.handleEtherscanClick}
className="transaction-list-item-details__header-button"
disabled={!hash}
>
>
<img src="/images/arrow-popout.svg" />
</Button>
</Tooltip>

@ -75,8 +75,8 @@ export default class TransactionList extends PureComponent {
{
completedTransactions.length > 0
? completedTransactions.map((transactionGroup, index) => (
this.renderTransaction(transactionGroup, index)
))
this.renderTransaction(transactionGroup, index)
))
: this.renderEmpty()
}
</div>

@ -43,38 +43,38 @@ export default class TransactionViewBalance extends PureComponent {
/>
</div>
) : (
<Tooltip position="top" title={this.context.t('balanceOutdated')} disabled={!balanceIsCached}>
<div className="transaction-view-balance__balance">
<div className="transaction-view-balance__primary-container">
<UserPreferencedCurrencyDisplay
className={classnames('transaction-view-balance__primary-balance', {
'transaction-view-balance__cached-balance': balanceIsCached,
})}
value={balance}
type={PRIMARY}
ethNumberOfDecimals={4}
hideTitle={true}
/>
{
balanceIsCached ? <span className="transaction-view-balance__cached-star">*</span> : null
}
</div>
{
showFiat && (
<UserPreferencedCurrencyDisplay
className={classnames({
'transaction-view-balance__cached-secondary-balance': balanceIsCached,
'transaction-view-balance__secondary-balance': !balanceIsCached,
})}
value={balance}
type={SECONDARY}
ethNumberOfDecimals={4}
hideTitle={true}
/>
)
}
<Tooltip position="top" title={this.context.t('balanceOutdated')} disabled={!balanceIsCached}>
<div className="transaction-view-balance__balance">
<div className="transaction-view-balance__primary-container">
<UserPreferencedCurrencyDisplay
className={classnames('transaction-view-balance__primary-balance', {
'transaction-view-balance__cached-balance': balanceIsCached,
})}
value={balance}
type={PRIMARY}
ethNumberOfDecimals={4}
hideTitle={true}
/>
{
balanceIsCached ? <span className="transaction-view-balance__cached-star">*</span> : null
}
</div>
</Tooltip>
{
showFiat && (
<UserPreferencedCurrencyDisplay
className={classnames({
'transaction-view-balance__cached-secondary-balance': balanceIsCached,
'transaction-view-balance__secondary-balance': !balanceIsCached,
})}
value={balance}
type={SECONDARY}
ethNumberOfDecimals={4}
hideTitle={true}
/>
)
}
</div>
</Tooltip>
)
}

@ -4,59 +4,59 @@ const h = require('react-hyperscript')
class Alert extends Component {
constructor (props) {
super(props)
this.state = {
visble: false,
msg: false,
className: '',
}
}
componentWillReceiveProps (nextProps) {
if (!this.props.visible && nextProps.visible) {
this.animateIn(nextProps)
} else if (this.props.visible && !nextProps.visible) {
this.animateOut()
}
}
constructor (props) {
super(props)
animateIn (props) {
this.setState({
msg: props.msg,
visible: true,
className: '.visible',
})
this.state = {
visble: false,
msg: false,
className: '',
}
}
animateOut () {
this.setState({
msg: null,
className: '.hidden',
})
setTimeout(_ => {
this.setState({visible: false})
}, 500)
componentWillReceiveProps (nextProps) {
if (!this.props.visible && nextProps.visible) {
this.animateIn(nextProps)
} else if (this.props.visible && !nextProps.visible) {
this.animateOut()
}
render () {
if (this.state.visible) {
return (
h(`div.global-alert${this.state.className}`, {},
h('a.msg', {}, this.state.msg)
)
)
}
return null
}
animateIn (props) {
this.setState({
msg: props.msg,
visible: true,
className: '.visible',
})
}
animateOut () {
this.setState({
msg: null,
className: '.hidden',
})
setTimeout(_ => {
this.setState({visible: false})
}, 500)
}
render () {
if (this.state.visible) {
return (
h(`div.global-alert${this.state.className}`, {},
h('a.msg', {}, this.state.msg)
)
)
}
return null
}
}
Alert.propTypes = {
visible: PropTypes.bool.isRequired,
msg: PropTypes.string,
visible: PropTypes.bool.isRequired,
msg: PropTypes.string,
}
module.exports = Alert

@ -59,40 +59,40 @@ describe('ButtonGroup Component', function () {
describe('renderButtons', () => {
it('should render a button for each child', () => {
const childButtons = wrapper.find('.button-group__button')
assert.equal(childButtons.length, 3)
const childButtons = wrapper.find('.button-group__button')
assert.equal(childButtons.length, 3)
})
it('should render the correct button with an active state', () => {
const childButtons = wrapper.find('.button-group__button')
const activeChildButton = wrapper.find('.button-group__button--active')
assert.deepEqual(childButtons.get(1), activeChildButton.get(0))
const childButtons = wrapper.find('.button-group__button')
const activeChildButton = wrapper.find('.button-group__button--active')
assert.deepEqual(childButtons.get(1), activeChildButton.get(0))
})
it('should call handleButtonClick and the respective button\'s onClick method when a button is clicked', () => {
assert.equal(ButtonGroup.prototype.handleButtonClick.callCount, 0)
assert.equal(childButtonSpies.onClick.callCount, 0)
const childButtons = wrapper.find('.button-group__button')
childButtons.at(0).props().onClick()
childButtons.at(1).props().onClick()
childButtons.at(2).props().onClick()
assert.equal(ButtonGroup.prototype.handleButtonClick.callCount, 3)
assert.equal(childButtonSpies.onClick.callCount, 3)
assert.equal(ButtonGroup.prototype.handleButtonClick.callCount, 0)
assert.equal(childButtonSpies.onClick.callCount, 0)
const childButtons = wrapper.find('.button-group__button')
childButtons.at(0).props().onClick()
childButtons.at(1).props().onClick()
childButtons.at(2).props().onClick()
assert.equal(ButtonGroup.prototype.handleButtonClick.callCount, 3)
assert.equal(childButtonSpies.onClick.callCount, 3)
})
it('should render all child buttons as disabled if props.disabled is true', () => {
const childButtons = wrapper.find('.button-group__button')
childButtons.forEach(button => {
assert.equal(button.props().disabled, undefined)
})
wrapper.setProps({ disabled: true })
const disabledChildButtons = wrapper.find('[disabled=true]')
assert.equal(disabledChildButtons.length, 3)
const childButtons = wrapper.find('.button-group__button')
childButtons.forEach(button => {
assert.equal(button.props().disabled, undefined)
})
wrapper.setProps({ disabled: true })
const disabledChildButtons = wrapper.find('[disabled=true]')
assert.equal(disabledChildButtons.length, 3)
})
it('should render the children of the button', () => {
const mockClass = wrapper.find('.mockClass')
assert.equal(mockClass.length, 1)
const mockClass = wrapper.find('.mockClass')
assert.equal(mockClass.length, 1)
})
})
@ -103,9 +103,9 @@ describe('ButtonGroup Component', function () {
})
it('should call renderButtons when rendering', () => {
assert.equal(ButtonGroup.prototype.renderButtons.callCount, 1)
wrapper.instance().render()
assert.equal(ButtonGroup.prototype.renderButtons.callCount, 2)
assert.equal(ButtonGroup.prototype.renderButtons.callCount, 1)
wrapper.instance().render()
assert.equal(ButtonGroup.prototype.renderButtons.callCount, 2)
})
})
})

@ -141,22 +141,22 @@ export default class CurrencyInput extends PureComponent {
const { decimalValue } = this.state
return (
<UnitInput
{...restProps}
suffix={this.shouldUseFiat() ? fiatSuffix : nativeSuffix}
onChange={this.handleChange}
onBlur={this.handleBlur}
value={decimalValue}
maxModeOn={maxModeOn}
actionComponent={(
<div
className="currency-input__swap-component"
onClick={this.swap}
/>
)}
>
{ this.renderConversionComponent() }
</UnitInput>
<UnitInput
{...restProps}
suffix={this.shouldUseFiat() ? fiatSuffix : nativeSuffix}
onChange={this.handleChange}
onBlur={this.handleBlur}
value={decimalValue}
maxModeOn={maxModeOn}
actionComponent={(
<div
className="currency-input__swap-component"
onClick={this.swap}
/>
)}
>
{ this.renderConversionComponent() }
</UnitInput>
)
}
}

@ -64,10 +64,10 @@ export default class SenderToRecipient extends PureComponent {
containerClassName="sender-to-recipient__tooltip-container"
onHidden={() => this.setState({ senderAddressCopied: false })}
>
<div className="sender-to-recipient__name">
{ addressOnly ? `${t('from')}: ${checksummedSenderAddress}` : senderName }
</div>
</Tooltip>
<div className="sender-to-recipient__name">
{ addressOnly ? `${t('from')}: ${checksummedSenderAddress}` : senderName }
</div>
</Tooltip>
)
}

@ -160,7 +160,7 @@ function reduceApp (state, action) {
transForward: false,
})
// intialize
// intialize
case actions.SHOW_CREATE_VAULT:
return extend(appState, {
@ -262,7 +262,7 @@ function reduceApp (state, action) {
transForward: true,
})
case actions.CREATE_NEW_VAULT_IN_PROGRESS:
case actions.CREATE_NEW_VAULT_IN_PROGRESS:
return extend(appState, {
currentView: {
name: 'createVault',
@ -310,7 +310,7 @@ function reduceApp (state, action) {
transForward: true,
})
// unlock
// unlock
case actions.UNLOCK_METAMASK:
return extend(appState, {
@ -347,7 +347,7 @@ function reduceApp (state, action) {
name: 'UnlockScreen',
},
})
// reveal seed words
// reveal seed words
case actions.REVEAL_SEED_CONFIRMATION:
return extend(appState, {
@ -358,7 +358,7 @@ function reduceApp (state, action) {
warning: null,
})
// accounts
// accounts
case actions.SET_SELECTED_ACCOUNT:
return extend(appState, {

@ -465,7 +465,7 @@ describe('Gas Duck', () => {
initState,
{ basicPriceAndTimeEstimatesLastRetrieved: 1000000 }
),
metamask: { provider: { type: 'ropsten' } },
metamask: { provider: { type: 'ropsten' } },
}))
assert.deepEqual(
mockDistpatch.getCall(0).args,
@ -542,7 +542,7 @@ describe('Gas Duck', () => {
initState,
{}
),
metamask: { provider: { type: 'ropsten' } },
metamask: { provider: { type: 'ropsten' } },
}))
assert.deepEqual(
mockDistpatch.getCall(0).args,
@ -586,7 +586,7 @@ describe('Gas Duck', () => {
initState,
{}
),
metamask: { provider: { type: 'ropsten' } },
metamask: { provider: { type: 'ropsten' } },
}))
assert.deepEqual(
mockDistpatch.getCall(0).args,
@ -647,7 +647,7 @@ describe('Gas Duck', () => {
initState,
{ priceAndTimeEstimatesLastRetrieved: 1000000 }
),
metamask: { provider: { type: 'ropsten' } },
metamask: { provider: { type: 'ropsten' } },
}))
assert.deepEqual(
mockDistpatch.getCall(0).args,
@ -701,7 +701,7 @@ describe('Gas Duck', () => {
}],
}
),
metamask: { provider: { type: 'ropsten' } },
metamask: { provider: { type: 'ropsten' } },
}))
assert.deepEqual(
mockDistpatch.getCall(0).args,

@ -372,13 +372,13 @@ export function fetchGasEstimates (blockTime) {
const promiseToFetch = Date.now() - timeLastRetrieved > 75000
? fetch('https://ethgasstation.info/json/predictTable.json', {
'headers': {},
'referrer': 'http://ethgasstation.info/json/',
'referrerPolicy': 'no-referrer-when-downgrade',
'body': null,
'method': 'GET',
'mode': 'cors'}
)
'headers': {},
'referrer': 'http://ethgasstation.info/json/',
'referrerPolicy': 'no-referrer-when-downgrade',
'body': null,
'method': 'GET',
'mode': 'cors'}
)
.then(r => r.json())
.then(r => {
const estimatedPricesAndTimes = r.map(({ expectedTime, expectedWait, gasprice }) => ({ expectedTime, expectedWait, gasprice }))
@ -429,14 +429,14 @@ export function fetchGasEstimates (blockTime) {
return timeMappedToSeconds
})
: Promise.resolve(priceAndTimeEstimates.length
? priceAndTimeEstimates
: loadLocalStorageData('GAS_API_ESTIMATES')
)
return promiseToFetch.then(estimates => {
dispatch(setPricesAndTimeEstimates(estimates))
dispatch(gasEstimatesLoadingFinished())
})
? priceAndTimeEstimates
: loadLocalStorageData('GAS_API_ESTIMATES')
)
return promiseToFetch.then(estimates => {
dispatch(setPricesAndTimeEstimates(estimates))
dispatch(gasEstimatesLoadingFinished())
})
}
}

@ -275,7 +275,7 @@ function reduceMetamask (state, action) {
},
})
case actions.UPDATE_SEND_ENS_RESOLUTION:
case actions.UPDATE_SEND_ENS_RESOLUTION:
return extend(metamaskState, {
send: {
...metamaskState.send,

@ -84,7 +84,7 @@ export default class ConfirmAddSuggestedToken extends Component {
</div>
</div>
)
})
})
}
</div>
</div>

@ -80,7 +80,7 @@ export default class ConfirmAddToken extends Component {
</div>
</div>
)
})
})
}
</div>
</div>

@ -6,18 +6,18 @@ const Select = require('react-select').default
import Button from '../../../components/ui/button'
class AccountList extends Component {
getHdPaths () {
return [
{
label: `Ledger Live`,
value: `m/44'/60'/0'/0/0`,
},
{
label: `Legacy (MEW / MyCrypto)`,
value: `m/44'/60'/0'`,
},
]
}
getHdPaths () {
return [
{
label: `Ledger Live`,
value: `m/44'/60'/0'/0/0`,
},
{
label: `Legacy (MEW / MyCrypto)`,
value: `m/44'/60'/0'`,
},
]
}
goToNextPage = () => {
// If we have < 5 accounts, it's restricted by BIP-44
@ -74,128 +74,128 @@ class AccountList extends Component {
}
renderAccounts () {
return h('div.hw-account-list', [
this.props.accounts.map((a, i) => {
return h('div.hw-account-list__item', { key: a.address }, [
h('div.hw-account-list__item__radio', [
h('input', {
type: 'radio',
name: 'selectedAccount',
id: `address-${i}`,
value: a.index,
onChange: (e) => this.props.onAccountChange(e.target.value),
checked: this.props.selectedAccount === a.index.toString(),
}),
h(
'label.hw-account-list__item__label',
{
htmlFor: `address-${i}`,
},
[
h('span.hw-account-list__item__index', a.index + 1),
`${a.address.slice(0, 4)}...${a.address.slice(-4)}`,
h('span.hw-account-list__item__balance', `${a.balance}`),
]),
return h('div.hw-account-list', [
this.props.accounts.map((a, i) => {
return h('div.hw-account-list__item', { key: a.address }, [
h('div.hw-account-list__item__radio', [
h('input', {
type: 'radio',
name: 'selectedAccount',
id: `address-${i}`,
value: a.index,
onChange: (e) => this.props.onAccountChange(e.target.value),
checked: this.props.selectedAccount === a.index.toString(),
}),
h(
'label.hw-account-list__item__label',
{
htmlFor: `address-${i}`,
},
[
h('span.hw-account-list__item__index', a.index + 1),
`${a.address.slice(0, 4)}...${a.address.slice(-4)}`,
h('span.hw-account-list__item__balance', `${a.balance}`),
]),
h(
'a.hw-account-list__item__link',
{
href: genAccountLink(a.address, this.props.network),
target: '_blank',
title: this.context.t('etherscanView'),
},
h('img', { src: 'images/popout.svg' })
),
])
}),
])
]),
h(
'a.hw-account-list__item__link',
{
href: genAccountLink(a.address, this.props.network),
target: '_blank',
title: this.context.t('etherscanView'),
},
h('img', { src: 'images/popout.svg' })
),
])
}),
])
}
renderPagination () {
return h('div.hw-list-pagination', [
h(
'button.hw-list-pagination__button',
{
onClick: this.goToPreviousPage,
},
`< ${this.context.t('prev')}`
),
h(
'button.hw-list-pagination__button',
{
onClick: this.goToNextPage,
},
`${this.context.t('next')} >`
),
])
}
renderButtons () {
const disabled = this.props.selectedAccount === null
const buttonProps = {}
if (disabled) {
buttonProps.disabled = true
renderPagination () {
return h('div.hw-list-pagination', [
h(
'button.hw-list-pagination__button',
{
onClick: this.goToPreviousPage,
},
`< ${this.context.t('prev')}`
),
h(
'button.hw-list-pagination__button',
{
onClick: this.goToNextPage,
},
`${this.context.t('next')} >`
),
])
}
return h('div.new-account-connect-form__buttons', {}, [
h(Button, {
type: 'default',
large: true,
className: 'new-account-connect-form__button',
onClick: this.props.onCancel.bind(this),
}, [this.context.t('cancel')]),
h(Button, {
type: 'primary',
large: true,
className: 'new-account-connect-form__button unlock',
disabled,
onClick: this.props.onUnlockAccount.bind(this, this.props.device),
}, [this.context.t('unlock')]),
])
}
renderButtons () {
const disabled = this.props.selectedAccount === null
const buttonProps = {}
if (disabled) {
buttonProps.disabled = true
}
renderForgetDevice () {
return h('div.hw-forget-device-container', {}, [
h('a', {
onClick: this.props.onForgetDevice.bind(this, this.props.device),
}, this.context.t('forgetDevice')),
])
}
return h('div.new-account-connect-form__buttons', {}, [
h(Button, {
type: 'default',
large: true,
className: 'new-account-connect-form__button',
onClick: this.props.onCancel.bind(this),
}, [this.context.t('cancel')]),
h(Button, {
type: 'primary',
large: true,
className: 'new-account-connect-form__button unlock',
disabled,
onClick: this.props.onUnlockAccount.bind(this, this.props.device),
}, [this.context.t('unlock')]),
])
}
render () {
return h('div.new-account-connect-form.account-list', {}, [
renderForgetDevice () {
return h('div.hw-forget-device-container', {}, [
h('a', {
onClick: this.props.onForgetDevice.bind(this, this.props.device),
}, this.context.t('forgetDevice')),
])
}
render () {
return h('div.new-account-connect-form.account-list', {}, [
this.renderHeader(),
this.renderAccounts(),
this.renderPagination(),
this.renderButtons(),
this.renderForgetDevice(),
])
}
])
}
}
AccountList.propTypes = {
onPathChange: PropTypes.func.isRequired,
selectedPath: PropTypes.string.isRequired,
device: PropTypes.string.isRequired,
accounts: PropTypes.array.isRequired,
onAccountChange: PropTypes.func.isRequired,
onForgetDevice: PropTypes.func.isRequired,
getPage: PropTypes.func.isRequired,
network: PropTypes.string,
selectedAccount: PropTypes.string,
history: PropTypes.object,
onUnlockAccount: PropTypes.func,
onCancel: PropTypes.func,
onAccountRestriction: PropTypes.func,
onPathChange: PropTypes.func.isRequired,
selectedPath: PropTypes.string.isRequired,
device: PropTypes.string.isRequired,
accounts: PropTypes.array.isRequired,
onAccountChange: PropTypes.func.isRequired,
onForgetDevice: PropTypes.func.isRequired,
getPage: PropTypes.func.isRequired,
network: PropTypes.string,
selectedAccount: PropTypes.string,
history: PropTypes.object,
onUnlockAccount: PropTypes.func,
onCancel: PropTypes.func,
onAccountRestriction: PropTypes.func,
}
AccountList.contextTypes = {
t: PropTypes.func,
t: PropTypes.func,
}
module.exports = AccountList

@ -4,12 +4,12 @@ const h = require('react-hyperscript')
import Button from '../../../components/ui/button'
class ConnectScreen extends Component {
constructor (props) {
super(props)
this.state = {
selectedDevice: null,
}
constructor (props) {
super(props)
this.state = {
selectedDevice: null,
}
}
connect = () => {
if (this.state.selectedDevice) {
@ -19,23 +19,23 @@ class ConnectScreen extends Component {
}
renderConnectToTrezorButton () {
return h(
`button.hw-connect__btn${this.state.selectedDevice === 'trezor' ? '.selected' : ''}`,
{ onClick: _ => this.setState({selectedDevice: 'trezor'}) },
h('img.hw-connect__btn__img', {
src: 'images/trezor-logo.svg',
})
)
return h(
`button.hw-connect__btn${this.state.selectedDevice === 'trezor' ? '.selected' : ''}`,
{ onClick: _ => this.setState({selectedDevice: 'trezor'}) },
h('img.hw-connect__btn__img', {
src: 'images/trezor-logo.svg',
})
)
}
renderConnectToLedgerButton () {
return h(
`button.hw-connect__btn${this.state.selectedDevice === 'ledger' ? '.selected' : ''}`,
{ onClick: _ => this.setState({selectedDevice: 'ledger'}) },
h('img.hw-connect__btn__img', {
src: 'images/ledger-logo.svg',
})
)
return h(
`button.hw-connect__btn${this.state.selectedDevice === 'ledger' ? '.selected' : ''}`,
{ onClick: _ => this.setState({selectedDevice: 'ledger'}) },
h('img.hw-connect__btn__img', {
src: 'images/ledger-logo.svg',
})
)
}
renderButtons () {
@ -57,30 +57,30 @@ class ConnectScreen extends Component {
}
renderUnsupportedBrowser () {
return (
h('div.new-account-connect-form.unsupported-browser', {}, [
h('div.hw-connect', [
h('h3.hw-connect__title', {}, this.context.t('browserNotSupported')),
h('p.hw-connect__msg', {}, this.context.t('chromeRequiredForHardwareWallets')),
]),
h(Button, {
type: 'primary',
large: true,
onClick: () => global.platform.openWindow({
url: 'https://google.com/chrome',
}),
}, this.context.t('downloadGoogleChrome')),
])
)
return (
h('div.new-account-connect-form.unsupported-browser', {}, [
h('div.hw-connect', [
h('h3.hw-connect__title', {}, this.context.t('browserNotSupported')),
h('p.hw-connect__msg', {}, this.context.t('chromeRequiredForHardwareWallets')),
]),
h(Button, {
type: 'primary',
large: true,
onClick: () => global.platform.openWindow({
url: 'https://google.com/chrome',
}),
}, this.context.t('downloadGoogleChrome')),
])
)
}
renderHeader () {
return (
h('div.hw-connect__header', {}, [
h('h3.hw-connect__header__title', {}, this.context.t(`hardwareWallets`)),
h('p.hw-connect__header__msg', {}, this.context.t(`hardwareWalletsMsg`)),
])
)
return (
h('div.hw-connect__header', {}, [
h('h3.hw-connect__header__title', {}, this.context.t(`hardwareWallets`)),
h('p.hw-connect__header__msg', {}, this.context.t(`hardwareWalletsMsg`)),
])
)
}
getAffiliateLinks () {
@ -96,10 +96,10 @@ class ConnectScreen extends Component {
}
renderTrezorAffiliateLink () {
return h('div.hw-connect__get-hw', {}, [
h('p.hw-connect__get-hw__msg', {}, this.context.t(`dontHaveAHardwareWallet`)),
this.getAffiliateLinks(),
])
return h('div.hw-connect__get-hw', {}, [
h('p.hw-connect__get-hw__msg', {}, this.context.t(`dontHaveAHardwareWallet`)),
this.getAffiliateLinks(),
])
}
@ -108,89 +108,89 @@ class ConnectScreen extends Component {
}
renderLearnMore () {
return (
h('p.hw-connect__learn-more', {
onClick: this.scrollToTutorial,
}, [
this.context.t('learnMore'),
h('img.hw-connect__learn-more__arrow', { src: 'images/caret-right.svg'}),
])
)
return (
h('p.hw-connect__learn-more', {
onClick: this.scrollToTutorial,
}, [
this.context.t('learnMore'),
h('img.hw-connect__learn-more__arrow', { src: 'images/caret-right.svg'}),
])
)
}
renderTutorialSteps () {
const steps = [
{
asset: 'hardware-wallet-step-1',
dimensions: {width: '225px', height: '75px'},
},
{
asset: 'hardware-wallet-step-2',
dimensions: {width: '300px', height: '100px'},
},
{
asset: 'hardware-wallet-step-3',
dimensions: {width: '120px', height: '90px'},
},
]
return h('.hw-tutorial', {
ref: node => { this.referenceNode = node },
const steps = [
{
asset: 'hardware-wallet-step-1',
dimensions: {width: '225px', height: '75px'},
},
{
asset: 'hardware-wallet-step-2',
dimensions: {width: '300px', height: '100px'},
},
steps.map((step, i) => (
h('div.hw-connect', {}, [
h('h3.hw-connect__title', {}, this.context.t(`step${i + 1}HardwareWallet`)),
h('p.hw-connect__msg', {}, this.context.t(`step${i + 1}HardwareWalletMsg`)),
h('img.hw-connect__step-asset', { src: `images/${step.asset}.svg`, ...step.dimensions }),
])
))
)
{
asset: 'hardware-wallet-step-3',
dimensions: {width: '120px', height: '90px'},
},
]
return h('.hw-tutorial', {
ref: node => { this.referenceNode = node },
},
steps.map((step, i) => (
h('div.hw-connect', {}, [
h('h3.hw-connect__title', {}, this.context.t(`step${i + 1}HardwareWallet`)),
h('p.hw-connect__msg', {}, this.context.t(`step${i + 1}HardwareWalletMsg`)),
h('img.hw-connect__step-asset', { src: `images/${step.asset}.svg`, ...step.dimensions }),
])
))
)
}
renderFooter () {
return (
h('div.hw-connect__footer', {}, [
h('h3.hw-connect__footer__title', {}, this.context.t(`readyToConnect`)),
this.renderButtons(),
h('p.hw-connect__footer__msg', {}, [
this.context.t(`havingTroubleConnecting`),
h('a.hw-connect__footer__link', {
href: 'https://support.metamask.io/',
target: '_blank',
}, this.context.t('getHelp')),
]),
])
)
return (
h('div.hw-connect__footer', {}, [
h('h3.hw-connect__footer__title', {}, this.context.t(`readyToConnect`)),
this.renderButtons(),
h('p.hw-connect__footer__msg', {}, [
this.context.t(`havingTroubleConnecting`),
h('a.hw-connect__footer__link', {
href: 'https://support.metamask.io/',
target: '_blank',
}, this.context.t('getHelp')),
]),
])
)
}
renderConnectScreen () {
return (
h('div.new-account-connect-form', {}, [
this.renderHeader(),
this.renderButtons(),
this.renderTrezorAffiliateLink(),
this.renderLearnMore(),
this.renderTutorialSteps(),
this.renderFooter(),
])
)
return (
h('div.new-account-connect-form', {}, [
this.renderHeader(),
this.renderButtons(),
this.renderTrezorAffiliateLink(),
this.renderLearnMore(),
this.renderTutorialSteps(),
this.renderFooter(),
])
)
}
render () {
if (this.props.browserSupported) {
return this.renderConnectScreen()
}
return this.renderUnsupportedBrowser()
if (this.props.browserSupported) {
return this.renderConnectScreen()
}
return this.renderUnsupportedBrowser()
}
}
ConnectScreen.propTypes = {
connectToHardwareWallet: PropTypes.func.isRequired,
browserSupported: PropTypes.bool.isRequired,
connectToHardwareWallet: PropTypes.func.isRequired,
browserSupported: PropTypes.bool.isRequired,
}
ConnectScreen.contextTypes = {
t: PropTypes.func,
t: PropTypes.func,
}
module.exports = ConnectScreen

@ -126,16 +126,16 @@ class ConnectHardwareForm extends Component {
onForgetDevice = (device) => {
this.props.forgetDevice(device)
.then(_ => {
this.setState({
error: null,
selectedAccount: null,
accounts: [],
unlocked: false,
.then(_ => {
this.setState({
error: null,
selectedAccount: null,
accounts: [],
unlocked: false,
})
}).catch(e => {
this.setState({ error: e.toString() })
})
}).catch(e => {
this.setState({ error: e.toString() })
})
}
onUnlockAccount = (device) => {
@ -145,28 +145,28 @@ class ConnectHardwareForm extends Component {
}
this.props.unlockHardwareWalletAccount(this.state.selectedAccount, device)
.then(_ => {
this.context.metricsEvent({
eventOpts: {
category: 'Accounts',
action: 'Connected Hardware Wallet',
name: 'Connected Account with: ' + device,
},
})
this.props.history.push(DEFAULT_ROUTE)
}).catch(e => {
this.context.metricsEvent({
eventOpts: {
category: 'Accounts',
action: 'Connected Hardware Wallet',
name: 'Error connecting hardware wallet',
},
customVariables: {
error: e.toString(),
},
.then(_ => {
this.context.metricsEvent({
eventOpts: {
category: 'Accounts',
action: 'Connected Hardware Wallet',
name: 'Connected Account with: ' + device,
},
})
this.props.history.push(DEFAULT_ROUTE)
}).catch(e => {
this.context.metricsEvent({
eventOpts: {
category: 'Accounts',
action: 'Connected Hardware Wallet',
name: 'Error connecting hardware wallet',
},
customVariables: {
error: e.toString(),
},
})
this.setState({ error: e.toString() })
})
this.setState({ error: e.toString() })
})
}
onCancel = () => {

@ -174,7 +174,7 @@ export default class ImportWithSeedPhrase extends PureComponent {
})
this.setState((prevState) => ({
termsChecked: !prevState.termsChecked,
termsChecked: !prevState.termsChecked,
}))
}

@ -102,7 +102,7 @@ export default class MetaMetricsOptIn extends Component {
.then(() => {
history.push(nextRoute)
})
})
})
}}
cancelText={'No Thanks'}
hideCancel={false}
@ -135,7 +135,7 @@ export default class MetaMetricsOptIn extends Component {
.then(() => {
history.push(nextRoute)
})
})
})
}}
submitText={'I agree'}
submitButtonType={'primary'}

@ -40,7 +40,7 @@ export default class SelectAction extends PureComponent {
const { t } = this.context
return (
<div className="select-action">
<div className="select-action">
<MetaFoxLogo />
<div className="select-action__wrapper">
@ -95,7 +95,7 @@ export default class SelectAction extends PureComponent {
</div>
</div>
</div>
</div>
)
}
}

@ -40,7 +40,7 @@ export default class Home extends PureComponent {
// suggested new tokens
if (Object.keys(suggestedTokens).length > 0) {
history.push(CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE)
history.push(CONFIRM_ADD_SUGGESTED_TOKEN_ROUTE)
}
}

@ -100,15 +100,15 @@ class MobileSyncPage extends Component {
}
if (message.event === 'start-sync') {
this.startSyncing()
this.startSyncing()
} else if (message.event === 'connection-info') {
this.handle && clearTimeout(this.handle)
this.disconnectWebsockets()
this.initWithCipherKeyAndChannelName(message.cipher, message.channel)
this.initWebsockets()
this.handle && clearTimeout(this.handle)
this.disconnectWebsockets()
this.initWithCipherKeyAndChannelName(message.cipher, message.channel)
this.initWebsockets()
} else if (message.event === 'end-sync') {
this.disconnectWebsockets()
this.setState({syncing: false, completed: true})
this.disconnectWebsockets()
this.setState({syncing: false, completed: true})
}
},
})
@ -126,10 +126,10 @@ class MobileSyncPage extends Component {
}
}
// Calculating a PubNub Message Payload Size.
// Calculating a PubNub Message Payload Size.
calculatePayloadSize (channel, message) {
return encodeURIComponent(
channel + JSON.stringify(message)
channel + JSON.stringify(message)
).length + 100
}
@ -153,14 +153,14 @@ class MobileSyncPage extends Component {
channel: this.channelName,
sendByPost: false, // true to send via post
storeInHistory: false,
},
(status, response) => {
if (!status.error) {
resolve()
} else {
reject(response)
}
})
},
(status, response) => {
if (!status.error) {
resolve()
} else {
reject(response)
}
})
})
}
@ -199,16 +199,16 @@ class MobileSyncPage extends Component {
sendMessage (data, pkg, count) {
return new Promise((resolve, reject) => {
this.pubnub.publish(
{
message: {
event: 'syncing-data',
data,
totalPkg: count,
currentPkg: pkg,
},
channel: this.channelName,
sendByPost: false, // true to send via post
storeInHistory: false,
{
message: {
event: 'syncing-data',
data,
totalPkg: count,
currentPkg: pkg,
},
channel: this.channelName,
sendByPost: false, // true to send via post
storeInHistory: false,
},
(status, response) => {
if (!status.error) {
@ -229,7 +229,7 @@ class MobileSyncPage extends Component {
renderWarning (text) {
return (
h('.page-container__warning-container', [
h('.page-container__warning-message', [
h('.page-container__warning-message', [
h('div', [text]),
]),
])
@ -245,12 +245,12 @@ class MobileSyncPage extends Component {
if (this.state.completed) {
return h('div.reveal-seed__content', {},
h('label.reveal-seed__label', {
style: {
width: '100%',
textAlign: 'center',
},
}, t('syncWithMobileComplete')),
h('label.reveal-seed__label', {
style: {
width: '100%',
textAlign: 'center',
},
}, t('syncWithMobileComplete')),
)
}
@ -303,8 +303,8 @@ class MobileSyncPage extends Component {
h('div', [
h('label.reveal-seed__label', {
style: {
width: '100%',
textAlign: 'center',
width: '100%',
textAlign: 'center',
},
}, t('syncWithMobileScanThisCode')),
h('.div.qr-wrapper', {
@ -370,7 +370,7 @@ class MobileSyncPage extends Component {
this.state.screen === PASSWORD_PROMPT_SCREEN ? h('.page-container__subtitle', this.context.t('syncWithMobileDescNewUsers')) : null,
]),
h('.page-container__content', [
this.renderContent(),
this.renderContent(),
]),
this.renderFooter(),
])

@ -194,16 +194,16 @@ class Routes extends Component {
const { transaction: sidebarTransaction } = props || {}
const sidebarOnOverlayClose = sidebarType === WALLET_VIEW_SIDEBAR
? () => {
this.context.metricsEvent({
eventOpts: {
category: 'Navigation',
action: 'Wallet Sidebar',
name: 'Closed Sidebare Via Overlay',
},
})
}
: null
? () => {
this.context.metricsEvent({
eventOpts: {
category: 'Navigation',
action: 'Wallet Sidebar',
name: 'Closed Sidebare Via Overlay',
},
})
}
: null
return (
<div

@ -1,8 +1,8 @@
import { connect } from 'react-redux'
import {
getConversionRate,
getCurrentCurrency,
getNativeCurrency,
getConversionRate,
getCurrentCurrency,
getNativeCurrency,
} from '../send.selectors.js'
import {
getIsMainnet,

@ -12,7 +12,7 @@ function getToDropdownOpen (state) {
}
function sendToIsInError (state) {
return Boolean(state.send.errors.to)
return Boolean(state.send.errors.to)
}
function sendToIsInWarning (state) {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save