nifty-wallet/ui/app/send-v2.js

604 lines
14 KiB
JavaScript
Raw Normal View History

const { inherits } = require('util')
const PersistentForm = require('../lib/persistent-form')
const h = require('react-hyperscript')
2017-10-26 09:43:12 -07:00
const ethUtil = require('ethereumjs-util')
const Identicon = require('./components/identicon')
const FromDropdown = require('./components/send/from-dropdown')
2017-10-06 03:30:45 -07:00
const ToAutoComplete = require('./components/send/to-autocomplete')
2017-10-09 09:25:23 -07:00
const CurrencyDisplay = require('./components/send/currency-display')
const MemoTextArea = require('./components/send/memo-textarea')
const GasFeeDisplay = require('./components/send/gas-fee-display-v2')
2017-10-26 09:43:12 -07:00
const {
MIN_GAS_TOTAL,
MIN_GAS_PRICE_HEX,
MIN_GAS_LIMIT_HEX,
} = require('./components/send/send-constants')
const {
multiplyCurrencies,
conversionGreaterThan,
2017-10-26 09:43:12 -07:00
subtractCurrencies,
} = require('./conversion-util')
const {
calcTokenAmount,
} = require('./token-util')
const {
isBalanceSufficient,
isTokenBalanceSufficient,
} = require('./components/send/send-utils')
2017-10-17 13:13:20 -07:00
const { isValidAddress } = require('./util')
module.exports = SendTransactionScreen
inherits(SendTransactionScreen, PersistentForm)
function SendTransactionScreen () {
PersistentForm.call(this)
this.state = {
2017-10-23 09:24:47 -07:00
fromDropdownOpen: false,
toDropdownOpen: false,
2017-10-17 13:13:20 -07:00
errors: {
to: null,
amount: null,
},
}
this.handleToChange = this.handleToChange.bind(this)
this.handleAmountChange = this.handleAmountChange.bind(this)
2017-10-17 13:13:20 -07:00
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,
selectedToken = {},
getGasPrice,
estimateGas,
selectedAddress,
data,
updateGasTotal,
from,
tokenContract,
2017-11-08 08:44:48 -08:00
editingTransactionId,
gasPrice,
gasLimit,
} = this.props
2017-11-06 11:44:46 -08:00
const { symbol } = selectedToken || {}
if (symbol) {
updateTokenExchangeRate(symbol)
}
const estimateGasParams = getParamsForGasEstimate(selectedAddress, symbol, data)
2017-11-09 07:14:32 -08:00
const tokenBalancePromise = tokenContract && tokenContract.balanceOf(from.address)
2017-11-08 08:44:48 -08:00
let newGasTotal
if (!editingTransactionId) {
Promise
.all([
getGasPrice(),
estimateGas(estimateGasParams),
2017-11-09 07:14:32 -08:00
tokenBalancePromise,
2017-11-08 08:44:48 -08:00
])
.then(([gasPrice, gas, usersToken]) => {
const newGasTotal = multiplyCurrencies(gas, gasPrice, {
toNumericBase: 'hex',
multiplicandBase: 16,
multiplierBase: 16,
})
updateGasTotal(newGasTotal)
this.updateSendTokenBalance(usersToken)
})
2017-11-08 08:44:48 -08:00
} else {
newGasTotal = multiplyCurrencies(gasLimit, gasPrice, {
toNumericBase: 'hex',
multiplicandBase: 16,
multiplierBase: 16,
})
2017-11-08 08:44:48 -08:00
updateGasTotal(newGasTotal)
2017-11-09 07:14:32 -08:00
tokenBalancePromise && tokenBalancePromise.then(
usersToken => this.updateSendTokenBalance(usersToken))
2017-11-08 08:44:48 -08:00
}
}
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
return h('div.send-v2__send-header-icon-container', [
selectedToken
? h(Identicon, {
diameter: 40,
address: selectedToken.address,
})
2017-11-02 05:15:59 -07:00
: h('img.send-v2__send-header-icon', { src: '../images/eth_logo.svg' }),
])
}
SendTransactionScreen.prototype.renderTitle = function () {
const { selectedToken } = this.props
return h('div.send-v2__title', [selectedToken ? 'Send Tokens' : 'Send Funds'])
}
SendTransactionScreen.prototype.renderCopy = function () {
const { selectedToken } = this.props
const tokenText = selectedToken ? 'tokens' : 'ETH'
2017-10-19 10:53:56 -07:00
return h('div.send-v2__form-header-copy', [
h('div.send-v2__copy', `Only send ${tokenText} to an Ethereum address.`),
h('div.send-v2__copy', 'Sending to a different crytpocurrency that is not Ethereum may result in permanent loss.'),
])
}
SendTransactionScreen.prototype.renderHeader = function () {
return h('div', [
h('div.send-v2__header', {}, [
this.renderHeaderIcon(),
h('div.send-v2__arrow-background', [
h('i.fa.fa-lg.fa-arrow-circle-right.send-v2__send-arrow-icon'),
]),
h('div.send-v2__header-tip'),
]),
])
}
2017-11-02 05:15:59 -07:00
SendTransactionScreen.prototype.renderErrorMessage = function (errorType) {
2017-10-17 13:13:20 -07:00
const { errors } = this.props
2017-11-02 05:15:59 -07:00
const errorMessage = errors[errorType]
2017-10-17 13:13:20 -07:00
return errorMessage
2017-11-02 05:15:59 -07:00
? h('div.send-v2__error', [ errorMessage ])
2017-10-17 13:13:20 -07:00
: 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,
} = this.props
2017-10-23 09:24:47 -07:00
const { fromDropdownOpen } = this.state
return h('div.send-v2__form-row', [
h('div.send-v2__form-label', 'From:'),
2017-10-19 10:53:56 -07:00
h('div.send-v2__form-field', [
h(FromDropdown, {
2017-10-23 09:24:47 -07:00
dropdownOpen: fromDropdownOpen,
2017-10-19 10:53:56 -07:00
accounts: fromAccounts,
selectedAccount: from,
onSelect: newFrom => this.handleFromChange(newFrom),
2017-10-23 09:24:47 -07:00
openDropdown: () => this.setState({ fromDropdownOpen: true }),
closeDropdown: () => this.setState({ fromDropdownOpen: false }),
2017-10-19 10:53:56 -07:00
conversionRate,
}),
]),
])
}
2017-10-23 09:24:47 -07:00
SendTransactionScreen.prototype.handleToChange = function (to) {
2017-10-25 01:12:53 -07:00
const {
updateSendTo,
updateSendErrors,
from: {address: from},
} = this.props
2017-10-17 13:13:20 -07:00
let toError = null
if (!to) {
toError = 'Required'
} else if (!isValidAddress(to)) {
2017-10-25 01:12:53 -07:00
toError = 'Recipient address is invalid'
} else if (to === from) {
toError = 'From and To address cannot be the same'
2017-10-17 13:13:20 -07:00
}
updateSendTo(to)
2017-10-17 13:13:20 -07:00
updateSendErrors({ to: toError })
}
SendTransactionScreen.prototype.renderToRow = function () {
2017-10-23 09:24:47 -07:00
const { toAccounts, errors, to } = this.props
const { toDropdownOpen } = this.state
return h('div.send-v2__form-row', [
2017-10-17 13:13:20 -07:00
h('div.send-v2__form-label', [
'To:',
this.renderErrorMessage('to'),
]),
2017-10-19 10:53:56 -07:00
h('div.send-v2__form-field', [
h(ToAutoComplete, {
to,
2017-10-23 09:24:47 -07:00
accounts: Object.entries(toAccounts).map(([key, account]) => account),
dropdownOpen: toDropdownOpen,
openDropdown: () => this.setState({ toDropdownOpen: true }),
closeDropdown: () => this.setState({ toDropdownOpen: false }),
2017-10-19 10:53:56 -07:00
onChange: this.handleToChange,
inError: Boolean(errors.to),
}),
]),
])
}
SendTransactionScreen.prototype.handleAmountChange = function (value) {
const amount = value
2017-10-17 13:13:20 -07:00
const { updateSendAmount } = this.props
this.validateAmount(amount)
updateSendAmount(amount)
}
2017-10-26 09:43:12 -07:00
SendTransactionScreen.prototype.setAmountToMax = function () {
const {
from: { balance },
updateSendAmount,
updateSendErrors,
updateGasPrice,
updateGasLimit,
updateGasTotal,
2017-10-30 11:07:30 -07:00
tokenBalance,
selectedToken,
2017-10-26 09:43:12 -07:00
} = this.props
2017-10-30 11:07:30 -07:00
const { decimals } = selectedToken || {}
const multiplier = Math.pow(10, Number(decimals || 0))
2017-10-26 09:43:12 -07:00
2017-10-30 11:07:30 -07:00
const maxAmount = selectedToken
? multiplyCurrencies(tokenBalance, multiplier, {toNumericBase: 'hex'})
: subtractCurrencies(
ethUtil.addHexPrefix(balance),
ethUtil.addHexPrefix(MIN_GAS_TOTAL),
2017-10-30 11:07:30 -07:00
{ toNumericBase: 'hex' }
)
2017-10-26 09:43:12 -07:00
updateSendErrors({ amount: null })
2017-11-07 17:17:14 -08:00
if (!selectedToken) {
updateGasPrice(MIN_GAS_PRICE_HEX)
updateGasLimit(MIN_GAS_LIMIT_HEX)
updateGasTotal(MIN_GAS_TOTAL)
}
2017-10-26 09:43:12 -07:00
updateSendAmount(maxAmount)
}
2017-10-17 13:13:20 -07:00
SendTransactionScreen.prototype.validateAmount = function (value) {
const {
from: { balance },
updateSendErrors,
amountConversionRate,
conversionRate,
primaryCurrency,
selectedToken,
gasTotal,
tokenBalance,
2017-10-17 13:13:20 -07:00
} = this.props
const { decimals } = selectedToken || {}
2017-10-17 13:13:20 -07:00
const amount = value
let amountError = null
const sufficientBalance = isBalanceSufficient({
2017-11-09 14:23:10 -08:00
amount: selectedToken ? '0x0' : amount,
gasTotal,
balance,
primaryCurrency,
amountConversionRate,
conversionRate,
})
let sufficientTokens
if (selectedToken) {
sufficientTokens = isTokenBalanceSufficient({
tokenBalance,
amount,
decimals,
})
}
2017-10-17 13:13:20 -07:00
const amountLessThanZero = conversionGreaterThan(
{ value: 0, fromNumericBase: 'dec' },
{ value: amount, fromNumericBase: 'hex' },
)
if (!sufficientBalance) {
amountError = 'Insufficient funds.'
} else if (selectedToken && !sufficientTokens) {
amountError = 'Insufficient tokens.'
2017-10-17 13:13:20 -07:00
} else if (amountLessThanZero) {
amountError = 'Can not send negative amounts of ETH.'
}
updateSendErrors({ amount: amountError })
}
SendTransactionScreen.prototype.renderAmountRow = function () {
const {
selectedToken,
primaryCurrency = 'ETH',
convertedCurrency,
amountConversionRate,
2017-10-17 13:13:20 -07:00
errors,
amount,
} = this.props
2017-11-08 08:44:48 -08:00
return h('div.send-v2__form-row', [
2017-11-09 14:23:10 -08:00
2017-10-17 13:13:20 -07:00
h('div.send-v2__form-label', [
'Amount:',
this.renderErrorMessage('amount'),
2017-10-26 09:43:12 -07:00
!errors.amount && h('div.send-v2__amount-max', {
onClick: (event) => {
event.preventDefault()
this.setAmountToMax()
},
}, [ 'Max' ]),
2017-10-17 13:13:20 -07:00
]),
2017-10-19 10:53:56 -07:00
h('div.send-v2__form-field', [
h(CurrencyDisplay, {
inError: Boolean(errors.amount),
primaryCurrency,
convertedCurrency,
2017-10-20 18:26:18 -07:00
selectedToken,
2017-10-30 15:04:21 -07:00
value: amount || '0x0',
2017-10-19 10:53:56 -07:00
conversionRate: amountConversionRate,
handleChange: this.handleAmountChange,
}),
]),
])
}
SendTransactionScreen.prototype.renderGasRow = function () {
const {
conversionRate,
convertedCurrency,
showCustomizeGasModal,
gasTotal = MIN_GAS_TOTAL,
} = this.props
return h('div.send-v2__form-row', [
h('div.send-v2__form-label', 'Gas fee:'),
2017-10-19 10:53:56 -07:00
h('div.send-v2__form-field', [
h(GasFeeDisplay, {
gasTotal,
conversionRate,
convertedCurrency,
2017-10-19 10:53:56 -07:00
onClick: showCustomizeGasModal,
}),
2017-10-20 18:26:18 -07:00
2017-10-19 10:53:56 -07:00
h('div.send-v2__sliders-icon-container', {
onClick: showCustomizeGasModal,
}, [
h('i.fa.fa-sliders.send-v2__sliders-icon'),
]),
2017-10-20 18:26:18 -07:00
]),
])
}
2017-10-06 03:30:45 -07:00
SendTransactionScreen.prototype.renderMemoRow = function () {
const { updateSendMemo, memo } = this.props
2017-10-06 03:30:45 -07:00
return h('div.send-v2__form-row', [
2017-10-06 03:30:45 -07:00
h('div.send-v2__form-label', 'Transaction Memo:'),
2017-10-06 03:30:45 -07:00
2017-10-19 10:53:56 -07:00
h('div.send-v2__form-field', [
h(MemoTextArea, {
memo,
onChange: (event) => updateSendMemo(event.target.value),
2017-10-20 18:26:18 -07:00
}),
2017-10-19 10:53:56 -07:00
]),
])
}
2017-10-09 09:25:23 -07:00
SendTransactionScreen.prototype.renderForm = function () {
return h('div.send-v2__form', {}, [
2017-10-09 09:25:23 -07:00
2017-10-19 10:53:56 -07:00
h('div.sendV2__form-header', [
this.renderTitle(),
this.renderCopy(),
]),
this.renderFromRow(),
2017-10-09 09:25:23 -07:00
this.renderToRow(),
2017-10-09 09:25:23 -07:00
this.renderAmountRow(),
2017-10-09 09:25:23 -07:00
this.renderGasRow(),
2017-10-09 09:25:23 -07:00
2017-10-24 22:43:49 -07:00
// this.renderMemoRow(),
])
}
SendTransactionScreen.prototype.renderFooter = function () {
const {
goHome,
clearSend,
2017-10-24 22:43:49 -07:00
errors: { amount: amountError, to: toError },
} = this.props
2017-10-24 22:43:49 -07:00
2017-10-30 15:04:21 -07:00
const noErrors = !amountError && toError === null
const errorClass = noErrors ? '' : '__disabled'
return h('div.send-v2__footer', [
h('button.send-v2__cancel-btn', {
onClick: () => {
clearSend()
goHome()
},
}, 'Cancel'),
h(`button.send-v2__next-btn${errorClass}`, {
2017-10-24 22:43:49 -07:00
onClick: event => this.onSubmit(event),
}, 'Next'),
])
}
SendTransactionScreen.prototype.render = function () {
return (
h('div.send-v2__container', [
2017-10-09 09:25:23 -07:00
this.renderHeader(),
2017-10-09 09:25:23 -07:00
this.renderForm(),
this.renderFooter(),
])
)
}
2017-10-12 10:29:03 -07:00
SendTransactionScreen.prototype.addToAddressBookIfNew = function (newAddress) {
const { toAccounts, addToAddressBook } = this.props
if (!toAccounts.find(({ address }) => newAddress === address)) {
// TODO: nickname, i.e. addToAddressBook(recipient, nickname)
addToAddressBook(newAddress)
}
}
2017-10-12 10:29:03 -07:00
SendTransactionScreen.prototype.onSubmit = function (event) {
event.preventDefault()
const {
from: {address: from},
2017-10-12 10:29:03 -07:00
to,
amount,
gasLimit: gas,
gasPrice,
signTokenTx,
signTx,
selectedToken,
2017-11-08 08:44:48 -08:00
editingTransactionId,
2017-10-24 22:43:49 -07:00
errors: { amount: amountError, to: toError },
2017-11-08 08:44:48 -08:00
backToConfirmScreen,
2017-10-12 10:29:03 -07:00
} = this.props
2017-10-30 15:04:21 -07:00
const noErrors = !amountError && toError === null
2017-10-24 22:43:49 -07:00
if (!noErrors) {
return
}
this.addToAddressBookIfNew(to)
2017-11-08 08:44:48 -08:00
if (editingTransactionId) {
backToConfirmScreen(editingTransactionId)
return
}
2017-10-12 10:29:03 -07:00
const txParams = {
from,
value: '0',
gas,
gasPrice,
}
if (!selectedToken) {
txParams.value = amount
txParams.to = to
}
selectedToken
? signTokenTx(selectedToken.address, to, amount, txParams)
: signTx(txParams)
}