2022-03-17 15:56:54 +00:00
|
|
|
import { apiGetChainNamespace, ChainsMap } from "caip-api";
|
2022-08-08 09:32:24 +00:00
|
|
|
import {
|
|
|
|
createContext,
|
|
|
|
ReactNode,
|
|
|
|
useContext,
|
|
|
|
useEffect,
|
|
|
|
useState,
|
|
|
|
} from "react";
|
2022-03-17 15:56:54 +00:00
|
|
|
import { SolanaChainData } from "../chains/solana";
|
2022-08-11 09:43:12 +00:00
|
|
|
import { PolkadotChainData } from "../chains/polkadot";
|
2022-03-17 15:56:54 +00:00
|
|
|
|
|
|
|
import { ChainNamespaces, getAllChainNamespaces } from "../helpers";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Types
|
|
|
|
*/
|
|
|
|
interface IContext {
|
|
|
|
chainData: ChainNamespaces;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Context
|
|
|
|
*/
|
|
|
|
export const ChainDataContext = createContext<IContext>({} as IContext);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Provider
|
|
|
|
*/
|
2022-08-08 09:32:24 +00:00
|
|
|
export function ChainDataContextProvider({
|
|
|
|
children,
|
|
|
|
}: {
|
|
|
|
children: ReactNode | ReactNode[];
|
|
|
|
}) {
|
2022-03-17 15:56:54 +00:00
|
|
|
const [chainData, setChainData] = useState<ChainNamespaces>({});
|
|
|
|
|
|
|
|
const loadChainData = async () => {
|
|
|
|
const namespaces = getAllChainNamespaces();
|
|
|
|
const chainData: ChainNamespaces = {};
|
|
|
|
await Promise.all(
|
2022-08-08 09:32:24 +00:00
|
|
|
namespaces.map(async (namespace) => {
|
2022-03-17 15:56:54 +00:00
|
|
|
let chains: ChainsMap | undefined;
|
|
|
|
try {
|
|
|
|
if (namespace === "solana") {
|
|
|
|
chains = SolanaChainData;
|
2022-08-11 09:43:12 +00:00
|
|
|
} else if (namespace === "polkadot") {
|
|
|
|
chains = PolkadotChainData;
|
2022-03-17 15:56:54 +00:00
|
|
|
} else {
|
|
|
|
chains = await apiGetChainNamespace(namespace);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
// ignore error
|
|
|
|
}
|
|
|
|
if (typeof chains !== "undefined") {
|
|
|
|
chainData[namespace] = chains;
|
|
|
|
}
|
2022-08-08 09:32:24 +00:00
|
|
|
})
|
2022-03-17 15:56:54 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
setChainData(chainData);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
loadChainData();
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<ChainDataContext.Provider
|
|
|
|
value={{
|
|
|
|
chainData,
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</ChainDataContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useChainData() {
|
|
|
|
const context = useContext(ChainDataContext);
|
|
|
|
if (context === undefined) {
|
2022-08-08 09:32:24 +00:00
|
|
|
throw new Error(
|
|
|
|
"useChainData must be used within a ChainDataContextProvider"
|
|
|
|
);
|
2022-03-17 15:56:54 +00:00
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|