Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Equivalent values for all tokens (ETH + ERC20s) #420

Merged
merged 4 commits into from
Nov 18, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions common/actions/rates/actionCreators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { TypeKeys } from './constants';
import { fetchRates } from './actionPayloads';

export type TFetchCCRates = typeof fetchCCRates;
export function fetchCCRates(symbol: string): interfaces.FetchCCRates {
export function fetchCCRates(symbols: string[] = []): interfaces.FetchCCRates {
return {
type: TypeKeys.RATES_FETCH_CC,
payload: fetchRates(symbol)
payload: fetchRates(symbols)
};
}
45 changes: 33 additions & 12 deletions common/actions/rates/actionPayloads.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,52 @@
import { handleJSONResponse } from 'api/utils';

export const rateSymbols = ['USD', 'EUR', 'GBP', 'BTC', 'CHF', 'REP', 'ETH'];
const rateSymbolsArg = rateSymbols.join(',');
// TODO - internationalize
const ERROR_MESSAGE = 'Could not fetch rate data.';
const CCApi = 'https://min-api.cryptocompare.com';

const CCRates = (symbol: string) => {
return `${CCApi}/data/price?fsym=${symbol}&tsyms=${rateSymbolsArg}`;
const CCRates = (symbols: string[]) => {
const tsyms = rateSymbols.concat(symbols).join(',');
return `${CCApi}/data/price?fsym=ETH&tsyms=${tsyms}`;
};

export interface CCResponse {
symbol: string;
rates: {
BTC: number;
[symbol: string]: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should break the rates reducer test recently merged into develop.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed!

USD: number;
EUR: number;
GBP: number;
BTC: number;
CHF: number;
REP: number;
ETH: number;
};
}

export const fetchRates = (symbol: string): Promise<CCResponse> =>
fetch(CCRates(symbol))
export const fetchRates = (symbols: string[] = []): Promise<CCResponse> =>
fetch(CCRates(symbols))
.then(response => handleJSONResponse(response, ERROR_MESSAGE))
.then(rates => ({
symbol,
rates
}));
.then(rates => {
// All currencies are in ETH right now. We'll do token -> eth -> value to
// do it all in one request
// to their respective rates via ETH.
return symbols.reduce(
(eqRates, sym) => {
eqRates[sym] = rateSymbols.reduce((symRates, rateSym) => {
symRates[rateSym] = 1 / rates[sym] * rates[rateSym];
return symRates;
}, {});
return eqRates;
},
{
ETH: {
USD: rates.USD,
EUR: rates.EUR,
GBP: rates.GBP,
BTC: rates.BTC,
CHF: rates.CHF,
REP: rates.REP,
ETH: 1
}
}
);
});
106 changes: 81 additions & 25 deletions common/components/BalanceSidebar/EquivalentValues.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
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';
Expand All @@ -8,6 +9,8 @@ import Spinner from 'components/ui/Spinner';
import UnitDisplay from 'components/ui/UnitDisplay';
import './EquivalentValues.scss';

const ALL_OPTION = 'All';

interface Props {
balance?: Balance;
tokenBalances?: TokenBalance[];
Expand All @@ -22,17 +25,18 @@ interface CmpState {

export default class EquivalentValues extends React.Component<Props, CmpState> {
public state = {
currency: 'ETH'
currency: ALL_OPTION
};
private balanceLookup = {};
private balanceLookup: { [key: string]: Balance['wei'] | undefined } = {};
private requestedCurrencies: string[] = [];

public constructor(props) {
super(props);
this.makeBalanceLookup(props);
}

public componentDidMount() {
this.props.fetchCCRates(this.state.currency);
if (props.balance && props.tokenBalances) {
this.fetchRates(props);
}
}

public componentWillReceiveProps(nextProps) {
Expand All @@ -42,18 +46,19 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
nextProps.tokenBalances !== tokenBalances
) {
this.makeBalanceLookup(nextProps);
this.fetchRates(nextProps);
}
}

public render() {
const { tokenBalances, rates, ratesError } = this.props;
const { currency } = this.state;
const balance = this.balanceLookup[currency];

let values;
if (balance && rates && rates[currency]) {
values = rateSymbols.map(key => {
if (!rates[currency][key] || key === currency) {
let valuesEl;
if (rates && (rates[currency] || currency === ALL_OPTION)) {
const values = this.getEquivalentValues(currency);
valuesEl = rateSymbols.map(key => {
if (!values[key] || key === currency) {
return null;
}

Expand All @@ -63,23 +68,19 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
{key}:
</span>{' '}
<span className="EquivalentValues-values-currency-value">
{balance.isPending ? (
<Spinner />
) : (
<UnitDisplay
unit={'ether'}
value={balance ? balance.muln(rates[currency][key]) : null}
displayShortBalance={2}
/>
)}
<UnitDisplay
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why get rid of the spinner?

Copy link
Contributor Author

@wbobeirne wbobeirne Nov 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spinner should never happen; It was replaced with the one large spinner on line 83.

Redacted, good call, that doesn't seem to be working.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Un-redacted, this is fixed.

unit={'ether'}
value={values[key]}
displayShortBalance={3}
Copy link
Contributor

@skubakdj skubakdj Nov 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we up this to 5? Low-value accounts (~$1) currently get rounded out to 0 BTC in the equiv values display.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was talking to henry about this, I think we need to have UnitDisplay show < 0.001 when the value is below the threshold, but above 0.

/>
</span>
</li>
);
});
} else if (ratesError) {
values = <h5>{ratesError}</h5>;
valuesEl = <h5>{ratesError}</h5>;
} else {
values = (
valuesEl = (
<div className="EquivalentValues-values-loader">
<Spinner size="x3" />
</div>
Expand All @@ -95,6 +96,7 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
onChange={this.changeCurrency}
value={currency}
>
<option value={ALL_OPTION}>All Tokens</option>
<option value="ETH">ETH</option>
{tokenBalances &&
tokenBalances.map(tk => {
Expand All @@ -111,17 +113,14 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
</select>
</h5>

<ul className="EquivalentValues-values">{values}</ul>
<ul className="EquivalentValues-values">{valuesEl}</ul>
</div>
);
}

private changeCurrency = (ev: React.FormEvent<HTMLSelectElement>) => {
const currency = ev.currentTarget.value;
this.setState({ currency });
if (!this.props.rates || !this.props.rates[currency]) {
this.props.fetchCCRates(currency);
}
};

private makeBalanceLookup(props: Props) {
Expand All @@ -136,4 +135,61 @@ export default class EquivalentValues extends React.Component<Props, CmpState> {
{ 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 (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 {};
}

return rateSymbols.reduce((prev, sym) => {
prev[sym] = balance ? balance.muln(rates[currency][sym]) : null;
return prev;
}, {});
}
}
2 changes: 1 addition & 1 deletion common/reducers/rates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function fetchCCRatesSucceeded(
...state,
rates: {
...state.rates,
[action.payload.symbol]: action.payload.rates
...action.payload
}
};
}
Expand Down