diff options
Simplify gas estimate actions and add local estimateGasPriceFromRecentBlocks method.
Diffstat (limited to 'ui/app/components/send_/send.utils.js')
-rw-r--r-- | ui/app/components/send_/send.utils.js | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/ui/app/components/send_/send.utils.js b/ui/app/components/send_/send.utils.js index 1c7fd2b42..6055c98b1 100644 --- a/ui/app/components/send_/send.utils.js +++ b/ui/app/components/send_/send.utils.js @@ -12,12 +12,15 @@ const { INSUFFICIENT_FUNDS_ERROR, INSUFFICIENT_TOKENS_ERROR, NEGATIVE_ETH_ERROR, + ONE_GWEI_IN_WEI_HEX, } = require('./send.constants') const abi = require('ethereumjs-abi') module.exports = { calcGasTotal, doesAmountErrorRequireUpdate, + estimateGas, + estimateGasPriceFromRecentBlocks, generateTokenTransferData, getAmountErrorObject, getParamsForGasEstimate, @@ -179,6 +182,17 @@ function doesAmountErrorRequireUpdate ({ return amountErrorRequiresUpdate } +function estimateGas (params = {}) { + return new Promise((resolve, reject) => { + global.ethQuery.estimateGas(params, (err, data) => { + if (err) { + return reject(err) + } + return resolve(data) + }) + }) +} + function generateTokenTransferData (selectedAddress, selectedToken) { if (!selectedToken) return console.log(`abi.rawEncode`, abi.rawEncode) @@ -187,3 +201,26 @@ function generateTokenTransferData (selectedAddress, selectedToken) { x => ('00' + x.toString(16)).slice(-2) ).join('') } + +function hexComparator (a, b) { + return conversionGreaterThan( + { value: a, fromNumericBase: 'hex' }, + { value: b, fromNumericBase: 'hex' }, + ) ? 1 : -1 +} + +function estimateGasPriceFromRecentBlocks (recentBlocks) { + // Return 1 gwei if no blocks have been observed: + if (!recentBlocks || recentBlocks.length === 0) { + return ONE_GWEI_IN_WEI_HEX + } + const lowestPrices = recentBlocks.map((block) => { + if (!block.gasPrices || block.gasPrices.length < 1) { + return ONE_GWEI_IN_WEI_HEX + } + return block.gasPrices + .sort(hexComparator)[0] + }) + .sort(hexComparator) + return lowestPrices[Math.floor(lowestPrices.length / 2)] +} |