Equivalent Values Bugfixes (#870)
Update <EquivalentValues /> component Now works on non-ethereum networks Update dropdown with new <Select /> from react-select Calculates total value for all coins & tokens
This commit is contained in:
parent
e0c4599b64
commit
f9c1134a16
|
@ -1,14 +1,56 @@
|
|||
import { handleJSONResponse } from 'api/utils';
|
||||
interface IRateSymbols {
|
||||
symbols: {
|
||||
all: TAllSymbols;
|
||||
fiat: TFiatSymbols;
|
||||
coinAndToken: TCoinAndTokenSymbols;
|
||||
};
|
||||
isFiat: isFiat;
|
||||
}
|
||||
|
||||
export const rateSymbols: Symbols = ['USD', 'EUR', 'GBP', 'BTC', 'CHF', 'REP', 'ETH'];
|
||||
type isFiat = (rate: string) => boolean;
|
||||
|
||||
export type TAllSymbols = (keyof ISymbol)[];
|
||||
export type TFiatSymbols = (keyof IFiatSymbols)[];
|
||||
export type TCoinAndTokenSymbols = (keyof ICoinAndTokenSymbols)[];
|
||||
interface ISymbol {
|
||||
USD: number;
|
||||
EUR: number;
|
||||
GBP: number;
|
||||
CHF: number;
|
||||
BTC: number;
|
||||
ETH: number;
|
||||
REP: number;
|
||||
}
|
||||
interface IFiatSymbols {
|
||||
USD: number;
|
||||
EUR: number;
|
||||
GBP: number;
|
||||
CHF: number;
|
||||
}
|
||||
interface ICoinAndTokenSymbols {
|
||||
BTC: number;
|
||||
ETH: number;
|
||||
REP: number;
|
||||
}
|
||||
|
||||
const fiat: TFiatSymbols = ['USD', 'EUR', 'GBP', 'CHF'];
|
||||
const coinAndToken: TCoinAndTokenSymbols = ['BTC', 'ETH', 'REP'];
|
||||
export const rateSymbols: IRateSymbols = {
|
||||
symbols: {
|
||||
all: [...fiat, ...coinAndToken],
|
||||
fiat,
|
||||
coinAndToken
|
||||
},
|
||||
isFiat: (rate: string) => (fiat as string[]).includes(rate)
|
||||
};
|
||||
|
||||
export type Symbols = (keyof ISymbol)[];
|
||||
// TODO - internationalize
|
||||
const ERROR_MESSAGE = 'Could not fetch rate data.';
|
||||
const CCApi = 'https://min-api.cryptocompare.com';
|
||||
|
||||
const CCRates = (symbols: string[]) => {
|
||||
const tsyms = rateSymbols.concat(symbols as any).join(',');
|
||||
const tsyms = rateSymbols.symbols.all.concat(symbols as any).join(',');
|
||||
return `${CCApi}/data/price?fsym=ETH&tsyms=${tsyms}`;
|
||||
};
|
||||
|
||||
|
@ -16,16 +58,6 @@ export interface CCResponse {
|
|||
[symbol: string]: ISymbol;
|
||||
}
|
||||
|
||||
interface ISymbol {
|
||||
USD: number;
|
||||
EUR: number;
|
||||
GBP: number;
|
||||
BTC: number;
|
||||
CHF: number;
|
||||
REP: number;
|
||||
ETH: number;
|
||||
}
|
||||
|
||||
interface IRates extends ISymbol {
|
||||
Response?: 'Error';
|
||||
}
|
||||
|
@ -45,7 +77,7 @@ export const fetchRates = (symbols: string[] = []): Promise<CCResponse> =>
|
|||
return symbols.reduce(
|
||||
(eqRates, sym: keyof ISymbol) => {
|
||||
if (rates[sym]) {
|
||||
eqRates[sym] = rateSymbols.reduce(
|
||||
eqRates[sym] = rateSymbols.symbols.all.reduce(
|
||||
(symRates, rateSym) => {
|
||||
symRates[rateSym] = 1 / rates[sym] * rates[rateSym];
|
||||
return symRates;
|
||||
|
@ -60,10 +92,10 @@ export const fetchRates = (symbols: string[] = []): Promise<CCResponse> =>
|
|||
USD: rates.USD,
|
||||
EUR: rates.EUR,
|
||||
GBP: rates.GBP,
|
||||
BTC: rates.BTC,
|
||||
CHF: rates.CHF,
|
||||
REP: rates.REP,
|
||||
ETH: 1
|
||||
BTC: rates.BTC,
|
||||
ETH: 1,
|
||||
REP: rates.REP
|
||||
}
|
||||
} as CCResponse
|
||||
);
|
||||
|
|
|
@ -2,43 +2,44 @@
|
|||
@import 'common/sass/mixins';
|
||||
|
||||
.EquivalentValues {
|
||||
&-title {
|
||||
margin-top: 0;
|
||||
&-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: $space;
|
||||
|
||||
.Select {
|
||||
flex-grow: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.Spinner {
|
||||
display: block;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
&-title {
|
||||
margin: 0;
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
&-values {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
@include clearfix;
|
||||
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
&-currency {
|
||||
float: left;
|
||||
width: 50%;
|
||||
margin-bottom: $space-xs;
|
||||
|
||||
&:nth-child(odd) {
|
||||
padding-right: $space-sm;
|
||||
}
|
||||
&:nth-child(even) {
|
||||
padding-left: $space-sm;
|
||||
}
|
||||
|
||||
&-label {
|
||||
white-space: pre-wrap;
|
||||
display: inline-block;
|
||||
min-width: 36px;
|
||||
opacity: 0.54;
|
||||
margin-right: 8px;
|
||||
}
|
||||
&-value {
|
||||
font-weight: 600;
|
||||
@include mono;
|
||||
}
|
||||
}
|
||||
|
||||
&-loader {
|
||||
padding: 25px 0;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
&-offline {
|
||||
|
|
|
@ -1,177 +1,234 @@
|
|||
import * as React from 'react';
|
||||
import BN from 'bn.js';
|
||||
import React from 'react';
|
||||
import translate from 'translations';
|
||||
import { State } from 'reducers/rates';
|
||||
import { rateSymbols, TFetchCCRates } from 'actions/rates';
|
||||
import { UnitDisplay, Spinner } from 'components/ui';
|
||||
import Select from 'react-select';
|
||||
import { TFetchCCRates, rateSymbols } from 'actions/rates';
|
||||
import { chain, flatMap } from 'lodash';
|
||||
import { State as RatesState } from 'reducers/rates';
|
||||
import { TokenBalance } from 'selectors/wallet';
|
||||
import { Balance } from 'libs/wallet';
|
||||
import { NetworkConfig } from 'config';
|
||||
import { ETH_DECIMAL, convertTokenBase } from 'libs/units';
|
||||
import Spinner from 'components/ui/Spinner';
|
||||
import UnitDisplay from 'components/ui/UnitDisplay';
|
||||
import './EquivalentValues.scss';
|
||||
import { Wei } from 'libs/units';
|
||||
|
||||
const ALL_OPTION = 'All';
|
||||
interface AllValue {
|
||||
symbol: string;
|
||||
balance: Balance['wei'];
|
||||
}
|
||||
|
||||
interface DefaultOption {
|
||||
label: string;
|
||||
value: AllValue[];
|
||||
}
|
||||
|
||||
interface Option {
|
||||
label: string;
|
||||
value: Balance['wei'] | AllValue[];
|
||||
}
|
||||
|
||||
interface State {
|
||||
equivalentValues: Option;
|
||||
options: Option[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
balance?: Balance;
|
||||
tokenBalances?: TokenBalance[];
|
||||
rates: State['rates'];
|
||||
ratesError?: State['ratesError'];
|
||||
balance: Balance;
|
||||
tokenBalances: TokenBalance[];
|
||||
rates: RatesState['rates'];
|
||||
fetchCCRates: TFetchCCRates;
|
||||
ratesError: RatesState['ratesError'];
|
||||
network: NetworkConfig;
|
||||
isOffline: boolean;
|
||||
offline: boolean;
|
||||
}
|
||||
|
||||
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 } = {};
|
||||
class Equiv extends React.Component<Props, State> {
|
||||
private requestedCurrencies: string[] | null = null;
|
||||
|
||||
public constructor(props: Props) {
|
||||
super(props);
|
||||
this.makeBalanceLookup(props);
|
||||
const { balance, tokenBalances, network } = this.props;
|
||||
this.state = {
|
||||
equivalentValues: this.defaultOption(balance, tokenBalances, network),
|
||||
options: []
|
||||
};
|
||||
|
||||
if (props.balance && props.tokenBalances) {
|
||||
this.fetchRates(props);
|
||||
}
|
||||
}
|
||||
|
||||
public defaultOption(
|
||||
balance: Balance,
|
||||
tokenBalances: TokenBalance[],
|
||||
network: NetworkConfig
|
||||
): DefaultOption {
|
||||
return {
|
||||
label: 'All',
|
||||
value: [{ symbol: network.unit, balance: balance.wei }, ...tokenBalances]
|
||||
};
|
||||
}
|
||||
|
||||
public componentWillReceiveProps(nextProps: Props) {
|
||||
const { balance, tokenBalances, isOffline } = this.props;
|
||||
const { balance, tokenBalances, offline } = this.props;
|
||||
if (
|
||||
nextProps.balance !== balance ||
|
||||
nextProps.tokenBalances !== tokenBalances ||
|
||||
nextProps.isOffline !== isOffline
|
||||
nextProps.offline !== offline
|
||||
) {
|
||||
this.makeBalanceLookup(nextProps);
|
||||
const defaultOption = this.defaultOption(
|
||||
nextProps.balance,
|
||||
nextProps.tokenBalances,
|
||||
nextProps.network
|
||||
);
|
||||
const options: Option[] = [
|
||||
defaultOption,
|
||||
{ label: nextProps.network.unit, value: nextProps.balance.wei },
|
||||
...Object.values(nextProps.tokenBalances).map(token => {
|
||||
return { label: token.symbol, value: token.balance };
|
||||
})
|
||||
];
|
||||
const equivalentValues =
|
||||
options.find(opt => opt.label === this.state.equivalentValues.label) || defaultOption;
|
||||
this.setState({
|
||||
equivalentValues,
|
||||
options
|
||||
});
|
||||
this.fetchRates(nextProps);
|
||||
}
|
||||
}
|
||||
|
||||
public render() {
|
||||
const { balance, tokenBalances, rates, ratesError, isOffline, network } = this.props;
|
||||
const { currency } = this.state;
|
||||
public selectOption = equivalentValues => {
|
||||
this.setState({ equivalentValues });
|
||||
};
|
||||
|
||||
// There are a bunch of reasons why the incorrect balances might be rendered
|
||||
// while we have incomplete data that's being fetched.
|
||||
public render(): JSX.Element {
|
||||
const { balance, offline, tokenBalances, rates, network, ratesError } = this.props;
|
||||
const { equivalentValues, options } = this.state;
|
||||
const isFetching =
|
||||
!balance || balance.isPending || !tokenBalances || Object.keys(rates).length === 0;
|
||||
// Currency exists in rates or the all option is selected
|
||||
const rateExistsOrAll = rates[currency] || currency === ALL_OPTION;
|
||||
|
||||
let valuesEl;
|
||||
if (!isFetching && rateExistsOrAll && !network.isTestnet) {
|
||||
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}
|
||||
checkOffline={true}
|
||||
/>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
});
|
||||
} else if (network.isTestnet) {
|
||||
valuesEl = (
|
||||
<div className="text-center">
|
||||
<h5 style={{ color: 'red' }}>
|
||||
On test network, equivalent values will not be displayed.
|
||||
</h5>
|
||||
</div>
|
||||
);
|
||||
} 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>
|
||||
);
|
||||
}
|
||||
const Value = ({ rate, value }) => (
|
||||
<div className="EquivalentValues-values-currency">
|
||||
<span className="EquivalentValues-values-currency-label">{rate}</span>{' '}
|
||||
<span className="EquivalentValues-values-currency-value">
|
||||
<UnitDisplay
|
||||
unit={'ether'}
|
||||
value={value}
|
||||
displayShortBalance={rateSymbols.isFiat(rate) ? 2 : 3}
|
||||
checkOffline={true}
|
||||
/>
|
||||
</span>
|
||||
</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;
|
||||
}
|
||||
const sym = tk.symbol;
|
||||
return (
|
||||
<option key={sym} value={sym}>
|
||||
{sym}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</h5>
|
||||
<div className="EquivalentValues-header">
|
||||
<h5 className="EquivalentValues-title">{translate('sidebar_Equiv')}</h5>
|
||||
<Select
|
||||
name="equivalentValues"
|
||||
// TODO: Update type
|
||||
value={equivalentValues as any}
|
||||
options={options as any}
|
||||
onChange={this.selectOption}
|
||||
clearable={false}
|
||||
searchable={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isOffline ? (
|
||||
{offline ? (
|
||||
<div className="EquivalentValues-offline well well-sm">
|
||||
Equivalent values are unavailable offline
|
||||
</div>
|
||||
) : network.isTestnet ? (
|
||||
<div className="text-center">
|
||||
<h5 style={{ color: 'red' }}>
|
||||
On test network, equivalent values will not be displayed.
|
||||
</h5>
|
||||
</div>
|
||||
) : ratesError ? (
|
||||
<h5>{ratesError}</h5>
|
||||
) : isFetching ? (
|
||||
<Spinner size="x2" />
|
||||
) : (
|
||||
<ul className="EquivalentValues-values">{valuesEl}</ul>
|
||||
<div className="EquivalentValues-values">
|
||||
{this.generateValues(equivalentValues.label, equivalentValues.value).map((equiv, i) => (
|
||||
<Value rate={equiv.rate} value={equiv.value} key={i} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
private changeCurrency = (ev: React.FormEvent<HTMLSelectElement>) => {
|
||||
const currency = ev.currentTarget.value;
|
||||
this.setState({ currency });
|
||||
// return the sum of all equivalent values (unit * rate * balance) grouped by rate (USD, EUR, ETH, etc...)
|
||||
private handleAllValues = (balance: AllValue[]) => {
|
||||
const { rates } = this.props;
|
||||
const allRates = Object.values(balance).map(
|
||||
value => !!rates[value.symbol] && rates[value.symbol]
|
||||
);
|
||||
const allEquivalentValues = allRates.map((rateType, i) => {
|
||||
return {
|
||||
symbol: Object.keys(rates)[i],
|
||||
equivalentValues: [
|
||||
...Object.keys(rateType).map(rate => {
|
||||
const balanceIndex: AllValue = balance[i];
|
||||
const value =
|
||||
balanceIndex && !!balanceIndex.balance
|
||||
? balanceIndex.balance.muln(rateType[rate])
|
||||
: null;
|
||||
return { rate, value };
|
||||
})
|
||||
]
|
||||
};
|
||||
});
|
||||
// flatten all equivalent values for each unit (ETH, ETC, OMG, etc...) into an array
|
||||
const collection = flatMap([
|
||||
...Object.values(allEquivalentValues).map(v => v.equivalentValues)
|
||||
]);
|
||||
// group equivalent values by rate (USD, EUR, etc...)
|
||||
const groupedCollection = chain(collection)
|
||||
.groupBy('rate')
|
||||
.mapValues(v => Object.values(v).map(s => s.value))
|
||||
.value();
|
||||
// finally, add all the equivalent values together and return an array of objects with the sum of equivalent values for each rate
|
||||
return Object.values(groupedCollection).map((v, i) => {
|
||||
return {
|
||||
rate: Object.keys(groupedCollection)[i],
|
||||
value: v.reduce((acc, curr) => acc && curr && acc.add(curr))
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
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 }
|
||||
);
|
||||
// return equivalent value (unit * rate * balance)
|
||||
private handleValues(unit: string, balance: Balance['wei']) {
|
||||
const { rates } = this.props;
|
||||
const ratesObj = { ...rates[unit] };
|
||||
return Object.keys(ratesObj).map(key => {
|
||||
const value = (balance as Wei).muln(ratesObj[key]);
|
||||
return { rate: key, value };
|
||||
});
|
||||
}
|
||||
|
||||
private generateValues = (
|
||||
unit: string,
|
||||
balance: Balance['wei'] | AllValue[]
|
||||
): { rate: string; value: Balance['wei'] }[] => {
|
||||
if (unit === 'All') {
|
||||
return this.handleAllValues(balance as AllValue[]);
|
||||
} else {
|
||||
return this.handleValues(unit, balance as Balance['wei']);
|
||||
}
|
||||
};
|
||||
|
||||
private fetchRates(props: Props) {
|
||||
const { balance, tokenBalances, offline, fetchCCRates } = props;
|
||||
// Duck out if we haven't gotten balances yet, or we're not going to
|
||||
if (!props.balance || !props.tokenBalances || props.isOffline) {
|
||||
if (!balance || !tokenBalances || offline) {
|
||||
return;
|
||||
}
|
||||
|
||||
// First determine which currencies we're asking for
|
||||
const currencies = props.tokenBalances
|
||||
const currencies = tokenBalances
|
||||
.filter(tk => !tk.balance.isZero())
|
||||
.map(tk => tk.symbol)
|
||||
.sort();
|
||||
|
@ -182,45 +239,9 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
|
|||
}
|
||||
|
||||
// Fire off the request and save the currencies requested
|
||||
this.props.fetchCCRates(currencies);
|
||||
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;
|
||||
}, {});
|
||||
}
|
||||
}
|
||||
|
||||
export default Equiv;
|
||||
|
|
|
@ -7,9 +7,9 @@ import { AppState } from 'reducers';
|
|||
import { getNetworkConfig } from 'selectors/config';
|
||||
import { getShownTokenBalances, getWalletInst, TokenBalance } from 'selectors/wallet';
|
||||
import AccountInfo from './AccountInfo';
|
||||
import EquivalentValues from './EquivalentValues';
|
||||
import Promos from './Promos';
|
||||
import TokenBalances from './TokenBalances';
|
||||
import EquivalentValues from 'components/BalanceSidebar/EquivalentValues';
|
||||
|
||||
interface Props {
|
||||
wallet: IWallet;
|
||||
|
@ -54,13 +54,13 @@ export class BalanceSidebar extends React.Component<Props, {}> {
|
|||
name: 'Equivalent Values',
|
||||
content: (
|
||||
<EquivalentValues
|
||||
network={network}
|
||||
balance={balance}
|
||||
tokenBalances={tokenBalances}
|
||||
offline={isOffline}
|
||||
rates={rates}
|
||||
balance={balance}
|
||||
network={network}
|
||||
tokenBalances={tokenBalances}
|
||||
ratesError={ratesError}
|
||||
fetchCCRates={this.props.fetchCCRates}
|
||||
isOffline={isOffline}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue