Skip to content

Commit

Permalink
Peter/fix vault dashboard volumes hook (#1557)
Browse files Browse the repository at this point in the history
* chore: update monetary to latest 0.7.3

* fix: show all collateral currencies on locked collateral card
  • Loading branch information
peterslany authored Sep 7, 2023
1 parent d21ddf6 commit e9414ef
Show file tree
Hide file tree
Showing 3 changed files with 119 additions and 51 deletions.
25 changes: 25 additions & 0 deletions src/hooks/use-all-cumulative-vault-collateral-volumes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { TickerToData } from '@interlay/interbtc-api';
import { useQuery, UseQueryResult } from 'react-query';

import cumulativeVaultCollateralVolumesFetcher, {
CUMULATIVE_VAULT_COLLATERALVOLUMES_FETCHER
} from '@/services/fetchers/cumulative-vault-collateral-volumes-fetcher';
import { VolumeDataPoint } from '@/services/fetchers/cumulative-volumes-fetcher';

import { useGetCollateralCurrencies } from './api/use-get-collateral-currencies';

const useAllCumulativeVaultCollateralVolumes = (
cutoffTimestamps: Array<Date>
): UseQueryResult<TickerToData<Array<VolumeDataPoint>>, Error> => {
const { data: collateralCurrencies } = useGetCollateralCurrencies(true);

return useQuery<TickerToData<Array<VolumeDataPoint>>, Error>(
[CUMULATIVE_VAULT_COLLATERALVOLUMES_FETCHER, cutoffTimestamps, collateralCurrencies],
cumulativeVaultCollateralVolumesFetcher,
{
enabled: !!collateralCurrencies
}
);
};

export default useAllCumulativeVaultCollateralVolumes;
65 changes: 14 additions & 51 deletions src/pages/Dashboard/sub-pages/Home/LockedCollateralsCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@ import { useTranslation } from 'react-i18next';

import { convertMonetaryAmountToValueInUSD, formatUSD, getLastMidnightTimestamps } from '@/common/utils/utils';
import { COUNT_OF_DATES_FOR_CHART } from '@/config/charts';
import {
GOVERNANCE_TOKEN,
GOVERNANCE_TOKEN_SYMBOL,
RELAY_CHAIN_NATIVE_TOKEN,
RELAY_CHAIN_NATIVE_TOKEN_SYMBOL
} from '@/config/relay-chains';
import { useGetPrices } from '@/hooks/api/use-get-prices';
import useCumulativeCollateralVolumes from '@/hooks/use-cumulative-collateral-volumes';
import useAllCumulativeVaultCollateralVolumes from '@/hooks/use-all-cumulative-vault-collateral-volumes';
import ErrorFallback from '@/legacy-components/ErrorFallback';
import { INTERLAY_DENIM, KINTSUGI_SUPERNOVA } from '@/utils/constants/colors';
import { PAGES } from '@/utils/constants/links';
Expand All @@ -29,44 +23,23 @@ const LockedCollateralsCard = (): JSX.Element => {
const prices = useGetPrices();

const {
isIdle: cumulativeRelayChainNativeTokenVolumesIdle,
isLoading: cumulativeRelayChainNativeTokenVolumesLoading,
data: cumulativeRelayChainNativeTokenVolumes,
error: cumulativeRelayChainNativeTokenVolumesError
} = useCumulativeCollateralVolumes(RELAY_CHAIN_NATIVE_TOKEN, cutoffTimestamps);
useErrorHandler(cumulativeRelayChainNativeTokenVolumesError);

const {
isIdle: cumulativeGovernanceTokenVolumesIdle,
isLoading: cumulativeGovernanceTokenVolumesLoading,
data: cumulativeGovernanceTokenVolumes,
error: cumulativeGovernanceTokenVolumesError
} = useCumulativeCollateralVolumes(GOVERNANCE_TOKEN, cutoffTimestamps);
useErrorHandler(cumulativeGovernanceTokenVolumesError);

const relayChainNativeTokenPriceInUSD = getTokenPrice(prices, RELAY_CHAIN_NATIVE_TOKEN_SYMBOL)?.usd;
const governanceTokenPriceInUSD = getTokenPrice(prices, GOVERNANCE_TOKEN_SYMBOL)?.usd;
data: allCumulativeVaultCollateralVolumes,
error: allCumulativeVaultCollateralVolumesError
} = useAllCumulativeVaultCollateralVolumes(cutoffTimestamps);
useErrorHandler(allCumulativeVaultCollateralVolumesError);

const cumulativeUSDVolumes = React.useMemo(() => {
if (cumulativeRelayChainNativeTokenVolumes === undefined || cumulativeGovernanceTokenVolumes === undefined) return;
if (allCumulativeVaultCollateralVolumes === undefined) return;

return Array<number>(COUNT_OF_DATES_FOR_CHART)
.fill(0)
.map((_, index) => {
const collaterals = [
{
cumulativeVolumes: cumulativeRelayChainNativeTokenVolumes,
tokenPriceInUSD: relayChainNativeTokenPriceInUSD
}
];

// Includes governance token data only if the price is available.
if (governanceTokenPriceInUSD !== undefined) {
collaterals.push({
cumulativeVolumes: cumulativeGovernanceTokenVolumes,
tokenPriceInUSD: governanceTokenPriceInUSD
});
}
const collateralTickers = Object.keys(allCumulativeVaultCollateralVolumes);

const collaterals = collateralTickers.map((ticker: string) => ({
cumulativeVolumes: allCumulativeVaultCollateralVolumes[ticker],
tokenPriceInUSD: getTokenPrice(prices, ticker)?.usd
}));

let sumValueInUSD = 0;
for (const collateral of collaterals) {
Expand All @@ -80,21 +53,11 @@ const LockedCollateralsCard = (): JSX.Element => {
tillTimestamp: cutoffTimestamps[index]
};
});
}, [
cumulativeRelayChainNativeTokenVolumes,
cumulativeGovernanceTokenVolumes,
relayChainNativeTokenPriceInUSD,
governanceTokenPriceInUSD
]);
}, [allCumulativeVaultCollateralVolumes, prices]);

const renderContent = () => {
// TODO: should use skeleton loaders
if (
cumulativeRelayChainNativeTokenVolumesIdle ||
cumulativeRelayChainNativeTokenVolumesLoading ||
cumulativeGovernanceTokenVolumesIdle ||
cumulativeGovernanceTokenVolumesLoading
) {
if (allCumulativeVaultCollateralVolumes === undefined) {
return <>Loading...</>;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { CollateralCurrencyExt, CurrencyExt, newMonetaryAmount, TickerToData } from '@interlay/interbtc-api';

import { WRAPPED_TOKEN } from '@/config/relay-chains';
import graphqlFetcher, { GRAPHQL_FETCHER } from '@/services/fetchers/graphql-fetcher';
import { getCurrencyEqualityCondition } from '@/utils/helpers/currencies';

import { VolumeDataPoint } from './cumulative-volumes-fetcher';

const CUMULATIVE_VAULT_COLLATERALVOLUMES_FETCHER = 'cumulative-vault-collateral-volumes-fetcher';

const cumulativeVaultCollateralVolumesFetcher = async (
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
{ queryKey }: any
): Promise<TickerToData<Array<VolumeDataPoint>>> => {
const [key, cutoffTimestamps, collateralCurrencies] = queryKey as CumulativeVaultCollateralVolumesFetcherParams;

if (key !== CUMULATIVE_VAULT_COLLATERALVOLUMES_FETCHER) throw new Error('Invalid key!');

const queryFragment = (date: Date, collateralCurrency: CurrencyExt) => {
const where = `{
tillTimestamp_lte: "${date.toISOString()}",
type_eq: Collateral,
${`collateralCurrency: {
${getCurrencyEqualityCondition(collateralCurrency)}}`},
${`wrappedCurrency: {
${getCurrencyEqualityCondition(WRAPPED_TOKEN)}}`},
}`;

return `
ts${date.getTime()}_${
collateralCurrency?.ticker
}: cumulativeVolumePerCurrencyPairs (where: ${where}, orderBy: tillTimestamp_DESC, limit: 1) {
amount
tillTimestamp
}
`;
};

const query = `
{
${cutoffTimestamps.map((date) => collateralCurrencies.map((currency) => queryFragment(date, currency)))}
}
`;

// TODO: should type properly (`Relay`)
const volumesData = await graphqlFetcher<Array<any>>()({
queryKey: [GRAPHQL_FETCHER, query]
});

const volumes = volumesData?.data || {};

return Object.entries(volumes).reduce((result, [key, [volumeData]]) => {
const [rawTimestamp, ticker] = key.split('_');
const timestamp = rawTimestamp.slice(2);
const currency = collateralCurrencies.find((collateralCurrency) => collateralCurrency.ticker === ticker);
if (currency === undefined) {
throw new Error('Ivalid query.');
}
return {
...result,
[ticker]: [
...(result[ticker] || []),
{
amount: newMonetaryAmount(volumeData.amount || 0, currency),
tillTimestamp: cutoffTimestamps.find((cutoffTimestamp) => cutoffTimestamp.getTime().toString() === timestamp)
}
]
};
}, {} as any);
};

type CumulativeVaultCollateralVolumesFetcherParams = [
queryKey: string,
cutoffTimestamp: Array<Date>,
collateralCurrency: Array<CollateralCurrencyExt>
];

export { CUMULATIVE_VAULT_COLLATERALVOLUMES_FETCHER };

export default cumulativeVaultCollateralVolumesFetcher;

2 comments on commit e9414ef

@vercel
Copy link

@vercel vercel bot commented on e9414ef Sep 7, 2023

Choose a reason for hiding this comment

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

@vercel
Copy link

@vercel vercel bot commented on e9414ef Sep 7, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.