1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-24 11:01:41 +01:00
metamask-extension/ui/app/send-v2.js

640 lines
15 KiB
JavaScript
Raw Normal View History

const { inherits } = require('util')
const PropTypes = require('prop-types')
const PersistentForm = require('../lib/persistent-form')
const h = require('react-hyperscript')
const ethAbi = require('ethereumjs-abi')
2017-10-26 18:43:12 +02:00
const ethUtil = require('ethereumjs-util')
const FromDropdown = require('./components/send/from-dropdown')
const EnsInput = require('./components/ens-input')
2017-10-09 18:25:23 +02: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 18:43:12 +02:00
const {
TOKEN_TRANSFER_FUNCTION_SIGNATURE,
2017-10-26 18:43:12 +02:00
} = require('./components/send/send-constants')
const {
multiplyCurrencies,
conversionGreaterThan,
2017-10-26 18:43:12 +02:00
subtractCurrencies,
} = require('./conversion-util')
const {
calcTokenAmount,
} = require('./token-util')
const {
isBalanceSufficient,
isTokenBalanceSufficient,
getGasTotal,
} = require('./components/send/send-utils')
2017-10-17 22:13:20 +02:00
const { isValidAddress } = require('./util')
2018-04-02 11:59:49 +02:00
const { CONFIRM_TRANSACTION_ROUTE, DEFAULT_ROUTE } = require('./routes')
SendTransactionScreen.contextTypes = {
t: PropTypes.func,
}
module.exports = SendTransactionScreen
inherits(SendTransactionScreen, PersistentForm)
function SendTransactionScreen () {
PersistentForm.call(this)
this.state = {
2017-10-23 18:24:47 +02:00
fromDropdownOpen: false,
toDropdownOpen: false,
2017-10-17 22:13:20 +02:00
errors: {
to: null,
amount: null,
},
gasLoadingError: false,
}
this.handleToChange = this.handleToChange.bind(this)
this.handleAmountChange = this.handleAmountChange.bind(this)
2017-10-17 22:13:20 +02: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 () {
this.updateGas()
}
SendTransactionScreen.prototype.updateGas = function () {
const {
selectedToken = {},
getGasPrice,
estimateGas,
selectedAddress,
data,
updateGasTotal,
from,
tokenContract,
2017-11-08 17:44:48 +01:00
editingTransactionId,
gasPrice,
gasLimit,
} = this.props
const { symbol } = selectedToken || {}
const tokenBalancePromise = tokenContract
? tokenContract.balanceOf(from.address)
: Promise.resolve()
tokenBalancePromise
.then(usersToken => this.updateSendTokenBalance(usersToken))
2017-11-08 17:44:48 +01:00
if (!editingTransactionId) {
const estimateGasParams = getParamsForGasEstimate(selectedAddress, symbol, data)
2017-11-08 17:44:48 +01:00
Promise
.all([
getGasPrice(),
estimateGas(estimateGasParams),
])
.then(([gasPrice, gas]) => {
const newGasTotal = getGasTotal(gas, gasPrice)
2017-11-08 17:44:48 +01:00
updateGasTotal(newGasTotal)
this.setState({ gasLoadingError: false })
})
.catch(err => {
this.setState({ gasLoadingError: true })
})
2017-11-08 17:44:48 +01:00
} else {
const newGasTotal = getGasTotal(gasLimit, gasPrice)
2017-11-08 17:44:48 +01:00
updateGasTotal(newGasTotal)
}
}
SendTransactionScreen.prototype.componentDidUpdate = function (prevProps) {
const {
from: { balance },
gasTotal,
tokenBalance,
amount,
selectedToken,
network,
} = this.props
const {
from: { balance: prevBalance },
gasTotal: prevGasTotal,
tokenBalance: prevTokenBalance,
network: prevNetwork,
} = prevProps
const uninitialized = [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 (!uninitialized) {
if (amountValidationChange) {
this.validateAmount(amount)
}
if (network !== prevNetwork && network !== 'loading') {
this.updateGas()
}
}
}
SendTransactionScreen.prototype.renderHeader = function () {
const { selectedToken, clearSend, history } = this.props
return h('div.page-container__header', [
h('div.page-container__title', selectedToken ? this.context.t('sendTokens') : this.context.t('sendETH')),
h('div.page-container__subtitle', this.context.t('onlySendToEtherAddress')),
2018-02-13 07:39:15 +01:00
h('div.page-container__header-close', {
onClick: () => {
clearSend()
2018-04-02 11:59:49 +02:00
history.push(DEFAULT_ROUTE)
2018-02-13 07:39:15 +01:00
},
}),
])
}
2017-11-02 13:15:59 +01:00
SendTransactionScreen.prototype.renderErrorMessage = function (errorType) {
2017-10-17 22:13:20 +02:00
const { errors } = this.props
2017-11-02 13:15:59 +01:00
const errorMessage = errors[errorType]
2017-10-17 22:13:20 +02:00
return errorMessage
2017-11-02 13:15:59 +01:00
? h('div.send-v2__error', [ errorMessage ])
2017-10-17 22:13:20 +02: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 18:24:47 +02:00
const { fromDropdownOpen } = this.state
return h('div.send-v2__form-row', [
h('div.send-v2__form-label', 'From:'),
2017-10-19 19:53:56 +02:00
h('div.send-v2__form-field', [
h(FromDropdown, {
2017-10-23 18:24:47 +02:00
dropdownOpen: fromDropdownOpen,
2017-10-19 19:53:56 +02:00
accounts: fromAccounts,
selectedAccount: from,
onSelect: newFrom => this.handleFromChange(newFrom),
2017-10-23 18:24:47 +02:00
openDropdown: () => this.setState({ fromDropdownOpen: true }),
closeDropdown: () => this.setState({ fromDropdownOpen: false }),
2017-10-19 19:53:56 +02:00
conversionRate,
}),
]),
])
}
SendTransactionScreen.prototype.handleToChange = function (to, nickname = '') {
2017-10-25 10:12:53 +02:00
const {
updateSendTo,
updateSendErrors,
} = this.props
2017-10-17 22:13:20 +02:00
let toError = null
if (!to) {
toError = this.context.t('required')
2017-10-17 22:13:20 +02:00
} else if (!isValidAddress(to)) {
toError = this.context.t('invalidAddressRecipient')
2017-10-17 22:13:20 +02:00
}
updateSendTo(to, nickname)
2017-10-17 22:13:20 +02:00
updateSendErrors({ to: toError })
}
SendTransactionScreen.prototype.renderToRow = function () {
const { toAccounts, errors, to, network } = this.props
2017-10-23 18:24:47 +02:00
const { toDropdownOpen } = this.state
return h('div.send-v2__form-row', [
2017-10-17 22:13:20 +02:00
h('div.send-v2__form-label', [
this.context.t('to'),
2017-10-17 22:13:20 +02:00
this.renderErrorMessage(this.context.t('to')),
2017-10-17 22:13:20 +02:00
]),
2017-10-19 19:53:56 +02:00
h('div.send-v2__form-field', [
h(EnsInput, {
name: 'address',
placeholder: 'Recipient Address',
network,
2017-10-19 19:53:56 +02:00
to,
2017-10-23 18:24:47 +02:00
accounts: Object.entries(toAccounts).map(([key, account]) => account),
dropdownOpen: toDropdownOpen,
openDropdown: () => this.setState({ toDropdownOpen: true }),
closeDropdown: () => this.setState({ toDropdownOpen: false }),
2017-10-19 19:53:56 +02:00
onChange: this.handleToChange,
inError: Boolean(errors.to),
}),
]),
])
}
SendTransactionScreen.prototype.handleAmountChange = function (value) {
const amount = value
const { updateSendAmount, setMaxModeTo } = this.props
setMaxModeTo(false)
this.validateAmount(amount)
updateSendAmount(amount)
}
2017-10-26 18:43:12 +02:00
SendTransactionScreen.prototype.setAmountToMax = function () {
const {
from: { balance },
updateSendAmount,
updateSendErrors,
2017-10-30 19:07:30 +01:00
tokenBalance,
selectedToken,
gasTotal,
2017-10-26 18:43:12 +02:00
} = this.props
2017-10-30 19:07:30 +01:00
const { decimals } = selectedToken || {}
const multiplier = Math.pow(10, Number(decimals || 0))
2017-10-26 18:43:12 +02:00
2017-10-30 19:07:30 +01:00
const maxAmount = selectedToken
? multiplyCurrencies(tokenBalance, multiplier, {toNumericBase: 'hex'})
: subtractCurrencies(
ethUtil.addHexPrefix(balance),
ethUtil.addHexPrefix(gasTotal),
2017-10-30 19:07:30 +01:00
{ toNumericBase: 'hex' }
)
2017-10-26 18:43:12 +02:00
updateSendErrors({ amount: null })
2017-10-26 18:43:12 +02:00
updateSendAmount(maxAmount)
}
2017-10-17 22:13:20 +02:00
SendTransactionScreen.prototype.validateAmount = function (value) {
const {
from: { balance },
updateSendErrors,
amountConversionRate,
conversionRate,
primaryCurrency,
selectedToken,
gasTotal,
tokenBalance,
2017-10-17 22:13:20 +02:00
} = this.props
const { decimals } = selectedToken || {}
2017-10-17 22:13:20 +02:00
const amount = value
let amountError = null
let sufficientBalance = true
if (gasTotal) {
sufficientBalance = isBalanceSufficient({
amount: selectedToken ? '0x0' : amount,
gasTotal,
balance,
primaryCurrency,
amountConversionRate,
conversionRate,
})
}
const verifyTokenBalance = selectedToken && tokenBalance !== null
let sufficientTokens
if (verifyTokenBalance) {
sufficientTokens = isTokenBalanceSufficient({
tokenBalance,
amount,
decimals,
})
}
2017-10-17 22:13:20 +02:00
const amountLessThanZero = conversionGreaterThan(
{ value: 0, fromNumericBase: 'dec' },
{ value: amount, fromNumericBase: 'hex' },
)
if (conversionRate && !sufficientBalance) {
amountError = this.context.t('insufficientFunds')
} else if (verifyTokenBalance && !sufficientTokens) {
amountError = this.context.t('insufficientTokens')
2017-10-17 22:13:20 +02:00
} else if (amountLessThanZero) {
amountError = this.context.t('negativeETH')
2017-10-17 22:13:20 +02:00
}
updateSendErrors({ amount: amountError })
}
SendTransactionScreen.prototype.renderAmountRow = function () {
const {
selectedToken,
primaryCurrency = 'ETH',
convertedCurrency,
amountConversionRate,
2017-10-17 22:13:20 +02:00
errors,
amount,
setMaxModeTo,
maxModeOn,
gasTotal,
} = this.props
2017-11-08 17:44:48 +01:00
return h('div.send-v2__form-row', [
2017-11-09 23:23:10 +01:00
h('div.send-v2__form-label', [
2017-10-17 22:13:20 +02:00
'Amount:',
this.renderErrorMessage('amount'),
!errors.amount && gasTotal && h('div.send-v2__amount-max', {
2017-10-26 18:43:12 +02:00
onClick: (event) => {
event.preventDefault()
setMaxModeTo(true)
2017-10-26 18:43:12 +02:00
this.setAmountToMax()
},
}, [ !maxModeOn ? this.context.t('max') : '' ]),
2017-10-17 22:13:20 +02:00
]),
2017-10-19 19:53:56 +02:00
h('div.send-v2__form-field', [
h(CurrencyDisplay, {
inError: Boolean(errors.amount),
primaryCurrency,
convertedCurrency,
2017-10-21 03:26:18 +02:00
selectedToken,
2017-10-30 23:04:21 +01:00
value: amount || '0x0',
2017-10-19 19:53:56 +02:00
conversionRate: amountConversionRate,
handleChange: this.handleAmountChange,
}),
]),
])
}
SendTransactionScreen.prototype.renderGasRow = function () {
const {
conversionRate,
convertedCurrency,
showCustomizeGasModal,
gasTotal,
} = this.props
const { gasLoadingError } = this.state
return h('div.send-v2__form-row', [
h('div.send-v2__form-label', this.context.t('gasFee')),
2017-10-19 19:53:56 +02:00
h('div.send-v2__form-field', [
h(GasFeeDisplay, {
gasTotal,
conversionRate,
convertedCurrency,
2017-10-19 19:53:56 +02:00
onClick: showCustomizeGasModal,
gasLoadingError,
2017-10-19 19:53:56 +02:00
}),
2017-10-21 03:26:18 +02:00
]),
])
}
2017-10-06 12:30:45 +02:00
SendTransactionScreen.prototype.renderMemoRow = function () {
const { updateSendMemo, memo } = this.props
2017-10-06 12:30:45 +02:00
return h('div.send-v2__form-row', [
2017-10-06 12:30:45 +02:00
h('div.send-v2__form-label', 'Transaction Memo:'),
2017-10-06 12:30:45 +02:00
2017-10-19 19:53:56 +02:00
h('div.send-v2__form-field', [
h(MemoTextArea, {
memo,
onChange: (event) => updateSendMemo(event.target.value),
2017-10-21 03:26:18 +02:00
}),
2017-10-19 19:53:56 +02:00
]),
])
}
2017-10-09 18:25:23 +02:00
SendTransactionScreen.prototype.renderForm = function () {
2018-03-20 00:12:09 +01:00
return h('.page-container__content', {}, [
h('.send-v2__form', [
this.renderFromRow(),
2017-10-09 18:25:23 +02:00
2018-03-20 00:12:09 +01:00
this.renderToRow(),
2017-10-09 18:25:23 +02:00
2018-03-20 00:12:09 +01:00
this.renderAmountRow(),
2017-10-09 18:25:23 +02:00
2018-03-20 00:12:09 +01:00
this.renderGasRow(),
2017-10-09 18:25:23 +02:00
2018-03-20 00:12:09 +01:00
// this.renderMemoRow(),
2018-03-20 00:12:09 +01:00
]),
])
}
SendTransactionScreen.prototype.renderFooter = function () {
const {
clearSend,
gasTotal,
tokenBalance,
selectedToken,
2017-10-25 07:43:49 +02:00
errors: { amount: amountError, to: toError },
history,
} = this.props
2017-10-25 07:43:49 +02:00
const missingTokenBalance = selectedToken && (tokenBalance === null || tokenBalance === undefined)
2017-10-30 23:04:21 +01:00
const noErrors = !amountError && toError === null
return h('div.page-container__footer', [
2018-03-26 07:19:42 +02:00
h('button.btn-secondary--lg.page-container__footer-button', {
onClick: () => {
clearSend()
2018-04-02 11:59:49 +02:00
history.push(DEFAULT_ROUTE)
},
}, this.context.t('cancel')),
2018-03-26 07:19:42 +02:00
h('button.btn-primary--lg.page-container__footer-button', {
disabled: !noErrors || !gasTotal || missingTokenBalance,
2017-10-25 07:43:49 +02:00
onClick: event => this.onSubmit(event),
}, this.context.t('next')),
])
}
SendTransactionScreen.prototype.render = function () {
return (
h('div.page-container', [
2017-10-09 18:25:23 +02:00
this.renderHeader(),
2017-10-09 18:25:23 +02:00
this.renderForm(),
this.renderFooter(),
])
)
}
2017-10-12 19:29:03 +02:00
SendTransactionScreen.prototype.addToAddressBookIfNew = function (newAddress, nickname = '') {
const { toAccounts, addToAddressBook } = this.props
if (!toAccounts.find(({ address }) => newAddress === address)) {
// TODO: nickname, i.e. addToAddressBook(recipient, nickname)
addToAddressBook(newAddress, nickname)
}
}
SendTransactionScreen.prototype.getEditedTx = function () {
const {
from: {address: from},
to,
amount,
gasLimit: gas,
gasPrice,
selectedToken,
editingTransactionId,
unapprovedTxs,
} = this.props
const editingTx = {
...unapprovedTxs[editingTransactionId],
txParams: {
from: ethUtil.addHexPrefix(from),
gas: ethUtil.addHexPrefix(gas),
gasPrice: ethUtil.addHexPrefix(gasPrice),
},
}
if (selectedToken) {
const data = TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call(
ethAbi.rawEncode(['address', 'uint256'], [to, ethUtil.addHexPrefix(amount)]),
x => ('00' + x.toString(16)).slice(-2)
).join('')
Object.assign(editingTx.txParams, {
value: ethUtil.addHexPrefix('0'),
to: ethUtil.addHexPrefix(selectedToken.address),
data,
})
} else {
const { data } = unapprovedTxs[editingTransactionId].txParams
Object.assign(editingTx.txParams, {
value: ethUtil.addHexPrefix(amount),
to: ethUtil.addHexPrefix(to),
data,
})
if (typeof editingTx.txParams.data === 'undefined') {
delete editingTx.txParams.data
}
}
return editingTx
}
2017-10-12 19:29:03 +02:00
SendTransactionScreen.prototype.onSubmit = function (event) {
event.preventDefault()
const {
from: {address: from},
to: _to,
2017-10-12 19:29:03 +02:00
amount,
gasLimit: gas,
gasPrice,
signTokenTx,
signTx,
updateTx,
2017-10-12 19:29:03 +02:00
selectedToken,
2017-11-08 17:44:48 +01:00
editingTransactionId,
toNickname,
2017-10-25 07:43:49 +02:00
errors: { amount: amountError, to: toError },
2017-10-12 19:29:03 +02:00
} = this.props
2017-10-30 23:04:21 +01:00
const noErrors = !amountError && toError === null
2017-10-25 07:43:49 +02:00
if (!noErrors) {
return
}
const to = ethUtil.addHexPrefix(_to)
this.addToAddressBookIfNew(to, toNickname)
2017-11-08 17:44:48 +01:00
if (editingTransactionId) {
const editedTx = this.getEditedTx()
updateTx(editedTx)
} else {
2017-11-08 17:44:48 +01:00
const txParams = {
from,
value: '0',
gas,
gasPrice,
}
2017-10-12 19:29:03 +02:00
if (!selectedToken) {
txParams.value = amount
txParams.to = to
}
2017-10-12 19:29:03 +02:00
Object.keys(txParams).forEach(key => {
txParams[key] = ethUtil.addHexPrefix(txParams[key])
})
selectedToken
? signTokenTx(selectedToken.address, to, amount, txParams)
: signTx(txParams)
}
2018-02-01 23:13:08 +01:00
this.props.history.push(CONFIRM_TRANSACTION_ROUTE)
2017-10-12 19:29:03 +02:00
}