-
I need to determine the correct chain only based on the RPC URL. Is there some way to make viem ask for the chainId and then set the correct chain automatically (e.g. if chain id = 1 set mainnet ...) or do I have to write this functionality on my own? And if I need to do this on my own can use a publicClient for this? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Yep, you will need to do this on your own, and create your own mapping before passing the chain to viem: import * as chains from 'viem/chains'
function getChain(id: number) {
return chains.find(x => x.id === id)
}
const id = getId()
const chain = getChain(id) |
Beta Was this translation helpful? Give feedback.
-
Thank you all for the responses. Here is the final code I used:
I couldn't use |
Beta Was this translation helpful? Give feedback.
-
@jxom To make use cases like this easier, I'd suggest to remove @benesjan To get around that (so you can optimize this fn a bit), you could do this for now: import * as all from "viem/chains";
const { defineChain: _, ...chains } = all;
/**
* Gets the chain object for the given chain id.
* @param chainId - Chain id of the target EVM chain.
* @returns Viem's chain object.
*/
function getChain(chainId: number) {
for (const chain of Object.values(chains)) {
if (chain.id === chainId) {
return chain;
}
}
throw new Error(`Chain with id ${chainId} not found`);
} |
Beta Was this translation helpful? Give feedback.
Yep, you will need to do this on your own, and create your own mapping before passing the chain to viem: