Created
May 5, 2023 18:50
-
-
Save tvler/0fc39e15e9a2fc86741b28a6df9e9bf0 to your computer and use it in GitHub Desktop.
Fast way to get a wagmi chain from a chainId
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as chains from '@wagmi/chains' | |
import type { Chain } from 'wagmi' | |
const chainValues = Object.values(chains) | |
const chainMap = new Map<number, Chain>() | |
for (const chain of chainValues) { | |
chainMap.set(chain.id, chain) | |
} | |
export function getChainFromId(id: number | null | undefined): Chain | |
export function getChainFromId( | |
id: number | null | undefined, | |
options: { fallbackToMainnet: false } | |
): Chain | undefined | |
export function getChainFromId( | |
id: number | null | undefined, | |
{ fallbackToMainnet = true }: { fallbackToMainnet?: boolean } = {} | |
): Chain | undefined { | |
const chain = id == undefined ? null : chainMap.get(id) | |
if (chain) { | |
return chain | |
} | |
if (fallbackToMainnet) { | |
return chains.mainnet | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment