Skip to content

Commit

Permalink
Peter/refactor fetch oracle status from chain (#1359)
Browse files Browse the repository at this point in the history
* chore: update monetary to latest 0.7.3

* refactor: fetch oracle status from chain

* chore: remove commented-out code
  • Loading branch information
peterslany authored Jun 27, 2023
1 parent 6d32c91 commit 9f967f5
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 85 deletions.
57 changes: 10 additions & 47 deletions src/pages/Dashboard/cards/OracleStatusCard/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
import { CurrencyExt } from '@interlay/interbtc-api';
import { Bitcoin, ExchangeRate } from '@interlay/monetary-js';
import clsx from 'clsx';
import { useErrorHandler, withErrorBoundary } from 'react-error-boundary';
import { withErrorBoundary } from 'react-error-boundary';
import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
import { useSelector } from 'react-redux';

import { StoreType } from '@/common/types/util.types';
import { RELAY_CHAIN_NATIVE_TOKEN, RELAY_CHAIN_NATIVE_TOKEN_SYMBOL } from '@/config/relay-chains';
import ErrorFallback from '@/legacy-components/ErrorFallback';
import Ring64, { Ring64Subtitle, Ring64Title, Ring64Value } from '@/legacy-components/Ring64';
import genericFetcher, { GENERIC_FETCHER } from '@/services/fetchers/generic-fetcher';
import {
BtcToCurrencyOracleStatus,
latestExchangeRateFetcher,
ORACLE_LATEST_EXCHANGE_RATE_FETCHER
} from '@/services/fetchers/oracle-exchange-rates-fetcher';
import { PAGES } from '@/utils/constants/links';
import { getColorShade } from '@/utils/helpers/colors';
import { OracleStatus, useGetOracleStatus } from '@/utils/hooks/api/oracle/use-get-oracle-status';
import { useGetExchangeRate } from '@/utils/hooks/api/use-get-exchange-rate';

import Stats, { StatsDd, StatsDt, StatsRouterLink } from '../../Stats';
import DashboardCard from '../DashboardCard';
Expand All @@ -28,53 +21,23 @@ interface Props {

const OracleStatusCard = ({ hasLinks }: Props): JSX.Element => {
const { t } = useTranslation();
const { bridgeLoaded } = useSelector((state: StoreType) => state.general);

const {
isIdle: oracleTimeoutIdle,
isLoading: oracleTimeoutLoading,
data: oracleTimeout,
error: oracleTimeoutError
} = useQuery<number, Error>([GENERIC_FETCHER, 'oracle', 'getOnlineTimeout'], genericFetcher<number>(), {
enabled: !!bridgeLoaded
});
useErrorHandler(oracleTimeoutError);

const {
isIdle: oracleStatusIdle,
isLoading: oracleStatusLoading,
data: oracleStatus,
error: oracleStatusError
} = useQuery<BtcToCurrencyOracleStatus | undefined, Error>(
[ORACLE_LATEST_EXCHANGE_RATE_FETCHER, RELAY_CHAIN_NATIVE_TOKEN, oracleTimeout],
latestExchangeRateFetcher,
{
enabled: !!oracleTimeout
}
const { data: oracleStatus, isLoading: isLoadingOracleStatus } = useGetOracleStatus();
const { data: relayChainExchangeRate, isLoading: isLoadingExchangeRate } = useGetExchangeRate(
RELAY_CHAIN_NATIVE_TOKEN
);
useErrorHandler(oracleStatusError);

const renderContent = () => {
// TODO: should use skeleton loaders
if (oracleStatusIdle || oracleStatusLoading || oracleTimeoutIdle || oracleTimeoutLoading) {
if (isLoadingOracleStatus || isLoadingExchangeRate) {
return <>Loading...</>;
}

if (oracleTimeout === undefined) {
throw new Error('Something went wrong!');
}

const exchangeRate = oracleStatus
? new ExchangeRate<Bitcoin, CurrencyExt>(
Bitcoin,
RELAY_CHAIN_NATIVE_TOKEN,
oracleStatus.exchangeRate.toBig(),
0,
0
)
const exchangeRate = relayChainExchangeRate
? new ExchangeRate<Bitcoin, CurrencyExt>(Bitcoin, RELAY_CHAIN_NATIVE_TOKEN, relayChainExchangeRate.toBig(), 0, 0)
: 0;

const oracleOnline = oracleStatus && oracleStatus.online;
const oracleOnline = oracleStatus && oracleStatus === OracleStatus.ONLINE;

let statusText;
let statusCircleText;
Expand Down
40 changes: 2 additions & 38 deletions src/services/fetchers/oracle-exchange-rates-fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@ import { Bitcoin, ExchangeRate } from '@interlay/monetary-js';
import graphqlFetcher, { GRAPHQL_FETCHER } from '@/services/fetchers/graphql-fetcher';
import { getCurrencyEqualityCondition } from '@/utils/helpers/currencies';

import oracleExchangeRatesQuery, { composableExchangeRateSubquery } from '../queries/oracle-exchange-rates-query';
import { composableExchangeRateSubquery } from '../queries/oracle-exchange-rates-query';

const ORACLE_LATEST_EXCHANGE_RATE_FETCHER = 'oracle-exchange-rate-fetcher';
const ORACLE_ALL_LATEST_UPDATES_FETCHER = 'oracle-all-latest-updates-fetcher';

type BtcToCurrencyOracleStatus = OracleStatus<Bitcoin, CurrencyExt>;

type LatestExchangeRateFetcherParams = [key: string, currency: CurrencyExt, onlineTimeout: number];

type AllOracleLatestUpdatesFetcherParams = [
key: string,
currency: CurrencyExt,
Expand All @@ -40,34 +37,6 @@ function decodeOracleValues(
};
}

// TODO: should type properly (`Relay`)
const latestExchangeRateFetcher = async (
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
{ queryKey }: any
): Promise<BtcToCurrencyOracleStatus | undefined> => {
const [key, currency, onlineTimeout] = queryKey as LatestExchangeRateFetcherParams;

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

// TODO: should type properly (`Relay`)
// TODO: Need to refactor when we want to support lend tokens as collateral for vaults.
const cond = 'foreignAsset' in currency ? `asset_eq: ${currency.foreignAsset.id}` : `token_eq: ${currency.ticker}`;
const latestOracleData = await graphqlFetcher<Array<any>>()({
queryKey: [GRAPHQL_FETCHER, oracleExchangeRatesQuery(`typeKey: {${cond}}`)]
});

// TODO: should type properly (`Relay`)
const rates = latestOracleData?.data?.oracleUpdates || [];
return rates.map((update) =>
decodeOracleValues(
update,
currency,
onlineTimeout,
new Map([[update.oracleId, update.oracleId]]) // placeholder, as not used in card
)
)[0];
};

const allLatestSubmissionsFetcher = async (
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
{ queryKey }: any
Expand Down Expand Up @@ -95,11 +64,6 @@ const allLatestSubmissionsFetcher = async (
.map(([update]) => decodeOracleValues(update, currency, onlineTimeout, namesMap));
};

export {
allLatestSubmissionsFetcher,
latestExchangeRateFetcher,
ORACLE_ALL_LATEST_UPDATES_FETCHER,
ORACLE_LATEST_EXCHANGE_RATE_FETCHER
};
export { allLatestSubmissionsFetcher, ORACLE_ALL_LATEST_UPDATES_FETCHER };

export type { BtcToCurrencyOracleStatus };
31 changes: 31 additions & 0 deletions src/utils/hooks/api/oracle/use-get-oracle-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useQuery } from 'react-query';

import { REFETCH_INTERVAL } from '@/utils/constants/api';

interface UseGetOracleStatusResult {
data: OracleStatus | undefined;
isLoading: boolean;
}

enum OracleStatus {
ONLINE = 'ONLINE',
OFFLINE = 'OFFLINE'
}

const getOracleStatus = async (): Promise<OracleStatus> => {
const isOracleOnline = await window.bridge.oracle.isOnline();
return isOracleOnline ? OracleStatus.ONLINE : OracleStatus.OFFLINE;
};

const useGetOracleStatus = (): UseGetOracleStatusResult => {
const { data, isLoading } = useQuery({
queryKey: 'oracle-status',
queryFn: getOracleStatus,
enabled: window.bridge !== undefined,
refetchInterval: REFETCH_INTERVAL.MINUTE
});

return { data, isLoading };
};

export { OracleStatus, useGetOracleStatus };

2 comments on commit 9f967f5

@vercel
Copy link

@vercel vercel bot commented on 9f967f5 Jun 27, 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 9f967f5 Jun 27, 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.