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')