Newer
Older
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
//
import BigNumber from 'bignumber.js';
import { Clickable, Form as FetherForm, Header } from 'fether-ui';
import { chainId$, withoutLoading } from '@parity/light.js';
import debounce from 'debounce-promise';
import { Field, Form } from 'react-final-form';
import { fromWei, toWei } from '@parity/api/lib/util/wei';
import { inject, observer } from 'mobx-react';
import { isAddress } from '@parity/api/lib/util/address';
import light from '@parity/light.js-react';
import { OnChange } from 'react-final-form-listeners';
import { estimateGas } from '../../utils/transaction';
Luke Schoen
committed
import RequireHealthOverlay from '../../RequireHealthOverlay';
import TokenBalance from '../../Tokens/TokensList/TokenBalance';
import TxDetails from './TxDetails';
import withAccount from '../../utils/withAccount';
import withBalance, { withEthBalance } from '../../utils/withBalance';
import withTokens from '../../utils/withTokens';
const DEFAULT_AMOUNT_MAX_CHARS = 9;
const MEDIUM_AMOUNT_MAX_CHARS = 14;
const MAX_GAS_PRICE = 40; // In Gwei
const MIN_GAS_PRICE = 3; // Safelow gas price from GasStation, in Gwei
@withProps(({ match: { params: { tokenAddress } }, tokens }) => ({
token: tokens[tokenAddress]
@light({
chainId: () => chainId$().pipe(withoutLoading())
})
@withBalance // Balance of current token (can be ETH)
@withEthBalance // ETH balance
class TxForm extends Component {
Luke Schoen
committed
state = {
Luke Schoen
committed
maxSelected: false,
showDetails: false
Luke Schoen
committed
};
decorator = createDecorator({
field: /to|amount/, // when the value of these fields change...
updates: {
// ...set field "gas"
Luke Schoen
committed
gas: async (value, allValues) => {
const { parityStore, token } = this.props;
Luke Schoen
committed
let newGasEstimate = null;
Luke Schoen
committed
try {
newGasEstimate = await estimateGas(
allValues,
token,
parityStore.api
);
} catch (error) {
console.error(error);
throw new Error('Unable to estimate gas');
}
Luke Schoen
committed
return newGasEstimate;
changeAmountFontSize = amount => {
const amountLen = amount.toString().length;
if (amountLen > MEDIUM_AMOUNT_MAX_CHARS) {
return '-resize-font-small'; // Resize to fit an amount as small as one Wei
} else if (
MEDIUM_AMOUNT_MAX_CHARS >= amountLen &&
amountLen > DEFAULT_AMOUNT_MAX_CHARS
) {
return '-resize-font-medium';
}
return '-resize-font-default';
};
calculateMax = (gas, gasPrice) => {
const { token, balance } = this.props;
const gasBn = gas ? new BigNumber(gas) : new BigNumber(21000);
const gasPriceBn = new BigNumber(gasPrice);
if (token.address === 'ETH') {
output = fromWei(
toWei(balance).minus(gasBn.multipliedBy(toWei(gasPriceBn, 'shannon')))
output = output.isNegative() ? new BigNumber(0) : output;
} else {
output = balance;
}
return output;
};
Luke Schoen
committed
estimatedTxFee = values => {
if (
!values.amount ||
!values.gas ||
!values.gasPrice ||
isNaN(values.amount) ||
isNaN(values.gas) ||
isNaN(values.gasPrice)
) {
return null;
}
return values.gas.multipliedBy(toWei(values.gasPrice, 'shannon'));
};
handleSubmit = values => {
const {
account: { address, type, transactionCount },
chainId,
history,
sendStore,
token
} = this.props;
if (!chainId) {
throw new Error('chaindId is required for an EthereumTx');
}
if (!address) {
throw new Error('address of an account is required');
}
if (!transactionCount) {
throw new Error('transactionCount is required for an EthereumTx');
}
if (!token || !token.address || !token.decimals) {
throw new Error('token information is required for an EthereumTx');
}
sendStore.setTx({ ...values, chainId, token, transactionCount });
if (type === 'signer') {
history.push(`/send/${token.address}/from/${address}/txqrcode`);
} else {
history.push(`/send/${token.address}/from/${address}/unlock`);
}
};
recalculateMax = (args, state, { changeValue }) => {
changeValue(state, 'amount', value => {
return this.calculateMax(
state.formState.values.gas,
state.formState.values.gasPrice
);
});
};
toggleMax = () => {
this.setState({ maxSelected: !this.state.maxSelected });
Luke Schoen
committed
showDetailsAnchor = () => {
return (
<span className='toggle-details'>
<Clickable onClick={this.toggleDetails}>↓ Details</Clickable>
Luke Schoen
committed
</span>
);
};
showHideAnchor = () => {
return (
<span className='toggle-details'>
<Clickable onClick={this.toggleDetails}>↑ Hide</Clickable>
Luke Schoen
committed
</span>
);
};
toggleDetails = () => {
const { showDetails } = this.state;
this.setState({ showDetails: !showDetails });
};
Luke Schoen
committed
const { showDetails } = this.state;
<Link to={`/tokens/${address}`} className='icon -back'>
title={token && <h1>Send {token.name}</h1>}
Luke Schoen
committed
<RequireHealthOverlay require='sync'>
<div className='window_content'>
<div className='box -padded'>
<TokenBalance
decimals={6}
drawers={[
<Form
key='txForm'
initialValues={{ from: address, gasPrice: 4, ...tx }}
onSubmit={this.handleSubmit}
validate={this.validateForm}
decorators={[this.decorator]}
mutators={{ recalculateMax: this.recalculateMax }}
render={({
handleSubmit,
valid,
validating,
values,
form: { mutators }
}) => (
<form className='send-form' onSubmit={handleSubmit}>
<fieldset className='form_fields'>
<Field
as='textarea'
autoFocus
className='-sm'
label='To'
name='to'
placeholder='0x...'
required
render={FetherForm.Field}
/>
className={`form_field_amount ${
!values.amount
? '-resize-font-default'
: this.changeAmountFontSize(values.amount)
}`}
disabled={this.state.maxSelected}
formNoValidate
label='Amount'
name='amount'
placeholder='0.00'
render={FetherForm.Field}
required
<button
type='button'
className={
this.state.maxSelected
? 'button -tiny active max'
: 'button -tiny max'
<Field
centerText={`${values.gasPrice} GWEI`}
className='-range'
label='Transaction Speed'
max={MAX_GAS_PRICE}
min={MIN_GAS_PRICE}
name='gasPrice'
render={FetherForm.Slider}
required
step={0.5}
type='range' // In Gwei
/>
<TxDetails
estimatedTxFee={this.estimatedTxFee(values)}
showDetails={showDetails}
token={token}
values={values}
/>
Luke Schoen
committed
<OnChange name='gasPrice'>
{(value, previous) => {
if (this.state.maxSelected) {
<span>
<h3>WARNING:</h3>
<p>
The sender and receiver addresses are the same.
</p>
</span>
</fieldset>
<nav className='form-nav'>
<div className='form-details-buttons'>
{showDetails
? this.showHideAnchor()
: this.showDetailsAnchor()}
</div>
<button
disabled={!valid || validating}
className='button'
>
{validating
? 'Checking...'
: type === 'signer'
? 'Scan'
: 'Send'}
</button>
</nav>
</form>
)}
/>
]}
onClick={null} // To disable cursor:pointer on card // TODO Can this be done better?
token={token}
/>
</div>
Luke Schoen
committed
</RequireHealthOverlay>
Luke Schoen
committed
if (!values) {
return;
}
if (!values.amount) {
}
const amountBn = new BigNumber(values.amount.toString());
if (amountBn.isNaN()) {
return { amount: 'Please enter a valid amount' };
} else if (amountBn.isZero()) {
if (this.state.maxSelected) {
return { amount: 'ETH balance too low to pay for gas.' };
}
return { amount: 'Please enter a non-zero amount' };
} else if (amountBn.isNegative()) {
Luke Schoen
committed
return { amount: 'Please enter a positive amount' };
} else if (token.address === 'ETH' && toWei(values.amount).lt(1)) {
Luke Schoen
committed
return { amount: 'Please enter at least 1 Wei' };
} else if (amountBn.dp() > token.decimals) {
Luke Schoen
committed
return {
amount: `Please enter a ${token.name} value of less than ${
Luke Schoen
committed
token.decimals
} decimal places`
};
} else if (balance && balance.lt(amountBn)) {
return { amount: `You don't have enough ${token.symbol} balance` };
} else if (!values.to || !isAddress(values.to)) {
return { to: 'Please enter a valid Ethereum address' };
Luke Schoen
committed
} else if (values.to === '0x0000000000000000000000000000000000000000') {
return {
to: `You are not permitted to send ${
token.name
} to the zero account (0x0)`
};
/**
* Estimate gas amount, and validate that the user has enough balance to make
* the tx.
*/
validateForm = debounce(values => {
Luke Schoen
committed
if (!values) {
return;
}
Luke Schoen
committed
if (!ethBalance) {
throw new Error('No "ethBalance"');
}
// If the gas hasn't been calculated yet, then we don't show any errors,
// just wait a bit more
Luke Schoen
committed
if (!this.estimatedTxFee(values)) {
// Verify that `gas + (eth amount if sending eth) <= ethBalance`
this.estimatedTxFee(values)
.plus(token.address === 'ETH' ? toWei(values.amount) : 0)
? { amount: 'ETH balance too low to pay for gas' }
amount: 'Failed estimating balance, please try again'