|
| 1 | +import { useQuery } from "@tanstack/react-query"; |
| 2 | +import { fetchProposalVetos } from "@/services/veto.service"; |
| 3 | +import type { Proposal, ProposalWithDAO } from "@/types"; |
| 4 | +import { useMemo } from "react"; |
| 5 | + |
| 6 | +interface UseVetoCheckProps { |
| 7 | + proposal: Proposal | ProposalWithDAO; |
| 8 | + votesForNum?: number; |
| 9 | +} |
| 10 | + |
| 11 | +interface VetoCheckResult { |
| 12 | + totalVetoAmount: number; |
| 13 | + rawTotalVetoAmount: string; |
| 14 | + vetoExceedsForVote: boolean; |
| 15 | + isLoading: boolean; |
| 16 | + error: boolean; |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Hook to check if veto amount exceeds the For votes |
| 21 | + * Vetos are formatted the same way as votes (divided by 1e8) |
| 22 | + */ |
| 23 | +export function useVetoCheck({ |
| 24 | + proposal, |
| 25 | + votesForNum = 0, |
| 26 | +}: UseVetoCheckProps): VetoCheckResult { |
| 27 | + // Fetch vetos for this proposal |
| 28 | + const { |
| 29 | + data: vetos, |
| 30 | + isLoading, |
| 31 | + error, |
| 32 | + } = useQuery({ |
| 33 | + queryKey: ["proposalVetos", proposal.id], |
| 34 | + queryFn: async () => { |
| 35 | + if (!proposal.id) { |
| 36 | + return []; |
| 37 | + } |
| 38 | + return await fetchProposalVetos(proposal.id); |
| 39 | + }, |
| 40 | + enabled: !!proposal.id, |
| 41 | + staleTime: 30000, // 30 seconds |
| 42 | + retry: 2, |
| 43 | + }); |
| 44 | + |
| 45 | + // Calculate total veto amount |
| 46 | + const vetoCalculations = useMemo(() => { |
| 47 | + if (!vetos || vetos.length === 0) { |
| 48 | + return { |
| 49 | + totalVetoAmount: 0, |
| 50 | + rawTotalVetoAmount: "0", |
| 51 | + vetoExceedsForVote: false, |
| 52 | + }; |
| 53 | + } |
| 54 | + |
| 55 | + // Sum up all veto amounts |
| 56 | + const totalRaw = vetos.reduce((sum, veto) => { |
| 57 | + const amount = veto.amount ? parseFloat(veto.amount) : 0; |
| 58 | + return sum + amount; |
| 59 | + }, 0); |
| 60 | + |
| 61 | + // Format veto amount the same way as votes (divide by 1e8) |
| 62 | + const totalFormatted = totalRaw; |
| 63 | + |
| 64 | + // Check if veto exceeds For votes |
| 65 | + const vetoExceedsForVote = totalFormatted > votesForNum; |
| 66 | + |
| 67 | + return { |
| 68 | + totalVetoAmount: totalFormatted, |
| 69 | + rawTotalVetoAmount: totalRaw.toString(), |
| 70 | + vetoExceedsForVote, |
| 71 | + }; |
| 72 | + }, [vetos, votesForNum]); |
| 73 | + |
| 74 | + return { |
| 75 | + ...vetoCalculations, |
| 76 | + isLoading, |
| 77 | + error: !!error, |
| 78 | + }; |
| 79 | +} |
0 commit comments