Generalize implementation to support multiple block queries

This commit is contained in:
Willian Mitsuda 2021-08-31 15:06:26 -03:00
parent a8f9a17c98
commit 8624c70877
1 changed files with 43 additions and 8 deletions

View File

@ -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<BigNumber>();
const [latestPriceData, setLatestPriceData] = useState<
Record<BlockTag, BigNumber>
>({});
useEffect(() => {
if (!ethFeed || !blockTag) {
if (!ethFeed) {
return;
}
const readData = async () => {
const priceReaders: Promise<BigNumber | undefined>[] = [];
for (const blockTag of blockTags) {
priceReaders.push(
(async () => {
try {
const priceData = await ethFeed.latestRoundData({ blockTag });
setLatestPriceData(BigNumber.from(priceData.answer));
return BigNumber.from(priceData.answer);
} catch (err) {
console.error(err);
return undefined;
}
})()
);
}
const readData = async () => {
const results = await Promise.all(priceReaders);
const priceMap: Record<BlockTag, BigNumber> = {};
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;
};