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: APY chart #1674

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions src/app/earn/components/chart-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Tab = { name: ChartTab; label: string }

const tabs: Tab[] = [
{ name: 'price', label: 'Token Price' },
{ name: 'apy', label: 'APY' },
{ name: 'tvl', label: 'TVL' },
]

Expand Down
10 changes: 9 additions & 1 deletion src/app/earn/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { ChartTabs } from '@/app/earn/components/chart-tabs'
import { FaqSection } from '@/app/earn/components/faq-section'
import { useEarnContext } from '@/app/earn/provider'
import { ChartTab } from '@/app/earn/types'
import { ApyChart } from '@/components/charts/apy-chart'
import { PriceChart } from '@/components/charts/price-chart'
import { TvlChart } from '@/components/charts/tvl-chart'

import { EarnWidget } from './components/earn-widget'
import { QuickStats } from './components/quick-stats'

export default function Page() {
const { indexToken, isFetchingStats, nav, tvl } = useEarnContext()
const { indexToken, isFetchingStats, apy, nav, tvl } = useEarnContext()
const [currentTab, setCurrentTab] = useState<ChartTab>('price')

return (
Expand All @@ -31,6 +32,13 @@ export default function Page() {
nav={nav}
/>
)}
{currentTab === 'apy' && (
<ApyChart
indexTokenAddress={indexToken.address ?? ''}
isFetchingStats={isFetchingStats}
apy={apy}
/>
)}
{currentTab === 'tvl' && (
<TvlChart
indexTokenAddress={indexToken.address ?? ''}
Expand Down
19 changes: 1 addition & 18 deletions src/app/earn/types.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1 @@
import { Token } from '@/constants/tokens'

export interface BaseTokenStats {
symbol: string
price: number
change24h: number
low24h: number
high24h: number
}

export type EnrichedToken = Token & {
balance: bigint
usd?: number
unitPriceUsd?: number
size?: string
}

export type ChartTab = 'tvl' | 'price'
export type ChartTab = 'tvl' | 'price' | 'apy'
57 changes: 57 additions & 0 deletions src/components/charts/apy-chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { formatPercentage } from '@/app/products/utils/formatters'
import ApyXyChart from '@/components/charts/apy-xy-chart'
import { PeriodSelector } from '@/components/charts/period-selector'
import { ChartPeriod } from '@/components/charts/types'
import { useChartData } from '@/components/charts/use-chart-data'
import { cn } from '@/lib/utils/tailwind'

type Props = {
indexTokenAddress: string
isFetchingStats?: boolean
apy: number | null
}

const periods = [ChartPeriod.Week, ChartPeriod.Month, ChartPeriod.Year]

export function ApyChart({
indexTokenAddress,
isFetchingStats = false,
apy,
}: Props) {
const { historicalData, selectedPeriod, setSelectedPeriod } = useChartData(
indexTokenAddress,
'apy',
)

return (
<div className='border-ic-gray-200 dark:border-ic-gray-600 flex h-full w-full flex-col rounded-lg border bg-[#F7F8F8] dark:bg-[#1C2C2E]'>
<div className='text-ic-gray-800 dark:text-ic-white flex w-full items-stretch px-4 pt-4 md:px-8 md:pt-6'>
<div
className={cn(
'basis-1/2 self-center text-lg font-semibold md:basis-1/4 md:text-2xl',
apy === null &&
isFetchingStats &&
'bg-ic-gray-200 h-[18px] animate-pulse rounded-md text-opacity-0 md:h-8',
)}
>
{formatPercentage(apy)}
</div>
<PeriodSelector
periods={periods}
selectedPeriod={selectedPeriod}
setSelectedPeriod={setSelectedPeriod}
/>
</div>
<div className='block h-full w-full dark:hidden'>
<ApyXyChart data={historicalData} selectedPeriod={selectedPeriod} />
</div>
<div className='hidden h-full w-full dark:block'>
<ApyXyChart
data={historicalData}
selectedPeriod={selectedPeriod}
isDark={true}
/>
</div>
</div>
)
}
110 changes: 110 additions & 0 deletions src/components/charts/apy-xy-chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { withParentSize } from '@visx/responsive'
import {
AnimatedAreaSeries,
AnimatedLineSeries,
Axis,
Tooltip,
XYChart,
} from '@visx/xychart'
import dayjs from 'dayjs'
import { useMemo } from 'react'

import { formatPercentage } from '@/app/products/utils/formatters'
import { ChartTooltip } from '@/components/charts/chart-tooltip'
import { LinearGradientFill } from '@/components/charts/linear-gradient-fill'
import { darkTheme, lightTheme } from '@/components/charts/themes'
import { ChartPeriod } from '@/components/charts/types'
import { tooltipTimestampFormat } from '@/constants/charts'
import { IndexData } from '@/lib/utils/api/index-data-provider'

type ApyChartIndexData = Pick<IndexData, 'APY' | 'CreatedTimestamp'>

type Props = {
data: ApyChartIndexData[]
isDark?: boolean
parentWidth: number
parentHeight: number
selectedPeriod: ChartPeriod
}

function TvlXYChart({
data,
isDark = false,
parentWidth,
parentHeight,
selectedPeriod,
}: Props) {
const { minDomainY, maxDomainY } = useMemo(() => {
const apys = data.map(({ APY }) => APY!)
const minApy = Math.min(...apys)
const maxApy = Math.max(...apys)
const diff = maxApy - minApy
return {
minDomainY: minApy - diff * 0.05,
maxDomainY: maxApy + diff * 0.05,
}
}, [data])

const seriesAccessors = {
xAccessor: (d: ApyChartIndexData) => new Date(d.CreatedTimestamp),
yAccessor: (d: ApyChartIndexData) => d.APY,
}

const tooltipAccessors = {
xAccessor: (d: ApyChartIndexData) =>
dayjs(d.CreatedTimestamp).format(tooltipTimestampFormat[selectedPeriod]),
yAccessor: (d: ApyChartIndexData) => formatPercentage(d.APY),
}

if (parentHeight === 0 || parentWidth === 0) return null

return (
<XYChart
height={parentHeight}
width={parentWidth}
margin={{ top: 20, right: 20, bottom: 40, left: 60 }}
theme={isDark ? darkTheme : lightTheme}
xScale={{ type: 'time' }}
yScale={{
type: 'linear',
domain: [minDomainY, maxDomainY],
nice: true,
zero: false,
}}
>
<Axis
orientation='left'
numTicks={5}
tickFormat={(d) => formatPercentage(d)}
/>
<Axis orientation='bottom' numTicks={5} />
<AnimatedLineSeries {...seriesAccessors} dataKey='tvls' data={data} />
<AnimatedAreaSeries
{...seriesAccessors}
fill='url(#gradient)'
dataKey='tvls'
data={data}
/>
<LinearGradientFill isDark={isDark} />
<Tooltip
snapTooltipToDatumX
snapTooltipToDatumY
showVerticalCrosshair
showSeriesGlyphs
renderTooltip={({ tooltipData }) => (
<ChartTooltip
isDark={isDark}
line1={tooltipAccessors.yAccessor(
tooltipData?.nearestDatum?.datum as ApyChartIndexData,
)}
line2={tooltipAccessors.xAccessor(
tooltipData?.nearestDatum?.datum as ApyChartIndexData,
)}
/>
)}
/>
</XYChart>
)
}

export default withParentSize(TvlXYChart)
9 changes: 7 additions & 2 deletions src/components/charts/period-selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ChartPeriod } from '@/components/charts/types'
import { useAnalytics } from '@/lib/hooks/use-analytics'
import { cn } from '@/lib/utils/tailwind'

const periods = [
const defaultPeriods = [
ChartPeriod.Hour,
ChartPeriod.Day,
ChartPeriod.Week,
Expand All @@ -13,11 +13,16 @@ const periods = [
]

type Props = {
periods?: ChartPeriod[]
selectedPeriod: ChartPeriod
setSelectedPeriod: Dispatch<SetStateAction<ChartPeriod>>
}

export function PeriodSelector({ selectedPeriod, setSelectedPeriod }: Props) {
export function PeriodSelector({
periods = defaultPeriods,
selectedPeriod,
setSelectedPeriod,
}: Props) {
const { logEvent } = useAnalytics()

const handleClick = (period: ChartPeriod) => {
Expand Down
13 changes: 2 additions & 11 deletions src/components/charts/price-xy-chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ChartTooltip } from '@/components/charts/chart-tooltip'
import { LinearGradientFill } from '@/components/charts/linear-gradient-fill'
import { darkTheme, lightTheme } from '@/components/charts/themes'
import { ChartPeriod } from '@/components/charts/types'
import { tooltipTimestampFormat } from '@/constants/charts'
import { formatDollarAmount } from '@/lib/utils'
import { IndexData } from '@/lib/utils/api/index-data-provider'

Expand All @@ -27,14 +28,6 @@ type Props = {
selectedPeriod: ChartPeriod
}

const tooltipTimestampFormatByPeriod: { [k in ChartPeriod]: string } = {
[ChartPeriod.Hour]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Day]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Week]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Month]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Year]: 'DD MMM YYYY',
}

function PriceXYChart({
data,
digits = 2,
Expand All @@ -61,9 +54,7 @@ function PriceXYChart({

const tooltipAccessors = {
xAccessor: (d: PriceChartIndexData) =>
dayjs(d.CreatedTimestamp).format(
tooltipTimestampFormatByPeriod[selectedPeriod],
),
dayjs(d.CreatedTimestamp).format(tooltipTimestampFormat[selectedPeriod]),
yAccessor: (d: PriceChartIndexData) =>
formatDollarAmount(d.NetAssetValue, undefined, digits),
}
Expand Down
13 changes: 2 additions & 11 deletions src/components/charts/tvl-xy-chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { ChartTooltip } from '@/components/charts/chart-tooltip'
import { LinearGradientFill } from '@/components/charts/linear-gradient-fill'
import { darkTheme, lightTheme } from '@/components/charts/themes'
import { ChartPeriod } from '@/components/charts/types'
import { tooltipTimestampFormat } from '@/constants/charts'
import { IndexData } from '@/lib/utils/api/index-data-provider'

type TvlChartIndexData = Pick<
Expand All @@ -29,14 +30,6 @@ type Props = {
selectedPeriod: ChartPeriod
}

const tooltipTimestampFormatByPeriod: { [k in ChartPeriod]: string } = {
[ChartPeriod.Hour]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Day]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Week]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Month]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Year]: 'DD MMM YYYY',
}

function TvlXYChart({
data,
isDark = false,
Expand All @@ -62,9 +55,7 @@ function TvlXYChart({

const tooltipAccessors = {
xAccessor: (d: TvlChartIndexData) =>
dayjs(d.CreatedTimestamp).format(
tooltipTimestampFormatByPeriod[selectedPeriod],
),
dayjs(d.CreatedTimestamp).format(tooltipTimestampFormat[selectedPeriod]),
yAccessor: (d: TvlChartIndexData) => formatTvl(d.ProductAssetValue),
}

Expand Down
11 changes: 10 additions & 1 deletion src/components/charts/use-chart-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,23 @@ function formatData(
}))
}

if (metric === 'apy') {
return data.map((datum) => ({
...datum,
APY: Number(datum.APY?.toFixed(4)),
}))
}

return []
}

export function useChartData(
indexTokenAddress?: string,
metric: IndexDataMetric = 'nav',
) {
const [selectedPeriod, setSelectedPeriod] = useState(ChartPeriod.Day)
const [selectedPeriod, setSelectedPeriod] = useState(
metric === 'apy' ? ChartPeriod.Week : ChartPeriod.Day,
)
const [historicalData, setHistoricalData] = useState<HistoricalData>([])
useQuery({
enabled: isAddress(indexTokenAddress ?? ''),
Expand Down
9 changes: 9 additions & 0 deletions src/constants/charts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ChartPeriod } from '@/components/charts/types'

export const tooltipTimestampFormat: { [k in ChartPeriod]: string } = {
[ChartPeriod.Hour]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Day]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Week]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Month]: 'DD MMM YYYY HH:mm',
[ChartPeriod.Year]: 'DD MMM YYYY',
}
Loading