generated from scaffold-eth/scaffold-eth
-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add useHeimdall hook and prefetch abis from heimdall backend (#166)
Co-authored-by: Shiv Bhonde <[email protected]>
- Loading branch information
1 parent
941c8f5
commit cc27388
Showing
3 changed files
with
85 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { useQuery } from "@tanstack/react-query"; | ||
import { Address, isAddress } from "viem"; | ||
import { HEIMDALL_API_URL } from "~~/utils/constants"; | ||
|
||
type UseHeimdallParams = { | ||
contractAddress?: Address; | ||
rpcUrl?: string; | ||
disabled?: boolean; | ||
}; | ||
|
||
export const useHeimdall = ({ contractAddress, rpcUrl, disabled = false }: UseHeimdallParams) => { | ||
const fetchFromHeimdall = async () => { | ||
if (!contractAddress || !isAddress(contractAddress)) { | ||
throw new Error("Invalid contract address"); | ||
} | ||
if (!rpcUrl) { | ||
throw new Error("RPC URL is required"); | ||
} | ||
|
||
const rpcUrlWithoutHttps = rpcUrl.substring(8); | ||
const response = await fetch(`${HEIMDALL_API_URL}/${contractAddress}?rpc_url=${rpcUrlWithoutHttps}`); | ||
|
||
if (!response.ok) { | ||
throw new Error(`HTTP error! status: ${response.status}`); | ||
} | ||
|
||
const abi = await response.json(); | ||
|
||
if (!Array.isArray(abi) || abi.length === 0) { | ||
throw new Error("Failed to fetch ABI from Heimdall"); | ||
} | ||
|
||
return abi; | ||
}; | ||
|
||
const { | ||
data: abi, | ||
error, | ||
isLoading, | ||
} = useQuery({ | ||
queryKey: ["heimdallAbi", { contractAddress, rpcUrl }], | ||
queryFn: fetchFromHeimdall, | ||
enabled: !disabled && Boolean(contractAddress) && Boolean(rpcUrl) && isAddress(contractAddress as Address), | ||
retry: false, | ||
}); | ||
|
||
return { | ||
abi, | ||
error, | ||
isLoading, | ||
}; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters