mango-v4-ui/hooks/useBirdeyeMarketPrices.ts

58 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-04-03 04:01:17 -07:00
import { Serum3Market } from '@blockworks-foundation/mango-v4'
import mangoStore from '@store/mangoStore'
import { useQuery } from '@tanstack/react-query'
import { makeApiRequest } from 'apis/birdeye/helpers'
export interface BirdeyePriceResponse {
2023-04-03 04:01:17 -07:00
address: string
unixTime: number
value: number
}
const fetchBirdeyePrices = async (
spotMarkets: Serum3Market[]
): Promise<{ data: BirdeyePriceResponse[]; mint: string }[]> => {
2023-04-03 04:01:17 -07:00
const mints = spotMarkets.map((market) =>
market.serumMarketExternal.toString()
)
const promises = []
2023-04-05 17:22:20 -07:00
const queryEnd = Math.floor(Date.now() / 1000)
const queryStart = queryEnd - 86400
2023-04-03 04:01:17 -07:00
for (const mint of mints) {
const query = `defi/history_price?address=${mint}&address_type=pair&type=30m&time_from=${queryStart}&time_to=${queryEnd}`
promises.push(makeApiRequest(query))
}
const responses = await Promise.all(promises)
2023-04-05 17:22:20 -07:00
if (responses?.length) {
2023-04-03 04:01:17 -07:00
return responses.map((res) => ({
data: res.data.items,
mint: res.data.items[0]?.address,
2023-04-03 04:01:17 -07:00
}))
}
return []
}
export const useBirdeyeMarketPrices = () => {
const spotMarkets = mangoStore((s) => s.serumMarkets)
const res = useQuery(
2023-04-03 04:01:17 -07:00
['birdeye-market-prices'],
() => fetchBirdeyePrices(spotMarkets),
{
cacheTime: 1000 * 60 * 15,
staleTime: 1000 * 60 * 10,
retry: 3,
enabled: !!spotMarkets?.length,
refetchOnWindowFocus: false,
}
)
return {
2023-04-03 16:20:59 -07:00
isFetching: res?.isFetching,
2023-04-03 04:01:17 -07:00
isLoading: res?.isLoading,
data: res?.data || [],
}
}