Create custom addHexPrefix function (#9306)

* create custom addHexPrefix function

* switch to custom addHexPrefix

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
Co-authored-by: Erik Marks <rekmarks@protonmail.com>
feature/default_network_editable
Patryk Łucka 4 years ago committed by GitHub
parent d1430e733e
commit ee205b893f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      app/scripts/account-import-strategies/index.js
  2. 19
      app/scripts/controllers/transactions/index.js
  3. 3
      app/scripts/controllers/transactions/lib/util.js
  4. 3
      app/scripts/lib/decrypt-message-manager.js
  5. 3
      app/scripts/lib/personal-message-manager.js
  6. 47
      app/scripts/lib/util.js
  7. 17
      app/scripts/migrations/025.js
  8. 3
      test/unit/app/controllers/metamask-controller-test.js
  9. 2
      ui/app/components/app/gas-customization/gas-modal-page-container/gas-modal-page-container.container.js
  10. 4
      ui/app/components/app/modals/cancel-transaction/cancel-transaction.container.js
  11. 4
      ui/app/components/ui/token-input/token-input.component.js
  12. 2
      ui/app/ducks/confirm-transaction/confirm-transaction.duck.js
  13. 6
      ui/app/helpers/utils/confirm-tx.util.js
  14. 4
      ui/app/helpers/utils/conversions.util.js
  15. 6
      ui/app/helpers/utils/transactions.util.js
  16. 7
      ui/app/helpers/utils/util.js
  17. 4
      ui/app/hooks/useCancelTransaction.js
  18. 3
      ui/app/pages/add-token/add-token.component.js
  19. 10
      ui/app/pages/send/send-content/send-amount-row/amount-max-button/amount-max-button.utils.js
  20. 4
      ui/app/pages/send/send-footer/send-footer.container.js
  21. 4
      ui/app/pages/send/send-footer/send-footer.utils.js
  22. 4
      ui/app/pages/send/send.constants.js
  23. 10
      ui/app/pages/send/send.utils.js
  24. 2
      ui/app/selectors/custom-gas.js
  25. 3
      ui/app/selectors/selectors.js
  26. 9
      ui/app/store/actions.js

@ -2,6 +2,7 @@ import log from 'loglevel'
import Wallet from 'ethereumjs-wallet' import Wallet from 'ethereumjs-wallet'
import importers from 'ethereumjs-wallet/thirdparty' import importers from 'ethereumjs-wallet/thirdparty'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
import { addHexPrefix } from '../lib/util'
const accountImporter = { const accountImporter = {
importAccount(strategy, args) { importAccount(strategy, args) {
@ -20,7 +21,7 @@ const accountImporter = {
throw new Error('Cannot import an empty key.') throw new Error('Cannot import an empty key.')
} }
const prefixed = ethUtil.addHexPrefix(privateKey) const prefixed = addHexPrefix(privateKey)
const buffer = ethUtil.toBuffer(prefixed) const buffer = ethUtil.toBuffer(prefixed)
if (!ethUtil.isValidPrivate(buffer)) { if (!ethUtil.isValidPrivate(buffer)) {

@ -10,7 +10,12 @@ import NonceTracker from 'nonce-tracker'
import log from 'loglevel' import log from 'loglevel'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import cleanErrorStack from '../../lib/cleanErrorStack' import cleanErrorStack from '../../lib/cleanErrorStack'
import { hexToBn, bnToHex, BnMultiplyByFraction } from '../../lib/util' import {
hexToBn,
bnToHex,
BnMultiplyByFraction,
addHexPrefix,
} from '../../lib/util'
import { TRANSACTION_NO_CONTRACT_ERROR_KEY } from '../../../../ui/app/helpers/constants/error-keys' import { TRANSACTION_NO_CONTRACT_ERROR_KEY } from '../../../../ui/app/helpers/constants/error-keys'
import { getSwapsTokensReceivedFromTxMeta } from '../../../../ui/app/pages/swaps/swaps.util' import { getSwapsTokensReceivedFromTxMeta } from '../../../../ui/app/pages/swaps/swaps.util'
import { import {
@ -264,7 +269,7 @@ export default class TransactionController extends EventEmitter {
// ensure value // ensure value
txMeta.txParams.value = txMeta.txParams.value txMeta.txParams.value = txMeta.txParams.value
? ethUtil.addHexPrefix(txMeta.txParams.value) ? addHexPrefix(txMeta.txParams.value)
: '0x0' : '0x0'
this.addTx(txMeta) this.addTx(txMeta)
@ -324,7 +329,7 @@ export default class TransactionController extends EventEmitter {
} }
const gasPrice = await this.query.gasPrice() const gasPrice = await this.query.gasPrice()
return ethUtil.addHexPrefix(gasPrice.toString(16)) return addHexPrefix(gasPrice.toString(16))
} }
/** /**
@ -365,7 +370,7 @@ export default class TransactionController extends EventEmitter {
// add additional gas buffer to our estimation for safety // add additional gas buffer to our estimation for safety
const gasLimit = this.txGasUtil.addGasBuffer( const gasLimit = this.txGasUtil.addGasBuffer(
ethUtil.addHexPrefix(estimatedGasHex), addHexPrefix(estimatedGasHex),
blockGasLimit, blockGasLimit,
) )
return { gasLimit, simulationFails } return { gasLimit, simulationFails }
@ -501,7 +506,7 @@ export default class TransactionController extends EventEmitter {
const customOrNonce = const customOrNonce =
customNonceValue === 0 ? customNonceValue : customNonceValue || nonce customNonceValue === 0 ? customNonceValue : customNonceValue || nonce
txMeta.txParams.nonce = ethUtil.addHexPrefix(customOrNonce.toString(16)) txMeta.txParams.nonce = addHexPrefix(customOrNonce.toString(16))
// add nonce debugging information to txMeta // add nonce debugging information to txMeta
txMeta.nonceDetails = nonceLock.nonceDetails txMeta.nonceDetails = nonceLock.nonceDetails
if (customNonceValue) { if (customNonceValue) {
@ -582,8 +587,8 @@ export default class TransactionController extends EventEmitter {
txHash = await this.query.sendRawTransaction(rawTx) txHash = await this.query.sendRawTransaction(rawTx)
} catch (error) { } catch (error) {
if (error.message.toLowerCase().includes('known transaction')) { if (error.message.toLowerCase().includes('known transaction')) {
txHash = ethUtil.sha3(ethUtil.addHexPrefix(rawTx)).toString('hex') txHash = ethUtil.sha3(addHexPrefix(rawTx)).toString('hex')
txHash = ethUtil.addHexPrefix(txHash) txHash = addHexPrefix(txHash)
} else { } else {
throw error throw error
} }

@ -1,4 +1,5 @@
import { addHexPrefix, isValidAddress } from 'ethereumjs-util' import { isValidAddress } from 'ethereumjs-util'
import { addHexPrefix } from '../../../lib/util'
const normalizers = { const normalizers = {
from: (from) => addHexPrefix(from), from: (from) => addHexPrefix(from),

@ -3,6 +3,7 @@ import ObservableStore from 'obs-store'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
import { ethErrors } from 'eth-json-rpc-errors' import { ethErrors } from 'eth-json-rpc-errors'
import log from 'loglevel' import log from 'loglevel'
import { addHexPrefix } from './util'
import createId from './random-id' import createId from './random-id'
import { MESSAGE_TYPE } from './enums' import { MESSAGE_TYPE } from './enums'
@ -329,7 +330,7 @@ export default class DecryptMessageManager extends EventEmitter {
try { try {
const stripped = ethUtil.stripHexPrefix(data) const stripped = ethUtil.stripHexPrefix(data)
if (stripped.match(hexRe)) { if (stripped.match(hexRe)) {
return ethUtil.addHexPrefix(stripped) return addHexPrefix(stripped)
} }
} catch (e) { } catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`) log.debug(`Message was not hex encoded, interpreting as utf8.`)

@ -3,6 +3,7 @@ import ObservableStore from 'obs-store'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
import { ethErrors } from 'eth-json-rpc-errors' import { ethErrors } from 'eth-json-rpc-errors'
import log from 'loglevel' import log from 'loglevel'
import { addHexPrefix } from './util'
import createId from './random-id' import createId from './random-id'
import { MESSAGE_TYPE } from './enums' import { MESSAGE_TYPE } from './enums'
@ -313,7 +314,7 @@ export default class PersonalMessageManager extends EventEmitter {
try { try {
const stripped = ethUtil.stripHexPrefix(data) const stripped = ethUtil.stripHexPrefix(data)
if (stripped.match(hexRe)) { if (stripped.match(hexRe)) {
return ethUtil.addHexPrefix(stripped) return addHexPrefix(stripped)
} }
} catch (e) { } catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`) log.debug(`Message was not hex encoded, interpreting as utf8.`)

@ -103,17 +103,6 @@ function sufficientBalance(txParams, hexBalance) {
return balance.gte(maxCost) return balance.gte(maxCost)
} }
/**
* Converts a BN object to a hex string with a '0x' prefix
*
* @param {BN} inputBn - The BN to convert to a hex string
* @returns {string} - A '0x' prefixed hex string
*
*/
function bnToHex(inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16))
}
/** /**
* Converts a hex string to a BN object * Converts a hex string to a BN object
* *
@ -173,13 +162,47 @@ function isPrefixedFormattedHexString(value) {
return /^0x[1-9a-f]+[0-9a-f]*$/iu.test(value) return /^0x[1-9a-f]+[0-9a-f]*$/iu.test(value)
} }
/**
* Prefixes a hex string with '0x' or '-0x' and returns it. Idempotent.
*
* @param {string} str - The string to prefix.
* @returns {string} The prefixed string.
*/
const addHexPrefix = (str) => {
if (typeof str !== 'string' || str.match(/^-?0x/u)) {
return str
}
if (str.match(/^-?0X/u)) {
return str.replace('0X', '0x')
}
if (str.startsWith('-')) {
return str.replace('-', '-0x')
}
return `0x${str}`
}
/**
* Converts a BN object to a hex string with a '0x' prefix
*
* @param {BN} inputBn - The BN to convert to a hex string
* @returns {string} - A '0x' prefixed hex string
*
*/
function bnToHex(inputBn) {
return addHexPrefix(inputBn.toString(16))
}
export { export {
getPlatform, getPlatform,
getEnvironmentType, getEnvironmentType,
sufficientBalance, sufficientBalance,
hexToBn, hexToBn,
bnToHex,
BnMultiplyByFraction, BnMultiplyByFraction,
checkForError, checkForError,
isPrefixedFormattedHexString, isPrefixedFormattedHexString,
addHexPrefix,
bnToHex,
} }

@ -4,9 +4,8 @@
normalizes txParams on unconfirmed txs normalizes txParams on unconfirmed txs
*/ */
import ethUtil from 'ethereumjs-util'
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
import { addHexPrefix } from '../lib/util'
const version = 25 const version = 25
@ -47,13 +46,13 @@ function transformState(state) {
function normalizeTxParams(txParams) { function normalizeTxParams(txParams) {
// functions that handle normalizing of that key in txParams // functions that handle normalizing of that key in txParams
const whiteList = { const whiteList = {
from: (from) => ethUtil.addHexPrefix(from).toLowerCase(), from: (from) => addHexPrefix(from).toLowerCase(),
to: () => ethUtil.addHexPrefix(txParams.to).toLowerCase(), to: () => addHexPrefix(txParams.to).toLowerCase(),
nonce: (nonce) => ethUtil.addHexPrefix(nonce), nonce: (nonce) => addHexPrefix(nonce),
value: (value) => ethUtil.addHexPrefix(value), value: (value) => addHexPrefix(value),
data: (data) => ethUtil.addHexPrefix(data), data: (data) => addHexPrefix(data),
gas: (gas) => ethUtil.addHexPrefix(gas), gas: (gas) => addHexPrefix(gas),
gasPrice: (gasPrice) => ethUtil.addHexPrefix(gasPrice), gasPrice: (gasPrice) => addHexPrefix(gasPrice),
} }
// apply only keys in the whiteList // apply only keys in the whiteList

@ -8,6 +8,7 @@ import EthQuery from 'eth-query'
import proxyquire from 'proxyquire' import proxyquire from 'proxyquire'
import firstTimeState from '../../localhostState' import firstTimeState from '../../localhostState'
import createTxMeta from '../../../lib/createTxMeta' import createTxMeta from '../../../lib/createTxMeta'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
const threeBoxSpies = { const threeBoxSpies = {
init: sinon.stub(), init: sinon.stub(),
@ -167,7 +168,7 @@ describe('MetaMaskController', function () {
const addressBuffer = ethUtil.pubToAddress(pubKeyBuffer) const addressBuffer = ethUtil.pubToAddress(pubKeyBuffer)
const privKey = ethUtil.bufferToHex(privKeyBuffer) const privKey = ethUtil.bufferToHex(privKeyBuffer)
const pubKey = ethUtil.bufferToHex(addressBuffer) const pubKey = ethUtil.bufferToHex(addressBuffer)
assert.equal(privKey, ethUtil.addHexPrefix(importPrivkey)) assert.equal(privKey, addHexPrefix(importPrivkey))
assert.equal(pubKey, '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc') assert.equal(pubKey, '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc')
}) })

@ -1,6 +1,6 @@
import { connect } from 'react-redux' import { connect } from 'react-redux'
import { captureException } from '@sentry/browser' import { captureException } from '@sentry/browser'
import { addHexPrefix } from 'ethereumjs-util' import { addHexPrefix } from '../../../../../../app/scripts/lib/util'
import { import {
hideModal, hideModal,
setGasLimit, setGasLimit,

@ -1,10 +1,10 @@
import { connect } from 'react-redux' import { connect } from 'react-redux'
import { compose } from 'redux' import { compose } from 'redux'
import ethUtil from 'ethereumjs-util'
import { multiplyCurrencies } from '../../../../helpers/utils/conversion-util' import { multiplyCurrencies } from '../../../../helpers/utils/conversion-util'
import withModalProps from '../../../../helpers/higher-order-components/with-modal-props' import withModalProps from '../../../../helpers/higher-order-components/with-modal-props'
import { showModal, createCancelTransaction } from '../../../../store/actions' import { showModal, createCancelTransaction } from '../../../../store/actions'
import { getHexGasTotal } from '../../../../helpers/utils/confirm-tx.util' import { getHexGasTotal } from '../../../../helpers/utils/confirm-tx.util'
import { addHexPrefix } from '../../../../../../app/scripts/lib/util'
import CancelTransaction from './cancel-transaction.component' import CancelTransaction from './cancel-transaction.component'
const mapStateToProps = (state, ownProps) => { const mapStateToProps = (state, ownProps) => {
@ -16,7 +16,7 @@ const mapStateToProps = (state, ownProps) => {
) )
const transactionStatus = transaction ? transaction.status : '' const transactionStatus = transaction ? transaction.status : ''
const defaultNewGasPrice = ethUtil.addHexPrefix( const defaultNewGasPrice = addHexPrefix(
multiplyCurrencies(originalGasPrice, 1.1, { multiplyCurrencies(originalGasPrice, 1.1, {
toNumericBase: 'hex', toNumericBase: 'hex',
multiplicandBase: 16, multiplicandBase: 16,

@ -1,6 +1,5 @@
import React, { PureComponent } from 'react' import React, { PureComponent } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import ethUtil from 'ethereumjs-util'
import UnitInput from '../unit-input' import UnitInput from '../unit-input'
import CurrencyDisplay from '../currency-display' import CurrencyDisplay from '../currency-display'
import { getWeiHexFromDecimalValue } from '../../../helpers/utils/conversions.util' import { getWeiHexFromDecimalValue } from '../../../helpers/utils/conversions.util'
@ -9,6 +8,7 @@ import {
multiplyCurrencies, multiplyCurrencies,
} from '../../../helpers/utils/conversion-util' } from '../../../helpers/utils/conversion-util'
import { ETH } from '../../../helpers/constants/common' import { ETH } from '../../../helpers/constants/common'
import { addHexPrefix } from '../../../../../app/scripts/lib/util'
/** /**
* Component that allows user to enter token values as a number, and props receive a converted * Component that allows user to enter token values as a number, and props receive a converted
@ -64,7 +64,7 @@ export default class TokenInput extends PureComponent {
const { value: hexValue, token: { decimals, symbol } = {} } = props const { value: hexValue, token: { decimals, symbol } = {} } = props
const multiplier = Math.pow(10, Number(decimals || 0)) const multiplier = Math.pow(10, Number(decimals || 0))
const decimalValueString = conversionUtil(ethUtil.addHexPrefix(hexValue), { const decimalValueString = conversionUtil(addHexPrefix(hexValue), {
fromNumericBase: 'hex', fromNumericBase: 'hex',
toNumericBase: 'dec', toNumericBase: 'dec',
toCurrency: symbol, toCurrency: symbol,

@ -1,4 +1,4 @@
import { addHexPrefix } from 'ethereumjs-util' import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { import {
conversionRateSelector, conversionRateSelector,
currentCurrencySelector, currentCurrencySelector,

@ -1,7 +1,7 @@
import currencyFormatter from 'currency-formatter' import currencyFormatter from 'currency-formatter'
import currencies from 'currency-formatter/currencies' import currencies from 'currency-formatter/currencies'
import ethUtil from 'ethereumjs-util'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { unconfirmedTransactionsCountSelector } from '../../selectors' import { unconfirmedTransactionsCountSelector } from '../../selectors'
import { import {
@ -12,7 +12,7 @@ import {
} from './conversion-util' } from './conversion-util'
export function increaseLastGasPrice(lastGasPrice) { export function increaseLastGasPrice(lastGasPrice) {
return ethUtil.addHexPrefix( return addHexPrefix(
multiplyCurrencies(lastGasPrice || '0x0', 1.1, { multiplyCurrencies(lastGasPrice || '0x0', 1.1, {
multiplicandBase: 16, multiplicandBase: 16,
multiplierBase: 10, multiplierBase: 10,
@ -29,7 +29,7 @@ export function hexGreaterThan(a, b) {
} }
export function getHexGasTotal({ gasLimit, gasPrice }) { export function getHexGasTotal({ gasLimit, gasPrice }) {
return ethUtil.addHexPrefix( return addHexPrefix(
multiplyCurrencies(gasLimit || '0x0', gasPrice || '0x0', { multiplyCurrencies(gasLimit || '0x0', gasPrice || '0x0', {
toNumericBase: 'hex', toNumericBase: 'hex',
multiplicandBase: 16, multiplicandBase: 16,

@ -1,6 +1,6 @@
import ethUtil from 'ethereumjs-util'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import { ETH, GWEI, WEI } from '../constants/common' import { ETH, GWEI, WEI } from '../constants/common'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { import {
conversionUtil, conversionUtil,
addCurrencies, addCurrencies,
@ -9,7 +9,7 @@ import {
import { formatCurrency } from './confirm-tx.util' import { formatCurrency } from './confirm-tx.util'
export function bnToHex(inputBn) { export function bnToHex(inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16)) return addHexPrefix(inputBn.toString(16))
} }
export function hexToDecimal(hexValue) { export function hexToDecimal(hexValue) {

@ -1,8 +1,8 @@
import ethUtil from 'ethereumjs-util'
import MethodRegistry from 'eth-method-registry' import MethodRegistry from 'eth-method-registry'
import abi from 'human-standard-token-abi' import abi from 'human-standard-token-abi'
import { ethers } from 'ethers' import { ethers } from 'ethers'
import log from 'loglevel' import log from 'loglevel'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { getEtherscanNetworkPrefix } from '../../../lib/etherscan-prefix-for-network' import { getEtherscanNetworkPrefix } from '../../../lib/etherscan-prefix-for-network'
import { import {
TRANSACTION_CATEGORIES, TRANSACTION_CATEGORIES,
@ -103,7 +103,7 @@ export async function getMethodDataAsync(fourBytePrefix) {
* @returns {string} - The four-byte method signature * @returns {string} - The four-byte method signature
*/ */
export function getFourBytePrefix(data = '') { export function getFourBytePrefix(data = '') {
const prefixedData = ethUtil.addHexPrefix(data) const prefixedData = addHexPrefix(data)
const fourBytePrefix = prefixedData.slice(0, 10) const fourBytePrefix = prefixedData.slice(0, 10)
return fourBytePrefix return fourBytePrefix
} }
@ -157,7 +157,7 @@ export function sumHexes(...args) {
}) })
}) })
return ethUtil.addHexPrefix(total) return addHexPrefix(total)
} }
/** /**

@ -3,6 +3,7 @@ import abi from 'human-standard-token-abi'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
import { DateTime } from 'luxon' import { DateTime } from 'luxon'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
// formatData :: ( date: <Unix Timestamp> ) -> String // formatData :: ( date: <Unix Timestamp> ) -> String
export function formatDate(date, format = "M/d/y 'at' T") { export function formatDate(date, format = "M/d/y 'at' T") {
@ -87,9 +88,7 @@ export function isValidAddress(address) {
if (!address || address === '0x0000000000000000000000000000000000000000') { if (!address || address === '0x0000000000000000000000000000000000000000') {
return false return false
} }
const prefixed = address.startsWith('0X') const prefixed = addHexPrefix(address)
? address
: ethUtil.addHexPrefix(address)
return ( return (
(isAllOneCase(prefixed.slice(2)) && ethUtil.isValidAddress(prefixed)) || (isAllOneCase(prefixed.slice(2)) && ethUtil.isValidAddress(prefixed)) ||
ethUtil.isValidChecksumAddress(prefixed) ethUtil.isValidChecksumAddress(prefixed)
@ -415,7 +414,7 @@ export function toPrecisionWithoutTrailingZeros(n, precision) {
*/ */
export function addHexPrefixToObjectValues(obj) { export function addHexPrefixToObjectValues(obj) {
return Object.keys(obj).reduce((newObj, key) => { return Object.keys(obj).reduce((newObj, key) => {
return { ...newObj, [key]: ethUtil.addHexPrefix(obj[key]) } return { ...newObj, [key]: addHexPrefix(obj[key]) }
}, {}) }, {})
} }

@ -20,7 +20,9 @@ import { getConversionRate, getSelectedAccount } from '../selectors'
*/ */
export function useCancelTransaction(transactionGroup) { export function useCancelTransaction(transactionGroup) {
const { primaryTransaction, initialTransaction } = transactionGroup const { primaryTransaction, initialTransaction } = transactionGroup
const gasPrice = primaryTransaction.txParams?.gasPrice const gasPrice = primaryTransaction.txParams?.gasPrice?.startsWith('-')
? '0x0'
: primaryTransaction.txParams?.gasPrice
const { id } = initialTransaction const { id } = initialTransaction
const dispatch = useDispatch() const dispatch = useDispatch()
const selectedAccount = useSelector(getSelectedAccount) const selectedAccount = useSelector(getSelectedAccount)

@ -7,6 +7,7 @@ import { CONFIRM_ADD_TOKEN_ROUTE } from '../../helpers/constants/routes'
import TextField from '../../components/ui/text-field' import TextField from '../../components/ui/text-field'
import PageContainer from '../../components/ui/page-container' import PageContainer from '../../components/ui/page-container'
import { Tabs, Tab } from '../../components/ui/tabs' import { Tabs, Tab } from '../../components/ui/tabs'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import TokenList from './token-list' import TokenList from './token-list'
import TokenSearch from './token-search' import TokenSearch from './token-search'
@ -161,7 +162,7 @@ class AddToken extends Component {
}) })
const isValidAddress = ethUtil.isValidAddress(customAddress) const isValidAddress = ethUtil.isValidAddress(customAddress)
const standardAddress = ethUtil.addHexPrefix(customAddress).toLowerCase() const standardAddress = addHexPrefix(customAddress).toLowerCase()
switch (true) { switch (true) {
case !isValidAddress: case !isValidAddress:

@ -1,8 +1,8 @@
import ethUtil from 'ethereumjs-util'
import { import {
multiplyCurrencies, multiplyCurrencies,
subtractCurrencies, subtractCurrencies,
} from '../../../../../helpers/utils/conversion-util' } from '../../../../../helpers/utils/conversion-util'
import { addHexPrefix } from '../../../../../../../app/scripts/lib/util'
export function calcMaxAmount({ balance, gasTotal, sendToken, tokenBalance }) { export function calcMaxAmount({ balance, gasTotal, sendToken, tokenBalance }) {
const { decimals } = sendToken || {} const { decimals } = sendToken || {}
@ -13,9 +13,7 @@ export function calcMaxAmount({ balance, gasTotal, sendToken, tokenBalance }) {
toNumericBase: 'hex', toNumericBase: 'hex',
multiplicandBase: 16, multiplicandBase: 16,
}) })
: subtractCurrencies( : subtractCurrencies(addHexPrefix(balance), addHexPrefix(gasTotal), {
ethUtil.addHexPrefix(balance), toNumericBase: 'hex',
ethUtil.addHexPrefix(gasTotal), })
{ toNumericBase: 'hex' },
)
} }

@ -1,5 +1,4 @@
import { connect } from 'react-redux' import { connect } from 'react-redux'
import ethUtil from 'ethereumjs-util'
import { import {
addToAddressBook, addToAddressBook,
clearSend, clearSend,
@ -27,6 +26,7 @@ import {
getDefaultActiveButtonIndex, getDefaultActiveButtonIndex,
} from '../../../selectors' } from '../../../selectors'
import { getMostRecentOverviewPage } from '../../../ducks/history/history' import { getMostRecentOverviewPage } from '../../../ducks/history/history'
import { addHexPrefix } from '../../../../../app/scripts/lib/util'
import SendFooter from './send-footer.component' import SendFooter from './send-footer.component'
import { import {
addressIsNew, addressIsNew,
@ -112,7 +112,7 @@ function mapDispatchToProps(dispatch) {
}, },
addToAddressBookIfNew: (newAddress, toAccounts, nickname = '') => { addToAddressBookIfNew: (newAddress, toAccounts, nickname = '') => {
const hexPrefixedAddress = ethUtil.addHexPrefix(newAddress) const hexPrefixedAddress = addHexPrefix(newAddress)
if (addressIsNew(toAccounts, hexPrefixedAddress)) { if (addressIsNew(toAccounts, hexPrefixedAddress)) {
// TODO: nickname, i.e. addToAddressBook(recipient, nickname) // TODO: nickname, i.e. addToAddressBook(recipient, nickname)
dispatch(addToAddressBook(hexPrefixedAddress, nickname)) dispatch(addToAddressBook(hexPrefixedAddress, nickname))

@ -1,6 +1,6 @@
import ethAbi from 'ethereumjs-abi' import ethAbi from 'ethereumjs-abi'
import ethUtil from 'ethereumjs-util'
import { TOKEN_TRANSFER_FUNCTION_SIGNATURE } from '../send.constants' import { TOKEN_TRANSFER_FUNCTION_SIGNATURE } from '../send.constants'
import { addHexPrefix } from '../../../../../app/scripts/lib/util'
import { addHexPrefixToObjectValues } from '../../../helpers/utils/util' import { addHexPrefixToObjectValues } from '../../../helpers/utils/util'
export function constructTxParams({ export function constructTxParams({
@ -71,7 +71,7 @@ export function constructUpdatedTx({
.call( .call(
ethAbi.rawEncode( ethAbi.rawEncode(
['address', 'uint256'], ['address', 'uint256'],
[to, ethUtil.addHexPrefix(amount)], [to, addHexPrefix(amount)],
), ),
(x) => `00${x.toString(16)}`.slice(-2), (x) => `00${x.toString(16)}`.slice(-2),
) )

@ -1,15 +1,15 @@
import ethUtil from 'ethereumjs-util'
import { import {
conversionUtil, conversionUtil,
multiplyCurrencies, multiplyCurrencies,
} from '../../helpers/utils/conversion-util' } from '../../helpers/utils/conversion-util'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
const MIN_GAS_PRICE_DEC = '0' const MIN_GAS_PRICE_DEC = '0'
const MIN_GAS_PRICE_HEX = parseInt(MIN_GAS_PRICE_DEC, 10).toString(16) const MIN_GAS_PRICE_HEX = parseInt(MIN_GAS_PRICE_DEC, 10).toString(16)
const MIN_GAS_LIMIT_DEC = '21000' const MIN_GAS_LIMIT_DEC = '21000'
const MIN_GAS_LIMIT_HEX = parseInt(MIN_GAS_LIMIT_DEC, 10).toString(16) const MIN_GAS_LIMIT_HEX = parseInt(MIN_GAS_LIMIT_DEC, 10).toString(16)
const MIN_GAS_PRICE_GWEI = ethUtil.addHexPrefix( const MIN_GAS_PRICE_GWEI = addHexPrefix(
conversionUtil(MIN_GAS_PRICE_HEX, { conversionUtil(MIN_GAS_PRICE_HEX, {
fromDenomination: 'WEI', fromDenomination: 'WEI',
toDenomination: 'GWEI', toDenomination: 'GWEI',

@ -1,5 +1,4 @@
import abi from 'ethereumjs-abi' import abi from 'ethereumjs-abi'
import ethUtil from 'ethereumjs-util'
import { import {
addCurrencies, addCurrencies,
conversionUtil, conversionUtil,
@ -10,6 +9,7 @@ import {
} from '../../helpers/utils/conversion-util' } from '../../helpers/utils/conversion-util'
import { calcTokenAmount } from '../../helpers/utils/token-util' import { calcTokenAmount } from '../../helpers/utils/token-util'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { import {
BASE_TOKEN_GAS_COST, BASE_TOKEN_GAS_COST,
@ -242,7 +242,7 @@ async function estimateGasForSend({
blockGasLimit = MIN_GAS_LIMIT_HEX blockGasLimit = MIN_GAS_LIMIT_HEX
} }
paramsForGasEstimate.gas = ethUtil.addHexPrefix( paramsForGasEstimate.gas = addHexPrefix(
multiplyCurrencies(blockGasLimit, 0.95, { multiplyCurrencies(blockGasLimit, 0.95, {
multiplicandBase: 16, multiplicandBase: 16,
multiplierBase: 10, multiplierBase: 10,
@ -259,7 +259,7 @@ async function estimateGasForSend({
blockGasLimit, blockGasLimit,
1.5, 1.5,
) )
return ethUtil.addHexPrefix(estimateWithBuffer) return addHexPrefix(estimateWithBuffer)
} catch (error) { } catch (error) {
const simulationFailed = const simulationFailed =
error.message.includes('Transaction execution error.') || error.message.includes('Transaction execution error.') ||
@ -272,7 +272,7 @@ async function estimateGasForSend({
blockGasLimit, blockGasLimit,
1.5, 1.5,
) )
return ethUtil.addHexPrefix(estimateWithBuffer) return addHexPrefix(estimateWithBuffer)
} }
throw error throw error
} }
@ -336,7 +336,7 @@ function generateTokenTransferData({
.call( .call(
abi.rawEncode( abi.rawEncode(
['address', 'uint256'], ['address', 'uint256'],
[toAddress, ethUtil.addHexPrefix(amount)], [toAddress, addHexPrefix(amount)],
), ),
(x) => `00${x.toString(16)}`.slice(-2), (x) => `00${x.toString(16)}`.slice(-2),
) )

@ -1,4 +1,4 @@
import { addHexPrefix } from 'ethereumjs-util' import { addHexPrefix } from '../../../app/scripts/lib/util'
import { import {
conversionUtil, conversionUtil,
multiplyCurrencies, multiplyCurrencies,

@ -1,5 +1,6 @@
import { stripHexPrefix, addHexPrefix } from 'ethereumjs-util' import { stripHexPrefix } from 'ethereumjs-util'
import { createSelector } from 'reselect' import { createSelector } from 'reselect'
import { addHexPrefix } from '../../../app/scripts/lib/util'
import { NETWORK_TYPES } from '../helpers/constants/common' import { NETWORK_TYPES } from '../helpers/constants/common'
import { import {
shortenAddress, shortenAddress,

@ -1,6 +1,5 @@
import abi from 'human-standard-token-abi' import abi from 'human-standard-token-abi'
import pify from 'pify' import pify from 'pify'
import ethUtil from 'ethereumjs-util'
import log from 'loglevel' import log from 'loglevel'
import { capitalize } from 'lodash' import { capitalize } from 'lodash'
import getBuyEthUrl from '../../../app/scripts/lib/buy-eth-url' import getBuyEthUrl from '../../../app/scripts/lib/buy-eth-url'
@ -17,7 +16,7 @@ import { ENVIRONMENT_TYPE_NOTIFICATION } from '../../../app/scripts/lib/enums'
import { hasUnconfirmedTransactions } from '../helpers/utils/confirm-tx.util' import { hasUnconfirmedTransactions } from '../helpers/utils/confirm-tx.util'
import { setCustomGasLimit } from '../ducks/gas/gas.duck' import { setCustomGasLimit } from '../ducks/gas/gas.duck'
import txHelper from '../../lib/tx-helper' import txHelper from '../../lib/tx-helper'
import { getEnvironmentType } from '../../../app/scripts/lib/util' import { getEnvironmentType, addHexPrefix } from '../../../app/scripts/lib/util'
import { import {
getPermittedAccountsForCurrentTab, getPermittedAccountsForCurrentTab,
getSelectedAddress, getSelectedAddress,
@ -791,9 +790,7 @@ export function signTokenTx(tokenAddress, toAddress, amount, txData) {
return (dispatch) => { return (dispatch) => {
dispatch(showLoadingIndication()) dispatch(showLoadingIndication())
const token = global.eth.contract(abi).at(tokenAddress) const token = global.eth.contract(abi).at(tokenAddress)
token token.transfer(toAddress, addHexPrefix(amount), txData).catch((err) => {
.transfer(toAddress, ethUtil.addHexPrefix(amount), txData)
.catch((err) => {
dispatch(hideLoadingIndication()) dispatch(hideLoadingIndication())
dispatch(displayWarning(err.message)) dispatch(displayWarning(err.message))
}) })
@ -2495,7 +2492,7 @@ export function loadingMethodDataFinished() {
export function getContractMethodData(data = '') { export function getContractMethodData(data = '') {
return (dispatch, getState) => { return (dispatch, getState) => {
const prefixedData = ethUtil.addHexPrefix(data) const prefixedData = addHexPrefix(data)
const fourBytePrefix = prefixedData.slice(0, 10) const fourBytePrefix = prefixedData.slice(0, 10)
const { knownMethodData } = getState().metamask const { knownMethodData } = getState().metamask

Loading…
Cancel
Save