Skip to content

Commit 7dd2a8e

Browse files
Merge pull request #426 from BootNodeDev/fix/explorer-link-missing-explorer
fix: throw when getExplorerLink has no block explorer URL available
2 parents 5456c99 + a23f494 commit 7dd2a8e

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/utils/getExplorerLink.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ describe('getExplorerLink', () => {
3939
).toThrow('Invalid hash or address')
4040
})
4141

42+
it('throws when chain has no block explorer and no explorerUrl is provided', () => {
43+
const chainWithoutExplorer: Chain = { ...chain, blockExplorers: undefined }
44+
expect(() => getExplorerLink({ chain: chainWithoutExplorer, hashOrAddress: address })).toThrow(
45+
'No block explorer URL available for this chain',
46+
)
47+
})
48+
4249
it('works with a chain that has no default block explorer (explorerUrl provided)', () => {
4350
const chainWithoutExplorer: Chain = { ...chain, blockExplorers: undefined }
4451
const explorerUrl = 'https://fallback.explorer.io'

src/utils/getExplorerLink.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export type GetExplorerUrlParams = {
1919
* @param {string} [params.explorerUrl] - Optional custom explorer URL to override the chain's default explorer
2020
*
2121
* @throws {Error} Throws an error if the provided hash or address is invalid
22+
* @throws {Error} Throws an error if no explorer URL is available (neither `explorerUrl` nor `chain.blockExplorers`)
2223
*
2324
* @returns {string} The complete explorer URL for the given hash or address
2425
*
@@ -43,15 +44,17 @@ export type GetExplorerUrlParams = {
4344
* ```
4445
*/
4546
export const getExplorerLink = ({ chain, explorerUrl, hashOrAddress }: GetExplorerUrlParams) => {
47+
const baseUrl = explorerUrl ?? chain.blockExplorers?.default.url
48+
49+
if (!baseUrl) {
50+
throw new Error('No block explorer URL available for this chain')
51+
}
52+
4653
if (isAddress(hashOrAddress)) {
47-
return explorerUrl
48-
? `${explorerUrl}/address/${hashOrAddress}`
49-
: `${chain.blockExplorers?.default.url}/address/${hashOrAddress}`
54+
return `${baseUrl}/address/${hashOrAddress}`
5055
}
5156
if (isHash(hashOrAddress)) {
52-
return explorerUrl
53-
? `${explorerUrl}/tx/${hashOrAddress}`
54-
: `${chain.blockExplorers?.default.url}/tx/${hashOrAddress}`
57+
return `${baseUrl}/tx/${hashOrAddress}`
5558
}
5659

5760
throw new Error('Invalid hash or address')

0 commit comments

Comments
 (0)