import { useQuery } from "@tanstack/react-query" import { parseUnits } from "viem" import { ONE_SECOND_MS } from "../utils/time" import { usePortalApiClient } from "./usePortalApiClient" import { useCollateralPrice } from "./useCollateralPrice" export const CONVERSION_RATE_DECIMALS = 18 // If the oracle has not been updated in at least 60 seconds, it is stale. const MAX_PRICE_DELAY = 60 * ONE_SECOND_MS export const QUERY_KEY = "passport.assetsConversionRates" /** * Hook to fetch assets conversion rates. * @see https://github.com/mezo-org/musd/blob/f0b2030315f0d8b0fc11a9fc778856fe4673051f/solidity/contracts/PriceFeed.sol * @returns {}.data.{}.price - The latest asset price. * @returns {}.data.{}.digits - The latest asset price digits. * @returns {}.isPending - Whether the request is pending. * @returns {}.isError - Whether there was an error fetching the price. */ export function useAssetsConversionRates() { const portalApiClient = usePortalApiClient() const { data: collateralPriceData } = useCollateralPrice() const collateralPrice = collateralPriceData?.toString() return useQuery({ queryKey: [QUERY_KEY, collateralPrice], queryFn: () => { if (!collateralPriceData) { throw new Error("Collateral price is not available.") } return Promise.all([ portalApiClient.getPortalStatistics(), new Promise((resolve) => { resolve(collateralPriceData) }) as Promise, ]) }, enabled: !!collateralPrice, select: ([portalStatistics, btcPrice]) => { const tTokenConversionRate = portalStatistics.tTokenPrice const tPrice = parseUnits( tTokenConversionRate.toString(), CONVERSION_RATE_DECIMALS, ) return { rates: { mT: tPrice, BTC: btcPrice, }, decimals: CONVERSION_RATE_DECIMALS, } }, refetchInterval: MAX_PRICE_DELAY, }) }