Skip to content

Commit

Permalink
Refactor useNetworkEnsNameAsync to handle chainId more robustly and f…
Browse files Browse the repository at this point in the history
…allback to mainnet if not provided
  • Loading branch information
Da-Colon committed Feb 4, 2025
1 parent 993d817 commit df440ed
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/hooks/useNetworkEnsName.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
import { Address, createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
import { useEnsName } from 'wagmi';
import {
supportedEnsNetworks,
Expand Down Expand Up @@ -34,12 +35,19 @@ export function useNetworkEnsNameAsync() {

const getEnsName = useCallback(
(args: { address: Address; chainId?: number }) => {
const propsOrFallbackChainId = args?.chainId ?? chain.id;
if (!supportedEnsNetworks.includes(propsOrFallbackChainId)) {
throw new Error(`ENS is not supported for chain ${propsOrFallbackChainId}`);
let effectiveChainId: number;

if (args.chainId !== undefined) {
if (!supportedEnsNetworks.includes(args.chainId)) {
throw new Error(`ENS is not supported for chain ${args.chainId}`);
}
effectiveChainId = args.chainId;
} else {
// No chain id provided: try to use network chain id, otherwise fallback to mainnet.
effectiveChainId = supportedEnsNetworks.includes(chain.id) ? chain.id : mainnet.id;
}

const networkConfig = getConfigByChainId(propsOrFallbackChainId);
const networkConfig = getConfigByChainId(effectiveChainId);
const publicClient = createPublicClient({
chain: networkConfig.chain,
transport: http(networkConfig.rpcEndpoint),
Expand Down

0 comments on commit df440ed

Please sign in to comment.