aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/components/inputs/token_amount_input.tsx
blob: 93ef516cfc5398d63d803bde64ed43692ed2e70b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { colors } from '@0xproject/react-shared';
import { BigNumber } from '@0xproject/utils';
import { Web3Wrapper } from '@0xproject/web3-wrapper';
import * as _ from 'lodash';
import * as React from 'react';
import { Link } from 'react-router-dom';
import { Blockchain } from 'ts/blockchain';
import { BalanceBoundedInput } from 'ts/components/inputs/balance_bounded_input';
import { Token, ValidatedBigNumberCallback, WebsitePaths } from 'ts/types';

interface TokenAmountInputProps {
    userAddress: string;
    networkId: number;
    blockchain: Blockchain;
    token: Token;
    label?: string;
    amount?: BigNumber;
    hintText?: string;
    shouldShowIncompleteErrs: boolean;
    shouldCheckBalance: boolean;
    shouldCheckAllowance: boolean;
    onChange: ValidatedBigNumberCallback;
    onErrorMsgChange?: (errorMsg: React.ReactNode) => void;
    lastForceTokenStateRefetch: number;
    shouldShowErrs?: boolean;
    shouldShowUnderline?: boolean;
    style?: React.CSSProperties;
    labelStyle?: React.CSSProperties;
    inputHintStyle?: React.CSSProperties;
}

interface TokenAmountInputState {
    balance: BigNumber;
    allowance: BigNumber;
    isBalanceAndAllowanceLoaded: boolean;
}

const HEIGHT_WITH_LABEL = 84;
const HEIGHT_WITHOUT_LABEL = 62;

export class TokenAmountInput extends React.Component<TokenAmountInputProps, TokenAmountInputState> {
    public static defaultProps: Partial<TokenAmountInputProps> = {
        shouldShowErrs: true,
        shouldShowUnderline: true,
    };
    private _isUnmounted: boolean;
    constructor(props: TokenAmountInputProps) {
        super(props);
        this._isUnmounted = false;
        const defaultAmount = new BigNumber(0);
        this.state = {
            balance: defaultAmount,
            allowance: defaultAmount,
            isBalanceAndAllowanceLoaded: false,
        };
    }
    public componentWillMount(): void {
        // tslint:disable-next-line:no-floating-promises
        this._fetchBalanceAndAllowanceAsync(this.props.token.address, this.props.userAddress);
    }
    public componentWillUnmount(): void {
        this._isUnmounted = true;
    }
    public componentWillReceiveProps(nextProps: TokenAmountInputProps): void {
        if (
            nextProps.userAddress !== this.props.userAddress ||
            nextProps.networkId !== this.props.networkId ||
            nextProps.token.address !== this.props.token.address ||
            nextProps.lastForceTokenStateRefetch !== this.props.lastForceTokenStateRefetch
        ) {
            // tslint:disable-next-line:no-floating-promises
            this._fetchBalanceAndAllowanceAsync(nextProps.token.address, nextProps.userAddress);
        }
    }
    public render(): React.ReactNode {
        const amount = this.props.amount
            ? Web3Wrapper.toUnitAmount(this.props.amount, this.props.token.decimals)
            : undefined;
        return (
            <div className="flex overflow-hidden" style={this._getStyle()}>
                <BalanceBoundedInput
                    label={this.props.label}
                    amount={amount}
                    balance={Web3Wrapper.toUnitAmount(this.state.balance, this.props.token.decimals)}
                    onChange={this._onChange.bind(this)}
                    onErrorMsgChange={this.props.onErrorMsgChange}
                    validate={this._validate.bind(this)}
                    shouldCheckBalance={this.props.shouldCheckBalance}
                    shouldShowIncompleteErrs={this.props.shouldShowIncompleteErrs}
                    isDisabled={!this.state.isBalanceAndAllowanceLoaded}
                    hintText={this.props.hintText}
                    shouldShowErrs={this.props.shouldShowErrs}
                    shouldShowUnderline={this.props.shouldShowUnderline}
                    inputStyle={this.props.style}
                    inputHintStyle={this.props.inputHintStyle}
                />
                <div style={this._getLabelStyle()}>{this.props.token.symbol}</div>
            </div>
        );
    }
    private _onChange(isValid: boolean, amount?: BigNumber): void {
        let baseUnitAmount;
        if (!_.isUndefined(amount)) {
            baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amount, this.props.token.decimals);
        }
        this.props.onChange(isValid, baseUnitAmount);
    }
    private _validate(amount: BigNumber): React.ReactNode {
        if (this.props.shouldCheckAllowance && amount.gt(this.state.allowance)) {
            return (
                <span>
                    Insufficient allowance.{' '}
                    <Link
                        to={`${WebsitePaths.Portal}/balances`}
                        style={{ cursor: 'pointer', color: colors.darkestGrey }}
                    >
                        Set allowance
                    </Link>
                </span>
            );
        } else {
            return undefined;
        }
    }
    private async _fetchBalanceAndAllowanceAsync(tokenAddress: string, userAddress: string): Promise<void> {
        this.setState({
            isBalanceAndAllowanceLoaded: false,
        });
        const userAddressIfExists = _.isEmpty(userAddress) ? undefined : userAddress;
        const [balance, allowance] = await this.props.blockchain.getTokenBalanceAndAllowanceAsync(
            userAddressIfExists,
            tokenAddress,
        );
        if (!this._isUnmounted) {
            this.setState({
                balance,
                allowance,
                isBalanceAndAllowanceLoaded: true,
            });
        }
    }
    private _getStyle(): React.CSSProperties {
        const hasLabel = !_.isUndefined(this.props.label);
        return !_.isUndefined(this.props.style)
            ? this.props.style
            : { height: hasLabel ? HEIGHT_WITH_LABEL : HEIGHT_WITHOUT_LABEL };
    }
    private _getLabelStyle(): React.CSSProperties {
        const hasLabel = !_.isUndefined(this.props.label);
        return this.props.labelStyle || { paddingTop: hasLabel ? 39 : 14 };
    }
}