Simplify SWR code
This commit is contained in:
parent
e9907f5925
commit
c2e9ad7bd8
|
@ -4,6 +4,7 @@ import { Contract } from "@ethersproject/contracts";
|
|||
import { BigNumber } from "@ethersproject/bignumber";
|
||||
import AggregatorV3Interface from "@chainlink/contracts/abi/v0.8/AggregatorV3Interface.json";
|
||||
import FeedRegistryInterface from "@chainlink/contracts/abi/v0.8/FeedRegistryInterface.json";
|
||||
import { Fetcher } from "swr";
|
||||
import useSWRImmutable from "swr/immutable";
|
||||
import { ChecksummedAddress } from "./types";
|
||||
|
||||
|
@ -13,10 +14,13 @@ const FEED_REGISTRY_MAINNET: ChecksummedAddress =
|
|||
// The USD "token" address for Chainlink feed registry's purposes
|
||||
const USD = "0x0000000000000000000000000000000000000348";
|
||||
|
||||
type FeedRegistryFetcherKey = [ChecksummedAddress, BlockTag];
|
||||
type FeedRegistryFetcherData = [BigNumber | undefined, number | undefined];
|
||||
|
||||
const feedRegistryFetcherKey = (
|
||||
tokenAddress: ChecksummedAddress,
|
||||
blockTag: BlockTag | undefined
|
||||
): [ChecksummedAddress, BlockTag] | null => {
|
||||
): FeedRegistryFetcherKey | null => {
|
||||
if (blockTag === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
@ -24,18 +28,17 @@ const feedRegistryFetcherKey = (
|
|||
};
|
||||
|
||||
const feedRegistryFetcher =
|
||||
(provider: JsonRpcProvider | undefined) =>
|
||||
async (
|
||||
tokenAddress: ChecksummedAddress,
|
||||
blockTag: BlockTag
|
||||
): Promise<[BigNumber | undefined, number | undefined]> => {
|
||||
(
|
||||
provider: JsonRpcProvider | undefined
|
||||
): Fetcher<FeedRegistryFetcherData, FeedRegistryFetcherKey> =>
|
||||
async (tokenAddress, blockTag) => {
|
||||
// It work works on ethereum mainnet and kovan, see:
|
||||
// https://docs.chain.link/docs/feed-registry/
|
||||
if (!provider || provider.network.chainId !== 1) {
|
||||
return [undefined, undefined];
|
||||
if (provider!.network.chainId !== 1) {
|
||||
throw new Error("FeedRegistry is supported only on mainnet");
|
||||
}
|
||||
|
||||
try {
|
||||
// Let SWR handle error
|
||||
const feedRegistry = new Contract(
|
||||
FEED_REGISTRY_MAINNET,
|
||||
FeedRegistryInterface,
|
||||
|
@ -49,10 +52,6 @@ const feedRegistryFetcher =
|
|||
blockTag,
|
||||
});
|
||||
return [quote, decimals];
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return [undefined, undefined];
|
||||
}
|
||||
};
|
||||
|
||||
export const useTokenUSDOracle = (
|
||||
|
|
Loading…
Reference in New Issue