Skip to content

Instantly share code, notes, and snippets.

@tvler
Created May 5, 2023 18:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/0fc39e15e9a2fc86741b28a6df9e9bf0 to your computer and use it in GitHub Desktop.
Save tvler/0fc39e15e9a2fc86741b28a6df9e9bf0 to your computer and use it in GitHub Desktop.
Fast way to get a wagmi chain from a chainId
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