Skip to content
TxForm.js 5.81 KiB
Newer Older
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
// This file is part of Parity.
//
Amaury Martiny's avatar
Amaury Martiny committed
// SPDX-License-Identifier: BSD-3-Clause
Amaury Martiny's avatar
Amaury Martiny committed
import React, { Component } from 'react';
import debounce from 'debounce-promise';
import { Field, Form } from 'react-final-form';
import { Form as FetherForm, Header } from 'fether-ui';
import { inject, observer } from 'mobx-react';
import { isAddress } from '@parity/api/lib/util/address';
import { Link } from 'react-router-dom';
import { toWei } from '@parity/api/lib/util/wei';
import { withProps } from 'recompose';

import { estimateGas } from '../../utils/estimateGas';
import TokenBalance from '../../Tokens/TokensList/TokenBalance';
import withAccount from '../../utils/withAccount.js';
import withBalance, { withEthBalance } from '../../utils/withBalance';
Amaury Martiny's avatar
Amaury Martiny committed
import withTokens from '../../utils/withTokens';
Amaury Martiny's avatar
Amaury Martiny committed
const MAX_GAS_PRICE = 40; // In Gwei
const MIN_GAS_PRICE = 3; // Safelow gas price from GasStation, in Gwei

Amaury Martiny's avatar
Amaury Martiny committed
@inject('parityStore', 'sendStore')
Amaury Martiny's avatar
Amaury Martiny committed
@withTokens
Axel Chalon's avatar
Axel Chalon committed
@withProps(({ match: { params: { tokenAddress } }, tokens }) => ({
  token: tokens[tokenAddress]
@withAccount
@withBalance // Balance of current token (can be ETH)
@withEthBalance // ETH balance
@observer
class Send extends Component {
  handleSubmit = values => {
Axel Chalon's avatar
Axel Chalon committed
    const { accountAddress, history, sendStore, token } = this.props;
    sendStore.setTx(values);
    history.push(`/send/${token.address}/from/${accountAddress}/signer`);
Amaury Martiny's avatar
Amaury Martiny committed
  render () {
      accountAddress,
      sendStore: { tx },
      token
    } = this.props;

    return (
Amaury Martiny's avatar
Amaury Martiny committed
      <div>
        <Header
          left={
Amaury Martiny's avatar
Amaury Martiny committed
            <Link to={`/tokens/${accountAddress}`} className='icon -close'>
Amaury Martiny's avatar
Amaury Martiny committed
              Close
            </Link>
          title={token && <h1>Send {token.name}</h1>}
Amaury Martiny's avatar
Amaury Martiny committed
        <div className='window_content'>
          <div className='box -padded'>
            <TokenBalance
              decimals={6}
              drawers={[
Amaury Martiny's avatar
Amaury Martiny committed
                  key='txForm'
                  initialValues={{ from: accountAddress, gasPrice: 4, ...tx }}
                  onSubmit={this.handleSubmit}
                  validate={this.validateForm}
                  render={({ handleSubmit, valid, validating, values }) => (
Amaury Martiny's avatar
Amaury Martiny committed
                    <form className='send-form' onSubmit={handleSubmit}>
                      <fieldset className='form_fields'>
Amaury Martiny's avatar
Amaury Martiny committed
                          className='form_field_amount'
                          formNoValidate
Amaury Martiny's avatar
Amaury Martiny committed
                          label='Amount'
                          name='amount'
                          placeholder='0.00'
                          render={FetherForm.Field}
                          required
Amaury Martiny's avatar
Amaury Martiny committed
                          type='number' // In ETH or coin
Amaury Martiny's avatar
Amaury Martiny committed
                          as='textarea'
                          className='-sm'
                          label='To'
                          name='to'
                          placeholder='0x...'
                          required
                          render={FetherForm.Field}
                        />

                        <Field
                          centerText={`${values.gasPrice} GWEI`}
Amaury Martiny's avatar
Amaury Martiny committed
                          className='-range'
                          label='Transaction Fee'
                          leftText='Slow'
                          max={MAX_GAS_PRICE}
                          min={MIN_GAS_PRICE}
Amaury Martiny's avatar
Amaury Martiny committed
                          name='gasPrice'
                          render={FetherForm.Slider}
                          required
Amaury Martiny's avatar
Amaury Martiny committed
                          rightText='Fast'
Amaury Martiny's avatar
Amaury Martiny committed
                          type='range' // In Gwei
Amaury Martiny's avatar
Amaury Martiny committed
                      <nav className='form-nav'>
                        <button
                          disabled={!valid || validating}
Amaury Martiny's avatar
Amaury Martiny committed
                          className='button'
Amaury Martiny's avatar
Amaury Martiny committed
                          {validating ? 'Checking...' : 'Send'}
              onClick={null} // To disable cursor:pointer on card // TODO Can this be done better?
              token={token}
            />
Amaury Martiny's avatar
Amaury Martiny committed
          </div>

  /**
   * Estimate gas amount, and validate that the user has enough balance to make
   * the tx.
   */
  validateAmount = debounce(async values => {
      const { balance, ethBalance, parityStore, token } = this.props;
Amaury Martiny's avatar
Amaury Martiny committed
      const amount = +values.amount;

      if (!amount || isNaN(amount)) {
Amaury Martiny's avatar
Amaury Martiny committed
        return { amount: 'Please enter a valid amount' };
Amaury Martiny's avatar
Amaury Martiny committed
      } else if (amount < 0) {
Amaury Martiny's avatar
Amaury Martiny committed
        return { amount: 'Please enter a positive amount ' };
Amaury Martiny's avatar
Amaury Martiny committed
      } else if (balance && balance.lt(amount)) {
Amaury Martiny's avatar
Amaury Martiny committed
        return { amount: `You don't have enough ${token.symbol} balance` };
Amaury Martiny's avatar
Amaury Martiny committed
      const estimated = await estimateGas(values, token, parityStore.api);
      if (!ethBalance || isNaN(estimated)) {
        throw new Error('No "ethBalance" or "estimated" value.');
Amaury Martiny's avatar
Amaury Martiny committed
      // Verify that `gas + (eth amount if sending eth) <= ethBalance`
Amaury Martiny's avatar
Amaury Martiny committed
        estimated
Amaury Martiny's avatar
Amaury Martiny committed
          .mul(toWei(values.gasPrice, 'shannon'))
          .plus(token.address === 'ETH' ? toWei(values.amount) : 0)
Amaury Martiny's avatar
Amaury Martiny committed
          .gt(toWei(ethBalance))
Amaury Martiny's avatar
Amaury Martiny committed
        return { amount: "You don't have enough ETH balance" };
      }
    } catch (err) {
      return {
Amaury Martiny's avatar
Amaury Martiny committed
        amount: 'Failed estimating balance, please try again'
      };
    }
  }, 1000);

  validateForm = values => {
    const errors = {};
    if (!isAddress(values.to)) {
Amaury Martiny's avatar
Amaury Martiny committed
      errors.to = 'Please enter a valid Ethereum address';
    return Object.keys(errors).length ? errors : this.validateAmount(values);
}

export default Send;