Merge pull request #2510 from danjm/NewUI-flat-token-balance

[NewUI] Improving gas precision and send (token) balance validation; max amount feature
feature/default_network_editable
Daniel Tsui 7 years ago committed by GitHub
commit da2e9b9765
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 9
      ui/app/actions.js
  2. 93
      ui/app/components/currency-input.js
  3. 19
      ui/app/components/customize-gas-modal/index.js
  4. 18
      ui/app/components/input-number.js
  5. 6
      ui/app/components/pending-tx/confirm-send-token.js
  6. 36
      ui/app/components/send/currency-display.js
  7. 1
      ui/app/components/send/send-constants.js
  8. 44
      ui/app/components/send/send-utils.js
  9. 5
      ui/app/components/send/send-v2-container.js
  10. 4
      ui/app/components/tx-list-item.js
  11. 18
      ui/app/conversion-util.js
  12. 9
      ui/app/css/itcss/components/send.scss
  13. 9
      ui/app/reducers/metamask.js
  14. 9
      ui/app/selectors.js
  15. 176
      ui/app/send-v2.js
  16. 0
      ui/app/token-tracker.js
  17. 9
      ui/app/token-util.js

@ -140,6 +140,7 @@ var actions = {
UPDATE_GAS_PRICE: 'UPDATE_GAS_PRICE', UPDATE_GAS_PRICE: 'UPDATE_GAS_PRICE',
UPDATE_GAS_TOTAL: 'UPDATE_GAS_TOTAL', UPDATE_GAS_TOTAL: 'UPDATE_GAS_TOTAL',
UPDATE_SEND_FROM: 'UPDATE_SEND_FROM', UPDATE_SEND_FROM: 'UPDATE_SEND_FROM',
UPDATE_SEND_TOKEN_BALANCE: 'UPDATE_SEND_TOKEN_BALANCE',
UPDATE_SEND_TO: 'UPDATE_SEND_TO', UPDATE_SEND_TO: 'UPDATE_SEND_TO',
UPDATE_SEND_AMOUNT: 'UPDATE_SEND_AMOUNT', UPDATE_SEND_AMOUNT: 'UPDATE_SEND_AMOUNT',
UPDATE_SEND_MEMO: 'UPDATE_SEND_MEMO', UPDATE_SEND_MEMO: 'UPDATE_SEND_MEMO',
@ -148,6 +149,7 @@ var actions = {
updateGasLimit, updateGasLimit,
updateGasPrice, updateGasPrice,
updateGasTotal, updateGasTotal,
updateSendTokenBalance,
updateSendFrom, updateSendFrom,
updateSendTo, updateSendTo,
updateSendAmount, updateSendAmount,
@ -584,6 +586,13 @@ function updateGasTotal (gasTotal) {
} }
} }
function updateSendTokenBalance (tokenBalance) {
return {
type: actions.UPDATE_SEND_TOKEN_BALANCE,
value: tokenBalance,
}
}
function updateSendFrom (from) { function updateSendFrom (from) {
return { return {
type: actions.UPDATE_SEND_FROM, type: actions.UPDATE_SEND_FROM,

@ -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),
})
}

@ -73,6 +73,8 @@ function getOriginalState (props) {
gasLimit, gasLimit,
gasTotal, gasTotal,
error: null, error: null,
priceSigZeros: '',
priceSigDec: '',
} }
} }
@ -107,7 +109,6 @@ CustomizeGasModal.prototype.validate = function ({ gasTotal, gasLimit }) {
const { const {
amount, amount,
balance, balance,
primaryCurrency,
selectedToken, selectedToken,
amountConversionRate, amountConversionRate,
conversionRate, conversionRate,
@ -119,7 +120,6 @@ CustomizeGasModal.prototype.validate = function ({ gasTotal, gasLimit }) {
amount, amount,
gasTotal, gasTotal,
balance, balance,
primaryCurrency,
selectedToken, selectedToken,
amountConversionRate, amountConversionRate,
conversionRate, conversionRate,
@ -170,6 +170,13 @@ CustomizeGasModal.prototype.convertAndSetGasLimit = function (newGasLimit) {
CustomizeGasModal.prototype.convertAndSetGasPrice = function (newGasPrice) { CustomizeGasModal.prototype.convertAndSetGasPrice = function (newGasPrice) {
const { gasLimit } = this.state 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, { const gasPrice = conversionUtil(newGasPrice, {
fromNumericBase: 'dec', fromNumericBase: 'dec',
@ -191,15 +198,17 @@ CustomizeGasModal.prototype.convertAndSetGasPrice = function (newGasPrice) {
CustomizeGasModal.prototype.render = function () { CustomizeGasModal.prototype.render = function () {
const { hideModal } = this.props 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', fromNumericBase: 'hex',
toNumericBase: 'dec', toNumericBase: 'dec',
fromDenomination: 'WEI', fromDenomination: 'WEI',
toDenomination: 'GWEI', toDenomination: 'GWEI',
}) })
convertedGasPrice += convertedGasPrice.match(/[.]/) ? priceSigZeros : `${priceSigDec}${priceSigZeros}`
const convertedGasLimit = conversionUtil(gasLimit, { const convertedGasLimit = conversionUtil(gasLimit, {
fromNumericBase: 'hex', fromNumericBase: 'hex',
toNumericBase: 'dec', toNumericBase: 'dec',
@ -224,7 +233,7 @@ CustomizeGasModal.prototype.render = function () {
value: convertedGasPrice, value: convertedGasPrice,
min: MIN_GAS_PRICE_GWEI, min: MIN_GAS_PRICE_GWEI,
// max: 1000, // max: 1000,
step: MIN_GAS_PRICE_GWEI, step: multiplyCurrencies(MIN_GAS_PRICE_GWEI, 10),
onChange: value => this.convertAndSetGasPrice(value), onChange: value => this.convertAndSetGasPrice(value),
title: 'Gas Price (GWEI)', title: 'Gas Price (GWEI)',
copy: 'We calculate the suggested gas prices based on network success rates.', copy: 'We calculate the suggested gas prices based on network success rates.',

@ -5,7 +5,7 @@ const {
addCurrencies, addCurrencies,
conversionGTE, conversionGTE,
conversionLTE, conversionLTE,
toNegative, subtractCurrencies,
} = require('../conversion-util') } = require('../conversion-util')
module.exports = InputNumber module.exports = InputNumber
@ -17,18 +17,24 @@ function InputNumber () {
this.setValue = this.setValue.bind(this) 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) { InputNumber.prototype.setValue = function (newValue) {
if (newValue && !isValidInput(newValue)) return
const { fixed, min = -1, max = Infinity, onChange } = this.props 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( const newValueGreaterThanMin = conversionGTE(
{ value: newValue, fromNumericBase: 'dec' }, { value: newValue || '0', fromNumericBase: 'dec' },
{ value: min, fromNumericBase: 'hex' }, { value: min, fromNumericBase: 'hex' },
) )
const newValueLessThanMax = conversionLTE( const newValueLessThanMax = conversionLTE(
{ value: newValue, fromNumericBase: 'dec' }, { value: newValue || '0', fromNumericBase: 'dec' },
{ value: max, fromNumericBase: 'hex' }, { value: max, fromNumericBase: 'hex' },
) )
if (newValueGreaterThanMin && newValueLessThanMax) { if (newValueGreaterThanMin && newValueLessThanMax) {
@ -46,8 +52,8 @@ InputNumber.prototype.render = function () {
return h('div.customize-gas-input-wrapper', {}, [ return h('div.customize-gas-input-wrapper', {}, [
h('input.customize-gas-input', { h('input.customize-gas-input', {
placeholder, placeholder,
type: 'number',
value, value,
step,
onChange: (e) => this.setValue(e.target.value), onChange: (e) => this.setValue(e.target.value),
}), }),
h('span.gas-tooltip-input-detail', {}, [unitLabel]), h('span.gas-tooltip-input-detail', {}, [unitLabel]),
@ -57,7 +63,7 @@ InputNumber.prototype.render = function () {
}), }),
h('i.fa.fa-angle-down', { h('i.fa.fa-angle-down', {
style: { cursor: 'pointer' }, style: { cursor: 'pointer' },
onClick: () => this.setValue(addCurrencies(value, toNegative(step))), onClick: () => this.setValue(subtractCurrencies(value, step)),
}), }),
]), ]),
]) ])

@ -15,6 +15,9 @@ const {
multiplyCurrencies, multiplyCurrencies,
addCurrencies, addCurrencies,
} = require('../../conversion-util') } = require('../../conversion-util')
const {
calcTokenAmount,
} = require('../../token-util')
const { MIN_GAS_PRICE_HEX } = require('../send/send-constants') const { MIN_GAS_PRICE_HEX } = require('../send/send-constants')
@ -73,8 +76,7 @@ ConfirmSendToken.prototype.getAmount = function () {
const { params = [] } = tokenData const { params = [] } = tokenData
const { value } = params[1] || {} const { value } = params[1] || {}
const { decimals } = token const { decimals } = token
const multiplier = Math.pow(10, Number(decimals || 0)) const sendTokenAmount = calcTokenAmount(value, decimals)
const sendTokenAmount = Number(value / multiplier)
return { return {
fiat: tokenExchangeRate fiat: tokenExchangeRate

@ -1,6 +1,7 @@
const Component = require('react').Component const Component = require('react').Component
const h = require('react-hyperscript') const h = require('react-hyperscript')
const inherits = require('util').inherits const inherits = require('util').inherits
const CurrencyInput = require('../currency-input')
const { conversionUtil, multiplyCurrencies } = require('../../conversion-util') const { conversionUtil, multiplyCurrencies } = require('../../conversion-util')
module.exports = CurrencyDisplay module.exports = CurrencyDisplay
@ -8,10 +9,6 @@ module.exports = CurrencyDisplay
inherits(CurrencyDisplay, Component) inherits(CurrencyDisplay, Component)
function CurrencyDisplay () { function CurrencyDisplay () {
Component.call(this) Component.call(this)
this.state = {
value: null,
}
} }
function isValidInput (text) { function isValidInput (text) {
@ -49,13 +46,11 @@ CurrencyDisplay.prototype.render = function () {
convertedCurrency, convertedCurrency,
readOnly = false, readOnly = false,
inError = false, inError = false,
value: initValue, value,
handleChange, handleChange,
validate,
} = this.props } = this.props
const { value } = this.state
const initValueToRender = conversionUtil(initValue, { const valueToRender = conversionUtil(value, {
fromNumericBase: 'hex', fromNumericBase: 'hex',
toNumericBase: 'dec', toNumericBase: 'dec',
fromDenomination: 'WEI', fromDenomination: 'WEI',
@ -63,7 +58,7 @@ CurrencyDisplay.prototype.render = function () {
conversionRate, conversionRate,
}) })
const convertedValue = conversionUtil(value || initValueToRender, { const convertedValue = conversionUtil(valueToRender, {
fromNumericBase: 'dec', fromNumericBase: 'dec',
fromCurrency: primaryCurrency, fromCurrency: primaryCurrency,
toCurrency: convertedCurrency, toCurrency: convertedCurrency,
@ -84,29 +79,14 @@ CurrencyDisplay.prototype.render = function () {
h('div.currency-display__input-wrapper', [ h('div.currency-display__input-wrapper', [
h('input', { h(CurrencyInput, {
className: primaryBalanceClassName, className: primaryBalanceClassName,
value: `${value || initValueToRender}`, value: `${valueToRender}`,
placeholder: '0', placeholder: '0',
size: (value || initValueToRender).length * inputSizeMultiplier,
readOnly, readOnly,
onChange: (event) => { onInputChange: newValue => {
let newValue = event.target.value handleChange(this.getAmount(newValue))
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 })
}
}, },
onBlur: event => !readOnly && handleChange(this.getAmount(event.target.value)),
}), }),
h('span.currency-display__currency-symbol', primaryCurrency), h('span.currency-display__currency-symbol', primaryCurrency),

@ -11,6 +11,7 @@ const MIN_GAS_PRICE_GWEI = ethUtil.addHexPrefix(conversionUtil(MIN_GAS_PRICE_HEX
toDenomination: 'GWEI', toDenomination: 'GWEI',
fromNumericBase: 'hex', fromNumericBase: 'hex',
toNumericBase: 'hex', toNumericBase: 'hex',
numberOfDecimals: 1,
})) }))
const MIN_GAS_TOTAL = multiplyCurrencies(MIN_GAS_LIMIT_HEX, MIN_GAS_PRICE_HEX, { const MIN_GAS_TOTAL = multiplyCurrencies(MIN_GAS_LIMIT_HEX, MIN_GAS_PRICE_HEX, {

@ -1,11 +1,17 @@
const { addCurrencies, conversionGreaterThan } = require('../../conversion-util') const {
addCurrencies,
conversionUtil,
conversionGTE,
} = require('../../conversion-util')
const {
calcTokenAmount,
} = require('../../token-util')
function isBalanceSufficient ({ function isBalanceSufficient({
amount, amount = '0x0',
gasTotal, gasTotal = '0x0',
balance, balance,
primaryCurrency, primaryCurrency,
selectedToken,
amountConversionRate, amountConversionRate,
conversionRate, conversionRate,
}) { }) {
@ -15,7 +21,7 @@ function isBalanceSufficient ({
toNumericBase: 'hex', toNumericBase: 'hex',
}) })
const balanceIsSufficient = conversionGreaterThan( const balanceIsSufficient = conversionGTE(
{ {
value: balance, value: balance,
fromNumericBase: 'hex', fromNumericBase: 'hex',
@ -26,13 +32,37 @@ function isBalanceSufficient ({
value: totalAmount, value: totalAmount,
fromNumericBase: 'hex', fromNumericBase: 'hex',
conversionRate: amountConversionRate, conversionRate: amountConversionRate,
fromCurrency: selectedToken || primaryCurrency, fromCurrency: primaryCurrency,
}, },
) )
return balanceIsSufficient 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 = { module.exports = {
isBalanceSufficient, isBalanceSufficient,
isTokenBalanceSufficient,
} }

@ -13,6 +13,7 @@ const {
getSendFrom, getSendFrom,
getCurrentCurrency, getCurrentCurrency,
getSelectedTokenToFiatRate, getSelectedTokenToFiatRate,
getSelectedTokenContract,
} = require('../../selectors') } = require('../../selectors')
module.exports = connect(mapStateToProps, mapDispatchToProps)(SendEther) module.exports = connect(mapStateToProps, mapDispatchToProps)(SendEther)
@ -48,6 +49,7 @@ function mapStateToProps (state) {
convertedCurrency: getCurrentCurrency(state), convertedCurrency: getCurrentCurrency(state),
data, data,
amountConversionRate: selectedToken ? tokenToFiatRate : conversionRate, amountConversionRate: selectedToken ? tokenToFiatRate : conversionRate,
tokenContract: getSelectedTokenContract(state),
} }
} }
@ -64,6 +66,9 @@ function mapDispatchToProps (dispatch) {
setSelectedAddress: address => dispatch(actions.setSelectedAddress(address)), setSelectedAddress: address => dispatch(actions.setSelectedAddress(address)),
addToAddressBook: address => dispatch(actions.addToAddressBook(address)), addToAddressBook: address => dispatch(actions.addToAddressBook(address)),
updateGasTotal: newTotal => dispatch(actions.updateGasTotal(newTotal)), 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)), updateSendFrom: newFrom => dispatch(actions.updateSendFrom(newFrom)),
updateSendTo: newTo => dispatch(actions.updateSendTo(newTo)), updateSendTo: newTo => dispatch(actions.updateSendTo(newTo)),
updateSendAmount: newAmount => dispatch(actions.updateSendAmount(newAmount)), updateSendAmount: newAmount => dispatch(actions.updateSendAmount(newAmount)),

@ -10,6 +10,7 @@ const Identicon = require('./identicon')
const contractMap = require('eth-contract-metadata') const contractMap = require('eth-contract-metadata')
const { conversionUtil, multiplyCurrencies } = require('../conversion-util') const { conversionUtil, multiplyCurrencies } = require('../conversion-util')
const { calcTokenAmount } = require('../token-util')
const { getCurrentCurrency } = require('../selectors') const { getCurrentCurrency } = require('../selectors')
@ -135,8 +136,7 @@ TxListItem.prototype.getSendTokenTotal = async function () {
const { params = [] } = decodedData || {} const { params = [] } = decodedData || {}
const { value } = params[1] || {} const { value } = params[1] || {}
const { decimals, symbol } = await this.getTokenInfo() const { decimals, symbol } = await this.getTokenInfo()
const multiplier = Math.pow(10, Number(decimals || 0)) const total = calcTokenAmount(value, decimals)
const total = Number(value / multiplier)
const pair = symbol && `${symbol.toLowerCase()}_eth` const pair = symbol && `${symbol.toLowerCase()}_eth`

@ -53,7 +53,7 @@ const toNormalizedDenomination = {
} }
const toSpecifiedDenomination = { const toSpecifiedDenomination = {
WEI: bigNumber => bigNumber.times(BIG_NUMBER_WEI_MULTIPLIER).round(), WEI: bigNumber => bigNumber.times(BIG_NUMBER_WEI_MULTIPLIER).round(),
GWEI: bigNumber => bigNumber.times(BIG_NUMBER_GWEI_MULTIPLIER).round(1), GWEI: bigNumber => bigNumber.times(BIG_NUMBER_GWEI_MULTIPLIER).round(9),
} }
const baseChange = { const baseChange = {
hex: n => n.toString(16), hex: n => n.toString(16),
@ -145,6 +145,20 @@ const addCurrencies = (a, b, options = {}) => {
}) })
} }
const subtractCurrencies = (a, b, options = {}) => {
const {
aBase,
bBase,
...conversionOptions
} = options
const value = (new BigNumber(a, aBase)).minus(b, bBase);
return converter({
value,
...conversionOptions,
})
}
const multiplyCurrencies = (a, b, options = {}) => { const multiplyCurrencies = (a, b, options = {}) => {
const { const {
multiplicandBase, multiplicandBase,
@ -169,6 +183,7 @@ const conversionGreaterThan = (
) => { ) => {
const firstValue = converter({ ...firstProps }) const firstValue = converter({ ...firstProps })
const secondValue = converter({ ...secondProps }) const secondValue = converter({ ...secondProps })
return firstValue.gt(secondValue) return firstValue.gt(secondValue)
} }
@ -202,4 +217,5 @@ module.exports = {
conversionGTE, conversionGTE,
conversionLTE, conversionLTE,
toNegative, toNegative,
subtractCurrencies,
} }

@ -629,6 +629,15 @@
} }
} }
&__amount-max {
color: $curious-blue;
font-family: Roboto;
font-size: 12px;
left: 8px;
border: none;
cursor: pointer;
}
&__gas-fee-display { &__gas-fee-display {
width: 100%; width: 100%;
} }

@ -27,6 +27,7 @@ function reduceMetamask (state, action) {
gasLimit: null, gasLimit: null,
gasPrice: null, gasPrice: null,
gasTotal: null, gasTotal: null,
tokenBalance: null,
from: '', from: '',
to: '', to: '',
amount: '0x0', amount: '0x0',
@ -196,6 +197,14 @@ function reduceMetamask (state, action) {
}, },
}) })
case actions.UPDATE_SEND_TOKEN_BALANCE:
return extend(metamaskState, {
send: {
...metamaskState.send,
tokenBalance: action.value,
},
})
case actions.UPDATE_SEND_FROM: case actions.UPDATE_SEND_FROM:
return extend(metamaskState, { return extend(metamaskState, {
send: { send: {

@ -1,4 +1,5 @@
const valuesFor = require('./util').valuesFor const valuesFor = require('./util').valuesFor
const abi = require('human-standard-token-abi')
const { const {
multiplyCurrencies, multiplyCurrencies,
@ -22,6 +23,7 @@ const selectors = {
getCurrentCurrency, getCurrentCurrency,
getSendAmount, getSendAmount,
getSelectedTokenToFiatRate, getSelectedTokenToFiatRate,
getSelectedTokenContract,
} }
module.exports = selectors module.exports = selectors
@ -149,3 +151,10 @@ function getSelectedTokenToFiatRate (state) {
return tokenToFiatRate return tokenToFiatRate
} }
function getSelectedTokenContract (state) {
const selectedToken = getSelectedToken(state)
return selectedToken
? global.eth.contract(abi).at(selectedToken.address)
: null
}

@ -2,6 +2,8 @@ const { inherits } = require('util')
const PersistentForm = require('../lib/persistent-form') const PersistentForm = require('../lib/persistent-form')
const h = require('react-hyperscript') const h = require('react-hyperscript')
const ethUtil = require('ethereumjs-util')
const Identicon = require('./components/identicon') const Identicon = require('./components/identicon')
const FromDropdown = require('./components/send/from-dropdown') const FromDropdown = require('./components/send/from-dropdown')
const ToAutoComplete = require('./components/send/to-autocomplete') const ToAutoComplete = require('./components/send/to-autocomplete')
@ -9,15 +11,24 @@ const CurrencyDisplay = require('./components/send/currency-display')
const MemoTextArea = require('./components/send/memo-textarea') const MemoTextArea = require('./components/send/memo-textarea')
const GasFeeDisplay = require('./components/send/gas-fee-display-v2') const GasFeeDisplay = require('./components/send/gas-fee-display-v2')
const { MIN_GAS_TOTAL } = require('./components/send/send-constants') const {
MIN_GAS_TOTAL,
MIN_GAS_PRICE_HEX,
MIN_GAS_LIMIT_HEX,
} = require('./components/send/send-constants')
const { const {
multiplyCurrencies, multiplyCurrencies,
conversionGreaterThan, conversionGreaterThan,
subtractCurrencies,
} = require('./conversion-util') } = require('./conversion-util')
const {
calcTokenAmount,
} = require('./token-util')
const { const {
isBalanceSufficient, isBalanceSufficient,
} = require('./components/send/send-utils.js') isTokenBalanceSufficient,
} = require('./components/send/send-utils')
const { isValidAddress } = require('./util') const { isValidAddress } = require('./util')
module.exports = SendTransactionScreen module.exports = SendTransactionScreen
@ -40,6 +51,37 @@ function SendTransactionScreen () {
this.validateAmount = this.validateAmount.bind(this) this.validateAmount = this.validateAmount.bind(this)
} }
const getParamsForGasEstimate = function (selectedAddress, symbol, data) {
const estimatedGasParams = {
from: selectedAddress,
gas: '746a528800',
}
if (symbol) {
Object.assign(estimatedGasParams, { value: '0x0' })
}
if (data) {
Object.assign(estimatedGasParams, { data })
}
return estimatedGasParams
}
SendTransactionScreen.prototype.updateSendTokenBalance = function (usersToken) {
if (!usersToken) return
const {
selectedToken = {},
updateSendTokenBalance,
} = this.props
const { decimals } = selectedToken || {}
const tokenBalance = calcTokenAmount(usersToken.balance.toString(), decimals)
updateSendTokenBalance(tokenBalance)
}
SendTransactionScreen.prototype.componentWillMount = function () { SendTransactionScreen.prototype.componentWillMount = function () {
const { const {
updateTokenExchangeRate, updateTokenExchangeRate,
@ -49,32 +91,24 @@ SendTransactionScreen.prototype.componentWillMount = function () {
selectedAddress, selectedAddress,
data, data,
updateGasTotal, updateGasTotal,
from,
tokenContract,
} = this.props } = this.props
const { symbol } = selectedToken || {} const { symbol } = selectedToken || {}
const estimateGasParams = {
from: selectedAddress,
gas: '746a528800',
}
if (symbol) { if (symbol) {
updateTokenExchangeRate(symbol) updateTokenExchangeRate(symbol)
Object.assign(estimateGasParams, { value: '0x0' })
} }
if (data) { const estimateGasParams = getParamsForGasEstimate(selectedAddress, symbol, data)
Object.assign(estimateGasParams, { data })
}
Promise Promise
.all([ .all([
getGasPrice(), getGasPrice(),
estimateGas({ estimateGas(estimateGasParams),
from: selectedAddress, tokenContract && tokenContract.balanceOf(from.address)
gas: '746a528800',
}),
]) ])
.then(([gasPrice, gas]) => { .then(([gasPrice, gas, usersToken]) => {
const newGasTotal = multiplyCurrencies(gas, gasPrice, { const newGasTotal = multiplyCurrencies(gas, gasPrice, {
toNumericBase: 'hex', toNumericBase: 'hex',
@ -82,9 +116,36 @@ SendTransactionScreen.prototype.componentWillMount = function () {
multiplierBase: 16, multiplierBase: 16,
}) })
updateGasTotal(newGasTotal) updateGasTotal(newGasTotal)
this.updateSendTokenBalance(usersToken)
}) })
} }
SendTransactionScreen.prototype.componentDidUpdate = function (prevProps) {
const {
from: { balance },
gasTotal,
tokenBalance,
amount,
selectedToken,
} = this.props
const {
from: { balance: prevBalance },
gasTotal: prevGasTotal,
tokenBalance: prevTokenBalance,
} = prevProps
const notFirstRender = [prevBalance, prevGasTotal].every(n => n !== null)
const balanceHasChanged = balance !== prevBalance
const gasTotalHasChange = gasTotal !== prevGasTotal
const tokenBalanceHasChanged = selectedToken && tokenBalance !== prevTokenBalance
const amountValidationChange = balanceHasChanged || gasTotalHasChange || tokenBalanceHasChanged
if (notFirstRender && amountValidationChange) {
this.validateAmount(amount)
}
}
SendTransactionScreen.prototype.renderHeaderIcon = function () { SendTransactionScreen.prototype.renderHeaderIcon = function () {
const { selectedToken } = this.props const { selectedToken } = this.props
@ -144,12 +205,24 @@ SendTransactionScreen.prototype.renderErrorMessage = function (errorType) {
: null : null
} }
SendTransactionScreen.prototype.handleFromChange = async function (newFrom) {
const {
updateSendFrom,
tokenContract,
} = this.props
if (tokenContract) {
const usersToken = await tokenContract.balanceOf(newFrom.address)
this.updateSendTokenBalance(usersToken)
}
updateSendFrom(newFrom)
}
SendTransactionScreen.prototype.renderFromRow = function () { SendTransactionScreen.prototype.renderFromRow = function () {
const { const {
from, from,
fromAccounts, fromAccounts,
conversionRate, conversionRate,
updateSendFrom,
} = this.props } = this.props
const { fromDropdownOpen } = this.state const { fromDropdownOpen } = this.state
@ -163,7 +236,7 @@ SendTransactionScreen.prototype.renderFromRow = function () {
dropdownOpen: fromDropdownOpen, dropdownOpen: fromDropdownOpen,
accounts: fromAccounts, accounts: fromAccounts,
selectedAccount: from, selectedAccount: from,
onSelect: updateSendFrom, onSelect: newFrom => this.handleFromChange(newFrom),
openDropdown: () => this.setState({ fromDropdownOpen: true }), openDropdown: () => this.setState({ fromDropdownOpen: true }),
closeDropdown: () => this.setState({ fromDropdownOpen: false }), closeDropdown: () => this.setState({ fromDropdownOpen: false }),
conversionRate, conversionRate,
@ -227,9 +300,40 @@ SendTransactionScreen.prototype.handleAmountChange = function (value) {
const amount = value const amount = value
const { updateSendAmount } = this.props const { updateSendAmount } = this.props
this.validateAmount(amount)
updateSendAmount(amount) updateSendAmount(amount)
} }
SendTransactionScreen.prototype.setAmountToMax = function () {
const {
from: { balance },
gasTotal,
updateSendAmount,
updateSendErrors,
updateGasPrice,
updateGasLimit,
updateGasTotal,
tokenBalance,
selectedToken,
} = this.props
const { decimals } = selectedToken || {}
const multiplier = Math.pow(10, Number(decimals || 0))
const maxAmount = selectedToken
? multiplyCurrencies(tokenBalance, multiplier, {toNumericBase: 'hex'})
: subtractCurrencies(
ethUtil.addHexPrefix(balance),
ethUtil.addHexPrefix(gasTotal),
{ toNumericBase: 'hex' }
)
updateSendErrors({ amount: null })
updateGasPrice(MIN_GAS_PRICE_HEX)
updateGasLimit(MIN_GAS_LIMIT_HEX)
updateGasTotal(MIN_GAS_TOTAL)
updateSendAmount(maxAmount)
}
SendTransactionScreen.prototype.validateAmount = function (value) { SendTransactionScreen.prototype.validateAmount = function (value) {
const { const {
from: { balance }, from: { balance },
@ -239,21 +343,31 @@ SendTransactionScreen.prototype.validateAmount = function (value) {
primaryCurrency, primaryCurrency,
selectedToken, selectedToken,
gasTotal, gasTotal,
tokenBalance,
} = this.props } = this.props
const { decimals } = selectedToken || {}
const amount = value const amount = value
let amountError = null let amountError = null
const sufficientBalance = isBalanceSufficient({ const sufficientBalance = isBalanceSufficient({
amount, amount: selectedToken ? '0x0' : amount,
gasTotal, gasTotal,
balance, balance,
primaryCurrency, primaryCurrency,
selectedToken,
amountConversionRate, amountConversionRate,
conversionRate, conversionRate,
}) })
let sufficientTokens
if (selectedToken) {
sufficientTokens = isTokenBalanceSufficient({
tokenBalance,
amount,
decimals,
})
}
const amountLessThanZero = conversionGreaterThan( const amountLessThanZero = conversionGreaterThan(
{ value: 0, fromNumericBase: 'dec' }, { value: 0, fromNumericBase: 'dec' },
{ value: amount, fromNumericBase: 'hex' }, { value: amount, fromNumericBase: 'hex' },
@ -261,6 +375,8 @@ SendTransactionScreen.prototype.validateAmount = function (value) {
if (!sufficientBalance) { if (!sufficientBalance) {
amountError = 'Insufficient funds.' amountError = 'Insufficient funds.'
} else if (selectedToken && !sufficientTokens) {
amountError = 'Insufficient tokens.'
} else if (amountLessThanZero) { } else if (amountLessThanZero) {
amountError = 'Can not send negative amounts of ETH.' amountError = 'Can not send negative amounts of ETH.'
} }
@ -275,15 +391,19 @@ SendTransactionScreen.prototype.renderAmountRow = function () {
convertedCurrency, convertedCurrency,
amountConversionRate, amountConversionRate,
errors, errors,
amount,
} = this.props } = this.props
const { amount } = this.state
return h('div.send-v2__form-row', [ return h('div.send-v2__form-row', [
h('div.send-v2__form-label', [ h('div.send-v2__form-label', [
'Amount:', 'Amount:',
this.renderErrorMessage('amount'), this.renderErrorMessage('amount'),
!errors.amount && h('div.send-v2__amount-max', {
onClick: (event) => {
event.preventDefault()
this.setAmountToMax()
},
}, [ 'Max' ]),
]), ]),
h('div.send-v2__form-field', [ h('div.send-v2__form-field', [
@ -292,10 +412,9 @@ SendTransactionScreen.prototype.renderAmountRow = function () {
primaryCurrency, primaryCurrency,
convertedCurrency, convertedCurrency,
selectedToken, selectedToken,
value: amount, value: amount || '0x0',
conversionRate: amountConversionRate, conversionRate: amountConversionRate,
handleChange: this.handleAmountChange, handleChange: this.handleAmountChange,
validate: this.validateAmount,
}), }),
]), ]),
@ -335,8 +454,7 @@ SendTransactionScreen.prototype.renderGasRow = function () {
} }
SendTransactionScreen.prototype.renderMemoRow = function () { SendTransactionScreen.prototype.renderMemoRow = function () {
const { updateSendMemo } = this.props const { updateSendMemo, memo } = this.props
const { memo } = this.state
return h('div.send-v2__form-row', [ return h('div.send-v2__form-row', [
@ -383,7 +501,7 @@ SendTransactionScreen.prototype.renderFooter = function () {
errors: { amount: amountError, to: toError }, errors: { amount: amountError, to: toError },
} = this.props } = this.props
const noErrors = amountError === null && toError === null const noErrors = !amountError && toError === null
const errorClass = noErrors ? '' : '__disabled' const errorClass = noErrors ? '' : '__disabled'
return h('div.send-v2__footer', [ return h('div.send-v2__footer', [
@ -437,7 +555,7 @@ SendTransactionScreen.prototype.onSubmit = function (event) {
errors: { amount: amountError, to: toError }, errors: { amount: amountError, to: toError },
} = this.props } = this.props
const noErrors = amountError === null && toError === null const noErrors = !amountError && toError === null
if (!noErrors) { if (!noErrors) {
return return

@ -31,6 +31,15 @@ const tokenInfoGetter = function () {
} }
} }
function calcTokenAmount (value, decimals) {
const multiplier = Math.pow(10, Number(decimals || 0))
const amount = Number(value / multiplier)
return amount
}
module.exports = { module.exports = {
tokenInfoGetter, tokenInfoGetter,
calcTokenAmount,
} }

Loading…
Cancel
Save