From a23f4944f0441e2abe3a239301040a80af820860 Mon Sep 17 00:00:00 2001 From: Gabito Esmiapodo <4015436+gabitoesmiapodo@users.noreply.github.com> Date: Wed, 25 Mar 2026 15:20:47 -0300 Subject: [PATCH] fix: throw when getExplorerLink has no block explorer URL available --- src/utils/getExplorerLink.test.ts | 7 +++++++ src/utils/getExplorerLink.ts | 15 +++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/utils/getExplorerLink.test.ts b/src/utils/getExplorerLink.test.ts index c7ca4fad..9833c82f 100644 --- a/src/utils/getExplorerLink.test.ts +++ b/src/utils/getExplorerLink.test.ts @@ -39,6 +39,13 @@ describe('getExplorerLink', () => { ).toThrow('Invalid hash or address') }) + it('throws when chain has no block explorer and no explorerUrl is provided', () => { + const chainWithoutExplorer: Chain = { ...chain, blockExplorers: undefined } + expect(() => getExplorerLink({ chain: chainWithoutExplorer, hashOrAddress: address })).toThrow( + 'No block explorer URL available for this chain', + ) + }) + it('works with a chain that has no default block explorer (explorerUrl provided)', () => { const chainWithoutExplorer: Chain = { ...chain, blockExplorers: undefined } const explorerUrl = 'https://fallback.explorer.io' diff --git a/src/utils/getExplorerLink.ts b/src/utils/getExplorerLink.ts index 17237132..50e4fb3e 100644 --- a/src/utils/getExplorerLink.ts +++ b/src/utils/getExplorerLink.ts @@ -19,6 +19,7 @@ export type GetExplorerUrlParams = { * @param {string} [params.explorerUrl] - Optional custom explorer URL to override the chain's default explorer * * @throws {Error} Throws an error if the provided hash or address is invalid + * @throws {Error} Throws an error if no explorer URL is available (neither `explorerUrl` nor `chain.blockExplorers`) * * @returns {string} The complete explorer URL for the given hash or address * @@ -43,15 +44,17 @@ export type GetExplorerUrlParams = { * ``` */ export const getExplorerLink = ({ chain, explorerUrl, hashOrAddress }: GetExplorerUrlParams) => { + const baseUrl = explorerUrl ?? chain.blockExplorers?.default.url + + if (!baseUrl) { + throw new Error('No block explorer URL available for this chain') + } + if (isAddress(hashOrAddress)) { - return explorerUrl - ? `${explorerUrl}/address/${hashOrAddress}` - : `${chain.blockExplorers?.default.url}/address/${hashOrAddress}` + return `${baseUrl}/address/${hashOrAddress}` } if (isHash(hashOrAddress)) { - return explorerUrl - ? `${explorerUrl}/tx/${hashOrAddress}` - : `${chain.blockExplorers?.default.url}/tx/${hashOrAddress}` + return `${baseUrl}/tx/${hashOrAddress}` } throw new Error('Invalid hash or address')