Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/utils/getExplorerLink.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
15 changes: 9 additions & 6 deletions src/utils/getExplorerLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand All @@ -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')
Expand Down
Loading