aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ui/app/actions.js9
-rw-r--r--ui/app/components/currency-input.js93
-rw-r--r--ui/app/components/customize-gas-modal/index.js21
-rw-r--r--ui/app/components/input-number.js18
-rw-r--r--ui/app/components/pending-tx/confirm-send-token.js6
-rw-r--r--ui/app/components/send/currency-display.js36
-rw-r--r--ui/app/components/send/send-constants.js1
-rw-r--r--ui/app/components/send/send-utils.js44
-rw-r--r--ui/app/components/send/send-v2-container.js5
-rw-r--r--ui/app/components/tx-list-item.js4
-rw-r--r--ui/app/conversion-util.js18
-rw-r--r--ui/app/css/itcss/components/send.scss9
-rw-r--r--ui/app/reducers/metamask.js9
-rw-r--r--ui/app/selectors.js9
-rw-r--r--ui/app/send-v2.js178
-rw-r--r--ui/app/token-tracker.js0
-rw-r--r--ui/app/token-util.js9
17 files changed, 387 insertions, 82 deletions
diff --git a/ui/app/actions.js b/ui/app/actions.js
index 5d3befa63..93cd40ed6 100644
--- a/ui/app/actions.js
+++ b/ui/app/actions.js
@@ -140,6 +140,7 @@ var actions = {
UPDATE_GAS_PRICE: 'UPDATE_GAS_PRICE',
UPDATE_GAS_TOTAL: 'UPDATE_GAS_TOTAL',
UPDATE_SEND_FROM: 'UPDATE_SEND_FROM',
+ UPDATE_SEND_TOKEN_BALANCE: 'UPDATE_SEND_TOKEN_BALANCE',
UPDATE_SEND_TO: 'UPDATE_SEND_TO',
UPDATE_SEND_AMOUNT: 'UPDATE_SEND_AMOUNT',
UPDATE_SEND_MEMO: 'UPDATE_SEND_MEMO',
@@ -148,6 +149,7 @@ var actions = {
updateGasLimit,
updateGasPrice,
updateGasTotal,
+ updateSendTokenBalance,
updateSendFrom,
updateSendTo,
updateSendAmount,
@@ -584,6 +586,13 @@ function updateGasTotal (gasTotal) {
}
}
+function updateSendTokenBalance (tokenBalance) {
+ return {
+ type: actions.UPDATE_SEND_TOKEN_BALANCE,
+ value: tokenBalance,
+ }
+}
+
function updateSendFrom (from) {
return {
type: actions.UPDATE_SEND_FROM,
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`
diff --git a/ui/app/conversion-util.js b/ui/app/conversion-util.js
index 9359d7c90..ee2950071 100644
--- a/ui/app/conversion-util.js
+++ b/ui/app/conversion-util.js
@@ -53,7 +53,7 @@ const toNormalizedDenomination = {
}
const toSpecifiedDenomination = {
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 = {
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 {
multiplicandBase,
@@ -169,6 +183,7 @@ const conversionGreaterThan = (
) => {
const firstValue = converter({ ...firstProps })
const secondValue = converter({ ...secondProps })
+
return firstValue.gt(secondValue)
}
@@ -202,4 +217,5 @@ module.exports = {
conversionGTE,
conversionLTE,
toNegative,
+ subtractCurrencies,
}
diff --git a/ui/app/css/itcss/components/send.scss b/ui/app/css/itcss/components/send.scss
index 4d7e6d71a..2bd192788 100644
--- a/ui/app/css/itcss/components/send.scss
+++ b/ui/app/css/itcss/components/send.scss
@@ -629,6 +629,15 @@
}
}
+ &__amount-max {
+ color: $curious-blue;
+ font-family: Roboto;
+ font-size: 12px;
+ left: 8px;
+ border: none;
+ cursor: pointer;
+ }
+
&__gas-fee-display {
width: 100%;
}
diff --git a/ui/app/reducers/metamask.js b/ui/app/reducers/metamask.js
index 50c9712ff..3b93a1625 100644
--- a/ui/app/reducers/metamask.js
+++ b/ui/app/reducers/metamask.js
@@ -27,6 +27,7 @@ function reduceMetamask (state, action) {
gasLimit: null,
gasPrice: null,
gasTotal: null,
+ tokenBalance: null,
from: '',
to: '',
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:
return extend(metamaskState, {
send: {
diff --git a/ui/app/selectors.js b/ui/app/selectors.js
index 3a15cef4c..a5f9a75d8 100644
--- a/ui/app/selectors.js
+++ b/ui/app/selectors.js
@@ -1,4 +1,5 @@
const valuesFor = require('./util').valuesFor
+const abi = require('human-standard-token-abi')
const {
multiplyCurrencies,
@@ -22,6 +23,7 @@ const selectors = {
getCurrentCurrency,
getSendAmount,
getSelectedTokenToFiatRate,
+ getSelectedTokenContract,
}
module.exports = selectors
@@ -149,3 +151,10 @@ function getSelectedTokenToFiatRate (state) {
return tokenToFiatRate
}
+
+function getSelectedTokenContract (state) {
+ const selectedToken = getSelectedToken(state)
+ return selectedToken
+ ? global.eth.contract(abi).at(selectedToken.address)
+ : null
+}
diff --git a/ui/app/send-v2.js b/ui/app/send-v2.js
index 6ce3e1b70..8c8b97a6d 100644
--- a/ui/app/send-v2.js
+++ b/ui/app/send-v2.js
@@ -2,6 +2,8 @@ const { inherits } = require('util')
const PersistentForm = require('../lib/persistent-form')
const h = require('react-hyperscript')
+const ethUtil = require('ethereumjs-util')
+
const Identicon = require('./components/identicon')
const FromDropdown = require('./components/send/from-dropdown')
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 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 {
multiplyCurrencies,
conversionGreaterThan,
+ subtractCurrencies,
} = require('./conversion-util')
const {
+ calcTokenAmount,
+} = require('./token-util')
+const {
isBalanceSufficient,
-} = require('./components/send/send-utils.js')
+ isTokenBalanceSufficient,
+} = require('./components/send/send-utils')
const { isValidAddress } = require('./util')
module.exports = SendTransactionScreen
@@ -40,6 +51,37 @@ function SendTransactionScreen () {
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 () {
const {
updateTokenExchangeRate,
@@ -49,32 +91,24 @@ SendTransactionScreen.prototype.componentWillMount = function () {
selectedAddress,
data,
updateGasTotal,
+ from,
+ tokenContract,
} = this.props
const { symbol } = selectedToken || {}
- const estimateGasParams = {
- from: selectedAddress,
- gas: '746a528800',
- }
-
if (symbol) {
updateTokenExchangeRate(symbol)
- Object.assign(estimateGasParams, { value: '0x0' })
}
- if (data) {
- Object.assign(estimateGasParams, { data })
- }
+ const estimateGasParams = getParamsForGasEstimate(selectedAddress, symbol, data)
Promise
.all([
getGasPrice(),
- estimateGas({
- from: selectedAddress,
- gas: '746a528800',
- }),
+ estimateGas(estimateGasParams),
+ tokenContract && tokenContract.balanceOf(from.address)
])
- .then(([gasPrice, gas]) => {
+ .then(([gasPrice, gas, usersToken]) => {
const newGasTotal = multiplyCurrencies(gas, gasPrice, {
toNumericBase: 'hex',
@@ -82,9 +116,36 @@ SendTransactionScreen.prototype.componentWillMount = function () {
multiplierBase: 16,
})
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 () {
const { selectedToken } = this.props
@@ -144,12 +205,24 @@ SendTransactionScreen.prototype.renderErrorMessage = function (errorType) {
: 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 () {
const {
from,
fromAccounts,
conversionRate,
- updateSendFrom,
} = this.props
const { fromDropdownOpen } = this.state
@@ -163,7 +236,7 @@ SendTransactionScreen.prototype.renderFromRow = function () {
dropdownOpen: fromDropdownOpen,
accounts: fromAccounts,
selectedAccount: from,
- onSelect: updateSendFrom,
+ onSelect: newFrom => this.handleFromChange(newFrom),
openDropdown: () => this.setState({ fromDropdownOpen: true }),
closeDropdown: () => this.setState({ fromDropdownOpen: false }),
conversionRate,
@@ -227,9 +300,40 @@ SendTransactionScreen.prototype.handleAmountChange = function (value) {
const amount = value
const { updateSendAmount } = this.props
+ this.validateAmount(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) {
const {
from: { balance },
@@ -239,21 +343,31 @@ SendTransactionScreen.prototype.validateAmount = function (value) {
primaryCurrency,
selectedToken,
gasTotal,
+ tokenBalance,
} = this.props
+ const { decimals } = selectedToken || {}
const amount = value
let amountError = null
const sufficientBalance = isBalanceSufficient({
- amount,
+ amount: selectedToken ? '0x0' : amount,
gasTotal,
balance,
primaryCurrency,
- selectedToken,
amountConversionRate,
conversionRate,
})
+ let sufficientTokens
+ if (selectedToken) {
+ sufficientTokens = isTokenBalanceSufficient({
+ tokenBalance,
+ amount,
+ decimals,
+ })
+ }
+
const amountLessThanZero = conversionGreaterThan(
{ value: 0, fromNumericBase: 'dec' },
{ value: amount, fromNumericBase: 'hex' },
@@ -261,6 +375,8 @@ SendTransactionScreen.prototype.validateAmount = function (value) {
if (!sufficientBalance) {
amountError = 'Insufficient funds.'
+ } else if (selectedToken && !sufficientTokens) {
+ amountError = 'Insufficient tokens.'
} else if (amountLessThanZero) {
amountError = 'Can not send negative amounts of ETH.'
}
@@ -275,15 +391,19 @@ SendTransactionScreen.prototype.renderAmountRow = function () {
convertedCurrency,
amountConversionRate,
errors,
+ amount,
} = this.props
-
- const { amount } = this.state
-
return h('div.send-v2__form-row', [
-
+
h('div.send-v2__form-label', [
'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', [
@@ -292,10 +412,9 @@ SendTransactionScreen.prototype.renderAmountRow = function () {
primaryCurrency,
convertedCurrency,
selectedToken,
- value: amount,
+ value: amount || '0x0',
conversionRate: amountConversionRate,
handleChange: this.handleAmountChange,
- validate: this.validateAmount,
}),
]),
@@ -335,8 +454,7 @@ SendTransactionScreen.prototype.renderGasRow = function () {
}
SendTransactionScreen.prototype.renderMemoRow = function () {
- const { updateSendMemo } = this.props
- const { memo } = this.state
+ const { updateSendMemo, memo } = this.props
return h('div.send-v2__form-row', [
@@ -383,7 +501,7 @@ SendTransactionScreen.prototype.renderFooter = function () {
errors: { amount: amountError, to: toError },
} = this.props
- const noErrors = amountError === null && toError === null
+ const noErrors = !amountError && toError === null
const errorClass = noErrors ? '' : '__disabled'
return h('div.send-v2__footer', [
@@ -437,7 +555,7 @@ SendTransactionScreen.prototype.onSubmit = function (event) {
errors: { amount: amountError, to: toError },
} = this.props
- const noErrors = amountError === null && toError === null
+ const noErrors = !amountError && toError === null
if (!noErrors) {
return
diff --git a/ui/app/token-tracker.js b/ui/app/token-tracker.js
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/ui/app/token-tracker.js
diff --git a/ui/app/token-util.js b/ui/app/token-util.js
index eec518556..f84051ef5 100644
--- a/ui/app/token-util.js
+++ b/ui/app/token-util.js
@@ -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 = {
tokenInfoGetter,
+ calcTokenAmount,
}