1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Token balance in send state; validating sufficient tokens, validation updates on 'from' switching.

This commit is contained in:
Dan 2017-10-30 15:18:50 -02:30
parent 9f70762434
commit 67bdfe87e3
11 changed files with 191 additions and 33 deletions

View File

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

View File

@ -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

View File

@ -1,11 +1,18 @@
const { addCurrencies, conversionGreaterThan } = require('../../conversion-util') const {
addCurrencies,
conversionGreaterThan,
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,
}) { }) {
@ -26,13 +33,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,
} }

View File

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

View File

@ -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`

View File

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

View File

@ -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: {

View File

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

View File

@ -10,14 +10,19 @@ 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 } = require('./components/send/send-constants')
const abi = require('human-standard-token-abi')
const { const {
multiplyCurrencies, multiplyCurrencies,
conversionGreaterThan, conversionGreaterThan,
} = 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 +45,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 +85,25 @@ SendTransactionScreen.prototype.componentWillMount = function () {
selectedAddress, selectedAddress,
data, data,
updateGasTotal, updateGasTotal,
updateSendTokenBalance,
from,
tokenContract,
} = this.props } = this.props
const { symbol } = selectedToken || {} const { symbol, decimals } = 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 +111,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 +200,31 @@ SendTransactionScreen.prototype.renderErrorMessage = function (errorType) {
: null : null
} }
SendTransactionScreen.prototype.handleFromChange = async function (newFrom) {
const {
from,
updateSendFrom,
updateSendTokenBalance,
tokenContract,
selectedToken,
} = this.props
const { decimals } = selectedToken || {}
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, updateSendFrom,
updateSendTokenBalance,
tokenContract,
} = this.props } = this.props
const { fromDropdownOpen } = this.state const { fromDropdownOpen } = this.state
@ -163,7 +238,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,
@ -239,21 +314,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 +346,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,10 +362,9 @@ 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', [
@ -335,8 +421,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', [

0
ui/app/token-tracker.js Normal file
View File

View File

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