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

feat: markets page APY range select #2288

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
100 changes: 100 additions & 0 deletions src/components/HistoricalAPYRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { SxProps, Theme, ToggleButton, ToggleButtonGroup, Typography } from '@mui/material';

const supportedHistoricalTimeRangeOptions = ['Now', '30D', '60D', '90D'] as const;

export enum ESupportedAPYTimeRanges {
Now = 'Now',
ThirtyDays = '30D',
SixtyDays = '60D',
NinetyDays = '90D',
}

export const reserveHistoricalRateTimeRangeOptions = [
ESupportedAPYTimeRanges.Now,
ESupportedAPYTimeRanges.ThirtyDays,
ESupportedAPYTimeRanges.SixtyDays,
ESupportedAPYTimeRanges.NinetyDays,
];

export type ReserveHistoricalRateTimeRange = typeof reserveHistoricalRateTimeRangeOptions[number];

export interface TimeRangeSelectorProps {
disabled?: boolean;
selectedTimeRange: ESupportedAPYTimeRanges;
onTimeRangeChanged: (value: ESupportedAPYTimeRanges) => void;
sx?: {
buttonGroup: SxProps<Theme>;
button: SxProps<Theme>;
};
}

export const HistoricalAPYRow = ({
disabled = false,
selectedTimeRange,
onTimeRangeChanged,
...props
}: TimeRangeSelectorProps) => {
const handleChange = (
_event: React.MouseEvent<HTMLElement>,
newInterval: ESupportedAPYTimeRanges
) => {
if (newInterval !== null) {
onTimeRangeChanged(newInterval);
}
};

return (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
gap: '10px',
}}
>
<Typography variant="secondary14">APY</Typography>
<ToggleButtonGroup
disabled={disabled}
value={selectedTimeRange}
exclusive
onChange={handleChange}
aria-label="Date range"
sx={{
height: '24px',
'&.MuiToggleButtonGroup-grouped': {
borderRadius: 'unset',
},
...props.sx?.buttonGroup,
}}
>
{supportedHistoricalTimeRangeOptions.map((interval) => {
return (
<ToggleButton
key={interval}
value={interval}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
sx={(theme): SxProps<Theme> | undefined => ({
'&.MuiToggleButtonGroup-grouped:not(.Mui-selected), &.MuiToggleButtonGroup-grouped&.Mui-disabled':
{
border: '0.5px solid transparent',
backgroundColor: 'background.surface',
color: 'action.disabled',
},
'&.MuiToggleButtonGroup-grouped&.Mui-selected': {
borderRadius: '4px',
border: `0.5px solid ${theme.palette.divider}`,
boxShadow: '0px 2px 1px rgba(0, 0, 0, 0.05), 0px 0px 1px rgba(0, 0, 0, 0.25)',
backgroundColor: 'background.paper',
},
...props.sx?.button,
})}
>
<Typography variant="buttonM">{interval}</Typography>
</ToggleButton>
);
})}
</ToggleButtonGroup>
</div>
);
};
7 changes: 2 additions & 5 deletions src/components/TitleWithSearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,10 @@ export const TitleWithSearchBar = <T extends React.ElementType>({
title,
}: TitleWithSearchBarProps<T>) => {
const [showSearchBar, setShowSearchBar] = useState(false);

const { breakpoints } = useTheme();
const sm = useMediaQuery(breakpoints.down('sm'));

const showSearchIcon = sm && !showSearchBar;
const showMarketTitle = !sm || !showSearchBar;

const showMarketTitle = (!sm || !showSearchBar) && !!title;
const handleCancelClick = () => {
setShowSearchBar(false);
onSearchTermChange('');
Expand All @@ -46,7 +43,7 @@ export const TitleWithSearchBar = <T extends React.ElementType>({
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
justifyContent: showMarketTitle && title ? 'space-between' : 'center',
}}
>
{showMarketTitle && (
Expand Down
162 changes: 162 additions & 0 deletions src/hooks/useHistoricalAPYData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { useEffect, useState } from 'react';
import { INDEX_CURRENT } from 'src/modules/markets/index-current-query';
import { INDEX_HISTORY } from 'src/modules/markets/index-history-query';

export interface HistoricalAPYData {
underlyingAsset: string;
liquidityIndex: string;
variableBorrowIndex: string;
timestamp: string;
liquidityRate: string;
variableBorrowRate: string;
}

interface Rates {
supplyAPY: string;
variableBorrowAPY: string;
}

function calculateImpliedAPY(
currentLiquidityIndex: number,
previousLiquidityIndex: number,
daysBetweenIndexes: number,
): string {
if (previousLiquidityIndex <= 0 || currentLiquidityIndex <= 0) {
throw new Error("Liquidity indexes must be positive values.");
}

const growthFactor = currentLiquidityIndex / previousLiquidityIndex;

const annualizedGrowthFactor = Math.pow(growthFactor, 365 / daysBetweenIndexes);

const impliedAPY = (annualizedGrowthFactor - 1);

return impliedAPY.toString();
}

export const useHistoricalAPYData = (
subgraphUrl: string,
selectedTimeRange: string
) => {
const [historicalAPYData, setHistoricalAPYData] = useState<Record<string, Rates>>({});

useEffect(() => {
const fetchHistoricalAPYData = async () => {
if (selectedTimeRange === 'Now') {
setHistoricalAPYData({});
return;
}

const timeRangeSecondsMap: Record<string, number | undefined> = {
'30D': 30 * 24 * 60 * 60,
'60D': 60 * 24 * 60 * 60,
'90D': 90 * 24 * 60 * 60,
};

const timeRangeDaysMap: Record<string, number | undefined> = {
'30D': 30,
'60D': 60,
'90D': 90,
};

const timeRangeInSeconds = timeRangeSecondsMap[selectedTimeRange];

if (timeRangeInSeconds === undefined) {
console.error(`Invalid time range: ${selectedTimeRange}`);
setHistoricalAPYData({});
return;
}

const timestamp = Math.floor(Date.now() / 1000) - timeRangeInSeconds;

try {
const requestBody = {
query: INDEX_HISTORY,
variables: { timestamp },
};
const response = await fetch(subgraphUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});

const requestBodyCurrent = {
query: INDEX_CURRENT,
};
const responseCurrent = await fetch(subgraphUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBodyCurrent),
});

if (!response.ok || !responseCurrent.ok) {
throw new Error(`Network error: ${response.status} - ${response.statusText}`);
}

const data = await response.json();
const dataCurrent = await responseCurrent.json();

const historyByAsset: Record<string, HistoricalAPYData> = {};
const currentByAsset: Record<string, HistoricalAPYData> = {};

data.data.reserveParamsHistoryItems.forEach((entry: any) => {
const assetKey = entry.reserve.underlyingAsset.toLowerCase();
if (!historyByAsset[assetKey]) {
historyByAsset[assetKey] = {
underlyingAsset: assetKey,
liquidityIndex: entry.liquidityIndex,
variableBorrowIndex: entry.variableBorrowIndex,
liquidityRate: entry.liquidityRate,
variableBorrowRate: entry.variableBorrowRate,
timestamp: entry.timestamp,
};
}
});

dataCurrent.data.reserveParamsHistoryItems.forEach((entry: any) => {
const assetKey = entry.reserve.underlyingAsset.toLowerCase();
if (!currentByAsset[assetKey]) {
currentByAsset[assetKey] = {
underlyingAsset: assetKey,
liquidityIndex: entry.liquidityIndex,
variableBorrowIndex: entry.variableBorrowIndex,
liquidityRate: entry.liquidityRate,
variableBorrowRate: entry.variableBorrowRate,
timestamp: entry.timestamp,
};
}
});

const allAssets = new Set([
...Object.keys(historyByAsset),
...Object.keys(currentByAsset),
]);

const results: Record<string, Rates> = {};
allAssets.forEach((asset) => {
const historical = historyByAsset[asset];
const current = currentByAsset[asset];

if (historical && current) {
results[asset] = {
supplyAPY: calculateImpliedAPY(Number(current.liquidityIndex), Number(historical.liquidityIndex), timeRangeDaysMap[selectedTimeRange] || 0),
variableBorrowAPY: calculateImpliedAPY(Number(current.variableBorrowIndex), Number(historical.variableBorrowIndex), timeRangeDaysMap[selectedTimeRange] || 0),
};
}
});
setHistoricalAPYData(results);
} catch (error) {
console.error('Error fetching historical APY data:', error);
setHistoricalAPYData({});
}
};

fetchHistoricalAPYData();
}, [selectedTimeRange]);

return historicalAPYData;
};
Loading
Loading