diff options
author | Daniel Tsui <szehungdanieltsui@gmail.com> | 2017-11-08 08:35:18 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-11-08 08:35:18 +0800 |
commit | da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c (patch) | |
tree | 99151d2b40844d5e90a4175550a4b37950d6c744 /ui/app/components | |
parent | 9f70762434deb1c973665a76623838289e655f22 (diff) | |
parent | c57d504794b6020d42dcdabe08a13ed412450fc1 (diff) | |
download | tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar.gz tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar.bz2 tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar.lz tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar.xz tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.tar.zst tangerine-wallet-browser-da2e9b9765ca32e7439a2a5687e6c3d8ca8bb63c.zip |
Merge pull request #2510 from danjm/NewUI-flat-token-balance
[NewUI] Improving gas precision and send (token) balance validation; max amount feature
Diffstat (limited to 'ui/app/components')
-rw-r--r-- | ui/app/components/currency-input.js | 93 | ||||
-rw-r--r-- | ui/app/components/customize-gas-modal/index.js | 21 | ||||
-rw-r--r-- | ui/app/components/input-number.js | 18 | ||||
-rw-r--r-- | ui/app/components/pending-tx/confirm-send-token.js | 6 | ||||
-rw-r--r-- | ui/app/components/send/currency-display.js | 36 | ||||
-rw-r--r-- | ui/app/components/send/send-constants.js | 1 | ||||
-rw-r--r-- | ui/app/components/send/send-utils.js | 44 | ||||
-rw-r--r-- | ui/app/components/send/send-v2-container.js | 5 | ||||
-rw-r--r-- | ui/app/components/tx-list-item.js | 4 |
9 files changed, 177 insertions, 51 deletions
diff --git a/ui/app/components/currency-input.js b/ui/app/components/currency-input.js new file mode 100644 index 000000000..5e534d87b --- /dev/null +++ b/ui/app/components/currency-input.js @@ -0,0 +1,93 @@ +const Component = require('react').Component +const h = require('react-hyperscript') +const inherits = require('util').inherits + +module.exports = CurrencyInput + +inherits(CurrencyInput, Component) +function CurrencyInput (props) { + Component.call(this) + + this.state = { + value: sanitizeValue(props.value), + } +} + +function removeNonDigits (str) { + return str.match(/\d|$/g).join('') +} + +// Removes characters that are not digits, then removes leading zeros +function sanitizeInteger (val) { + return String(parseInt(removeNonDigits(val) || '0', 10)) +} + +function sanitizeDecimal (val) { + return removeNonDigits(val) +} + +// Take a single string param and returns a non-negative integer or float as a string. +// Breaks the input into three parts: the integer, the decimal point, and the decimal/fractional part. +// Removes leading zeros from the integer, and non-digits from the integer and decimal +// The integer is returned as '0' in cases where it would be empty. A decimal point is +// included in the returned string if one is included in the param +// Examples: +// sanitizeValue('0') -> '0' +// sanitizeValue('a') -> '0' +// sanitizeValue('010.') -> '10.' +// sanitizeValue('0.005') -> '0.005' +// sanitizeValue('22.200') -> '22.200' +// sanitizeValue('.200') -> '0.200' +// sanitizeValue('a.b.1.c,89.123') -> '0.189123' +function sanitizeValue (value) { + let [,integer, point, decimal] = (/([^.]*)([.]?)([^.]*)/).exec(value) + + integer = sanitizeInteger(integer) || '0' + decimal = sanitizeDecimal(decimal) + + return `${integer}${point}${decimal}` +} + +CurrencyInput.prototype.handleChange = function (newValue) { + const { onInputChange } = this.props + + this.setState({ value: sanitizeValue(newValue) }) + + onInputChange(sanitizeValue(newValue)) +} + +// If state.value === props.value plus a decimal point, or at least one +// zero or a decimal point and at least one zero, then this returns state.value +// after it is sanitized with getValueParts +CurrencyInput.prototype.getValueToRender = function () { + const { value } = this.props + const { value: stateValue } = this.state + + const trailingStateString = (new RegExp(`^${value}(.+)`)).exec(stateValue) + const trailingDecimalAndZeroes = trailingStateString && (/^[.0]0*/).test(trailingStateString[1]) + + return sanitizeValue(trailingDecimalAndZeroes + ? stateValue + : value) +} + +CurrencyInput.prototype.render = function () { + const { + className, + placeholder, + readOnly, + } = this.props + + const inputSizeMultiplier = readOnly ? 1 : 1.2 + + const valueToRender = this.getValueToRender() + + return h('input', { + className, + value: valueToRender, + placeholder, + size: valueToRender.length * inputSizeMultiplier, + readOnly, + onChange: e => this.handleChange(e.target.value), + }) +} diff --git a/ui/app/components/customize-gas-modal/index.js b/ui/app/components/customize-gas-modal/index.js index 101a19d9f..b77e1990f 100644 --- a/ui/app/components/customize-gas-modal/index.js +++ b/ui/app/components/customize-gas-modal/index.js @@ -73,6 +73,8 @@ function getOriginalState (props) { gasLimit, gasTotal, error: null, + priceSigZeros: '', + priceSigDec: '', } } @@ -107,19 +109,17 @@ CustomizeGasModal.prototype.validate = function ({ gasTotal, gasLimit }) { const { amount, balance, - primaryCurrency, selectedToken, amountConversionRate, conversionRate, } = this.props let error = null - + const balanceIsSufficient = isBalanceSufficient({ amount, gasTotal, balance, - primaryCurrency, selectedToken, amountConversionRate, conversionRate, @@ -170,6 +170,13 @@ CustomizeGasModal.prototype.convertAndSetGasLimit = function (newGasLimit) { CustomizeGasModal.prototype.convertAndSetGasPrice = function (newGasPrice) { const { gasLimit } = this.state + const sigZeros = String(newGasPrice).match(/^\d+[.]\d*?(0+)$/) + const sigDec = String(newGasPrice).match(/^\d+([.])0*$/) + + this.setState({ + priceSigZeros: sigZeros && sigZeros[1] || '', + priceSigDec: sigDec && sigDec[1] || '', + }) const gasPrice = conversionUtil(newGasPrice, { fromNumericBase: 'dec', @@ -191,15 +198,17 @@ CustomizeGasModal.prototype.convertAndSetGasPrice = function (newGasPrice) { CustomizeGasModal.prototype.render = function () { const { hideModal } = this.props - const { gasPrice, gasLimit, gasTotal, error } = this.state + const { gasPrice, gasLimit, gasTotal, error, priceSigZeros, priceSigDec } = this.state - const convertedGasPrice = conversionUtil(gasPrice, { + let convertedGasPrice = conversionUtil(gasPrice, { fromNumericBase: 'hex', toNumericBase: 'dec', fromDenomination: 'WEI', toDenomination: 'GWEI', }) + convertedGasPrice += convertedGasPrice.match(/[.]/) ? priceSigZeros : `${priceSigDec}${priceSigZeros}` + const convertedGasLimit = conversionUtil(gasLimit, { fromNumericBase: 'hex', toNumericBase: 'dec', @@ -224,7 +233,7 @@ CustomizeGasModal.prototype.render = function () { value: convertedGasPrice, min: MIN_GAS_PRICE_GWEI, // max: 1000, - step: MIN_GAS_PRICE_GWEI, + step: multiplyCurrencies(MIN_GAS_PRICE_GWEI, 10), onChange: value => this.convertAndSetGasPrice(value), title: 'Gas Price (GWEI)', copy: 'We calculate the suggested gas prices based on network success rates.', diff --git a/ui/app/components/input-number.js b/ui/app/components/input-number.js index e28807c13..12dec2957 100644 --- a/ui/app/components/input-number.js +++ b/ui/app/components/input-number.js @@ -5,7 +5,7 @@ const { addCurrencies, conversionGTE, conversionLTE, - toNegative, + subtractCurrencies, } = require('../conversion-util') module.exports = InputNumber @@ -17,18 +17,24 @@ function InputNumber () { this.setValue = this.setValue.bind(this) } +function isValidInput (text) { + const re = /^([1-9]\d*|0)(\.|\.\d*)?$/ + return re.test(text) +} + InputNumber.prototype.setValue = function (newValue) { + if (newValue && !isValidInput(newValue)) return const { fixed, min = -1, max = Infinity, onChange } = this.props - newValue = Number(fixed ? newValue.toFixed(4) : newValue) + newValue = fixed ? newValue.toFixed(4) : newValue const newValueGreaterThanMin = conversionGTE( - { value: newValue, fromNumericBase: 'dec' }, + { value: newValue || '0', fromNumericBase: 'dec' }, { value: min, fromNumericBase: 'hex' }, ) const newValueLessThanMax = conversionLTE( - { value: newValue, fromNumericBase: 'dec' }, + { value: newValue || '0', fromNumericBase: 'dec' }, { value: max, fromNumericBase: 'hex' }, ) if (newValueGreaterThanMin && newValueLessThanMax) { @@ -46,8 +52,8 @@ InputNumber.prototype.render = function () { return h('div.customize-gas-input-wrapper', {}, [ h('input.customize-gas-input', { placeholder, - type: 'number', value, + step, onChange: (e) => this.setValue(e.target.value), }), h('span.gas-tooltip-input-detail', {}, [unitLabel]), @@ -57,7 +63,7 @@ InputNumber.prototype.render = function () { }), h('i.fa.fa-angle-down', { style: { cursor: 'pointer' }, - onClick: () => this.setValue(addCurrencies(value, toNegative(step))), + onClick: () => this.setValue(subtractCurrencies(value, step)), }), ]), ]) diff --git a/ui/app/components/pending-tx/confirm-send-token.js b/ui/app/components/pending-tx/confirm-send-token.js index 3b8ae7f7f..f14da38ef 100644 --- a/ui/app/components/pending-tx/confirm-send-token.js +++ b/ui/app/components/pending-tx/confirm-send-token.js @@ -15,6 +15,9 @@ const { multiplyCurrencies, addCurrencies, } = require('../../conversion-util') +const { + calcTokenAmount, +} = require('../../token-util') const { MIN_GAS_PRICE_HEX } = require('../send/send-constants') @@ -73,8 +76,7 @@ ConfirmSendToken.prototype.getAmount = function () { const { params = [] } = tokenData const { value } = params[1] || {} const { decimals } = token - const multiplier = Math.pow(10, Number(decimals || 0)) - const sendTokenAmount = Number(value / multiplier) + const sendTokenAmount = calcTokenAmount(value, decimals) return { fiat: tokenExchangeRate diff --git a/ui/app/components/send/currency-display.js b/ui/app/components/send/currency-display.js index 45986e371..8b72b3e6d 100644 --- a/ui/app/components/send/currency-display.js +++ b/ui/app/components/send/currency-display.js @@ -1,6 +1,7 @@ const Component = require('react').Component const h = require('react-hyperscript') const inherits = require('util').inherits +const CurrencyInput = require('../currency-input') const { conversionUtil, multiplyCurrencies } = require('../../conversion-util') module.exports = CurrencyDisplay @@ -8,10 +9,6 @@ module.exports = CurrencyDisplay inherits(CurrencyDisplay, Component) function CurrencyDisplay () { Component.call(this) - - this.state = { - value: null, - } } function isValidInput (text) { @@ -49,13 +46,11 @@ CurrencyDisplay.prototype.render = function () { convertedCurrency, readOnly = false, inError = false, - value: initValue, + value, handleChange, - validate, } = this.props - const { value } = this.state - const initValueToRender = conversionUtil(initValue, { + const valueToRender = conversionUtil(value, { fromNumericBase: 'hex', toNumericBase: 'dec', fromDenomination: 'WEI', @@ -63,7 +58,7 @@ CurrencyDisplay.prototype.render = function () { conversionRate, }) - const convertedValue = conversionUtil(value || initValueToRender, { + const convertedValue = conversionUtil(valueToRender, { fromNumericBase: 'dec', fromCurrency: primaryCurrency, toCurrency: convertedCurrency, @@ -84,29 +79,14 @@ CurrencyDisplay.prototype.render = function () { h('div.currency-display__input-wrapper', [ - h('input', { + h(CurrencyInput, { className: primaryBalanceClassName, - value: `${value || initValueToRender}`, + value: `${valueToRender}`, placeholder: '0', - size: (value || initValueToRender).length * inputSizeMultiplier, readOnly, - onChange: (event) => { - let newValue = event.target.value - - if (newValue === '') { - newValue = '0' - } else if (newValue.match(/^0[1-9]$/)) { - newValue = newValue.match(/[1-9]/)[0] - } - - if (newValue && !isValidInput(newValue)) { - event.preventDefault() - } else { - validate(this.getAmount(newValue)) - this.setState({ value: newValue }) - } + onInputChange: newValue => { + handleChange(this.getAmount(newValue)) }, - onBlur: event => !readOnly && handleChange(this.getAmount(event.target.value)), }), h('span.currency-display__currency-symbol', primaryCurrency), diff --git a/ui/app/components/send/send-constants.js b/ui/app/components/send/send-constants.js index 0a4f85bc9..a961ffcd8 100644 --- a/ui/app/components/send/send-constants.js +++ b/ui/app/components/send/send-constants.js @@ -11,6 +11,7 @@ const MIN_GAS_PRICE_GWEI = ethUtil.addHexPrefix(conversionUtil(MIN_GAS_PRICE_HEX toDenomination: 'GWEI', fromNumericBase: 'hex', toNumericBase: 'hex', + numberOfDecimals: 1, })) const MIN_GAS_TOTAL = multiplyCurrencies(MIN_GAS_LIMIT_HEX, MIN_GAS_PRICE_HEX, { diff --git a/ui/app/components/send/send-utils.js b/ui/app/components/send/send-utils.js index 6ec04a223..bd1197950 100644 --- a/ui/app/components/send/send-utils.js +++ b/ui/app/components/send/send-utils.js @@ -1,11 +1,17 @@ -const { addCurrencies, conversionGreaterThan } = require('../../conversion-util') +const { + addCurrencies, + conversionUtil, + conversionGTE, +} = require('../../conversion-util') +const { + calcTokenAmount, +} = require('../../token-util') -function isBalanceSufficient ({ - amount, - gasTotal, +function isBalanceSufficient({ + amount = '0x0', + gasTotal = '0x0', balance, primaryCurrency, - selectedToken, amountConversionRate, conversionRate, }) { @@ -15,7 +21,7 @@ function isBalanceSufficient ({ toNumericBase: 'hex', }) - const balanceIsSufficient = conversionGreaterThan( + const balanceIsSufficient = conversionGTE( { value: balance, fromNumericBase: 'hex', @@ -26,13 +32,37 @@ function isBalanceSufficient ({ value: totalAmount, fromNumericBase: 'hex', conversionRate: amountConversionRate, - fromCurrency: selectedToken || primaryCurrency, + fromCurrency: primaryCurrency, }, ) return balanceIsSufficient } +function isTokenBalanceSufficient({ + amount = '0x0', + tokenBalance, + decimals, +}) { + const amountInDec = conversionUtil(amount, { + fromNumericBase: 'hex', + }) + + const tokenBalanceIsSufficient = conversionGTE( + { + value: tokenBalance, + fromNumericBase: 'dec', + }, + { + value: calcTokenAmount(amountInDec, decimals), + fromNumericBase: 'dec', + }, + ) + + return tokenBalanceIsSufficient +} + module.exports = { isBalanceSufficient, + isTokenBalanceSufficient, } diff --git a/ui/app/components/send/send-v2-container.js b/ui/app/components/send/send-v2-container.js index 5a6e83ae6..51d5c4f89 100644 --- a/ui/app/components/send/send-v2-container.js +++ b/ui/app/components/send/send-v2-container.js @@ -13,6 +13,7 @@ const { getSendFrom, getCurrentCurrency, getSelectedTokenToFiatRate, + getSelectedTokenContract, } = require('../../selectors') module.exports = connect(mapStateToProps, mapDispatchToProps)(SendEther) @@ -48,6 +49,7 @@ function mapStateToProps (state) { convertedCurrency: getCurrentCurrency(state), data, amountConversionRate: selectedToken ? tokenToFiatRate : conversionRate, + tokenContract: getSelectedTokenContract(state), } } @@ -64,6 +66,9 @@ function mapDispatchToProps (dispatch) { setSelectedAddress: address => dispatch(actions.setSelectedAddress(address)), addToAddressBook: address => dispatch(actions.addToAddressBook(address)), updateGasTotal: newTotal => dispatch(actions.updateGasTotal(newTotal)), + updateGasPrice: newGasPrice => dispatch(actions.updateGasPrice(newGasPrice)), + updateGasLimit: newGasLimit => dispatch(actions.updateGasLimit(newGasLimit)), + updateSendTokenBalance: tokenBalance => dispatch(actions.updateSendTokenBalance(tokenBalance)), updateSendFrom: newFrom => dispatch(actions.updateSendFrom(newFrom)), updateSendTo: newTo => dispatch(actions.updateSendTo(newTo)), updateSendAmount: newAmount => dispatch(actions.updateSendAmount(newAmount)), diff --git a/ui/app/components/tx-list-item.js b/ui/app/components/tx-list-item.js index 26de19f15..4e76147a1 100644 --- a/ui/app/components/tx-list-item.js +++ b/ui/app/components/tx-list-item.js @@ -10,6 +10,7 @@ const Identicon = require('./identicon') const contractMap = require('eth-contract-metadata') const { conversionUtil, multiplyCurrencies } = require('../conversion-util') +const { calcTokenAmount } = require('../token-util') const { getCurrentCurrency } = require('../selectors') @@ -135,8 +136,7 @@ TxListItem.prototype.getSendTokenTotal = async function () { const { params = [] } = decodedData || {} const { value } = params[1] || {} const { decimals, symbol } = await this.getTokenInfo() - const multiplier = Math.pow(10, Number(decimals || 0)) - const total = Number(value / multiplier) + const total = calcTokenAmount(value, decimals) const pair = symbol && `${symbol.toLowerCase()}_eth` |