From 8624c70877eabf423ab032f6cf4edeb2939b78b5 Mon Sep 17 00:00:00 2001 From: Willian Mitsuda Date: Tue, 31 Aug 2021 15:06:26 -0300 Subject: [PATCH] Generalize implementation to support multiple block queries --- src/usePriceOracle.ts | 51 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/src/usePriceOracle.ts b/src/usePriceOracle.ts index e318a47..0fc909a 100644 --- a/src/usePriceOracle.ts +++ b/src/usePriceOracle.ts @@ -7,6 +7,18 @@ import AggregatorV3Interface from "@chainlink/contracts/abi/v0.8/AggregatorV3Int export const useETHUSDOracle = ( provider: JsonRpcProvider | undefined, blockTag: BlockTag | undefined +) => { + const priceMap = useMultipleETHUSDOracle(provider, [blockTag]); + + if (blockTag === undefined) { + return undefined; + } + return priceMap[blockTag]; +}; + +export const useMultipleETHUSDOracle = ( + provider: JsonRpcProvider | undefined, + blockTags: (BlockTag | undefined)[] ) => { const ethFeed = useMemo(() => { if (!provider || provider.network.chainId !== 1) { @@ -21,22 +33,45 @@ export const useETHUSDOracle = ( } }, [provider]); - const [latestPriceData, setLatestPriceData] = useState(); + const [latestPriceData, setLatestPriceData] = useState< + Record + >({}); useEffect(() => { - if (!ethFeed || !blockTag) { + if (!ethFeed) { return; } + const priceReaders: Promise[] = []; + for (const blockTag of blockTags) { + priceReaders.push( + (async () => { + try { + const priceData = await ethFeed.latestRoundData({ blockTag }); + return BigNumber.from(priceData.answer); + } catch (err) { + console.error(err); + return undefined; + } + })() + ); + } const readData = async () => { - try { - const priceData = await ethFeed.latestRoundData({ blockTag }); - setLatestPriceData(BigNumber.from(priceData.answer)); - } catch (err) { - console.error(err); + const results = await Promise.all(priceReaders); + const priceMap: Record = {}; + for (let i = 0; i < blockTags.length; i++) { + const blockTag = blockTags[i]; + const result = results[i]; + if (blockTag === undefined || result === undefined) { + continue; + } + + priceMap[blockTag] = result; } + + setLatestPriceData(priceMap); }; readData(); - }, [ethFeed, blockTag]); + }, [ethFeed, blockTags]); return latestPriceData; };