asi-calculator/features/prices/hooks/use-prices.tsx

67 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-04-01 15:23:01 +02:00
'use client'
2024-03-30 19:11:24 +01:00
import { tokens } from '@/constants'
import { fetcher, getTokenAddressBySymbol } from '@/lib'
2024-03-30 19:11:24 +01:00
import useSWR from 'swr'
2024-03-31 16:48:31 +02:00
const tokenAddresses = tokens.map((token) => token.address).toString()
2024-04-14 12:52:37 +02:00
export type PriceCoingecko = {
usd: number
usd_24h_change: number
}
2024-04-01 14:42:08 +02:00
export type Prices = {
2024-04-14 12:52:37 +02:00
ocean: PriceCoingecko
fet: PriceCoingecko
agix: PriceCoingecko
cudos: PriceCoingecko
2024-04-14 12:52:37 +02:00
asi: PriceCoingecko
2024-04-01 14:42:08 +02:00
}
2024-03-31 05:32:11 +02:00
export function usePrices(): {
prices: Prices
2024-03-31 05:32:11 +02:00
isValidating: boolean
2024-03-31 15:24:07 +02:00
isLoading: boolean
2024-03-31 05:32:11 +02:00
} {
2024-09-21 03:06:44 +02:00
const { data, error, isValidating, isLoading } = useSWR(
`/api/prices?tokens=${tokenAddresses}`,
2024-03-30 19:11:24 +01:00
fetcher
)
2024-03-31 16:48:31 +02:00
const oceanAddress = getTokenAddressBySymbol('OCEAN')
const fetAddress = getTokenAddressBySymbol('FET')
const agixAddress = getTokenAddressBySymbol('AGIX')
const cudosAddress = getTokenAddressBySymbol('CUDOS')
2024-03-31 16:48:31 +02:00
2024-09-21 03:06:44 +02:00
const pricesEmpty = {
ocean: { usd: 0, usd_24h_change: 0 },
fet: { usd: 0, usd_24h_change: 0 },
agix: { usd: 0, usd_24h_change: 0 },
cudos: { usd: 0, usd_24h_change: 0 },
asi: { usd: 0, usd_24h_change: 0 }
}
const isError =
!data ||
error ||
!oceanAddress ||
!fetAddress ||
!agixAddress ||
!cudosAddress
return {
prices: isError
? pricesEmpty
: {
ocean: data[oceanAddress],
fet: data[fetAddress],
agix: data[agixAddress],
cudos: data[cudosAddress],
asi: data[fetAddress]
},
isValidating,
isLoading
}
2024-03-30 19:11:24 +01:00
}