MyCrypto/common/components/BalanceSidebar/EquivalentValues.tsx

199 lines
6.1 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import BN from 'bn.js';
import translate from 'translations';
import { State } from 'reducers/rates';
import { rateSymbols, TFetchCCRates } from 'actions/rates';
import { TokenBalance } from 'selectors/wallet';
import { Balance } from 'libs/wallet';
import { ETH_DECIMAL, convertTokenBase } from 'libs/units';
import Spinner from 'components/ui/Spinner';
import UnitDisplay from 'components/ui/UnitDisplay';
import './EquivalentValues.scss';
const ALL_OPTION = 'All';
Migrate to Typescript (#224) * Refactor babel/types * Refactor entry point * Refactor actions * Refactor api * Full project refactor -- Broad type fixing sweep * - completely fix merge conflicts - handle various type errors * Add tslint to package.json * Dependency cleanup * Fix module resolution * Work on type definitions for untyped libs * progress commit * Add more definition typing * various type additions * Add unit types * Fix sagaiterator + unit types * various types added * additional type additions * Fix typing on Sagas * remove flowfixmes; swap translate for translateRaw * Get rid of contracts - awaiting Henry's contract PR * Remove contracts from routing * Fix most of actions/reducers * refactor actions directory structure * fix reducer action type imports * Fix most of type errors pre-actions refactor * fix action creator imports in containers * Refactor more * Refactor index of actions * fix action imports; use module level index export * package-lock.json updated * Use action types in props * Type up action creators * Fix most of connect errors * Typefixing progress * More types * Fix run-time errors * Caching improvements for webpack * Remove path resolve from webpack * Update non-breaking packages to latest version * Fix token typing * Remove unused color code * Fix wallet decrypt dispatch * Set redux-form related props/functions to ANY, since we're stripping it out later on * Revert BigNumber.js package changes * Extend window to custom object for Perf * Format Navigation * Typecase keystore errors as any (since we shouldnt touch this) * Push wallet context fix * - find/replace value->payload in swap - properly type swap state properties - extract inline reducer into reducer function * - type local storage retrieved items as generic * - bind all RPCClient methods with fat arrow * - reformat * Change to enums for constants * Change state into any * Fix swap errors * ensure that seconds are passed into state as integers * Fix rest of errors * use parseInt explicitly instead of type coercion * Fix derivation-checker, remove flow command, add tslint command, add tslint-react, tell travis to use tslint instead of flow. * Whoops, remove those tests. * Remove unsupported (yet) config option. * Fix precommit to target ts and tsx files. * Fix some errors, ignore some silly rules. * Revert jest to v19, use ts-jest and make all tests typescript. Fixes all but one. * Get rid of saga tests * Fix tslint errors
2017-09-24 19:06:28 -07:00
interface Props {
balance?: Balance;
tokenBalances?: TokenBalance[];
rates: State['rates'];
ratesError?: State['ratesError'];
fetchCCRates: TFetchCCRates;
Migrate to Typescript (#224) * Refactor babel/types * Refactor entry point * Refactor actions * Refactor api * Full project refactor -- Broad type fixing sweep * - completely fix merge conflicts - handle various type errors * Add tslint to package.json * Dependency cleanup * Fix module resolution * Work on type definitions for untyped libs * progress commit * Add more definition typing * various type additions * Add unit types * Fix sagaiterator + unit types * various types added * additional type additions * Fix typing on Sagas * remove flowfixmes; swap translate for translateRaw * Get rid of contracts - awaiting Henry's contract PR * Remove contracts from routing * Fix most of actions/reducers * refactor actions directory structure * fix reducer action type imports * Fix most of type errors pre-actions refactor * fix action creator imports in containers * Refactor more * Refactor index of actions * fix action imports; use module level index export * package-lock.json updated * Use action types in props * Type up action creators * Fix most of connect errors * Typefixing progress * More types * Fix run-time errors * Caching improvements for webpack * Remove path resolve from webpack * Update non-breaking packages to latest version * Fix token typing * Remove unused color code * Fix wallet decrypt dispatch * Set redux-form related props/functions to ANY, since we're stripping it out later on * Revert BigNumber.js package changes * Extend window to custom object for Perf * Format Navigation * Typecase keystore errors as any (since we shouldnt touch this) * Push wallet context fix * - find/replace value->payload in swap - properly type swap state properties - extract inline reducer into reducer function * - type local storage retrieved items as generic * - bind all RPCClient methods with fat arrow * - reformat * Change to enums for constants * Change state into any * Fix swap errors * ensure that seconds are passed into state as integers * Fix rest of errors * use parseInt explicitly instead of type coercion * Fix derivation-checker, remove flow command, add tslint command, add tslint-react, tell travis to use tslint instead of flow. * Whoops, remove those tests. * Remove unsupported (yet) config option. * Fix precommit to target ts and tsx files. * Fix some errors, ignore some silly rules. * Revert jest to v19, use ts-jest and make all tests typescript. Fixes all but one. * Get rid of saga tests * Fix tslint errors
2017-09-24 19:06:28 -07:00
}
interface CmpState {
currency: string;
}
export default class EquivalentValues extends React.Component<Props, CmpState> {
public state = {
currency: ALL_OPTION
};
private balanceLookup: { [key: string]: Balance['wei'] | undefined } = {};
private decimalLookup: { [key: string]: number } = {};
private requestedCurrencies: string[] | null = null;
public constructor(props) {
super(props);
this.makeBalanceLookup(props);
if (props.balance && props.tokenBalances) {
this.fetchRates(props);
}
}
public componentWillReceiveProps(nextProps) {
const { balance, tokenBalances } = this.props;
if (nextProps.balance !== balance || nextProps.tokenBalances !== tokenBalances) {
this.makeBalanceLookup(nextProps);
this.fetchRates(nextProps);
}
}
Migrate to Typescript (#224) * Refactor babel/types * Refactor entry point * Refactor actions * Refactor api * Full project refactor -- Broad type fixing sweep * - completely fix merge conflicts - handle various type errors * Add tslint to package.json * Dependency cleanup * Fix module resolution * Work on type definitions for untyped libs * progress commit * Add more definition typing * various type additions * Add unit types * Fix sagaiterator + unit types * various types added * additional type additions * Fix typing on Sagas * remove flowfixmes; swap translate for translateRaw * Get rid of contracts - awaiting Henry's contract PR * Remove contracts from routing * Fix most of actions/reducers * refactor actions directory structure * fix reducer action type imports * Fix most of type errors pre-actions refactor * fix action creator imports in containers * Refactor more * Refactor index of actions * fix action imports; use module level index export * package-lock.json updated * Use action types in props * Type up action creators * Fix most of connect errors * Typefixing progress * More types * Fix run-time errors * Caching improvements for webpack * Remove path resolve from webpack * Update non-breaking packages to latest version * Fix token typing * Remove unused color code * Fix wallet decrypt dispatch * Set redux-form related props/functions to ANY, since we're stripping it out later on * Revert BigNumber.js package changes * Extend window to custom object for Perf * Format Navigation * Typecase keystore errors as any (since we shouldnt touch this) * Push wallet context fix * - find/replace value->payload in swap - properly type swap state properties - extract inline reducer into reducer function * - type local storage retrieved items as generic * - bind all RPCClient methods with fat arrow * - reformat * Change to enums for constants * Change state into any * Fix swap errors * ensure that seconds are passed into state as integers * Fix rest of errors * use parseInt explicitly instead of type coercion * Fix derivation-checker, remove flow command, add tslint command, add tslint-react, tell travis to use tslint instead of flow. * Whoops, remove those tests. * Remove unsupported (yet) config option. * Fix precommit to target ts and tsx files. * Fix some errors, ignore some silly rules. * Revert jest to v19, use ts-jest and make all tests typescript. Fixes all but one. * Get rid of saga tests * Fix tslint errors
2017-09-24 19:06:28 -07:00
public render() {
const { balance, tokenBalances, rates, ratesError } = this.props;
const { currency } = this.state;
// There are a bunch of reasons why the incorrect balances might be rendered
// while we have incomplete data that's being fetched.
const isFetching =
!balance || balance.isPending || !tokenBalances || Object.keys(rates).length === 0;
let valuesEl;
if (!isFetching && (rates[currency] || currency === ALL_OPTION)) {
const values = this.getEquivalentValues(currency);
valuesEl = rateSymbols.map(key => {
if (!values[key] || key === currency) {
return null;
}
return (
<li className="EquivalentValues-values-currency" key={key}>
<span className="EquivalentValues-values-currency-label">{key}:</span>{' '}
<span className="EquivalentValues-values-currency-value">
<UnitDisplay unit={'ether'} value={values[key]} displayShortBalance={3} />
</span>
</li>
);
});
} else if (ratesError) {
valuesEl = <h5>{ratesError}</h5>;
} else if (tokenBalances && tokenBalances.length === 0) {
valuesEl = <h5>No tokens found!</h5>;
} else {
valuesEl = (
<div className="EquivalentValues-values-loader">
<Spinner size="x3" />
</div>
);
}
return (
<div className="EquivalentValues">
<h5 className="EquivalentValues-title">
{translate('sidebar_Equiv')} for{' '}
<select
className="EquivalentValues-title-symbol"
onChange={this.changeCurrency}
value={currency}
>
<option value={ALL_OPTION}>All Tokens</option>
<option value="ETH">ETH</option>
{tokenBalances &&
tokenBalances.map(tk => {
if (!tk.balance || tk.balance.isZero() || !rates[tk.symbol]) {
return;
Migrate to Typescript (#224) * Refactor babel/types * Refactor entry point * Refactor actions * Refactor api * Full project refactor -- Broad type fixing sweep * - completely fix merge conflicts - handle various type errors * Add tslint to package.json * Dependency cleanup * Fix module resolution * Work on type definitions for untyped libs * progress commit * Add more definition typing * various type additions * Add unit types * Fix sagaiterator + unit types * various types added * additional type additions * Fix typing on Sagas * remove flowfixmes; swap translate for translateRaw * Get rid of contracts - awaiting Henry's contract PR * Remove contracts from routing * Fix most of actions/reducers * refactor actions directory structure * fix reducer action type imports * Fix most of type errors pre-actions refactor * fix action creator imports in containers * Refactor more * Refactor index of actions * fix action imports; use module level index export * package-lock.json updated * Use action types in props * Type up action creators * Fix most of connect errors * Typefixing progress * More types * Fix run-time errors * Caching improvements for webpack * Remove path resolve from webpack * Update non-breaking packages to latest version * Fix token typing * Remove unused color code * Fix wallet decrypt dispatch * Set redux-form related props/functions to ANY, since we're stripping it out later on * Revert BigNumber.js package changes * Extend window to custom object for Perf * Format Navigation * Typecase keystore errors as any (since we shouldnt touch this) * Push wallet context fix * - find/replace value->payload in swap - properly type swap state properties - extract inline reducer into reducer function * - type local storage retrieved items as generic * - bind all RPCClient methods with fat arrow * - reformat * Change to enums for constants * Change state into any * Fix swap errors * ensure that seconds are passed into state as integers * Fix rest of errors * use parseInt explicitly instead of type coercion * Fix derivation-checker, remove flow command, add tslint command, add tslint-react, tell travis to use tslint instead of flow. * Whoops, remove those tests. * Remove unsupported (yet) config option. * Fix precommit to target ts and tsx files. * Fix some errors, ignore some silly rules. * Revert jest to v19, use ts-jest and make all tests typescript. Fixes all but one. * Get rid of saga tests * Fix tslint errors
2017-09-24 19:06:28 -07:00
}
const sym = tk.symbol;
return (
<option key={sym} value={sym}>
{sym}
</option>
);
})}
</select>
</h5>
<ul className="EquivalentValues-values">{valuesEl}</ul>
</div>
);
}
private changeCurrency = (ev: React.FormEvent<HTMLSelectElement>) => {
const currency = ev.currentTarget.value;
this.setState({ currency });
};
private makeBalanceLookup(props: Props) {
const tokenBalances = props.tokenBalances || [];
this.balanceLookup = tokenBalances.reduce(
(prev, tk) => {
// Piggy-back off of this reduce to add to decimal lookup
this.decimalLookup[tk.symbol] = tk.decimal;
prev[tk.symbol] = tk.balance;
return prev;
},
{ ETH: props.balance && props.balance.wei }
);
}
private fetchRates(props: Props) {
// Duck out if we haven't gotten balances yet
if (!props.balance || !props.tokenBalances) {
return;
}
// First determine which currencies we're asking for
const currencies = props.tokenBalances
.filter(tk => !tk.balance.isZero())
.map(tk => tk.symbol)
.sort();
// If it's the same currencies as we have, skip it
if (this.requestedCurrencies && currencies.join() === this.requestedCurrencies.join()) {
return;
}
// Fire off the request and save the currencies requested
this.props.fetchCCRates(currencies);
this.requestedCurrencies = currencies;
}
private getEquivalentValues(
currency: string
): {
[key: string]: BN | undefined;
} {
// Recursively call on all currencies
if (currency === ALL_OPTION) {
return ['ETH'].concat(this.requestedCurrencies || []).reduce(
(prev, curr) => {
const currValues = this.getEquivalentValues(curr);
rateSymbols.forEach(sym => (prev[sym] = prev[sym].add(currValues[sym] || new BN(0))));
return prev;
},
rateSymbols.reduce((prev, sym) => {
prev[sym] = new BN(0);
return prev;
}, {})
);
}
// Calculate rates for a single currency
const { rates } = this.props;
const balance = this.balanceLookup[currency];
if (!balance || !rates[currency]) {
return {};
}
// Tokens with non-ether like decimals need to be adjusted to match
const decimal =
this.decimalLookup[currency] === undefined ? ETH_DECIMAL : this.decimalLookup[currency];
const adjustedBalance = convertTokenBase(balance, decimal, ETH_DECIMAL);
return rateSymbols.reduce((prev, sym) => {
prev[sym] = adjustedBalance.muln(rates[currency][sym]);
return prev;
}, {});
}
}