You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
333 lines
8.5 KiB
333 lines
8.5 KiB
7 years ago
|
const {
|
||
|
addCurrencies,
|
||
|
conversionUtil,
|
||
|
conversionGTE,
|
||
|
multiplyCurrencies,
|
||
7 years ago
|
conversionGreaterThan,
|
||
7 years ago
|
conversionLessThan,
|
||
6 years ago
|
} = require('../../helpers/utils/conversion-util')
|
||
7 years ago
|
const {
|
||
|
calcTokenAmount,
|
||
6 years ago
|
} = require('../../helpers/utils/token-util')
|
||
7 years ago
|
const {
|
||
7 years ago
|
BASE_TOKEN_GAS_COST,
|
||
7 years ago
|
INSUFFICIENT_FUNDS_ERROR,
|
||
|
INSUFFICIENT_TOKENS_ERROR,
|
||
|
NEGATIVE_ETH_ERROR,
|
||
7 years ago
|
ONE_GWEI_IN_WEI_HEX,
|
||
7 years ago
|
SIMPLE_GAS_COST,
|
||
7 years ago
|
TOKEN_TRANSFER_FUNCTION_SIGNATURE,
|
||
7 years ago
|
} = require('./send.constants')
|
||
7 years ago
|
const abi = require('ethereumjs-abi')
|
||
7 years ago
|
const ethUtil = require('ethereumjs-util')
|
||
7 years ago
|
|
||
|
module.exports = {
|
||
7 years ago
|
addGasBuffer,
|
||
7 years ago
|
calcGasTotal,
|
||
7 years ago
|
calcTokenBalance,
|
||
7 years ago
|
doesAmountErrorRequireUpdate,
|
||
7 years ago
|
estimateGas,
|
||
|
estimateGasPriceFromRecentBlocks,
|
||
7 years ago
|
generateTokenTransferData,
|
||
|
getAmountErrorObject,
|
||
7 years ago
|
getGasFeeErrorObject,
|
||
7 years ago
|
getToAddressForGasUpdate,
|
||
7 years ago
|
isBalanceSufficient,
|
||
|
isTokenBalanceSufficient,
|
||
7 years ago
|
removeLeadingZeroes,
|
||
7 years ago
|
}
|
||
7 years ago
|
|
||
7 years ago
|
function calcGasTotal (gasLimit = '0', gasPrice = '0') {
|
||
7 years ago
|
return multiplyCurrencies(gasLimit, gasPrice, {
|
||
|
toNumericBase: 'hex',
|
||
|
multiplicandBase: 16,
|
||
|
multiplierBase: 16,
|
||
|
})
|
||
|
}
|
||
|
|
||
7 years ago
|
function isBalanceSufficient ({
|
||
|
amount = '0x0',
|
||
7 years ago
|
amountConversionRate = 1,
|
||
|
balance = '0x0',
|
||
|
conversionRate = 1,
|
||
7 years ago
|
gasTotal = '0x0',
|
||
|
primaryCurrency,
|
||
7 years ago
|
}) {
|
||
|
const totalAmount = addCurrencies(amount, gasTotal, {
|
||
|
aBase: 16,
|
||
|
bBase: 16,
|
||
|
toNumericBase: 'hex',
|
||
|
})
|
||
|
|
||
|
const balanceIsSufficient = conversionGTE(
|
||
|
{
|
||
|
value: balance,
|
||
|
fromNumericBase: 'hex',
|
||
|
fromCurrency: primaryCurrency,
|
||
|
conversionRate,
|
||
|
},
|
||
|
{
|
||
|
value: totalAmount,
|
||
|
fromNumericBase: 'hex',
|
||
7 years ago
|
conversionRate: Number(amountConversionRate) || conversionRate,
|
||
7 years ago
|
fromCurrency: primaryCurrency,
|
||
|
},
|
||
|
)
|
||
|
|
||
|
return balanceIsSufficient
|
||
|
}
|
||
|
|
||
|
function isTokenBalanceSufficient ({
|
||
|
amount = '0x0',
|
||
|
tokenBalance,
|
||
|
decimals,
|
||
|
}) {
|
||
|
const amountInDec = conversionUtil(amount, {
|
||
|
fromNumericBase: 'hex',
|
||
|
})
|
||
|
|
||
|
const tokenBalanceIsSufficient = conversionGTE(
|
||
|
{
|
||
|
value: tokenBalance,
|
||
6 years ago
|
fromNumericBase: 'hex',
|
||
7 years ago
|
},
|
||
|
{
|
||
|
value: calcTokenAmount(amountInDec, decimals),
|
||
|
},
|
||
|
)
|
||
|
|
||
|
return tokenBalanceIsSufficient
|
||
|
}
|
||
|
|
||
7 years ago
|
function getAmountErrorObject ({
|
||
|
amount,
|
||
|
amountConversionRate,
|
||
|
balance,
|
||
|
conversionRate,
|
||
|
gasTotal,
|
||
|
primaryCurrency,
|
||
|
selectedToken,
|
||
|
tokenBalance,
|
||
|
}) {
|
||
|
let insufficientFunds = false
|
||
7 years ago
|
if (gasTotal && conversionRate && !selectedToken) {
|
||
7 years ago
|
insufficientFunds = !isBalanceSufficient({
|
||
7 years ago
|
amount,
|
||
7 years ago
|
amountConversionRate,
|
||
|
balance,
|
||
|
conversionRate,
|
||
|
gasTotal,
|
||
|
primaryCurrency,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
let inSufficientTokens = false
|
||
|
if (selectedToken && tokenBalance !== null) {
|
||
|
const { decimals } = selectedToken
|
||
|
inSufficientTokens = !isTokenBalanceSufficient({
|
||
|
tokenBalance,
|
||
|
amount,
|
||
|
decimals,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
const amountLessThanZero = conversionGreaterThan(
|
||
|
{ value: 0, fromNumericBase: 'dec' },
|
||
|
{ value: amount, fromNumericBase: 'hex' },
|
||
|
)
|
||
|
|
||
|
let amountError = null
|
||
|
|
||
|
if (insufficientFunds) {
|
||
7 years ago
|
amountError = INSUFFICIENT_FUNDS_ERROR
|
||
7 years ago
|
} else if (inSufficientTokens) {
|
||
7 years ago
|
amountError = INSUFFICIENT_TOKENS_ERROR
|
||
7 years ago
|
} else if (amountLessThanZero) {
|
||
7 years ago
|
amountError = NEGATIVE_ETH_ERROR
|
||
7 years ago
|
}
|
||
|
|
||
|
return { amount: amountError }
|
||
|
}
|
||
|
|
||
7 years ago
|
function getGasFeeErrorObject ({
|
||
|
amountConversionRate,
|
||
|
balance,
|
||
|
conversionRate,
|
||
|
gasTotal,
|
||
|
primaryCurrency,
|
||
|
}) {
|
||
|
let gasFeeError = null
|
||
|
|
||
|
if (gasTotal && conversionRate) {
|
||
|
const insufficientFunds = !isBalanceSufficient({
|
||
|
amount: '0x0',
|
||
|
amountConversionRate,
|
||
|
balance,
|
||
|
conversionRate,
|
||
|
gasTotal,
|
||
|
primaryCurrency,
|
||
|
})
|
||
|
|
||
|
if (insufficientFunds) {
|
||
|
gasFeeError = INSUFFICIENT_FUNDS_ERROR
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return { gasFee: gasFeeError }
|
||
|
}
|
||
|
|
||
7 years ago
|
function calcTokenBalance ({ selectedToken, usersToken }) {
|
||
|
const { decimals } = selectedToken || {}
|
||
6 years ago
|
return calcTokenAmount(usersToken.balance.toString(), decimals).toString(16)
|
||
7 years ago
|
}
|
||
|
|
||
|
function doesAmountErrorRequireUpdate ({
|
||
|
balance,
|
||
|
gasTotal,
|
||
|
prevBalance,
|
||
|
prevGasTotal,
|
||
|
prevTokenBalance,
|
||
|
selectedToken,
|
||
|
tokenBalance,
|
||
|
}) {
|
||
|
const balanceHasChanged = balance !== prevBalance
|
||
|
const gasTotalHasChange = gasTotal !== prevGasTotal
|
||
|
const tokenBalanceHasChanged = selectedToken && tokenBalance !== prevTokenBalance
|
||
|
const amountErrorRequiresUpdate = balanceHasChanged || gasTotalHasChange || tokenBalanceHasChanged
|
||
|
|
||
|
return amountErrorRequiresUpdate
|
||
|
}
|
||
|
|
||
6 years ago
|
async function estimateGas ({
|
||
|
selectedAddress,
|
||
|
selectedToken,
|
||
|
blockGasLimit,
|
||
|
to,
|
||
|
value,
|
||
|
data,
|
||
|
gasPrice,
|
||
|
estimateGasMethod,
|
||
|
}) {
|
||
7 years ago
|
const paramsForGasEstimate = { from: selectedAddress, value, gasPrice }
|
||
7 years ago
|
|
||
6 years ago
|
// if recipient has no code, gas is 21k max:
|
||
|
if (!selectedToken && !data) {
|
||
|
const code = Boolean(to) && await global.eth.getCode(to)
|
||
6 years ago
|
// Geth will return '0x', and ganache-core v2.2.1 will return '0x0'
|
||
|
const codeIsEmpty = !code || code === '0x' || code === '0x0'
|
||
|
if (codeIsEmpty) {
|
||
6 years ago
|
return SIMPLE_GAS_COST
|
||
|
}
|
||
|
} else if (selectedToken && !to) {
|
||
|
return BASE_TOKEN_GAS_COST
|
||
|
}
|
||
|
|
||
7 years ago
|
if (selectedToken) {
|
||
|
paramsForGasEstimate.value = '0x0'
|
||
|
paramsForGasEstimate.data = generateTokenTransferData({ toAddress: to, amount: value, selectedToken })
|
||
6 years ago
|
paramsForGasEstimate.to = selectedToken.address
|
||
|
} else {
|
||
|
if (data) {
|
||
|
paramsForGasEstimate.data = data
|
||
|
}
|
||
|
|
||
|
if (to) {
|
||
|
paramsForGasEstimate.to = to
|
||
|
}
|
||
6 years ago
|
|
||
|
if (!value || value === '0') {
|
||
|
paramsForGasEstimate.value = '0xff'
|
||
|
}
|
||
7 years ago
|
}
|
||
|
|
||
|
// if not, fall back to block gasLimit
|
||
6 years ago
|
paramsForGasEstimate.gas = ethUtil.addHexPrefix(multiplyCurrencies(blockGasLimit || '0x5208', 0.95, {
|
||
7 years ago
|
multiplicandBase: 16,
|
||
|
multiplierBase: 10,
|
||
|
roundDown: '0',
|
||
|
toNumericBase: 'hex',
|
||
7 years ago
|
}))
|
||
7 years ago
|
// run tx
|
||
7 years ago
|
return new Promise((resolve, reject) => {
|
||
7 years ago
|
return estimateGasMethod(paramsForGasEstimate, (err, estimatedGas) => {
|
||
7 years ago
|
if (err) {
|
||
7 years ago
|
const simulationFailed = (
|
||
|
err.message.includes('Transaction execution error.') ||
|
||
|
err.message.includes('gas required exceeds allowance or always failing transaction')
|
||
|
)
|
||
|
if (simulationFailed) {
|
||
7 years ago
|
const estimateWithBuffer = addGasBuffer(paramsForGasEstimate.gas, blockGasLimit, 1.5)
|
||
7 years ago
|
return resolve(ethUtil.addHexPrefix(estimateWithBuffer))
|
||
7 years ago
|
} else {
|
||
|
return reject(err)
|
||
|
}
|
||
7 years ago
|
}
|
||
7 years ago
|
const estimateWithBuffer = addGasBuffer(estimatedGas.toString(16), blockGasLimit, 1.5)
|
||
7 years ago
|
return resolve(ethUtil.addHexPrefix(estimateWithBuffer))
|
||
7 years ago
|
})
|
||
|
})
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
function addGasBuffer (initialGasLimitHex, blockGasLimitHex, bufferMultiplier = 1.5) {
|
||
|
const upperGasLimit = multiplyCurrencies(blockGasLimitHex, 0.9, {
|
||
|
toNumericBase: 'hex',
|
||
|
multiplicandBase: 16,
|
||
|
multiplierBase: 10,
|
||
|
numberOfDecimals: '0',
|
||
|
})
|
||
|
const bufferedGasLimit = multiplyCurrencies(initialGasLimitHex, bufferMultiplier, {
|
||
|
toNumericBase: 'hex',
|
||
|
multiplicandBase: 16,
|
||
|
multiplierBase: 10,
|
||
|
numberOfDecimals: '0',
|
||
|
})
|
||
|
|
||
|
// if initialGasLimit is above blockGasLimit, dont modify it
|
||
|
if (conversionGreaterThan(
|
||
|
{ value: initialGasLimitHex, fromNumericBase: 'hex' },
|
||
|
{ value: upperGasLimit, fromNumericBase: 'hex' },
|
||
|
)) return initialGasLimitHex
|
||
|
// if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
|
||
|
if (conversionLessThan(
|
||
|
{ value: bufferedGasLimit, fromNumericBase: 'hex' },
|
||
|
{ value: upperGasLimit, fromNumericBase: 'hex' },
|
||
|
)) return bufferedGasLimit
|
||
|
// otherwise use blockGasLimit
|
||
|
return upperGasLimit
|
||
|
}
|
||
|
|
||
7 years ago
|
function generateTokenTransferData ({ toAddress = '0x0', amount = '0x0', selectedToken }) {
|
||
7 years ago
|
if (!selectedToken) return
|
||
7 years ago
|
return TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call(
|
||
|
abi.rawEncode(['address', 'uint256'], [toAddress, ethUtil.addHexPrefix(amount)]),
|
||
7 years ago
|
x => ('00' + x.toString(16)).slice(-2)
|
||
|
).join('')
|
||
7 years ago
|
}
|
||
7 years ago
|
|
||
|
function estimateGasPriceFromRecentBlocks (recentBlocks) {
|
||
|
// Return 1 gwei if no blocks have been observed:
|
||
|
if (!recentBlocks || recentBlocks.length === 0) {
|
||
|
return ONE_GWEI_IN_WEI_HEX
|
||
|
}
|
||
7 years ago
|
|
||
7 years ago
|
const lowestPrices = recentBlocks.map((block) => {
|
||
|
if (!block.gasPrices || block.gasPrices.length < 1) {
|
||
|
return ONE_GWEI_IN_WEI_HEX
|
||
|
}
|
||
7 years ago
|
return block.gasPrices.reduce((currentLowest, next) => {
|
||
|
return parseInt(next, 16) < parseInt(currentLowest, 16) ? next : currentLowest
|
||
|
})
|
||
7 years ago
|
})
|
||
7 years ago
|
.sort((a, b) => parseInt(a, 16) > parseInt(b, 16) ? 1 : -1)
|
||
7 years ago
|
|
||
7 years ago
|
return lowestPrices[Math.floor(lowestPrices.length / 2)]
|
||
|
}
|
||
7 years ago
|
|
||
|
function getToAddressForGasUpdate (...addresses) {
|
||
|
return [...addresses, ''].find(str => str !== undefined && str !== null).toLowerCase()
|
||
|
}
|
||
7 years ago
|
|
||
|
function removeLeadingZeroes (str) {
|
||
|
return str.replace(/^0*(?=\d)/, '')
|
||
|
}
|