|
| 1 | +import { useMemo, useState } from "react"; |
| 2 | +import type { Address, Hash } from "viem"; |
| 3 | +import { |
| 4 | + createConfig, |
| 5 | + http, |
| 6 | + useTransactionReceipt, |
| 7 | + useWatchBlocks, |
| 8 | +} from "wagmi"; |
| 9 | +import { Stack } from "~/api/stacks"; |
| 10 | +import { useAnvilNodeInfo, useForkChainId } from "./useAnvil"; |
| 11 | + |
| 12 | +export interface LatestTransaction { |
| 13 | + hash: Hash; |
| 14 | + success: boolean; |
| 15 | + timestamp: number; |
| 16 | +} |
| 17 | + |
| 18 | +export function useStackInfo(stack: Stack) { |
| 19 | + const config = useMemo( |
| 20 | + () => |
| 21 | + createConfig({ |
| 22 | + chains: [ |
| 23 | + { |
| 24 | + id: stack.chain_id, |
| 25 | + name: stack.slug, |
| 26 | + nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, |
| 27 | + rpcUrls: { |
| 28 | + default: { http: [stack.rpc_url] }, |
| 29 | + }, |
| 30 | + }, |
| 31 | + ], |
| 32 | + transports: { |
| 33 | + [stack.chain_id]: http(stack.rpc_url), |
| 34 | + }, |
| 35 | + }), |
| 36 | + [stack.chain_id, stack.rpc_url, stack.slug], |
| 37 | + ); |
| 38 | + |
| 39 | + const [latestStackInfo, setLatestStackInfo] = useState< |
| 40 | + | { |
| 41 | + latestBlockNumber: number; |
| 42 | + latestBlockTimestamp: number; |
| 43 | + latestTxHash: Hash; |
| 44 | + } |
| 45 | + | undefined |
| 46 | + >(); |
| 47 | + |
| 48 | + const { data: anvilInfo } = useAnvilNodeInfo(stack.slug, stack.rpc_url); |
| 49 | + const { data: forkChainId } = useForkChainId( |
| 50 | + stack.slug, |
| 51 | + stack.anvil_opts?.fork_url, |
| 52 | + ); |
| 53 | + |
| 54 | + useWatchBlocks({ |
| 55 | + config, |
| 56 | + includeTransactions: true, |
| 57 | + emitOnBegin: true, |
| 58 | + onBlock(block) { |
| 59 | + if (latestStackInfo?.latestBlockNumber === Number(block.number)) return; |
| 60 | + const tx = block.transactions[block.transactions.length - 1]; |
| 61 | + setLatestStackInfo((prev) => ({ |
| 62 | + latestTxHash: tx?.hash ?? prev?.latestTxHash, |
| 63 | + latestBlockNumber: Number(block.number), |
| 64 | + latestBlockTimestamp: Number(block.timestamp), |
| 65 | + })); |
| 66 | + }, |
| 67 | + }); |
| 68 | + |
| 69 | + const { data: receipt } = useTransactionReceipt({ |
| 70 | + config, |
| 71 | + hash: latestStackInfo?.latestTxHash, |
| 72 | + }); |
| 73 | + |
| 74 | + return { |
| 75 | + data: { |
| 76 | + liveInfo: { |
| 77 | + ...latestStackInfo, |
| 78 | + txStatusSuccess: receipt?.status === "success", |
| 79 | + }, |
| 80 | + anvilInfo, |
| 81 | + forkChainId, |
| 82 | + }, |
| 83 | + }; |
| 84 | +} |
0 commit comments