Generalize implementation to support multiple block queries
This commit is contained in:
parent
a8f9a17c98
commit
8624c70877
@ -7,6 +7,18 @@ import AggregatorV3Interface from "@chainlink/contracts/abi/v0.8/AggregatorV3Int
|
|||||||
export const useETHUSDOracle = (
|
export const useETHUSDOracle = (
|
||||||
provider: JsonRpcProvider | undefined,
|
provider: JsonRpcProvider | undefined,
|
||||||
blockTag: BlockTag | 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(() => {
|
const ethFeed = useMemo(() => {
|
||||||
if (!provider || provider.network.chainId !== 1) {
|
if (!provider || provider.network.chainId !== 1) {
|
||||||
@ -21,22 +33,45 @@ export const useETHUSDOracle = (
|
|||||||
}
|
}
|
||||||
}, [provider]);
|
}, [provider]);
|
||||||
|
|
||||||
const [latestPriceData, setLatestPriceData] = useState<BigNumber>();
|
const [latestPriceData, setLatestPriceData] = useState<
|
||||||
|
Record<BlockTag, BigNumber>
|
||||||
|
>({});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!ethFeed || !blockTag) {
|
if (!ethFeed) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const readData = async () => {
|
const priceReaders: Promise<BigNumber | undefined>[] = [];
|
||||||
|
for (const blockTag of blockTags) {
|
||||||
|
priceReaders.push(
|
||||||
|
(async () => {
|
||||||
try {
|
try {
|
||||||
const priceData = await ethFeed.latestRoundData({ blockTag });
|
const priceData = await ethFeed.latestRoundData({ blockTag });
|
||||||
setLatestPriceData(BigNumber.from(priceData.answer));
|
return BigNumber.from(priceData.answer);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(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();
|
readData();
|
||||||
}, [ethFeed, blockTag]);
|
}, [ethFeed, blockTags]);
|
||||||
|
|
||||||
return latestPriceData;
|
return latestPriceData;
|
||||||
};
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user