Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create custom addHexPrefix function #9306

Merged
merged 14 commits into from
Nov 6, 2020
3 changes: 2 additions & 1 deletion app/scripts/account-import-strategies/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import log from 'loglevel'
import Wallet from 'ethereumjs-wallet'
import importers from 'ethereumjs-wallet/thirdparty'
import ethUtil from 'ethereumjs-util'
import { addHexPrefix } from '../lib/util'

const accountImporter = {
importAccount(strategy, args) {
Expand All @@ -20,7 +21,7 @@ const accountImporter = {
throw new Error('Cannot import an empty key.')
}

const prefixed = ethUtil.addHexPrefix(privateKey)
const prefixed = addHexPrefix(privateKey)
const buffer = ethUtil.toBuffer(prefixed)

if (!ethUtil.isValidPrivate(buffer)) {
Expand Down
19 changes: 12 additions & 7 deletions app/scripts/controllers/transactions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import NonceTracker from 'nonce-tracker'
import log from 'loglevel'
import BigNumber from 'bignumber.js'
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 { getSwapsTokensReceivedFromTxMeta } from '../../../../ui/app/pages/swaps/swaps.util'
import {
Expand Down Expand Up @@ -264,7 +269,7 @@ export default class TransactionController extends EventEmitter {

// ensure value
txMeta.txParams.value = txMeta.txParams.value
? ethUtil.addHexPrefix(txMeta.txParams.value)
? addHexPrefix(txMeta.txParams.value)
: '0x0'

this.addTx(txMeta)
Expand Down Expand Up @@ -324,7 +329,7 @@ export default class TransactionController extends EventEmitter {
}
const gasPrice = await this.query.gasPrice()

return ethUtil.addHexPrefix(gasPrice.toString(16))
return addHexPrefix(gasPrice.toString(16))
}

/**
Expand Down Expand Up @@ -365,7 +370,7 @@ export default class TransactionController extends EventEmitter {

// add additional gas buffer to our estimation for safety
const gasLimit = this.txGasUtil.addGasBuffer(
ethUtil.addHexPrefix(estimatedGasHex),
addHexPrefix(estimatedGasHex),
blockGasLimit,
)
return { gasLimit, simulationFails }
Expand Down Expand Up @@ -501,7 +506,7 @@ export default class TransactionController extends EventEmitter {
const customOrNonce =
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
txMeta.nonceDetails = nonceLock.nonceDetails
if (customNonceValue) {
Expand Down Expand Up @@ -582,8 +587,8 @@ export default class TransactionController extends EventEmitter {
txHash = await this.query.sendRawTransaction(rawTx)
} catch (error) {
if (error.message.toLowerCase().includes('known transaction')) {
txHash = ethUtil.sha3(ethUtil.addHexPrefix(rawTx)).toString('hex')
txHash = ethUtil.addHexPrefix(txHash)
txHash = ethUtil.sha3(addHexPrefix(rawTx)).toString('hex')
txHash = addHexPrefix(txHash)
} else {
throw error
}
Expand Down
3 changes: 2 additions & 1 deletion app/scripts/controllers/transactions/lib/util.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { addHexPrefix, isValidAddress } from 'ethereumjs-util'
import { isValidAddress } from 'ethereumjs-util'
import { addHexPrefix } from '../../../lib/util'

const normalizers = {
from: (from) => addHexPrefix(from),
Expand Down
3 changes: 2 additions & 1 deletion app/scripts/lib/decrypt-message-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ObservableStore from 'obs-store'
import ethUtil from 'ethereumjs-util'
import { ethErrors } from 'eth-json-rpc-errors'
import log from 'loglevel'
import { addHexPrefix } from './util'
import createId from './random-id'
import { MESSAGE_TYPE } from './enums'

Expand Down Expand Up @@ -329,7 +330,7 @@ export default class DecryptMessageManager extends EventEmitter {
try {
const stripped = ethUtil.stripHexPrefix(data)
if (stripped.match(hexRe)) {
return ethUtil.addHexPrefix(stripped)
return addHexPrefix(stripped)
}
} catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`)
Expand Down
3 changes: 2 additions & 1 deletion app/scripts/lib/personal-message-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ObservableStore from 'obs-store'
import ethUtil from 'ethereumjs-util'
import { ethErrors } from 'eth-json-rpc-errors'
import log from 'loglevel'
import { addHexPrefix } from './util'
import createId from './random-id'
import { MESSAGE_TYPE } from './enums'

Expand Down Expand Up @@ -313,7 +314,7 @@ export default class PersonalMessageManager extends EventEmitter {
try {
const stripped = ethUtil.stripHexPrefix(data)
if (stripped.match(hexRe)) {
return ethUtil.addHexPrefix(stripped)
return addHexPrefix(stripped)
}
} catch (e) {
log.debug(`Message was not hex encoded, interpreting as utf8.`)
Expand Down
47 changes: 35 additions & 12 deletions app/scripts/lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,17 +103,6 @@ function sufficientBalance(txParams, hexBalance) {
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
*
Expand Down Expand Up @@ -173,13 +162,47 @@ function isPrefixedFormattedHexString(value) {
return /^0x[1-9a-f]+[0-9a-f]*$/iu.test(value)
}

/**
* Prefixes a hex string with '0x' or '-0x' and returns it. Idempotent.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice use of the word "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
rekmarks marked this conversation as resolved.
Show resolved Hide resolved
}

if (str.match(/^-?0X/u)) {
return str.replace('0X', '0x')
}

if (str.startsWith('-')) {
return str.replace('-', '-0x')
}

return `0x${str}`
}
Comment on lines +165 to +185
Copy link
Member

@rekmarks rekmarks Nov 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


/**
* 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 {
getPlatform,
getEnvironmentType,
sufficientBalance,
hexToBn,
bnToHex,
BnMultiplyByFraction,
checkForError,
isPrefixedFormattedHexString,
addHexPrefix,
bnToHex,
}
17 changes: 8 additions & 9 deletions app/scripts/migrations/025.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
normalizes txParams on unconfirmed txs

*/
import ethUtil from 'ethereumjs-util'

import { cloneDeep } from 'lodash'
import { addHexPrefix } from '../lib/util'

const version = 25

Expand Down Expand Up @@ -47,13 +46,13 @@ function transformState(state) {
function normalizeTxParams(txParams) {
// functions that handle normalizing of that key in txParams
const whiteList = {
from: (from) => ethUtil.addHexPrefix(from).toLowerCase(),
to: () => ethUtil.addHexPrefix(txParams.to).toLowerCase(),
nonce: (nonce) => ethUtil.addHexPrefix(nonce),
value: (value) => ethUtil.addHexPrefix(value),
data: (data) => ethUtil.addHexPrefix(data),
gas: (gas) => ethUtil.addHexPrefix(gas),
gasPrice: (gasPrice) => ethUtil.addHexPrefix(gasPrice),
from: (from) => addHexPrefix(from).toLowerCase(),
to: () => addHexPrefix(txParams.to).toLowerCase(),
nonce: (nonce) => addHexPrefix(nonce),
value: (value) => addHexPrefix(value),
data: (data) => addHexPrefix(data),
gas: (gas) => addHexPrefix(gas),
gasPrice: (gasPrice) => addHexPrefix(gasPrice),
}

// apply only keys in the whiteList
Expand Down
3 changes: 2 additions & 1 deletion test/unit/app/controllers/metamask-controller-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import EthQuery from 'eth-query'
import proxyquire from 'proxyquire'
import firstTimeState from '../../localhostState'
import createTxMeta from '../../../lib/createTxMeta'
import { addHexPrefix } from '../../../../app/scripts/lib/util'

const threeBoxSpies = {
init: sinon.stub(),
Expand Down Expand Up @@ -167,7 +168,7 @@ describe('MetaMaskController', function () {
const addressBuffer = ethUtil.pubToAddress(pubKeyBuffer)
const privKey = ethUtil.bufferToHex(privKeyBuffer)
const pubKey = ethUtil.bufferToHex(addressBuffer)
assert.equal(privKey, ethUtil.addHexPrefix(importPrivkey))
assert.equal(privKey, addHexPrefix(importPrivkey))
assert.equal(pubKey, '0xe18035bf8712672935fdb4e5e431b1a0183d2dfc')
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { connect } from 'react-redux'
import { captureException } from '@sentry/browser'
import { addHexPrefix } from 'ethereumjs-util'
import { addHexPrefix } from '../../../../../../app/scripts/lib/util'
import {
hideModal,
setGasLimit,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { connect } from 'react-redux'
import { compose } from 'redux'
import ethUtil from 'ethereumjs-util'
import { multiplyCurrencies } from '../../../../helpers/utils/conversion-util'
import withModalProps from '../../../../helpers/higher-order-components/with-modal-props'
import { showModal, createCancelTransaction } from '../../../../store/actions'
import { getHexGasTotal } from '../../../../helpers/utils/confirm-tx.util'
import { addHexPrefix } from '../../../../../../app/scripts/lib/util'
import CancelTransaction from './cancel-transaction.component'

const mapStateToProps = (state, ownProps) => {
Expand All @@ -16,7 +16,7 @@ const mapStateToProps = (state, ownProps) => {
)
const transactionStatus = transaction ? transaction.status : ''

const defaultNewGasPrice = ethUtil.addHexPrefix(
const defaultNewGasPrice = addHexPrefix(
multiplyCurrencies(originalGasPrice, 1.1, {
toNumericBase: 'hex',
multiplicandBase: 16,
Expand Down
4 changes: 2 additions & 2 deletions ui/app/components/ui/token-input/token-input.component.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import ethUtil from 'ethereumjs-util'
import UnitInput from '../unit-input'
import CurrencyDisplay from '../currency-display'
import { getWeiHexFromDecimalValue } from '../../../helpers/utils/conversions.util'
Expand All @@ -9,6 +8,7 @@ import {
multiplyCurrencies,
} from '../../../helpers/utils/conversion-util'
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
Expand Down Expand Up @@ -64,7 +64,7 @@ export default class TokenInput extends PureComponent {
const { value: hexValue, token: { decimals, symbol } = {} } = props

const multiplier = Math.pow(10, Number(decimals || 0))
const decimalValueString = conversionUtil(ethUtil.addHexPrefix(hexValue), {
const decimalValueString = conversionUtil(addHexPrefix(hexValue), {
fromNumericBase: 'hex',
toNumericBase: 'dec',
toCurrency: symbol,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addHexPrefix } from 'ethereumjs-util'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import {
conversionRateSelector,
currentCurrencySelector,
Expand Down
6 changes: 3 additions & 3 deletions ui/app/helpers/utils/confirm-tx.util.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import currencyFormatter from 'currency-formatter'
import currencies from 'currency-formatter/currencies'
import ethUtil from 'ethereumjs-util'
import BigNumber from 'bignumber.js'
import { addHexPrefix } from '../../../../app/scripts/lib/util'

import { unconfirmedTransactionsCountSelector } from '../../selectors'
import {
Expand All @@ -12,7 +12,7 @@ import {
} from './conversion-util'

export function increaseLastGasPrice(lastGasPrice) {
return ethUtil.addHexPrefix(
return addHexPrefix(
multiplyCurrencies(lastGasPrice || '0x0', 1.1, {
multiplicandBase: 16,
multiplierBase: 10,
Expand All @@ -29,7 +29,7 @@ export function hexGreaterThan(a, b) {
}

export function getHexGasTotal({ gasLimit, gasPrice }) {
return ethUtil.addHexPrefix(
return addHexPrefix(
multiplyCurrencies(gasLimit || '0x0', gasPrice || '0x0', {
toNumericBase: 'hex',
multiplicandBase: 16,
Expand Down
4 changes: 2 additions & 2 deletions ui/app/helpers/utils/conversions.util.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ethUtil from 'ethereumjs-util'
import BigNumber from 'bignumber.js'
import { ETH, GWEI, WEI } from '../constants/common'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import {
conversionUtil,
addCurrencies,
Expand All @@ -9,7 +9,7 @@ import {
import { formatCurrency } from './confirm-tx.util'

export function bnToHex(inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16))
return addHexPrefix(inputBn.toString(16))
}

export function hexToDecimal(hexValue) {
Expand Down
6 changes: 3 additions & 3 deletions ui/app/helpers/utils/transactions.util.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import ethUtil from 'ethereumjs-util'
import MethodRegistry from 'eth-method-registry'
import abi from 'human-standard-token-abi'
import { ethers } from 'ethers'
import log from 'loglevel'
import { addHexPrefix } from '../../../../app/scripts/lib/util'
import { getEtherscanNetworkPrefix } from '../../../lib/etherscan-prefix-for-network'
import {
TRANSACTION_CATEGORIES,
Expand Down Expand Up @@ -103,7 +103,7 @@ export async function getMethodDataAsync(fourBytePrefix) {
* @returns {string} - The four-byte method signature
*/
export function getFourBytePrefix(data = '') {
const prefixedData = ethUtil.addHexPrefix(data)
const prefixedData = addHexPrefix(data)
const fourBytePrefix = prefixedData.slice(0, 10)
return fourBytePrefix
}
Expand Down Expand Up @@ -157,7 +157,7 @@ export function sumHexes(...args) {
})
})

return ethUtil.addHexPrefix(total)
return addHexPrefix(total)
}

/**
Expand Down
7 changes: 3 additions & 4 deletions ui/app/helpers/utils/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import abi from 'human-standard-token-abi'
import BigNumber from 'bignumber.js'
import ethUtil from 'ethereumjs-util'
import { DateTime } from 'luxon'
import { addHexPrefix } from '../../../../app/scripts/lib/util'

// formatData :: ( date: <Unix Timestamp> ) -> String
export function formatDate(date, format = "M/d/y 'at' T") {
Expand Down Expand Up @@ -87,9 +88,7 @@ export function isValidAddress(address) {
if (!address || address === '0x0000000000000000000000000000000000000000') {
return false
}
const prefixed = address.startsWith('0X')
? address
: ethUtil.addHexPrefix(address)
const prefixed = addHexPrefix(address)
return (
(isAllOneCase(prefixed.slice(2)) && ethUtil.isValidAddress(prefixed)) ||
ethUtil.isValidChecksumAddress(prefixed)
Expand Down Expand Up @@ -415,7 +414,7 @@ export function toPrecisionWithoutTrailingZeros(n, precision) {
*/
export function addHexPrefixToObjectValues(obj) {
return Object.keys(obj).reduce((newObj, key) => {
return { ...newObj, [key]: ethUtil.addHexPrefix(obj[key]) }
return { ...newObj, [key]: addHexPrefix(obj[key]) }
}, {})
}

Expand Down
Loading