Convert useETHUSDOracle to SWR

This commit is contained in:
Willian Mitsuda 2022-08-22 02:08:58 -03:00
parent 728d86d7cb
commit 9f5f223b0f
No known key found for this signature in database
1 changed files with 25 additions and 6 deletions

View File

@ -70,17 +70,36 @@ export const useTokenUSDOracle = (
return data ?? [undefined, undefined]; return data ?? [undefined, undefined];
}; };
const ethUSDFetcherKey = (blockTag: BlockTag | undefined) => {
if (blockTag === undefined) {
return null;
}
return ["ethusd", blockTag];
};
const ethUSDFetcher =
(
provider: JsonRpcProvider | undefined
): Fetcher<BigNumber | undefined, ["ethusd", BlockTag | undefined]> =>
async (_, blockTag) => {
if (provider?.network.chainId !== 1) {
return undefined;
}
const c = new Contract("eth-usd.data.eth", AggregatorV3Interface, provider);
const priceData = await c.latestRoundData({ blockTag });
return BigNumber.from(priceData.answer);
};
export const useETHUSDOracle = ( export const useETHUSDOracle = (
provider: JsonRpcProvider | undefined, provider: JsonRpcProvider | undefined,
blockTag: BlockTag | undefined blockTag: BlockTag | undefined
) => { ): BigNumber | undefined => {
const blockTags = useMemo(() => [blockTag], [blockTag]); const fetcher = ethUSDFetcher(provider);
const priceMap = useMultipleETHUSDOracle(provider, blockTags); const { data, error } = useSWRImmutable(ethUSDFetcherKey(blockTag), fetcher);
if (error) {
if (blockTag === undefined) {
return undefined; return undefined;
} }
return priceMap[blockTag]; return data;
}; };
export const useMultipleETHUSDOracle = ( export const useMultipleETHUSDOracle = (