2022-08-22 19:05:37 +00:00
|
|
|
import { createContext, useContext } from "react";
|
|
|
|
import useSWRImmutable from "swr/immutable";
|
2022-03-28 17:10:42 +00:00
|
|
|
import { chainInfoURL } from "./url";
|
|
|
|
import { OtterscanRuntime } from "./useRuntime";
|
2022-03-26 00:38:12 +00:00
|
|
|
|
|
|
|
export type ChainInfo = {
|
2022-04-11 04:04:56 +00:00
|
|
|
network: string | undefined;
|
2022-04-06 01:38:27 +00:00
|
|
|
faucets: string[];
|
2022-04-02 17:56:36 +00:00
|
|
|
nativeCurrency: {
|
|
|
|
name: string;
|
|
|
|
symbol: string;
|
|
|
|
decimals: number;
|
|
|
|
};
|
2022-03-26 00:38:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const defaultChainInfo: ChainInfo = {
|
2022-04-11 04:04:56 +00:00
|
|
|
network: undefined,
|
2022-04-06 01:38:27 +00:00
|
|
|
faucets: [],
|
2022-04-02 17:56:36 +00:00
|
|
|
nativeCurrency: {
|
|
|
|
name: "Ether",
|
|
|
|
symbol: "ETH",
|
|
|
|
decimals: 18,
|
|
|
|
},
|
2022-03-26 00:38:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const ChainInfoContext = createContext<ChainInfo | undefined>(undefined);
|
|
|
|
|
2022-08-22 19:05:37 +00:00
|
|
|
const chainInfoFetcher = async (assetsURLPrefix: string, chainId: number) => {
|
|
|
|
const url = chainInfoURL(assetsURLPrefix, chainId);
|
|
|
|
const res = await fetch(url);
|
|
|
|
if (!res.ok) {
|
|
|
|
return defaultChainInfo;
|
|
|
|
}
|
|
|
|
|
|
|
|
const info: ChainInfo = await res.json();
|
|
|
|
return info;
|
|
|
|
};
|
|
|
|
|
2022-03-28 17:10:42 +00:00
|
|
|
export const useChainInfoFromMetadataFile = (
|
|
|
|
runtime: OtterscanRuntime | undefined
|
|
|
|
): ChainInfo | undefined => {
|
|
|
|
const assetsURLPrefix = runtime?.config?.assetsURLPrefix;
|
|
|
|
const chainId = runtime?.provider?.network.chainId;
|
|
|
|
|
2022-08-22 19:05:37 +00:00
|
|
|
const { data, error } = useSWRImmutable(
|
|
|
|
assetsURLPrefix !== undefined && chainId !== undefined
|
|
|
|
? [assetsURLPrefix, chainId]
|
|
|
|
: null,
|
|
|
|
chainInfoFetcher
|
|
|
|
);
|
|
|
|
if (error) {
|
|
|
|
return defaultChainInfo;
|
|
|
|
}
|
|
|
|
return data;
|
2022-03-28 17:10:42 +00:00
|
|
|
};
|
|
|
|
|
2022-03-26 00:38:12 +00:00
|
|
|
export const useChainInfo = (): ChainInfo => {
|
|
|
|
const chainInfo = useContext(ChainInfoContext);
|
|
|
|
if (chainInfo === undefined) {
|
|
|
|
throw new Error("no chain info");
|
|
|
|
}
|
|
|
|
return chainInfo;
|
|
|
|
};
|