2021-08-31 05:56:05 +00:00
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
|
|
import { JsonRpcProvider, BlockTag } from "@ethersproject/providers";
|
|
|
|
import { Contract } from "@ethersproject/contracts";
|
|
|
|
import { BigNumber } from "@ethersproject/bignumber";
|
|
|
|
import AggregatorV3Interface from "@chainlink/contracts/abi/v0.8/AggregatorV3Interface.json";
|
|
|
|
|
|
|
|
export const useETHUSDOracle = (
|
|
|
|
provider: JsonRpcProvider | undefined,
|
|
|
|
blockTag: BlockTag | undefined
|
2021-08-31 18:06:26 +00:00
|
|
|
) => {
|
2021-09-01 08:53:57 +00:00
|
|
|
const blockTags = useMemo(() => [blockTag], [blockTag]);
|
|
|
|
const priceMap = useMultipleETHUSDOracle(provider, blockTags);
|
2021-08-31 18:06:26 +00:00
|
|
|
|
|
|
|
if (blockTag === undefined) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
return priceMap[blockTag];
|
|
|
|
};
|
|
|
|
|
|
|
|
export const useMultipleETHUSDOracle = (
|
|
|
|
provider: JsonRpcProvider | undefined,
|
|
|
|
blockTags: (BlockTag | undefined)[]
|
2021-08-31 05:56:05 +00:00
|
|
|
) => {
|
|
|
|
const ethFeed = useMemo(() => {
|
|
|
|
if (!provider || provider.network.chainId !== 1) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
return new Contract("eth-usd.data.eth", AggregatorV3Interface, provider);
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}, [provider]);
|
|
|
|
|
2021-08-31 18:06:26 +00:00
|
|
|
const [latestPriceData, setLatestPriceData] = useState<
|
|
|
|
Record<BlockTag, BigNumber>
|
|
|
|
>({});
|
2021-08-31 05:56:05 +00:00
|
|
|
useEffect(() => {
|
2021-08-31 18:06:26 +00:00
|
|
|
if (!ethFeed) {
|
2021-08-31 05:56:05 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-08-31 18:06:26 +00:00
|
|
|
const priceReaders: Promise<BigNumber | undefined>[] = [];
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
})()
|
|
|
|
);
|
|
|
|
}
|
2021-08-31 05:56:05 +00:00
|
|
|
const readData = async () => {
|
2021-08-31 18:06:26 +00:00
|
|
|
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;
|
2021-08-31 05:56:05 +00:00
|
|
|
}
|
2021-08-31 18:06:26 +00:00
|
|
|
|
|
|
|
setLatestPriceData(priceMap);
|
2021-08-31 05:56:05 +00:00
|
|
|
};
|
|
|
|
readData();
|
2021-08-31 18:06:26 +00:00
|
|
|
}, [ethFeed, blockTags]);
|
2021-08-31 05:56:05 +00:00
|
|
|
|
|
|
|
return latestPriceData;
|
|
|
|
};
|