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 13 commits into
base: main
Choose a base branch
from
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', '180D', '1Y'] as const;

export enum ESupportedAPYTimeRanges {
Now = 'Now',
ThirtyDays = '30D',
OneHunredEightyDays = '180D',
OneYear = '1Y',
}

export const reserveHistoricalRateTimeRangeOptions = [
ESupportedAPYTimeRanges.Now,
ESupportedAPYTimeRanges.ThirtyDays,
ESupportedAPYTimeRanges.OneHunredEightyDays,
ESupportedAPYTimeRanges.OneYear,
];

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
48 changes: 26 additions & 22 deletions src/components/incentives/IncentivesCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ interface IncentivesCardProps {
tooltip?: ReactNode;
market: string;
protocolAction?: ProtocolAction;
showIncentives?: boolean;
}

export const IncentivesCard = ({
Expand All @@ -37,6 +38,7 @@ export const IncentivesCard = ({
tooltip,
market,
protocolAction,
showIncentives = true,
}: IncentivesCardProps) => {
const isTableChangedToCards = useMediaQuery('(max-width:1125px)');
return (
Expand All @@ -49,7 +51,7 @@ export const IncentivesCard = ({
textAlign: 'center',
}}
>
{value.toString() !== '-1' ? (
{value.toString() !== '-1' && value.toString() !== 'N/A' ? (
<Box sx={{ display: 'flex' }}>
<FormattedNumber
data-cy={`apy`}
Expand All @@ -65,27 +67,29 @@ export const IncentivesCard = ({
) : (
<NoData variant={variant} color={color || 'text.secondary'} />
)}
<Box
sx={
isTableChangedToCards
? { display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '4px' }
: {
display: 'flex',
justifyContent: 'center',
gap: '4px',
flexWrap: 'wrap',
flex: '0 0 50%', // 2 items per row
}
}
>
<IncentivesButton incentives={incentives} symbol={symbol} />
<MeritIncentivesButton symbol={symbol} market={market} protocolAction={protocolAction} />
<ZkIgniteIncentivesButton
market={market}
rewardedAsset={address}
protocolAction={protocolAction}
/>
</Box>
{Boolean(showIncentives) && (
<Box
sx={
isTableChangedToCards
? { display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '4px' }
: {
display: 'flex',
justifyContent: 'center',
gap: '4px',
flexWrap: 'wrap',
flex: '0 0 50%', // 2 items per row
}
}
>
<IncentivesButton incentives={incentives} symbol={symbol} />
<MeritIncentivesButton symbol={symbol} market={market} protocolAction={protocolAction} />
<ZkIgniteIncentivesButton
market={market}
rewardedAsset={address}
protocolAction={protocolAction}
/>
</Box>
)}
</Box>
);
};
170 changes: 170 additions & 0 deletions src/hooks/useHistoricalAPYData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { useQuery } from '@tanstack/react-query';
import { constructIndexCurrentQuery } from 'src/modules/markets/index-current-query';
import { constructIndexHistoryQuery } from 'src/modules/markets/index-history-query';
import { generateAliases } from 'src/utils/generateSubgraphQueryAlias';

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();
}

const fetchHistoricalAPYData = async (
subgraphUrl: string,
selectedTimeRange: string,
underlyingAssets: string[]
) => {
if (selectedTimeRange === 'Now' || underlyingAssets.length === 0) {
return {};
}

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

const timeRangeDaysMap: Record<string, number | undefined> = {
'30D': 30,
'60D': 60,
'180D': 180,
'1Y': 365,
};

const timeRangeInSeconds = timeRangeSecondsMap[selectedTimeRange];

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

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

const requestBodyHistory = {
query: constructIndexHistoryQuery(underlyingAssets),
variables: { timestamp },
};

const requestBodyCurrent = {
query: constructIndexCurrentQuery(underlyingAssets),
};

const [responseHistory, responseCurrent] = await Promise.all([
fetch(subgraphUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBodyHistory),
}),
fetch(subgraphUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBodyCurrent),
}),
]);

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

const dataHistory = await responseHistory.json();
const dataCurrent = await responseCurrent.json();

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

const aliases = generateAliases(underlyingAssets.length);

underlyingAssets.forEach((_, index) => {
const alias = aliases[index];

const historicalEntry = dataHistory.data[alias];
if (historicalEntry && historicalEntry.length > 0) {
const entry = historicalEntry[0];
const assetKey = entry.reserve.underlyingAsset.toLowerCase();
historyByAsset[assetKey] = {
underlyingAsset: assetKey,
liquidityIndex: entry.liquidityIndex,
variableBorrowIndex: entry.variableBorrowIndex,
liquidityRate: entry.liquidityRate,
variableBorrowRate: entry.variableBorrowRate,
timestamp: entry.timestamp,
};
}

const currentEntry = dataCurrent.data[alias];
if (currentEntry && currentEntry.length > 0) {
const entry = currentEntry[0];
const assetKey = entry.reserve.underlyingAsset.toLowerCase();
currentByAsset[assetKey] = {
underlyingAsset: assetKey,
liquidityIndex: entry.liquidityIndex,
variableBorrowIndex: entry.variableBorrowIndex,
liquidityRate: entry.liquidityRate,
variableBorrowRate: entry.variableBorrowRate,
timestamp: entry.timestamp,
};
}
});

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

if (historical && current) {
results[assetKey] = {
supplyAPY: calculateImpliedAPY(
Number(current.liquidityIndex),
Number(historical.liquidityIndex),
timeRangeDaysMap[selectedTimeRange] || 0
),
variableBorrowAPY: calculateImpliedAPY(
Number(current.variableBorrowIndex),
Number(historical.variableBorrowIndex),
timeRangeDaysMap[selectedTimeRange] || 0
),
};
}
});

return results;
};

export const useHistoricalAPYData = (
subgraphUrl: string,
selectedTimeRange: string,
underlyingAssets: string[]
) => {
return useQuery({
queryKey: ['historicalAPYData', subgraphUrl, selectedTimeRange, underlyingAssets],
queryFn: () => fetchHistoricalAPYData(subgraphUrl, selectedTimeRange, underlyingAssets),
staleTime: 5 * 60 * 1000, // 5 minutes
refetchInterval: 5 * 60 * 1000, // 5 minutes
});
};
Loading
Loading