diff --git a/src/components/common/RageQuitPanel.tsx b/src/components/common/RageQuitPanel.tsx new file mode 100644 index 00000000..ce73a50f --- /dev/null +++ b/src/components/common/RageQuitPanel.tsx @@ -0,0 +1,177 @@ +import { useState } from 'react'; +import { AlertTriangle, LoaderCircle, LogOut } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { useRageQuit } from '@/hooks/useRageQuit'; +import { useStellarWallet } from '@/hooks/useStellarWallet'; +import { formatCompactNumber } from '@/utils/numberFormat.utils'; + +export interface RageQuitPanelProps { + proposalId: string; +} + +const ELIGIBILITY_MESSAGE: Record = { + voted_for: + 'You voted for this proposal and are not eligible to rage-quit.', + window_closed: 'The rage-quit window has closed for this proposal.', + cap_reached: + 'The maximum exit cap has been reached. No further rage-quits are allowed.', +}; + +/** + * Rage-quit panel surfaced on passed proposals during the exit window (#1253). + * + * Eligible holders (voted against or abstained, held keys at snapshot) can + * burn their keys and receive a pro-rata share of the reserve. + * Hidden entirely when the wallet is disconnected or the window is closed. + */ +export default function RageQuitPanel({ proposalId }: RageQuitPanelProps) { + const { address } = useStellarWallet(); + const { + rageQuitStatus, + isLoading, + isWindowOpen, + eligibility, + payoutPerKey, + windowEndsAt, + exitedFraction, + maxExitFraction, + isSubmitting, + submitRageQuit, + } = useRageQuit(proposalId, address); + + const [amount, setAmount] = useState(''); + + // Don't render if wallet is not connected + if (!address) return null; + + if (isLoading) { + return ( +
+ ); + } + + // Ineligible states: show a brief notice only + if ( + eligibility === 'voted_for' || + eligibility === 'window_closed' || + eligibility === 'cap_reached' || + !isWindowOpen + ) { + const message = ELIGIBILITY_MESSAGE[eligibility]; + if (!message) return null; + return ( +
+
+
+
+ ); + } + + const parsedAmount = parseInt(amount, 10); + const validAmount = + Number.isInteger(parsedAmount) && parsedAmount > 0; + + const capPercent = Math.round(maxExitFraction * 100); + const exitedPercent = Math.round(exitedFraction * 100); + const deadline = windowEndsAt + ? new Date(windowEndsAt).toLocaleString() + : null; + + return ( +
+
+
+ +

+ You voted against or abstained on this proposal. Burn your keys now + to receive a pro-rata share of the reserve before execution. +

+ +
+ {payoutPerKey !== null && ( +
+
Payout / key
+
+ {formatCompactNumber(payoutPerKey)} XLM +
+
+ )} +
+
Exited
+
+ {exitedPercent}% of {capPercent}% cap +
+
+ {deadline && ( +
+
Window closes
+
{deadline}
+
+ )} +
+ + {rageQuitStatus && ( +
+ + setAmount(e.target.value)} + placeholder="e.g. 10" + className="bg-white/[0.04] text-white placeholder:text-white/30" + data-testid="ragequit-amount-input" + /> + +
+ )} +
+ ); +} diff --git a/src/hooks/useRageQuit.ts b/src/hooks/useRageQuit.ts new file mode 100644 index 00000000..81d7374e --- /dev/null +++ b/src/hooks/useRageQuit.ts @@ -0,0 +1,70 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { rageQuitService, type RageQuitResult } from '@/services/rageQuit.service'; +import { queryKeys } from '@/lib/queryKeys'; +import { buildStellarExpertTxUrl } from '@/constants/stellar'; +import { env } from '@/utils/env.utils'; +import showToast from '@/utils/toast.util'; + +/** Poll the rage-quit window every 10 s while it is open. */ +const POLL_INTERVAL_MS = 10_000; + +/** + * Fetches rage-quit eligibility and window state, and exposes a mutation + * to submit the rage-quit transaction (#1253). + * + * Only fetches when both proposalId and wallet are provided. + */ +export function useRageQuit(proposalId: string, wallet: string | undefined) { + const queryClient = useQueryClient(); + const enabled = Boolean(proposalId && wallet); + + const statusQuery = useQuery({ + queryKey: queryKeys.governance.rageQuit(proposalId, wallet ?? ''), + queryFn: () => rageQuitService.getRageQuitStatus(proposalId, wallet!), + enabled, + staleTime: 5_000, + refetchInterval: data => + data?.isOpen ? POLL_INTERVAL_MS : false, + }); + + const submitMutation = useMutation({ + mutationFn: ({ amount }) => + rageQuitService.submitRageQuit(proposalId, wallet!, amount), + onSuccess: result => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.governance.rageQuit(proposalId, wallet ?? ''), + }); + void queryClient.invalidateQueries({ + queryKey: queryKeys.governance.proposal(proposalId), + }); + const txUrl = result.txHash + ? buildStellarExpertTxUrl(result.txHash, env.VITE_STELLAR_NETWORK) + : undefined; + showToast.transactionSuccess( + 'Rage-quit submitted', + `${result.keysBurned} key(s) burned. ${result.amountPaid.toFixed(2)} XLM returned.`, + result.txHash ?? undefined, + txUrl + ); + }, + onError: () => { + showToast.error('Rage-quit failed. Please try again.'); + }, + }); + + const status = statusQuery.data ?? null; + + return { + rageQuitStatus: status, + isLoading: statusQuery.isLoading, + isError: statusQuery.isError, + isWindowOpen: status?.isOpen ?? false, + eligibility: status?.eligibility ?? 'unknown', + payoutPerKey: status?.payoutPerKey ?? null, + windowEndsAt: status?.windowEndsAt ?? null, + exitedFraction: status?.exitedFraction ?? 0, + maxExitFraction: status?.maxExitFraction ?? 0, + isSubmitting: submitMutation.isPending, + submitRageQuit: (amount: number) => submitMutation.mutate({ amount }), + }; +} diff --git a/src/hooks/useRagequit.ts b/src/hooks/useRagequit.ts deleted file mode 100644 index ec9040fe..00000000 --- a/src/hooks/useRagequit.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { useEffect, useState } from 'react'; -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { queryKeys } from '@/lib/queryKeys'; -import { ragequitService } from '@/services/ragequit.service'; -import type { RagequitState } from '@/types/ragequit'; -import showToast from '@/utils/toast.util'; - -export interface UseRagequitResult { - /** Full ragequit state. */ - data: RagequitState | undefined; - /** Whether the ragequit grace window is currently open. */ - isWindowOpen: boolean; - /** ISO string timestamp when window ends. */ - windowEndsAt: string; - /** Remaining time in seconds until the window closes (live ticked). */ - remainingSeconds: number; - /** Formatted countdown string (HH:MM:SS or DDd HHh). */ - countdownText: string; - /** Total reserve available backing creator keys. */ - totalReserveXlm: number; - /** Cumulative keys exited so far. */ - cumulativeExits: number; - /** Maximum keys allowed to exit in this window. */ - exitCap: number; - /** Percentage of exit cap reached. */ - exitCapPercent: number; - /** Whether the current user is eligible to exit with reserve share. */ - isEligible: boolean; - /** Reason explaining why the user is ineligible, if applicable. */ - ineligibilityReason?: string; - /** User's opposing keys available to burn. */ - userKeys: number; - /** Estimated total payout in XLM if user burns their eligible keys. */ - estimatedPayoutXlm: number; - /** Proportional reserve payout per individual key. */ - payoutPerKeyXlm: number; - /** Whether proposal was executed after the window closed. */ - isExecuted: boolean; - /** Linked executed proposal ID. */ - executedProposalId?: string; - /** Execute ragequit exit mutation. */ - executeRagequit: (keysToBurn: number) => Promise<{ txHash: string; payoutXlm: number }>; - /** Loading state. */ - isLoading: boolean; - /** Mutation pending. */ - isMutating: boolean; - /** Error state. */ - error: Error | null; -} - -export function formatCountdown(seconds: number): string { - const safe = Math.max(0, seconds); - if (safe === 0) return '00:00:00 (Window Ended)'; - - const days = Math.floor(safe / 86400); - const hours = Math.floor((safe % 86400) / 3600); - const minutes = Math.floor((safe % 3600) / 60); - const secs = safe % 60; - - if (days > 0) { - return `${days}d ${hours.toString().padStart(2, '0')}h ${minutes.toString().padStart(2, '0')}m`; - } - - return [ - hours.toString().padStart(2, '0'), - minutes.toString().padStart(2, '0'), - secs.toString().padStart(2, '0'), - ].join(':'); -} - -export function useRagequit( - proposalId: string, - userAddress?: string -): UseRagequitResult { - const queryClient = useQueryClient(); - - const { data, isLoading, error } = useQuery({ - queryKey: queryKeys.ragequit.state(proposalId, userAddress), - queryFn: () => ragequitService.getRagequitState(proposalId, userAddress), - enabled: Boolean(proposalId), - }); - - // Live countdown timer state - const [remainingSeconds, setRemainingSeconds] = useState(0); - - useEffect(() => { - if (!data?.windowEndsAt) return; - const endMs = new Date(data.windowEndsAt).getTime(); - - const update = () => { - const diff = Math.max(0, Math.floor((endMs - Date.now()) / 1000)); - setRemainingSeconds(diff); - }; - - update(); - const interval = setInterval(update, 1000); - return () => clearInterval(interval); - }, [data?.windowEndsAt]); - - const mutation = useMutation({ - mutationFn: (keysToBurn: number) => - ragequitService.executeRagequit(proposalId, keysToBurn, userAddress), - onSuccess: res => { - showToast.success( - `Ragequit successful! Burned keys and received ${res.payoutXlm.toFixed(2)} XLM from reserve.` - ); - void queryClient.invalidateQueries({ - queryKey: queryKeys.ragequit.all(), - }); - }, - onError: (err: Error) => { - showToast.error(err.message || 'Failed to execute ragequit'); - }, - }); - - const isWindowOpen = Boolean(data?.isOpen) && remainingSeconds > 0; - const isExecuted = Boolean(data?.isExecuted); - const executedProposalId = - data?.executedProposalId ?? (isExecuted ? proposalId : undefined); - - const cumulativeExits = data?.cumulativeExits ?? 0; - const exitCap = Math.max(1, data?.exitCap ?? 1); - const exitCapPercent = Math.min(100, (cumulativeExits / exitCap) * 100); - - return { - data, - isWindowOpen, - windowEndsAt: data?.windowEndsAt ?? '', - remainingSeconds, - countdownText: formatCountdown(remainingSeconds), - totalReserveXlm: data?.totalReserveXlm ?? 0, - cumulativeExits, - exitCap, - exitCapPercent, - isEligible: isWindowOpen && Boolean(data?.isEligible), - ineligibilityReason: !isWindowOpen - ? 'The ragequit window for this proposal has closed.' - : data?.ineligibilityReason, - userKeys: data?.userKeys ?? 0, - estimatedPayoutXlm: data?.estimatedPayoutXlm ?? 0, - payoutPerKeyXlm: data?.payoutPerKeyXlm ?? 0, - isExecuted, - executedProposalId, - executeRagequit: mutation.mutateAsync, - isLoading, - isMutating: mutation.isPending, - error: (error as Error) || null, - }; -} diff --git a/src/lib/queryKeys.ts b/src/lib/queryKeys.ts index 966980fc..a70a81b2 100644 --- a/src/lib/queryKeys.ts +++ b/src/lib/queryKeys.ts @@ -262,6 +262,9 @@ export const queryKeys = { events: (type?: string) => ['governance', 'events', type ?? 'all'] as const, admin: () => ['governance', 'admin'] as const, + /** Rage-quit window state scoped to a proposal + wallet (#1253). */ + rageQuit: (proposalId: string, wallet: string) => + ['governance', 'proposal', proposalId, 'ragequit', wallet] as const, }, conviction: { all: () => ['conviction'] as const, diff --git a/src/pages/ProposalDetailPage.tsx b/src/pages/ProposalDetailPage.tsx index 41ad71e7..01fff485 100644 --- a/src/pages/ProposalDetailPage.tsx +++ b/src/pages/ProposalDetailPage.tsx @@ -12,6 +12,7 @@ import RagequitBanner from '@/components/governance/RagequitBanner'; import ProposalVoteHistory from '@/components/common/ProposalVoteHistory'; import { ProposalVotePanel } from '@/components/common/ProposalVotePanel'; import QuorumIndicator from '@/components/common/QuorumIndicator'; +import RageQuitPanel from '@/components/common/RageQuitPanel'; import { useGovernanceProposal } from '@/hooks/useGovernanceProposals'; import { useDocumentTitle } from '@/hooks/useDocumentTitle'; import { cn } from '@/lib/utils'; @@ -228,6 +229,11 @@ export default function ProposalDetailPage() {
)} + {/* Rage-quit window for passed proposals (#1253) */} + {proposal.status === 'passed' && ( + + )} +

Result and participation diff --git a/src/services/rageQuit.service.ts b/src/services/rageQuit.service.ts new file mode 100644 index 00000000..62b492e1 --- /dev/null +++ b/src/services/rageQuit.service.ts @@ -0,0 +1,84 @@ +import { BaseApiService, type APIResponse } from './api.service'; +import type { RageQuitStatus } from '@/types/governance'; + +export interface RageQuitResult { + txHash: string | null; + amountPaid: number; + keysBurned: number; +} + +function asRecord(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function normalizeRageQuitStatus(raw: unknown): RageQuitStatus { + const r = asRecord(raw); + return { + proposalId: String(r.proposalId ?? r.proposal_id ?? ''), + isOpen: Boolean(r.isOpen ?? r.is_open ?? false), + windowEndsAt: + typeof r.windowEndsAt === 'string' + ? r.windowEndsAt + : typeof r.window_ends_at === 'string' + ? r.window_ends_at + : null, + exitedFraction: Number(r.exitedFraction ?? r.exited_fraction ?? 0), + maxExitFraction: Number(r.maxExitFraction ?? r.max_exit_fraction ?? 0), + eligibility: + (r.eligibility as RageQuitStatus['eligibility']) ?? 'unknown', + payoutPerKey: + r.payoutPerKey !== undefined + ? Number(r.payoutPerKey) + : r.payout_per_key !== undefined + ? Number(r.payout_per_key) + : null, + }; +} + +class RageQuitService extends BaseApiService { + /** + * Fetch rage-quit window state for a proposal. + * GET /governance/proposals/:id/ragequit?wallet=:wallet + */ + async getRageQuitStatus( + proposalId: string, + wallet: string + ): Promise { + try { + const response = await this.api.get>( + `/governance/proposals/${encodeURIComponent(proposalId)}/ragequit`, + { params: { wallet } } + ); + return normalizeRageQuitStatus(response.data.data); + } catch (error) { + throw this.handleError(error); + } + } + + /** + * Submit a rage-quit transaction. + * POST /governance/proposals/:id/ragequit + * + * The backend assembles the Stellar transaction; the client signs and + * broadcasts it, then posts the signed XDR back to record the exit. + */ + async submitRageQuit( + proposalId: string, + wallet: string, + amount: number + ): Promise { + try { + const response = await this.api.post>( + `/governance/proposals/${encodeURIComponent(proposalId)}/ragequit`, + { wallet, amount } + ); + return response.data.data; + } catch (error) { + throw this.handleError(error); + } + } +} + +export const rageQuitService = new RageQuitService(); diff --git a/src/services/ragequit.service.ts b/src/services/ragequit.service.ts deleted file mode 100644 index 07b91a90..00000000 --- a/src/services/ragequit.service.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { BaseApiService } from './api.service'; -import type { RagequitState } from '@/types/ragequit'; - -class RagequitService extends BaseApiService { - private overrides: Map> = new Map(); - - async getRagequitState( - proposalId: string, - _userAddress?: string - ): Promise { - const override = this.overrides.get(proposalId); - - const now = Date.now(); - const defaultEnd = now + 2 * 3600 * 1000; // 2 hours from now - const totalReserveXlm = 50000; - const totalCirculatingKeys = 10000; - const payoutPerKeyXlm = totalReserveXlm / totalCirculatingKeys; // 5.0 XLM per key - const userKeys = 50; - - const base: RagequitState = { - proposalId, - isOpen: true, - windowEndsAt: new Date(defaultEnd).toISOString(), - remainingSeconds: Math.max(0, Math.floor((defaultEnd - now) / 1000)), - totalReserveXlm, - totalCirculatingKeys, - cumulativeExits: 500, - exitCap: 2000, - isExecuted: false, - executedProposalId: proposalId, - isEligible: true, - userKeys, - userVoteDirection: 'against', - payoutPerKeyXlm, - estimatedPayoutXlm: userKeys * payoutPerKeyXlm, // 250 XLM - }; - - if (override) { - const merged = { ...base, ...override }; - const endMs = new Date(merged.windowEndsAt).getTime(); - const remaining = Math.max(0, Math.floor((endMs - Date.now()) / 1000)); - merged.remainingSeconds = remaining; - - if (remaining <= 0) { - merged.isOpen = false; - } - - // Validate eligibility constraints - if (!merged.isOpen) { - merged.isEligible = false; - merged.ineligibilityReason = - merged.ineligibilityReason || 'The ragequit window for this proposal has closed.'; - } else if (merged.userVoteDirection === 'for') { - merged.isEligible = false; - merged.ineligibilityReason = - 'You voted in favor of this proposal and are not eligible to ragequit.'; - merged.estimatedPayoutXlm = 0; - } else if (merged.userKeys <= 0) { - merged.isEligible = false; - merged.ineligibilityReason = - 'You hold 0 keys for this creator and have no reserve share to claim.'; - merged.estimatedPayoutXlm = 0; - } else if (merged.cumulativeExits >= merged.exitCap) { - merged.isEligible = false; - merged.ineligibilityReason = `Cumulative exits have reached the cap of ${merged.exitCap.toLocaleString()} keys.`; - } - - return structuredClone(merged); - } - - return structuredClone(base); - } - - async executeRagequit( - proposalId: string, - keysToBurn: number, - _userAddress?: string - ): Promise<{ txHash: string; payoutXlm: number }> { - const state = await this.getRagequitState(proposalId); - if (!state.isOpen) { - throw new Error('Ragequit window is closed'); - } - if (!state.isEligible) { - throw new Error(state.ineligibilityReason || 'Ineligible to ragequit'); - } - if (keysToBurn <= 0 || keysToBurn > state.userKeys) { - throw new Error(`Invalid keys to burn (${keysToBurn})`); - } - if (state.cumulativeExits + keysToBurn > state.exitCap) { - throw new Error('Exits would exceed the exit cap'); - } - - const payoutXlm = keysToBurn * state.payoutPerKeyXlm; - const updatedState: Partial = { - userKeys: state.userKeys - keysToBurn, - cumulativeExits: state.cumulativeExits + keysToBurn, - estimatedPayoutXlm: (state.userKeys - keysToBurn) * state.payoutPerKeyXlm, - }; - this.setMockRagequitState(proposalId, updatedState); - - return { - txHash: `0x${Math.random().toString(16).slice(2)}`, - payoutXlm, - }; - } - - setMockRagequitState(proposalId: string, state: Partial) { - const existing = this.overrides.get(proposalId) || {}; - this.overrides.set(proposalId, { ...existing, ...state }); - } - - reset() { - this.overrides.clear(); - } -} - -export const ragequitService = new RagequitService(); diff --git a/src/types/governance.ts b/src/types/governance.ts index 1e6d4566..6a0c4ca6 100644 --- a/src/types/governance.ts +++ b/src/types/governance.ts @@ -18,6 +18,36 @@ export type ProposalStatus = export type ProposalOutcome = 'passed' | 'failed' | 'quorum_not_met'; +// ── Rage-quit (#1253) ───────────────────────────────────────────────────── + +/** + * Whether the connected holder is eligible to rage-quit a proposal. + * Holders who voted *for* the proposal are not eligible. + */ +export type RageQuitEligibility = + | 'eligible' + | 'voted_for' + | 'window_closed' + | 'cap_reached' + | 'unknown'; + +/** On-chain rage-quit window state for a passed proposal. */ +export interface RageQuitStatus { + proposalId: string; + /** True while the rage-quit window is open and the cap has not been hit. */ + isOpen: boolean; + /** ISO timestamp when the window closes. */ + windowEndsAt: string | null; + /** Total keys that have already rage-quit as a fraction of supply (0–1). */ + exitedFraction: number; + /** Maximum fraction of supply that may rage-quit (0–1). */ + maxExitFraction: number; + /** Eligibility of the connected wallet. */ + eligibility: RageQuitEligibility; + /** Pro-rata XLM payout the connected wallet would receive per key. */ + payoutPerKey: number | null; +} + /** A single selectable option on an on-chain proposal. */ export interface ProposalOption { label: string;