diff --git a/src/components/common/__tests__/OracleHealthBadge.test.tsx b/src/components/common/__tests__/OracleHealthBadge.test.tsx
new file mode 100644
index 00000000..06daeb00
--- /dev/null
+++ b/src/components/common/__tests__/OracleHealthBadge.test.tsx
@@ -0,0 +1,114 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { describe, expect, it, beforeEach } from 'vitest';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import OracleHealthBadge from '../OracleHealthBadge';
+import { oracleService } from '@/services/oracle.service';
+
+function renderWithQuery(ui: React.ReactElement) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
{ui} );
+}
+
+describe('OracleHealthBadge', () => {
+ beforeEach(() => {
+ oracleService.reset();
+ });
+
+ it('reflects healthy status reported by contract', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'healthy',
+ source: 'primary',
+ sourceName: 'Primary Chainlink Feed',
+ priceXlm: 1.5,
+ updatedAt: Date.now() - 10_000,
+ deviationPercent: 0.1,
+ });
+
+ renderWithQuery(
);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('oracle-health-badge')).toBeInTheDocument();
+ });
+
+ const badge = screen.getByTestId('oracle-health-badge');
+ expect(badge).toHaveAttribute('data-status', 'healthy');
+ expect(screen.getByTestId('oracle-status-label')).toHaveTextContent('Oracle: Healthy');
+ });
+
+ it('reflects fallback status reported by contract', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'fallback',
+ source: 'fallback',
+ sourceName: 'Secondary Band Feed',
+ priceXlm: 1.48,
+ updatedAt: Date.now() - 20_000,
+ deviationPercent: 1.2,
+ });
+
+ renderWithQuery(
);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('oracle-health-badge')).toBeInTheDocument();
+ });
+
+ const badge = screen.getByTestId('oracle-health-badge');
+ expect(badge).toHaveAttribute('data-status', 'fallback');
+ expect(screen.getByTestId('oracle-status-label')).toHaveTextContent('Oracle: Fallback');
+ });
+
+ it('reflects stale status reported by contract', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'stale',
+ source: 'primary',
+ sourceName: 'Primary Chainlink Feed',
+ priceXlm: 1.5,
+ updatedAt: Date.now() - 600_000, // 10 minutes ago
+ deviationPercent: 0.1,
+ });
+
+ renderWithQuery(
);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('oracle-health-badge')).toBeInTheDocument();
+ });
+
+ const badge = screen.getByTestId('oracle-health-badge');
+ expect(badge).toHaveAttribute('data-status', 'stale');
+ expect(screen.getByTestId('oracle-status-label')).toHaveTextContent('Oracle: Stale');
+ });
+
+ it('opens popover with details on click', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'healthy',
+ source: 'primary',
+ sourceName: 'Primary Feed',
+ priceXlm: 1.52,
+ updatedAt: Date.now() - 15_000,
+ deviationPercent: 0.25,
+ });
+
+ renderWithQuery(
);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('oracle-health-badge')).toBeInTheDocument();
+ });
+
+ fireEvent.click(screen.getByTestId('oracle-health-badge'));
+
+ expect(screen.getByTestId('oracle-health-popover')).toBeInTheDocument();
+ expect(screen.getByTestId('popover-source-name')).toHaveTextContent('Primary Feed (primary)');
+ expect(screen.getByTestId('popover-price')).toHaveTextContent('1.5200 XLM');
+ expect(screen.getByTestId('popover-deviation')).toHaveTextContent('0.25%');
+ expect(screen.getByTestId('popover-relative-age')).toHaveTextContent(/ago|just now/);
+ });
+
+ it('hides badge when hidden prop is true or asset is missing', () => {
+ const { container: c1 } = renderWithQuery(
);
+ expect(c1).toBeEmptyDOMElement();
+
+ const { container: c2 } = renderWithQuery(
);
+ expect(c2).toBeEmptyDOMElement();
+ });
+});
diff --git a/src/components/creator/LiveClaimable.tsx b/src/components/creator/LiveClaimable.tsx
new file mode 100644
index 00000000..13cb074a
--- /dev/null
+++ b/src/components/creator/LiveClaimable.tsx
@@ -0,0 +1,78 @@
+import React, { useEffect, useState } from 'react';
+import { PauseCircle, TrendingUp } from 'lucide-react';
+import type { EarningsStream } from '@/types/stream';
+import { calculateClaimableBalance } from '@/utils/stream.utils';
+import { cn } from '@/lib/utils';
+
+export interface LiveClaimableProps {
+ stream: EarningsStream;
+ className?: string;
+}
+
+export const LiveClaimable: React.FC
= ({
+ stream,
+ className,
+}) => {
+ const [currentTime, setCurrentTime] = useState(Date.now());
+
+ useEffect(() => {
+ // When stream is paused, accrual stops and value is frozen (#acceptance criteria)
+ if (stream.isPaused) return;
+
+ const interval = setInterval(() => {
+ setCurrentTime(Date.now());
+ }, 1000);
+
+ return () => clearInterval(interval);
+ }, [stream.isPaused]);
+
+ const claimable = calculateClaimableBalance(stream, currentTime);
+
+ return (
+
+
+
+ {stream.isPaused ? (
+
+ ) : (
+
+ )}
+ Accrued Claimable Balance
+
+ {stream.isPaused && (
+
+ Frozen (Paused)
+
+ )}
+
+
+
+
+ {claimable.toLocaleString(undefined, {
+ minimumFractionDigits: 4,
+ maximumFractionDigits: 6,
+ })}
+
+ XLM
+
+
+
+ Max capacity: {(stream.fundedAmount - stream.withdrawnAmount).toLocaleString()} XLM
+
+
+ );
+};
+
+export default LiveClaimable;
diff --git a/src/components/creator/StreamHistoryTable.tsx b/src/components/creator/StreamHistoryTable.tsx
new file mode 100644
index 00000000..f53fa24d
--- /dev/null
+++ b/src/components/creator/StreamHistoryTable.tsx
@@ -0,0 +1,90 @@
+import React from 'react';
+import { ExternalLink, History } from 'lucide-react';
+import type { StreamWithdrawal } from '@/types/stream';
+import { shortenAddress } from '@/lib/web3/format';
+
+export interface StreamHistoryTableProps {
+ withdrawals: StreamWithdrawal[];
+}
+
+export const StreamHistoryTable: React.FC = ({
+ withdrawals,
+}) => {
+ if (!withdrawals || withdrawals.length === 0) {
+ return (
+
+ No past withdrawals recorded for this stream.
+
+ );
+ }
+
+ return (
+
+
+
+ Withdrawal History
+
+
+
+
+
+
+ Date & Time
+ Amount
+ Fee
+ Net Payout
+ Transaction
+
+
+
+ {withdrawals.map(tx => (
+
+
+ {new Date(tx.timestamp).toLocaleDateString()} ·{' '}
+ {new Date(tx.timestamp).toLocaleTimeString([], {
+ hour: '2-digit',
+ minute: '2-digit',
+ })}
+
+
+ {tx.amountXlm.toFixed(2)} XLM
+
+
+ {tx.feeXlm.toFixed(4)} XLM
+
+
+ {tx.netAmountXlm.toFixed(2)} XLM
+
+
+ {/* History rows link to correct transactions (#acceptance criteria) */}
+
+ {shortenAddress(tx.txHash, 6)}
+
+
+
+
+ ))}
+
+
+
+
+ );
+};
+
+export default StreamHistoryTable;
diff --git a/src/components/creator/StreamWithdrawForm.tsx b/src/components/creator/StreamWithdrawForm.tsx
new file mode 100644
index 00000000..6e6bfbff
--- /dev/null
+++ b/src/components/creator/StreamWithdrawForm.tsx
@@ -0,0 +1,129 @@
+import React, { useState } from 'react';
+import { ArrowDownToLine, AlertCircle } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { calculateWithdrawalFee } from '@/utils/stream.utils';
+
+export interface StreamWithdrawFormProps {
+ streamId: string;
+ claimableBalance: number;
+ onWithdraw: (amount: number) => Promise | void;
+ isPending?: boolean;
+}
+
+export const StreamWithdrawForm: React.FC = ({
+ streamId: _streamId,
+ claimableBalance,
+ onWithdraw,
+ isPending = false,
+}) => {
+ const [amount, setAmount] = useState('');
+
+ const parsedAmount = Number(amount) || 0;
+ const isExceeding = parsedAmount > claimableBalance;
+ const isZeroOrNegative = parsedAmount <= 0;
+ const isDisabled = isExceeding || isZeroOrNegative || isPending;
+
+ const { feeXlm, netAmountXlm } = calculateWithdrawalFee(parsedAmount);
+
+ const handleMax = () => {
+ // Round down to 4 decimals to avoid micro precision overflows
+ const safeMax = Math.floor(claimableBalance * 10000) / 10000;
+ setAmount(safeMax.toString());
+ };
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (isDisabled) return;
+ await onWithdraw(parsedAmount);
+ setAmount('');
+ };
+
+ return (
+
+ );
+};
+
+export default StreamWithdrawForm;
diff --git a/src/components/creator/__tests__/LiveClaimable.test.tsx b/src/components/creator/__tests__/LiveClaimable.test.tsx
new file mode 100644
index 00000000..51e04ac6
--- /dev/null
+++ b/src/components/creator/__tests__/LiveClaimable.test.tsx
@@ -0,0 +1,83 @@
+import { render, screen, act } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import LiveClaimable from '../LiveClaimable';
+import type { EarningsStream } from '@/types/stream';
+
+describe('LiveClaimable', () => {
+ it('ticks up using stream rate and never exceeds funded minus withdrawn', () => {
+ vi.useFakeTimers();
+ const now = Date.now();
+
+ const stream: EarningsStream = {
+ id: 'test-s1',
+ creatorAddress: 'GCXW1234',
+ keyId: 'key-1',
+ keySymbol: 'TEST',
+ keyName: 'Test Key',
+ fundedAmount: 100,
+ withdrawnAmount: 20, // max claimable = 80
+ ratePerSecond: 1.0, // 1 XLM per second
+ startTime: now - 20 * 1000, // 20s elapsed covers the 20 withdrawn
+ stopTime: now + 200 * 1000,
+ lastWithdrawalTime: now,
+ isPaused: false,
+ withdrawals: [],
+ };
+
+ render( );
+
+ // Initially at now, 20s elapsed * 1.0 = 20 accrued - 20 withdrawn = 0 claimable
+ expect(screen.getByTestId('live-claimable-value')).toHaveTextContent('0.0000');
+
+ // Fast forward 10 seconds => 10 XLM accrued
+ act(() => {
+ vi.advanceTimersByTime(10_000);
+ });
+ expect(screen.getByTestId('live-claimable-value')).toHaveTextContent('10.0000');
+
+ // Fast forward 150 seconds => reaches max claimable (funded - withdrawn = 80)
+ act(() => {
+ vi.advanceTimersByTime(150_000);
+ });
+ expect(screen.getByTestId('live-claimable-value')).toHaveTextContent('80.0000');
+
+ vi.useRealTimers();
+ });
+
+ it('shows paused notice and frozen claimable value when paused', () => {
+ vi.useFakeTimers();
+ const now = Date.now();
+
+ const stream: EarningsStream = {
+ id: 'test-s2',
+ creatorAddress: 'GCXW1234',
+ keyId: 'key-2',
+ keySymbol: 'PAUSED',
+ keyName: 'Paused Stream',
+ fundedAmount: 1000,
+ withdrawnAmount: 100,
+ ratePerSecond: 0.5,
+ startTime: now - 100 * 1000, // started 100s ago
+ stopTime: now + 1000 * 1000,
+ lastWithdrawalTime: now - 100 * 1000,
+ isPaused: true,
+ pausedAt: now - 50 * 1000, // paused 50s after start => accrued 25, withdrawn 100 => 0 or accrued before
+ withdrawals: [],
+ };
+
+ render( );
+
+ // Frozen badge is present
+ expect(screen.getByTestId('claimable-frozen-badge')).toBeInTheDocument();
+
+ // Advancing time does NOT change value
+ const valueBefore = screen.getByTestId('live-claimable-value').textContent;
+ act(() => {
+ vi.advanceTimersByTime(20_000);
+ });
+ const valueAfter = screen.getByTestId('live-claimable-value').textContent;
+ expect(valueBefore).toBe(valueAfter);
+
+ vi.useRealTimers();
+ });
+});
diff --git a/src/components/creator/__tests__/StreamWithdrawForm.test.tsx b/src/components/creator/__tests__/StreamWithdrawForm.test.tsx
new file mode 100644
index 00000000..2b25e5e0
--- /dev/null
+++ b/src/components/creator/__tests__/StreamWithdrawForm.test.tsx
@@ -0,0 +1,70 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import StreamWithdrawForm from '../StreamWithdrawForm';
+
+describe('StreamWithdrawForm', () => {
+ it('blocks withdrawing above claimable balance inline and disables submit', () => {
+ const onWithdraw = vi.fn();
+ render(
+
+ );
+
+ const input = screen.getByTestId('stream-withdraw-input');
+ const submitButton = screen.getByTestId('stream-withdraw-submit');
+
+ // Enter amount exceeding claimable balance (60 > 50)
+ fireEvent.change(input, { target: { value: '60' } });
+
+ // Error message displayed inline (#acceptance criteria)
+ expect(screen.getByTestId('withdraw-exceed-error')).toBeInTheDocument();
+ expect(screen.getByTestId('withdraw-exceed-error')).toHaveTextContent(
+ 'Amount exceeds claimable balance of 50.0000 XLM.'
+ );
+
+ // Button is disabled
+ expect(submitButton).toBeDisabled();
+
+ // Enter valid amount within claimable balance
+ fireEvent.change(input, { target: { value: '40' } });
+ expect(screen.queryByTestId('withdraw-exceed-error')).toBeNull();
+ expect(submitButton).not.toBeDisabled();
+ });
+
+ it('displays fee preview with protocol fee and net payout', () => {
+ render(
+
+ );
+
+ const input = screen.getByTestId('stream-withdraw-input');
+ fireEvent.change(input, { target: { value: '100' } });
+
+ expect(screen.getByTestId('withdraw-fee-preview')).toBeInTheDocument();
+ // 0.5% of 100 = 0.5 XLM fee, net = 99.5 XLM
+ expect(screen.getByTestId('withdraw-fee-preview')).toHaveTextContent('0.5000 XLM');
+ expect(screen.getByTestId('withdraw-net-payout')).toHaveTextContent('99.5000 XLM');
+ });
+
+ it('clicking max sets amount to claimable balance', () => {
+ render(
+
+ );
+
+ const maxBtn = screen.getByTestId('withdraw-max-button');
+ fireEvent.click(maxBtn);
+
+ const input = screen.getByTestId('stream-withdraw-input') as HTMLInputElement;
+ expect(input.value).toBe('75.5');
+ });
+});
diff --git a/src/components/events/CreateEventForm.tsx b/src/components/events/CreateEventForm.tsx
new file mode 100644
index 00000000..6d3df11f
--- /dev/null
+++ b/src/components/events/CreateEventForm.tsx
@@ -0,0 +1,195 @@
+import { useState } from 'react';
+import { useAccount } from 'wagmi';
+import { CalendarPlus } from 'lucide-react';
+import ConnectWalletButton from '@/components/common/ConnectWalletButton';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import { useCreateEvent } from '@/hooks/useEvents';
+import { useWalletHoldings } from '@/hooks/useWallet';
+import { cn } from '@/lib/utils';
+
+function localDateTime(offsetHours: number): string {
+ const date = new Date(Date.now() + offsetHours * 3_600_000);
+ const pad = (value: number) => String(value).padStart(2, '0');
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
+ date.getDate()
+ )}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
+}
+
+export default function CreateEventForm() {
+ const { address } = useAccount();
+ const holdingsQuery = useWalletHoldings(address ?? '');
+ const createEvent = useCreateEvent();
+ const [title, setTitle] = useState('');
+ const [description, setDescription] = useState('');
+ const [keyId, setKeyId] = useState('');
+ const [startsAt, setStartsAt] = useState(() => localDateTime(1));
+ const [endsAt, setEndsAt] = useState(() => localDateTime(72));
+ const [passSupply, setPassSupply] = useState('50');
+ const [perWalletCap, setPerWalletCap] = useState('1');
+
+ const heldKeys = (holdingsQuery.data ?? []).filter(
+ position => (position.quantity ?? 0) > 0
+ );
+
+ const handleSubmit = (event: React.FormEvent) => {
+ event.preventDefault();
+ if (!address || !keyId) return;
+ createEvent.mutate({
+ creator: address,
+ keyId,
+ keyName: keyId,
+ title,
+ description,
+ startsAt: new Date(startsAt).toISOString(),
+ endsAt: new Date(endsAt).toISOString(),
+ passSupply: Number(passSupply),
+ perWalletCap: Number(perWalletCap),
+ });
+ if (!createEvent.isError) {
+ setTitle('');
+ setDescription('');
+ setKeyId('');
+ }
+ };
+
+ return (
+
+
+
+
Create an event
+
+
+ Redeemable passes are limited to holders of the key you select.
+
+
+ {!address ? (
+
+
+ Connect your creator wallet to publish an event.
+
+
+
+ ) : heldKeys.length === 0 ? (
+
+ You need to hold a key before you can create a holder event.
+
+ ) : (
+
+ )}
+
+ );
+}
diff --git a/src/components/events/CreatorEventsPanel.tsx b/src/components/events/CreatorEventsPanel.tsx
new file mode 100644
index 00000000..c08e654c
--- /dev/null
+++ b/src/components/events/CreatorEventsPanel.tsx
@@ -0,0 +1,89 @@
+import { useAccount } from 'wagmi';
+import { TicketX } from 'lucide-react';
+import ConnectWalletButton from '@/components/common/ConnectWalletButton';
+import CreateEventForm from '@/components/events/CreateEventForm';
+import { Button } from '@/components/ui/button';
+import { useCloseEvent, useEvents } from '@/hooks/useEvents';
+import { useNowMs } from '@/hooks/useNowMs';
+import { getEventStatus } from '@/services/events.service';
+
+export interface CreatorEventsPanelProps {
+ creatorId: string;
+}
+
+export default function CreatorEventsPanel({
+ creatorId,
+}: CreatorEventsPanelProps) {
+ const { address } = useAccount();
+ const nowMs = useNowMs(5000);
+ const eventsQuery = useEvents(address);
+ const closeEvent = useCloseEvent();
+
+ const events = (eventsQuery.data ?? []).filter(
+ event => event.keyId === creatorId
+ );
+
+ return (
+
+
+
+
+
Your events
+ {!address && (
+
+
+ Connect your creator wallet to manage events.
+
+
+
+ )}
+ {address && events.length === 0 && (
+
+ No events created for this key yet.
+
+ )}
+ {events.map(event => {
+ const status = getEventStatus(event, nowMs);
+ return (
+
+
+
+ {event.title}
+
+
+ {event.redeemed}/{event.passSupply} passes redeemed ·{' '}
+ {status.status}
+
+
+ {status.status !== 'closed' && address && (
+
+ closeEvent.mutate({
+ eventId: event.id,
+ creator: address,
+ })
+ }
+ className="border-rose-500/30 text-rose-200 hover:bg-rose-500/10"
+ data-testid={`close-event-${event.id}`}
+ >
+
+ Close event
+
+ )}
+
+ );
+ })}
+
+
+ );
+}
diff --git a/src/components/events/RedeemPassCard.tsx b/src/components/events/RedeemPassCard.tsx
new file mode 100644
index 00000000..c4668b7d
--- /dev/null
+++ b/src/components/events/RedeemPassCard.tsx
@@ -0,0 +1,123 @@
+import { useAccount } from 'wagmi';
+import { Clock3, Ticket, Users } from 'lucide-react';
+import ConnectWalletButton from '@/components/common/ConnectWalletButton';
+import { Button } from '@/components/ui/button';
+import { useEventRedemption, useRedeemPass } from '@/hooks/useEvents';
+import { useNowMs } from '@/hooks/useNowMs';
+import { getEventStatus, type CreatorEvent } from '@/services/events.service';
+import { formatCountdownDuration } from '@/utils/mergeProposal.utils';
+import { cn } from '@/lib/utils';
+
+export interface RedeemPassCardProps {
+ event: CreatorEvent;
+ heldKeyIds: string[];
+}
+
+export default function RedeemPassCard({
+ event,
+ heldKeyIds,
+}: RedeemPassCardProps) {
+ const { address } = useAccount();
+ const nowMs = useNowMs();
+ const redemption = useEventRedemption(event.id, address, heldKeyIds);
+ const redeem = useRedeemPass();
+ const status = getEventStatus(event, nowMs);
+ const eligibility = redemption.eligibility;
+
+ const countdown =
+ status.status === 'upcoming'
+ ? `Starts in ${formatCountdownDuration(
+ new Date(event.startsAt).getTime() - nowMs
+ )}`
+ : status.status === 'open'
+ ? `Closes in ${formatCountdownDuration(
+ new Date(event.endsAt).getTime() - nowMs
+ )}`
+ : status.closeReason === 'exhausted'
+ ? 'Closed — all passes redeemed'
+ : 'Closed';
+
+ return (
+
+
+
+
+ {event.keyName}
+
+
{event.title}
+
{event.description}
+
+
+ {status.status === 'open' && (
+
+ )}
+ {status.status}
+
+
+
+
+
+
+ {status.remaining} of {event.passSupply} passes left
+
+
+
+ Max {event.perWalletCap} per wallet
+
+ {countdown}
+
+
+
+ {!address ? (
+
+ ) : (
+
+ redeem.mutate({
+ eventId: event.id,
+ wallet: address,
+ heldKeyIds,
+ })
+ }
+ className="bg-amber-400 font-semibold text-slate-950 hover:bg-amber-300"
+ data-testid={`redeem-${event.id}`}
+ >
+ {redeem.isPending ? 'Redeeming…' : 'Redeem pass'}
+
+ )}
+ {eligibility.redeemedByWallet > 0 && (
+
+ You have redeemed {eligibility.redeemedByWallet} pass
+ {eligibility.redeemedByWallet === 1 ? '' : 'es'}.
+
+ )}
+ {address && !eligibility.eligible && eligibility.reason && (
+
+ {eligibility.reason}
+
+ )}
+
+
+ );
+}
diff --git a/src/components/fees/FeeImpactPreview.tsx b/src/components/fees/FeeImpactPreview.tsx
new file mode 100644
index 00000000..c96259be
--- /dev/null
+++ b/src/components/fees/FeeImpactPreview.tsx
@@ -0,0 +1,56 @@
+import { ArrowRight } from 'lucide-react';
+import type { FeeChangeState } from '@/services/feeChange.service';
+import { bpsToPercent } from '@/utils/numberFormat.utils';
+import { formatDisplayKeyPrice } from '@/utils/keyPriceDisplay.utils';
+import { cn } from '@/lib/utils';
+
+export interface FeeImpactPreviewProps {
+ pending: FeeChangeState;
+ totalStroops?: number | null;
+}
+
+export default function FeeImpactPreview({
+ pending,
+ totalStroops,
+}: FeeImpactPreviewProps) {
+ if (!pending.queuedFeeBps) return null;
+
+ const notional = Math.max(0, totalStroops ?? 0);
+ const currentFeeStroops = Math.round(
+ (notional * pending.currentFeeBps) / 10_000
+ );
+ const queuedFeeStroops = Math.round(
+ (notional * pending.queuedFeeBps) / 10_000
+ );
+ const deltaStroops = queuedFeeStroops - currentFeeStroops;
+
+ return (
+
+
Queued fee change
+
+
+ {bpsToPercent(pending.currentFeeBps)}
+
+
+
+ {bpsToPercent(pending.queuedFeeBps)}
+
+
+
+ Fee on this order would be {formatDisplayKeyPrice(queuedFeeStroops)}{' '}
+ instead of {formatDisplayKeyPrice(currentFeeStroops)}.
+
+ {deltaStroops !== 0 && (
+
+ {deltaStroops > 0 ? '+' : '−'}
+ {formatDisplayKeyPrice(Math.abs(deltaStroops))} after execution.
+
+ )}
+
+ );
+}
diff --git a/src/components/fees/PendingFeeChangeBanner.tsx b/src/components/fees/PendingFeeChangeBanner.tsx
new file mode 100644
index 00000000..3c086ab4
--- /dev/null
+++ b/src/components/fees/PendingFeeChangeBanner.tsx
@@ -0,0 +1,40 @@
+import { AlertTriangle, Clock3 } from 'lucide-react';
+import { useNowMs } from '@/hooks/useNowMs';
+import { usePendingFeeChange } from '@/hooks/useFeeChange';
+import { bpsToPercent } from '@/utils/numberFormat.utils';
+import { formatCountdownDuration } from '@/utils/mergeProposal.utils';
+
+export default function PendingFeeChangeBanner() {
+ const pending = usePendingFeeChange();
+ const nowMs = useNowMs(1000);
+
+ if (!pending?.queuedFeeBps || !pending.eta) return null;
+
+ const etaMs = new Date(pending.eta).getTime();
+ const etaLabel = formatCountdownDuration(etaMs - nowMs);
+
+ return (
+
+
+
Fee change pending
+
+ Current: {bpsToPercent(pending.currentFeeBps)}
+
+
+ Queued: {bpsToPercent(pending.queuedFeeBps)}
+
+
+
+ Executes in {etaLabel}
+
+
+ );
+}
diff --git a/src/components/fees/__tests__/PendingFeeChangeBanner.test.tsx b/src/components/fees/__tests__/PendingFeeChangeBanner.test.tsx
new file mode 100644
index 00000000..7e18d106
--- /dev/null
+++ b/src/components/fees/__tests__/PendingFeeChangeBanner.test.tsx
@@ -0,0 +1,76 @@
+import { act, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import FeeImpactPreview from '@/components/fees/FeeImpactPreview';
+import PendingFeeChangeBanner from '@/components/fees/PendingFeeChangeBanner';
+import { useFeeChangeStore } from '@/hooks/useFeeChange';
+import {
+ queueFeeChange,
+ resetFeeChangeStore,
+} from '@/services/feeChange.service';
+
+describe('pending fee change UI', () => {
+ beforeEach(() => {
+ resetFeeChangeStore();
+ useFeeChangeStore.getState().refresh();
+ });
+
+ afterEach(() => {
+ resetFeeChangeStore();
+ useFeeChangeStore.getState().refresh();
+ });
+
+ it('shows current, queued and ETA to every user while pending', () => {
+ act(() => {
+ queueFeeChange({
+ queuedFeeBps: 750,
+ eta: new Date(Date.now() + 3_600_000).toISOString(),
+ });
+ useFeeChangeStore.getState().refresh();
+ });
+
+ render( );
+ expect(screen.getByTestId('pending-fee-change-banner')).toBeTruthy();
+ expect(screen.getByTestId('fee-change-current').textContent).toContain(
+ '5%'
+ );
+ expect(screen.getByTestId('fee-change-queued').textContent).toContain(
+ '7.5%'
+ );
+ expect(screen.getByTestId('fee-change-eta').textContent).toMatch(
+ /Executes in/
+ );
+
+ act(() => useFeeChangeStore.getState().cancel());
+ expect(screen.queryByTestId('pending-fee-change-banner')).toBeNull();
+ });
+
+ it('previews the queued fee on a trade confirmation', () => {
+ act(() => {
+ queueFeeChange({
+ queuedFeeBps: 700,
+ eta: new Date(Date.now() + 3_600_000).toISOString(),
+ });
+ useFeeChangeStore.getState().refresh();
+ });
+
+ render(
+
+ );
+
+ expect(
+ screen.getByTestId('fee-impact-current-rate').textContent
+ ).toContain('5%');
+ expect(
+ screen.getByTestId('fee-impact-queued-rate').textContent
+ ).toContain('7%');
+ expect(screen.getByTestId('fee-impact-fees').textContent).toContain(
+ '0.07 XLM'
+ );
+ expect(screen.getByTestId('fee-impact-delta').textContent).toContain(
+ '0.02 XLM'
+ );
+ });
+});
diff --git a/src/components/governance/AllocateStakeModal.tsx b/src/components/governance/AllocateStakeModal.tsx
new file mode 100644
index 00000000..ac55aa3c
--- /dev/null
+++ b/src/components/governance/AllocateStakeModal.tsx
@@ -0,0 +1,198 @@
+import React, { useEffect, useState } from 'react';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { getMaxStakeForProposal } from '@/utils/conviction.utils';
+
+export interface AllocateStakeModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ proposalId: string;
+ proposalTitle: string;
+ currentStake?: number;
+ unallocatedBalance: number;
+ onAllocate: (amount: number) => Promise | void;
+ isPending?: boolean;
+}
+
+export const AllocateStakeModal: React.FC = ({
+ isOpen,
+ onClose,
+ proposalId: _proposalId,
+ proposalTitle,
+ currentStake = 0,
+ unallocatedBalance,
+ onAllocate,
+ isPending = false,
+}) => {
+ const maxAllowed = getMaxStakeForProposal(unallocatedBalance, currentStake);
+ const [amount, setAmount] = useState(currentStake);
+
+ useEffect(() => {
+ if (isOpen) {
+ setAmount(Math.min(currentStake, maxAllowed));
+ }
+ }, [isOpen, currentStake, maxAllowed]);
+
+ const handleSliderChange = (e: React.ChangeEvent) => {
+ const val = Number(e.target.value);
+ // Crucial constraint: slider never exceeds maxAllowed (unallocated balance + existing stake)
+ const clamped = Math.min(maxAllowed, Math.max(0, val));
+ setAmount(clamped);
+ };
+
+ const handleInputChange = (e: React.ChangeEvent) => {
+ const parsed = Number(e.target.value);
+ if (Number.isNaN(parsed)) {
+ setAmount(0);
+ return;
+ }
+ // Strict clamp against unallocated balance ceiling
+ const clamped = Math.min(maxAllowed, Math.max(0, parsed));
+ setAmount(clamped);
+ };
+
+ const handleMax = () => {
+ setAmount(maxAllowed);
+ };
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (amount > maxAllowed) return;
+ await onAllocate(amount);
+ onClose();
+ };
+
+ return (
+ !open && onClose()}>
+
+
+
+
+ Allocate Stake
+
+
+ Allocate governance voting stake to accumulate conviction for{' '}
+ "{proposalTitle}" .
+
+
+
+
+ {/* Balances info */}
+
+
+ Current Stake
+
+ {currentStake.toLocaleString()}
+
+
+
+ Unallocated Available
+
+ {unallocatedBalance.toLocaleString()}
+
+
+
+
+ {/* Input & Slider */}
+
+
+
+ Stake to Allocate
+
+
+ Max ({maxAllowed.toLocaleString()})
+
+
+
+
+
+
+ VOTE
+
+
+
+ {/* Slider explicitly capped at maxAllowed */}
+
+
+
+ 0
+ {maxAllowed.toLocaleString()} max
+
+
+
+
+ {amount > maxAllowed && (
+
+ Amount exceeds unallocated balance of {maxAllowed}.
+
+ )}
+
+
+
+
+ Cancel
+
+ maxAllowed}
+ className="bg-cyan-500 hover:bg-cyan-400 text-black font-semibold"
+ data-testid="modal-confirm-button"
+ >
+ {isPending ? 'Allocating…' : 'Confirm Allocation'}
+
+
+
+
+
+ );
+};
+
+export default AllocateStakeModal;
diff --git a/src/components/governance/ConvictionMeter.tsx b/src/components/governance/ConvictionMeter.tsx
new file mode 100644
index 00000000..75d90373
--- /dev/null
+++ b/src/components/governance/ConvictionMeter.tsx
@@ -0,0 +1,127 @@
+import React from 'react';
+import { CheckCircle2, Clock, AlertCircle } from 'lucide-react';
+import { cn } from '@/lib/utils';
+import type { ConvictionProjection } from '@/types/conviction';
+import { calculateConvictionProjection } from '@/utils/conviction.utils';
+
+export interface ConvictionMeterProps {
+ /** Current accumulated conviction. */
+ conviction: number;
+ /** Conviction threshold required to pass. */
+ threshold: number;
+ /** Total stake allocated by all users. */
+ totalStake?: number;
+ /** Alpha decay parameter (optional). */
+ alpha?: number;
+ /** Precomputed projection (optional). */
+ projection?: ConvictionProjection;
+ /** Optional class name. */
+ className?: string;
+}
+
+export const ConvictionMeter: React.FC = ({
+ conviction,
+ threshold,
+ totalStake = 0,
+ alpha = 0.9,
+ projection: customProjection,
+ className,
+}) => {
+ const validThreshold = Math.max(1, threshold);
+ const validConviction = Math.max(0, conviction);
+ const percentage = Math.min(100, (validConviction / validThreshold) * 100);
+
+ const projection =
+ customProjection ??
+ calculateConvictionProjection(validConviction, validThreshold, totalStake, alpha);
+
+ const isCrossed = validConviction >= validThreshold;
+
+ return (
+
+
+
Conviction Progress
+
+
+ {Math.round(validConviction).toLocaleString()} /{' '}
+ {Math.round(validThreshold).toLocaleString()}
+
+
+ {percentage.toFixed(1)}%
+
+
+
+
+ {/* Progress track */}
+
+
+ {/* Projection & status note */}
+
+
+ {isCrossed ? (
+ <>
+
+
+ {projection.displayText}
+
+ >
+ ) : projection.isReachable ? (
+ <>
+
+
+ {projection.displayText}
+
+ >
+ ) : (
+ <>
+
+
+ {projection.displayText}
+
+ >
+ )}
+
+
+ Threshold: {Math.round(validThreshold).toLocaleString()}
+
+
+
+ );
+};
+
+export default ConvictionMeter;
diff --git a/src/components/governance/RagequitBanner.tsx b/src/components/governance/RagequitBanner.tsx
new file mode 100644
index 00000000..99f2ca21
--- /dev/null
+++ b/src/components/governance/RagequitBanner.tsx
@@ -0,0 +1,217 @@
+import React, { useState } from 'react';
+import { Link } from 'react-router';
+import {
+ Clock,
+ Flame,
+ ShieldAlert,
+ CheckCircle,
+ ArrowRight,
+ AlertCircle,
+} from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { RagequitModal } from '@/components/governance/RagequitModal';
+import { useRagequit } from '@/hooks/useRagequit';
+import { cn } from '@/lib/utils';
+
+export interface RagequitBannerProps {
+ proposalId: string;
+ className?: string;
+}
+
+export const RagequitBanner: React.FC = ({
+ proposalId,
+ className,
+}) => {
+ const {
+ isWindowOpen,
+ countdownText,
+ cumulativeExits,
+ exitCap,
+ exitCapPercent,
+ isEligible,
+ ineligibilityReason,
+ userKeys,
+ estimatedPayoutXlm,
+ payoutPerKeyXlm,
+ isExecuted,
+ executedProposalId,
+ executeRagequit,
+ isMutating,
+ } = useRagequit(proposalId);
+
+ const [isModalOpen, setIsModalOpen] = useState(false);
+
+ // When the window ends and is not executed / no results: banner disappears (#acceptance criteria)
+ if (!isWindowOpen && !isExecuted) {
+ return null;
+ }
+
+ // After the window closes and proposal executed: show final result and link to executed proposal
+ if (!isWindowOpen && isExecuted) {
+ return (
+
+
+
+
+
+
+ Ragequit Window Closed & Proposal Executed
+
+
+ The grace period ended. Total {cumulativeExits.toLocaleString()} keys exited before execution.
+
+
+
+
+ {executedProposalId && (
+
+ View Executed Proposal #{executedProposalId}
+
+
+ )}
+
+
+ );
+ }
+
+ return (
+
+
+
+
+
+
+ Ragequit Window Active
+
+
+
+ Exit Grace Window: Leave with Reserve Share
+
+
+ Holders opposing this passed proposal can burn their keys and exit
+ with their fair share of the reserve before execution.
+
+
+
+ {/* Countdown clock (#acceptance criteria) */}
+
+
+
+ Window Closes In
+
+
+ {countdownText}
+
+
+
+
+ {/* Cumulative exits against the cap progress bar (#acceptance criteria) */}
+
+
+ Cumulative Exits Progress
+
+ {cumulativeExits.toLocaleString()} / {exitCap.toLocaleString()} keys ({exitCapPercent.toFixed(1)}% of cap)
+
+
+
+
+
+ {/* Bottom section: Eligible vs Ineligible */}
+
+ {isEligible ? (
+ <>
+
+ Your Estimated Reserve Payout:
+
+ {estimatedPayoutXlm.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })}{' '}
+ XLM{' '}
+
+ ({userKeys.toLocaleString()} keys @ {payoutPerKeyXlm.toFixed(2)} XLM/key)
+
+
+
+
+
setIsModalOpen(true)}
+ className="bg-red-500 hover:bg-red-600 text-white font-semibold gap-1.5 shadow-lg shadow-red-950/50"
+ data-testid="ragequit-exit-button"
+ >
+
+ Ragequit & Exit
+
+ >
+ ) : (
+ /* Ineligible holders see reason and NO exit button (#acceptance criteria) */
+
+
+
+ Ineligible to ragequit:{' '}
+
+ {ineligibilityReason || 'You are not eligible for reserve exit.'}
+
+
+
+ )}
+
+
+ {isEligible && (
+ setIsModalOpen(false)}
+ proposalId={proposalId}
+ maxKeys={userKeys}
+ payoutPerKeyXlm={payoutPerKeyXlm}
+ onConfirm={keys => executeRagequit(keys)}
+ isPending={isMutating}
+ />
+ )}
+
+ );
+};
+
+export default RagequitBanner;
diff --git a/src/components/governance/RagequitModal.tsx b/src/components/governance/RagequitModal.tsx
new file mode 100644
index 00000000..98745e58
--- /dev/null
+++ b/src/components/governance/RagequitModal.tsx
@@ -0,0 +1,206 @@
+import React, { useEffect, useState } from 'react';
+import { AlertTriangle, Flame, ShieldAlert } from 'lucide-react';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+
+export interface RagequitModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ proposalId: string;
+ maxKeys: number;
+ payoutPerKeyXlm: number;
+ onConfirm: (keysToBurn: number) => Promise | void;
+ isPending?: boolean;
+}
+
+export const RagequitModal: React.FC = ({
+ isOpen,
+ onClose,
+ proposalId,
+ maxKeys,
+ payoutPerKeyXlm,
+ onConfirm,
+ isPending = false,
+}) => {
+ const [keysToBurn, setKeysToBurn] = useState(maxKeys);
+ const [acknowledged, setAcknowledged] = useState(false);
+
+ useEffect(() => {
+ if (isOpen) {
+ setKeysToBurn(maxKeys);
+ setAcknowledged(false);
+ }
+ }, [isOpen, maxKeys]);
+
+ const safeKeys = Math.min(maxKeys, Math.max(0, keysToBurn));
+ const estimatedPayout = safeKeys * payoutPerKeyXlm;
+
+ const handleKeysChange = (e: React.ChangeEvent) => {
+ const val = Number(e.target.value);
+ if (Number.isNaN(val)) {
+ setKeysToBurn(0);
+ return;
+ }
+ setKeysToBurn(Math.min(maxKeys, Math.max(0, Math.floor(val))));
+ };
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!acknowledged || safeKeys <= 0) return;
+ await onConfirm(safeKeys);
+ onClose();
+ };
+
+ return (
+ !open && onClose()}>
+
+
+
+
+
+ Reserve Exit Grace Window
+
+
+ Ragequit & Burn Keys
+
+
+ Oppose Proposal #{proposalId} by burning your creator keys to withdraw your proportional share of the liquidity reserve.
+
+
+
+ {/* Warning alert */}
+
+
+
+
+ Warning: Action is Irreversible
+
+
+ Once confirmed, your creator keys will be burned immediately and permanently from circulation. You cannot reclaim your keys or reverse this transaction.
+
+
+
+
+ {/* Keys to Burn Input */}
+
+
+
+ Keys to Burn
+
+ setKeysToBurn(maxKeys)}
+ className="text-cyan-400 hover:text-cyan-300 font-medium"
+ data-testid="ragequit-max-button"
+ >
+ Max ({maxKeys.toLocaleString()} keys)
+
+
+
+
+
+ KEYS
+
+
+
+
+ {/* Payout calculation */}
+
+
+ Reserve rate per key:
+
+ {payoutPerKeyXlm.toFixed(2)} XLM
+
+
+
+
+ Estimated Payout:
+
+
+ {estimatedPayout.toLocaleString(undefined, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ })}{' '}
+ XLM
+
+
+
+
+ {/* Explicit acknowledgement of irreversibility checkbox (#acceptance criteria) */}
+
+
+ setAcknowledged(e.target.checked)}
+ className="mt-0.5 rounded border-white/20 text-red-500 focus:ring-red-400 accent-red-500 cursor-pointer"
+ data-testid="ragequit-ack-checkbox"
+ />
+
+ I acknowledge and confirm that burning my keys is{' '}
+
+ permanent and irreversible
+
+ .
+
+
+
+
+
+
+ Cancel
+
+
+
+ {isPending ? 'Burning keys…' : 'Confirm Ragequit'}
+
+
+
+
+
+ );
+};
+
+export default RagequitModal;
diff --git a/src/components/governance/__tests__/AllocateStakeModal.test.tsx b/src/components/governance/__tests__/AllocateStakeModal.test.tsx
new file mode 100644
index 00000000..e906ddf1
--- /dev/null
+++ b/src/components/governance/__tests__/AllocateStakeModal.test.tsx
@@ -0,0 +1,57 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import AllocateStakeModal from '../AllocateStakeModal';
+
+describe('AllocateStakeModal', () => {
+ it('slider and input never exceed the unallocated balance plus current stake', () => {
+ const onAllocate = vi.fn();
+ render(
+
+ );
+
+ const slider = screen.getByTestId('modal-stake-slider') as HTMLInputElement;
+ expect(slider.max).toBe('100');
+
+ // Attempting to change slider beyond maxAllowed clamps it
+ fireEvent.change(slider, { target: { value: '150' } });
+ expect(slider.value).toBe('100');
+
+ // Input also clamps
+ const input = screen.getByTestId('modal-amount-input') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: '250' } });
+ expect(input.value).toBe('100');
+ });
+
+ it('clicking max sets the amount to the maximum allowed stake', () => {
+ const onAllocate = vi.fn();
+ render(
+
+ );
+
+ const maxButton = screen.getByTestId('modal-max-button');
+ fireEvent.click(maxButton);
+
+ const input = screen.getByTestId('modal-amount-input') as HTMLInputElement;
+ expect(input.value).toBe('120');
+
+ const confirmButton = screen.getByTestId('modal-confirm-button');
+ fireEvent.click(confirmButton);
+ expect(onAllocate).toHaveBeenCalledWith(120);
+ });
+});
diff --git a/src/components/governance/__tests__/ConvictionMeter.test.tsx b/src/components/governance/__tests__/ConvictionMeter.test.tsx
new file mode 100644
index 00000000..ceb745e4
--- /dev/null
+++ b/src/components/governance/__tests__/ConvictionMeter.test.tsx
@@ -0,0 +1,48 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+import ConvictionMeter from '../ConvictionMeter';
+
+describe('ConvictionMeter', () => {
+ it('shows conviction relative to the threshold', () => {
+ render(
+
+ );
+
+ expect(screen.getByTestId('conviction-meter')).toBeInTheDocument();
+ expect(screen.getByTestId('conviction-values')).toHaveTextContent('750 / 1,000');
+ expect(screen.getByTestId('conviction-percentage')).toHaveTextContent('75.0%');
+ });
+
+ it('displays projected crossing time when reachable', () => {
+ render(
+
+ );
+
+ const projection = screen.getByTestId('conviction-projection');
+ expect(projection).toHaveTextContent(/Estimated crossing/);
+ });
+
+ it('indicates when threshold is crossed', () => {
+ render(
+
+ );
+
+ expect(screen.getByTestId('conviction-percentage')).toHaveTextContent('100.0%');
+ expect(screen.getByTestId('conviction-projection')).toHaveTextContent(
+ 'Threshold reached - ready to execute'
+ );
+ });
+});
diff --git a/src/components/governance/__tests__/RagequitBanner.test.tsx b/src/components/governance/__tests__/RagequitBanner.test.tsx
new file mode 100644
index 00000000..003a1a32
--- /dev/null
+++ b/src/components/governance/__tests__/RagequitBanner.test.tsx
@@ -0,0 +1,134 @@
+import { render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, beforeEach } from 'vitest';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { MemoryRouter } from 'react-router';
+import RagequitBanner from '../RagequitBanner';
+import { ragequitService } from '@/services/ragequit.service';
+
+function renderWithProviders(ui: React.ReactElement) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+
+ {ui}
+
+ );
+}
+
+describe('RagequitBanner', () => {
+ beforeEach(() => {
+ ragequitService.reset();
+ });
+
+ it('eligible holders see the banner, countdown, estimated payout and exit button', async () => {
+ ragequitService.setMockRagequitState('prop-101', {
+ isOpen: true,
+ windowEndsAt: new Date(Date.now() + 3600 * 1000).toISOString(),
+ totalReserveXlm: 100000,
+ totalCirculatingKeys: 10000,
+ payoutPerKeyXlm: 10,
+ userKeys: 25,
+ estimatedPayoutXlm: 250,
+ isEligible: true,
+ cumulativeExits: 500,
+ exitCap: 2000,
+ });
+
+ renderWithProviders( );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('ragequit-banner')).toBeInTheDocument();
+ });
+
+ // Banner & countdown
+ expect(screen.getByTestId('ragequit-countdown')).toBeInTheDocument();
+
+ // Estimated payout
+ expect(screen.getByTestId('ragequit-payout-estimate')).toHaveTextContent('250.00 XLM');
+
+ // Exit button is visible for eligible holders
+ expect(screen.getByTestId('ragequit-exit-button')).toBeInTheDocument();
+ });
+
+ it('ineligible holders (e.g. voted in favor) see the reason and NO exit button', async () => {
+ ragequitService.setMockRagequitState('prop-102', {
+ isOpen: true,
+ windowEndsAt: new Date(Date.now() + 3600 * 1000).toISOString(),
+ userVoteDirection: 'for',
+ isEligible: false,
+ });
+
+ renderWithProviders( );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('ragequit-banner')).toBeInTheDocument();
+ });
+
+ // Displays reason
+ expect(screen.getByTestId('ragequit-ineligible-notice')).toHaveTextContent(
+ /You voted in favor of this proposal and are not eligible to ragequit/i
+ );
+
+ // NO exit button
+ expect(screen.queryByTestId('ragequit-exit-button')).toBeNull();
+ });
+
+ it('the exits progress bar reflects cumulative exits against the cap', async () => {
+ ragequitService.setMockRagequitState('prop-103', {
+ isOpen: true,
+ windowEndsAt: new Date(Date.now() + 3600 * 1000).toISOString(),
+ cumulativeExits: 800,
+ exitCap: 2000,
+ });
+
+ renderWithProviders( );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('ragequit-banner')).toBeInTheDocument();
+ });
+
+ expect(screen.getByTestId('ragequit-exits-progress-text')).toHaveTextContent(
+ '800 / 2,000 keys (40.0% of cap)'
+ );
+
+ const bar = screen.getByTestId('ragequit-exits-bar');
+ expect(bar).toHaveStyle({ width: '40%' });
+ });
+
+ it('the banner disappears when the window ends', async () => {
+ // Window ended in the past, not executed
+ ragequitService.setMockRagequitState('prop-104', {
+ isOpen: false,
+ windowEndsAt: new Date(Date.now() - 10000).toISOString(),
+ isExecuted: false,
+ });
+
+ const { container } = renderWithProviders( );
+
+ await waitFor(() => {
+ expect(container).toBeEmptyDOMElement();
+ });
+ });
+
+ it('shows final result and link to executed proposal after window closes with execution', async () => {
+ ragequitService.setMockRagequitState('prop-105', {
+ isOpen: false,
+ windowEndsAt: new Date(Date.now() - 10000).toISOString(),
+ isExecuted: true,
+ executedProposalId: 'prop-105',
+ cumulativeExits: 1200,
+ });
+
+ renderWithProviders( );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('ragequit-closed-banner')).toBeInTheDocument();
+ });
+
+ expect(screen.getByTestId('executed-proposal-link')).toHaveAttribute(
+ 'href',
+ '/governance/prop-105'
+ );
+ });
+});
diff --git a/src/components/governance/__tests__/RagequitModal.test.tsx b/src/components/governance/__tests__/RagequitModal.test.tsx
new file mode 100644
index 00000000..9af69c75
--- /dev/null
+++ b/src/components/governance/__tests__/RagequitModal.test.tsx
@@ -0,0 +1,55 @@
+import { render, screen, fireEvent } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import RagequitModal from '../RagequitModal';
+
+describe('RagequitModal', () => {
+ it('requires explicit acknowledgement of irreversibility before confirming', () => {
+ const onConfirm = vi.fn();
+ render(
+
+ );
+
+ const confirmButton = screen.getByTestId('ragequit-confirm-button');
+ // Button should be disabled initially
+ expect(confirmButton).toBeDisabled();
+
+ // Check the estimated payout display
+ expect(screen.getByTestId('ragequit-estimated-payout')).toHaveTextContent('200.00 XLM');
+
+ // Toggle acknowledgement checkbox
+ const checkbox = screen.getByTestId('ragequit-ack-checkbox');
+ fireEvent.click(checkbox);
+
+ // Now confirm button is enabled
+ expect(confirmButton).not.toBeDisabled();
+
+ // Submit
+ fireEvent.click(confirmButton);
+ expect(onConfirm).toHaveBeenCalledWith(40);
+ });
+
+ it('updates estimated payout when user changes keys to burn', () => {
+ render(
+
+ );
+
+ const input = screen.getByTestId('ragequit-keys-input');
+ fireEvent.change(input, { target: { value: '20' } });
+
+ expect(screen.getByTestId('ragequit-estimated-payout')).toHaveTextContent('200.00 XLM');
+ });
+});
diff --git a/src/components/grants/SubmitEvidenceModal.tsx b/src/components/grants/SubmitEvidenceModal.tsx
new file mode 100644
index 00000000..f8dc27de
--- /dev/null
+++ b/src/components/grants/SubmitEvidenceModal.tsx
@@ -0,0 +1,189 @@
+import { useEffect, useState } from 'react';
+import { Upload, Link2 } from 'lucide-react';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import { computeEvidenceHash } from '@/utils/hash.utils';
+
+export interface EvidenceValues {
+ link: string;
+ description: string;
+ fileHash: string;
+ fileName?: string;
+}
+
+export interface SubmitEvidenceModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ milestoneTitle: string;
+ isSubmitting?: boolean;
+ onSubmit: (values: EvidenceValues) => void;
+}
+
+export default function SubmitEvidenceModal({
+ open,
+ onOpenChange,
+ milestoneTitle,
+ isSubmitting = false,
+ onSubmit,
+}: SubmitEvidenceModalProps) {
+ const [link, setLink] = useState('');
+ const [description, setDescription] = useState('');
+ const [file, setFile] = useState(null);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setLink('');
+ setDescription('');
+ setFile(null);
+ setError(null);
+ }, [open, milestoneTitle]);
+
+ const handleSubmit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ if (link.trim() && !/^https?:\/\//i.test(link.trim())) {
+ setError('Enter a valid http(s) link.');
+ return;
+ }
+ if (!link.trim() && !file) {
+ setError('Add a link or an evidence file.');
+ return;
+ }
+
+ let bytes: ArrayBuffer | null = null;
+ if (file) {
+ try {
+ bytes = await file.arrayBuffer();
+ } catch {
+ setError('The evidence file could not be read.');
+ return;
+ }
+ }
+
+ setError(null);
+ onSubmit({
+ link: link.trim(),
+ description: description.trim(),
+ fileHash: computeEvidenceHash(link, description, bytes),
+ fileName: file?.name,
+ });
+ };
+
+ return (
+
+
+
+
+ Submit evidence
+
+
+ {milestoneTitle} — evidence is hashed before it is sent for
+ review.
+
+
+
+ void handleSubmit(event)}
+ className="space-y-4"
+ >
+
+
Link to work
+
+
+ setLink(event.target.value)}
+ className="pl-8"
+ data-testid="evidence-link"
+ />
+
+
+
+
+ Evidence file
+
+
+
+ {file?.name ?? 'Choose a file to upload'}
+
+
+ setFile(event.target.files?.[0] ?? null)
+ }
+ data-testid="evidence-file"
+ />
+
+
+
+
+ Description
+ setDescription(event.target.value)}
+ placeholder="Summarise what this milestone delivered"
+ data-testid="evidence-description"
+ />
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+
+ onOpenChange(false)}
+ >
+ Cancel
+
+
+ {isSubmitting ? 'Submitting…' : 'Submit evidence'}
+
+
+
+
+
+ );
+}
diff --git a/src/hooks/__tests__/useBounties.test.tsx b/src/hooks/__tests__/useBounties.test.tsx
new file mode 100644
index 00000000..5c51fa55
--- /dev/null
+++ b/src/hooks/__tests__/useBounties.test.tsx
@@ -0,0 +1,201 @@
+import { act, renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ useAwardSubmission,
+ useReclaimBounty,
+ useRejectSubmission,
+ useSubmitWork,
+} from '@/hooks/useBounties';
+import {
+ getBounties,
+ getBounty,
+ getRemainingWinners,
+ getSubmissions,
+ resetBountyStore,
+} from '@/services/bounty.service';
+import { computeProofHash } from '@/utils/hash.utils';
+
+vi.mock('@/hooks/useWallet', () => ({
+ useWalletHoldings: vi.fn(() => ({ data: [], isLoading: false })),
+}));
+
+const { showToastSuccess, showToastError } = vi.hoisted(() => ({
+ showToastSuccess: vi.fn(),
+ showToastError: vi.fn(),
+}));
+
+vi.mock('@/utils/toast.util', () => ({
+ default: { success: showToastSuccess, error: showToastError },
+}));
+
+const CREATOR = 'GCREATOR_A';
+const WORKER = 'GWORKER_1';
+
+describe('bounties (#1441)', () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetBountyStore();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ );
+
+ const workInput = (bountyId: string, isHolder = true) => ({
+ bountyId,
+ worker: WORKER,
+ link: 'https://example.com/work',
+ description: 'Here is the completed launch banner design.',
+ proofHash: computeProofHash(
+ 'https://example.com/work',
+ 'Here is the completed launch banner design.'
+ ),
+ isHolder,
+ });
+
+ it('filters the board by key, reward range and status', () => {
+ const all = getBounties();
+ expect(all.length).toBeGreaterThan(0);
+
+ expect(
+ getBounties({ key: 'creator-beta' }).every(
+ b => b.keyId === 'creator-beta'
+ )
+ ).toBe(true);
+ expect(
+ getBounties({ minReward: 30_000_000 }).every(
+ b => b.rewardStroops >= 30_000_000
+ )
+ ).toBe(true);
+ expect(
+ getBounties({ minReward: 10_000_000, maxReward: 30_000_000 }).every(
+ b => b.rewardStroops >= 10_000_000 && b.rewardStroops <= 30_000_000
+ )
+ ).toBe(true);
+ expect(
+ getBounties({ status: 'active' }).every(b => b.status === 'open')
+ ).toBe(true);
+ });
+
+ it('submits work with a proof hash and blocks non-holders on gated bounties', async () => {
+ const { result } = renderHook(() => useSubmitWork(), { wrapper });
+ const proofHash = workInput('bounty-1').proofHash;
+
+ await act(async () => {
+ await result.current.mutateAsync(workInput('bounty-1'));
+ });
+
+ const submissions = getSubmissions('bounty-1');
+ expect(submissions).toHaveLength(1);
+ expect(submissions[0].worker).toBe(WORKER);
+ expect(submissions[0].proofHash).toBe(proofHash);
+ expect(submissions[0].proofHash).toMatch(/^0x[0-9a-f]{64}$/);
+
+ await expect(
+ result.current.mutateAsync(workInput('bounty-1', false))
+ ).rejects.toThrow(/must hold/i);
+ expect(getSubmissions('bounty-1')).toHaveLength(1);
+ });
+
+ it('awards at most the winner limit and keeps remaining winners in sync', async () => {
+ const submit = renderHook(() => useSubmitWork(), { wrapper });
+ const award = renderHook(() => useAwardSubmission(CREATOR), { wrapper });
+
+ for (const worker of [
+ 'GWORKER_1',
+ 'GWORKER_2',
+ 'GWORKER_3',
+ 'GWORKER_4',
+ ]) {
+ await act(async () => {
+ await submit.result.current.mutateAsync({
+ ...workInput('bounty-1'),
+ worker,
+ });
+ });
+ }
+
+ const all = getSubmissions('bounty-1');
+ for (const submission of all.slice(0, 3)) {
+ await act(async () => {
+ await award.result.current.mutateAsync(submission.id);
+ });
+ }
+
+ expect(getBounty('bounty-1')?.status).toBe('awarded');
+ expect(getRemainingWinners(getBounty('bounty-1')!)).toBe(0);
+
+ await expect(award.result.current.mutateAsync(all[3].id)).rejects.toThrow(
+ /winner slots/i
+ );
+ expect(
+ getSubmissions('bounty-1').filter(s => s.status === 'awarded')
+ ).toHaveLength(3);
+ });
+
+ it('rejecting grants one resubmission which updates the worker state', async () => {
+ const submit = renderHook(() => useSubmitWork(), { wrapper });
+ const reject = renderHook(() => useRejectSubmission(CREATOR), {
+ wrapper,
+ });
+
+ await act(async () => {
+ await submit.result.current.mutateAsync(workInput('bounty-1'));
+ });
+ const submission = getSubmissions('bounty-1')[0];
+
+ await act(async () => {
+ await reject.result.current.mutateAsync({
+ submissionId: submission.id,
+ reason: 'Please add a source link',
+ });
+ });
+
+ const rejected = getSubmissions('bounty-1')[0];
+ expect(rejected.status).toBe('rejected');
+ expect(rejected.resubmissionAllowed).toBe(true);
+
+ await act(async () => {
+ await submit.result.current.mutateAsync({
+ ...workInput('bounty-1'),
+ link: 'https://example.com/revised',
+ });
+ });
+
+ const resubmitted = getSubmissions('bounty-1')[0];
+ expect(resubmitted.status).toBe('pending');
+ expect(resubmitted.resubmissions).toBe(1);
+ expect(resubmitted.resubmissionAllowed).toBe(false);
+ expect(resubmitted.resubmissionUsed).toBe(true);
+
+ await expect(
+ submit.result.current.mutateAsync(workInput('bounty-1'))
+ ).rejects.toThrow(/already has your submission/i);
+ });
+
+ it('reclaims unpaid rewards only after the deadline', async () => {
+ const reclaim = renderHook(() => useReclaimBounty(CREATOR), { wrapper });
+ await expect(
+ reclaim.result.current.mutateAsync('bounty-1')
+ ).rejects.toThrow(/deadline/i);
+
+ let reclaimed = 0;
+ await act(async () => {
+ const result = await reclaim.result.current.mutateAsync('bounty-3');
+ reclaimed = result.reclaimedStroops;
+ });
+
+ expect(reclaimed).toBe(60_000_000 * 2);
+ expect(getBounty('bounty-3')?.status).toBe('reclaimed');
+ expect(
+ getBounties({ status: 'active' }).some(b => b.id === 'bounty-3')
+ ).toBe(false);
+ });
+});
diff --git a/src/hooks/__tests__/useEvents.test.tsx b/src/hooks/__tests__/useEvents.test.tsx
new file mode 100644
index 00000000..b320e6c4
--- /dev/null
+++ b/src/hooks/__tests__/useEvents.test.tsx
@@ -0,0 +1,143 @@
+import { act, renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useCreateEvent, useRedeemPass } from '@/hooks/useEvents';
+import {
+ closeEvent,
+ createEvent,
+ getEvent,
+ getEventStatus,
+ getRedemptionEligibility,
+ getWalletRedemption,
+ listEvents,
+ redeemPass,
+ resetEventStore,
+} from '@/services/events.service';
+
+const CREATOR = 'GEVENT_CREATOR';
+const HOLDER = 'GHOLDER_1';
+
+const { showToastSuccess, showToastError } = vi.hoisted(() => ({
+ showToastSuccess: vi.fn(),
+ showToastError: vi.fn(),
+}));
+
+vi.mock('@/utils/toast.util', () => ({
+ default: { success: showToastSuccess, error: showToastError },
+}));
+
+describe('creator events (#1443)', () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetEventStore();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ );
+
+ it('lists open events with remaining supply and auto-closes expired ones', () => {
+ const open = getEvent('event-1')!;
+ expect(getEventStatus(open).status).toBe('open');
+ expect(getEventStatus(open).remaining).toBe(88);
+
+ const expired = getEvent('event-3')!;
+ expect(getEventStatus(expired, Date.now()).status).toBe('closed');
+ expect(getEventStatus(expired, Date.now()).closeReason).toBe('expired');
+ expect(listEvents().length).toBe(3);
+ });
+
+ it('checks holder eligibility before redemption', () => {
+ expect(getRedemptionEligibility('event-1', HOLDER, []).eligible).toBe(
+ false
+ );
+ const eligible = getRedemptionEligibility('event-1', HOLDER, [
+ 'creator-alpha',
+ ]);
+ expect(eligible.eligible).toBe(true);
+ expect(eligible.redeemedByWallet).toBe(1);
+ });
+
+ it('enforces the per-wallet cap', () => {
+ const held = ['creator-alpha'];
+ redeemPass('event-1', HOLDER, held);
+ expect(getWalletRedemption('event-1', HOLDER)?.passes).toBe(2);
+ expect(getRedemptionEligibility('event-1', HOLDER, held).eligible).toBe(
+ false
+ );
+
+ expect(() => redeemPass('event-1', HOLDER, held)).toThrowError(
+ /per-wallet redemption cap/i
+ );
+ expect(getEvent('event-1')?.redeemed).toBe(13);
+ });
+
+ it('closes an event automatically when supply is exhausted', () => {
+ const event = createEvent({
+ creator: CREATOR,
+ keyId: 'creator-alpha',
+ keyName: 'Alpha Key',
+ title: 'Limited drop',
+ description: 'One pass total.',
+ startsAt: new Date(Date.now() - 60_000).toISOString(),
+ endsAt: new Date(Date.now() + 3_600_000).toISOString(),
+ passSupply: 1,
+ perWalletCap: 1,
+ });
+
+ redeemPass(event.id, 'GHOLDER_2', ['creator-alpha']);
+ expect(getEventStatus(getEvent(event.id)!).status).toBe('closed');
+ expect(getEvent(event.id)?.closeReason).toBe('exhausted');
+ expect(() =>
+ redeemPass(event.id, 'GHOLDER_3', ['creator-alpha'])
+ ).toThrowError(/redeemed/i);
+ });
+
+ it('lets only the creator close an event manually', () => {
+ expect(() => closeEvent('event-1', HOLDER)).toThrowError(
+ /Only the event creator/
+ );
+ const closed = closeEvent('event-1', CREATOR);
+ expect(closed.closeReason).toBe('manual');
+ expect(getEventStatus(getEvent('event-1')!).status).toBe('closed');
+ });
+
+ it('creates events through the mutation hook', async () => {
+ const { result } = renderHook(() => useCreateEvent(), { wrapper });
+ let createdId = '';
+ await act(async () => {
+ const created = await result.current.mutateAsync({
+ creator: CREATOR,
+ keyId: 'creator-alpha',
+ keyName: 'Alpha Key',
+ title: 'Hook-created event',
+ description: 'Created via React Query.',
+ startsAt: new Date(Date.now() - 60_000).toISOString(),
+ endsAt: new Date(Date.now() + 3_600_000).toISOString(),
+ passSupply: 10,
+ perWalletCap: 2,
+ });
+ createdId = created.id;
+ });
+ expect(getEvent(createdId)?.title).toBe('Hook-created event');
+ });
+
+ it('redeems through the mutation hook', async () => {
+ const { result } = renderHook(() => useRedeemPass(), { wrapper });
+ await act(async () => {
+ await result.current.mutateAsync({
+ eventId: 'event-1',
+ wallet: HOLDER,
+ heldKeyIds: ['creator-alpha'],
+ });
+ });
+ expect(getWalletRedemption('event-1', HOLDER)?.passes).toBe(2);
+ expect(getEvent('event-1')?.redeemed).toBe(13);
+ });
+});
diff --git a/src/hooks/__tests__/useFeeChange.test.ts b/src/hooks/__tests__/useFeeChange.test.ts
new file mode 100644
index 00000000..8c42622f
--- /dev/null
+++ b/src/hooks/__tests__/useFeeChange.test.ts
@@ -0,0 +1,86 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ getFeeChangeState,
+ getPendingFeeChange,
+ queueFeeChange,
+ resetFeeChangeStore,
+} from '@/services/feeChange.service';
+import { useFeeChangeStore, usePendingFeeChange } from '@/hooks/useFeeChange';
+
+const futureEta = () => new Date(Date.now() + 3_600_000).toISOString();
+
+describe('pending fee changes (#1442)', () => {
+ beforeEach(() => {
+ resetFeeChangeStore();
+ useFeeChangeStore.getState().refresh();
+ });
+
+ afterEach(() => {
+ resetFeeChangeStore();
+ useFeeChangeStore.getState().refresh();
+ });
+
+ it('starts with no pending change', () => {
+ expect(getFeeChangeState().status).toBe('none');
+ expect(getPendingFeeChange()).toBeNull();
+
+ const { result } = renderHook(() => usePendingFeeChange());
+ expect(result.current).toBeNull();
+ });
+
+ it('exposes current value, queued value and ETA while pending', () => {
+ const queued = queueFeeChange({
+ queuedFeeBps: 725,
+ eta: futureEta(),
+ });
+ act(() => useFeeChangeStore.getState().refresh());
+
+ const { result } = renderHook(() => usePendingFeeChange());
+ expect(result.current?.status).toBe('pending');
+ expect(result.current?.currentFeeBps).toBe(500);
+ expect(result.current?.queuedFeeBps).toBe(725);
+ expect(result.current?.eta).toBe(queued.eta);
+ });
+
+ it('keeps the history on cancel and clears the pending banner', () => {
+ queueFeeChange({ queuedFeeBps: 650, eta: futureEta() });
+ act(() => useFeeChangeStore.getState().cancel());
+
+ const state = getFeeChangeState();
+ expect(state.status).toBe('cancelled');
+ expect(state.currentFeeBps).toBe(500);
+ expect(state.cancelledAt).toBeDefined();
+ expect(getPendingFeeChange()).toBeNull();
+
+ const { result } = renderHook(() => usePendingFeeChange());
+ expect(result.current).toBeNull();
+ });
+
+ it('applies the queued value on execution', () => {
+ queueFeeChange({ queuedFeeBps: 800, eta: futureEta() });
+ act(() => useFeeChangeStore.getState().execute());
+
+ const state = getFeeChangeState();
+ expect(state.status).toBe('executed');
+ expect(state.currentFeeBps).toBe(800);
+ expect(state.executedAt).toBeDefined();
+ expect(getPendingFeeChange()).toBeNull();
+ });
+
+ it('rejects out-of-bounds fees and past ETAs', () => {
+ expect(() =>
+ queueFeeChange({
+ queuedFeeBps: 2000,
+ eta: futureEta(),
+ })
+ ).toThrowError(/between/);
+ expect(() =>
+ queueFeeChange({
+ queuedFeeBps: 600,
+ eta: new Date(Date.now() - 60_000).toISOString(),
+ })
+ ).toThrowError(/future/);
+ expect(getPendingFeeChange()).toBeNull();
+ });
+});
diff --git a/src/hooks/__tests__/useGrants.test.tsx b/src/hooks/__tests__/useGrants.test.tsx
new file mode 100644
index 00000000..1209ed75
--- /dev/null
+++ b/src/hooks/__tests__/useGrants.test.tsx
@@ -0,0 +1,138 @@
+import { act, renderHook } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useReviewMilestone } from '@/hooks/useGrants';
+import { queryKeys } from '@/lib/queryKeys';
+import {
+ getGrant,
+ listGrants,
+ resetGrantStore,
+ reviewMilestone,
+ submitEvidence,
+} from '@/services/grants.service';
+import { computeEvidenceHash } from '@/utils/hash.utils';
+
+const RECIPIENT = 'GRECIPIENT_1';
+const REVIEWER = 'GREVIEWER_1';
+const OUTSIDER = 'GOUTSIDER';
+
+const { showToastSuccess, showToastError } = vi.hoisted(() => ({
+ showToastSuccess: vi.fn(),
+ showToastError: vi.fn(),
+}));
+
+vi.mock('@/utils/toast.util', () => ({
+ default: { success: showToastSuccess, error: showToastError },
+}));
+
+describe('grants (#1440)', () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetGrantStore();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ );
+
+ it('paginates grants with cursors', () => {
+ const first = listGrants({ limit: 2 });
+ expect(first.grants).toHaveLength(2);
+ expect(first.nextCursor).toBe('2');
+
+ const second = listGrants({ limit: 2, cursor: first.nextCursor });
+ expect(second.grants).toHaveLength(1);
+ expect(second.nextCursor).toBeNull();
+ expect(second.grants[0].id).toBe('grant-3');
+ });
+
+ it('shows returned funds on cancelled grants', () => {
+ const cancelled = listGrants({ status: 'cancelled' }).grants;
+ expect(cancelled).toHaveLength(1);
+ expect(cancelled[0].returnedAmountStroops).toBe(13_000_000);
+ });
+
+ it('gates evidence submission to the recipient', () => {
+ const evidence = {
+ milestoneId: 'grant-1-m3',
+ link: 'https://github.com/example/sdk',
+ description: 'SDK published',
+ fileHash: computeEvidenceHash('https://github.com/example/sdk'),
+ };
+
+ expect(() =>
+ submitEvidence({ ...evidence, wallet: OUTSIDER })
+ ).toThrowError(/Only the grant recipient/);
+ expect(() =>
+ submitEvidence({ ...evidence, wallet: REVIEWER, link: 'not-a-link' })
+ ).toThrowError(/valid http\(s\)/);
+
+ const result = submitEvidence({ ...evidence, wallet: RECIPIENT });
+ expect(result.milestone.state).toBe('submitted');
+ expect(result.milestone.evidence?.fileHash).toBe(evidence.fileHash);
+ });
+
+ it('requires a reason on rejection and returns the milestone to pending', () => {
+ submitEvidence({
+ milestoneId: 'grant-1-m3',
+ wallet: RECIPIENT,
+ link: 'https://github.com/example/sdk',
+ description: 'Draft',
+ fileHash: computeEvidenceHash('draft'),
+ });
+
+ expect(() =>
+ reviewMilestone({
+ grantId: 'grant-1',
+ milestoneId: 'grant-1-m3',
+ wallet: REVIEWER,
+ decision: 'reject',
+ })
+ ).toThrowError(/reason is required/i);
+
+ const result = reviewMilestone({
+ grantId: 'grant-1',
+ milestoneId: 'grant-1-m3',
+ wallet: REVIEWER,
+ decision: 'reject',
+ reason: 'Add the missing type exports.',
+ });
+ expect(result.milestone.state).toBe('pending');
+ expect(result.milestone.rejectionReason).toBe(
+ 'Add the missing type exports.'
+ );
+ expect(result.grant.releasedStroops).toBe(20_000_000);
+ });
+
+ it('updates released balance and timeline on approval', async () => {
+ const { result } = renderHook(() => useReviewMilestone(), { wrapper });
+ queryClient.setQueryData(
+ queryKeys.grants.detail('grant-1'),
+ getGrant('grant-1')
+ );
+
+ await act(async () => {
+ await result.current.mutateAsync({
+ grantId: 'grant-1',
+ milestoneId: 'grant-1-m2',
+ wallet: REVIEWER,
+ decision: 'approve',
+ });
+ });
+
+ const grant = getGrant('grant-1')!;
+ expect(grant.releasedStroops).toBe(45_000_000);
+ expect(grant.releases.some(r => r.milestoneId === 'grant-1-m2')).toBe(
+ true
+ );
+ expect(grant.milestones.find(m => m.id === 'grant-1-m2')?.state).toBe(
+ 'approved'
+ );
+ });
+});
diff --git a/src/hooks/__tests__/useOracleStatus.test.tsx b/src/hooks/__tests__/useOracleStatus.test.tsx
new file mode 100644
index 00000000..e7b1a22d
--- /dev/null
+++ b/src/hooks/__tests__/useOracleStatus.test.tsx
@@ -0,0 +1,104 @@
+import { renderHook, waitFor, act } from '@testing-library/react';
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { useOracleStatus } from '../useOracleStatus';
+import { oracleService } from '@/services/oracle.service';
+
+function createWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return ({ children }: { children: React.ReactNode }) => (
+ {children}
+ );
+}
+
+describe('useOracleStatus', () => {
+ beforeEach(() => {
+ oracleService.reset();
+ });
+
+ it('returns healthy status for fresh primary feed', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'healthy',
+ source: 'primary',
+ updatedAt: Date.now() - 10_000,
+ });
+
+ const { result } = renderHook(() => useOracleStatus('XLM'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ expect(result.current.status).toBe('healthy');
+ expect(result.current.isHealthy).toBe(true);
+ expect(result.current.isFallback).toBe(false);
+ expect(result.current.isStale).toBe(false);
+ });
+
+ it('returns fallback status when contract reports fallback source', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'fallback',
+ source: 'fallback',
+ updatedAt: Date.now() - 10_000,
+ });
+
+ const { result } = renderHook(() => useOracleStatus('XLM'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ expect(result.current.status).toBe('fallback');
+ expect(result.current.isFallback).toBe(true);
+ expect(result.current.isStale).toBe(false);
+ });
+
+ it('returns stale status when contract price is outdated', async () => {
+ oracleService.setMockStatus('XLM', {
+ status: 'stale',
+ updatedAt: Date.now() - 600_000,
+ });
+
+ const { result } = renderHook(() => useOracleStatus('XLM'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => {
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ expect(result.current.status).toBe('stale');
+ expect(result.current.isStale).toBe(true);
+ expect(result.current.staleReason).toContain('stale');
+ });
+
+ it('updates relative time dynamically', async () => {
+ vi.useFakeTimers();
+
+ oracleService.setMockStatus('XLM', {
+ status: 'healthy',
+ updatedAt: Date.now(),
+ });
+
+ const { result } = renderHook(() => useOracleStatus('XLM'), {
+ wrapper: createWrapper(),
+ });
+
+ await vi.advanceTimersByTimeAsync(50);
+ expect(result.current.relativeTime).toBe('just now');
+
+ act(() => {
+ vi.advanceTimersByTime(30_000);
+ });
+
+ expect(result.current.relativeTime).toBe('30s ago');
+
+ vi.useRealTimers();
+ });
+});
diff --git a/src/hooks/useBounties.ts b/src/hooks/useBounties.ts
new file mode 100644
index 00000000..39915b4f
--- /dev/null
+++ b/src/hooks/useBounties.ts
@@ -0,0 +1,175 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { useWalletHoldings } from '@/hooks/useWallet';
+import { queryKeys } from '@/lib/queryKeys';
+import {
+ awardSubmission,
+ createBounty,
+ getBounties,
+ getBounty,
+ getSubmissions,
+ reclaimBounty,
+ rejectSubmission,
+ submitWork,
+ type Bounty,
+ type BountyFilters,
+ type CreateBountyInput,
+ type SubmitWorkInput,
+} from '@/services/bounty.service';
+import showToast from '@/utils/toast.util';
+
+function message(error: unknown, fallback: string): string {
+ return error instanceof Error ? error.message : fallback;
+}
+
+export function useBounties(filters: BountyFilters = {}) {
+ return useQuery({
+ queryKey: queryKeys.bounties.list(filters as Record),
+ queryFn: () => getBounties(filters),
+ staleTime: 15_000,
+ });
+}
+
+export function useBounty(bountyId: string | undefined) {
+ return useQuery({
+ queryKey: queryKeys.bounties.detail(bountyId ?? ''),
+ queryFn: () => getBounty(bountyId ?? ''),
+ enabled: Boolean(bountyId),
+ staleTime: 15_000,
+ });
+}
+
+export function useBountySubmissions(bountyId: string | undefined) {
+ return useQuery({
+ queryKey: queryKeys.bounties.submissions(bountyId ?? ''),
+ queryFn: () => getSubmissions(bountyId ?? ''),
+ enabled: Boolean(bountyId),
+ staleTime: 10_000,
+ });
+}
+
+export function useBountyEligibility(
+ bounty: Bounty | undefined,
+ wallet: string | undefined
+) {
+ const { data: holdings = [], isLoading } = useWalletHoldings(wallet ?? '');
+ const isHolder = Boolean(
+ bounty &&
+ holdings.some(
+ position =>
+ position.creatorId === bounty.keyId && (position.quantity ?? 0) > 0
+ )
+ );
+
+ let reason: string | null = null;
+ if (bounty?.holderGated) {
+ if (!wallet)
+ reason = 'Connect your wallet to submit work on this bounty.';
+ else if (!isHolder && !isLoading)
+ reason = `You must hold ${bounty.keyName} to submit work on this bounty.`;
+ }
+
+ return {
+ isHolder,
+ isEligible: !bounty?.holderGated || Boolean(wallet && isHolder),
+ reason,
+ isLoading,
+ };
+}
+
+function useInvalidateBounties() {
+ const queryClient = useQueryClient();
+ return () =>
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.bounties.all(),
+ });
+}
+
+export function useCreateBounty(wallet: string | undefined) {
+ const invalidate = useInvalidateBounties();
+ return useMutation({
+ mutationKey: ['bounty', 'create', wallet],
+ mutationFn: async (input: CreateBountyInput) => {
+ if (!wallet) throw new Error('Connect a wallet to post a bounty.');
+ return createBounty(input, wallet);
+ },
+ onSuccess: () => {
+ showToast.success('Bounty posted and rewards escrowed');
+ invalidate();
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not post bounty')),
+ });
+}
+
+export function useSubmitWork() {
+ const invalidate = useInvalidateBounties();
+ return useMutation({
+ mutationKey: ['bounty', 'submit-work'],
+ mutationFn: async (input: SubmitWorkInput) => submitWork(input),
+ onSuccess: () => {
+ showToast.success('Work submitted');
+ invalidate();
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not submit work')),
+ });
+}
+
+export function useAwardSubmission(wallet: string | undefined) {
+ const invalidate = useInvalidateBounties();
+ return useMutation({
+ mutationKey: ['bounty', 'award', wallet],
+ mutationFn: async (submissionId: string) => {
+ if (!wallet) throw new Error('Connect the creator wallet to award.');
+ return awardSubmission(submissionId, wallet);
+ },
+ onSuccess: () => {
+ showToast.success('Winner awarded');
+ invalidate();
+ },
+ onError: error => showToast.error(message(error, 'Could not award work')),
+ });
+}
+
+export function useRejectSubmission(wallet: string | undefined) {
+ const invalidate = useInvalidateBounties();
+ return useMutation({
+ mutationKey: ['bounty', 'reject', wallet],
+ mutationFn: async (variables: {
+ submissionId: string;
+ reason?: string;
+ }) => {
+ if (!wallet) throw new Error('Connect the creator wallet to reject.');
+ return rejectSubmission(
+ variables.submissionId,
+ wallet,
+ variables.reason
+ );
+ },
+ onSuccess: () => {
+ showToast.success('Submission rejected — one resubmission allowed');
+ invalidate();
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not reject work')),
+ });
+}
+
+export function useReclaimBounty(wallet: string | undefined) {
+ const invalidate = useInvalidateBounties();
+ return useMutation({
+ mutationKey: ['bounty', 'reclaim', wallet],
+ mutationFn: async (bountyId: string) => {
+ if (!wallet) throw new Error('Connect the creator wallet to reclaim.');
+ return reclaimBounty(bountyId, wallet);
+ },
+ onSuccess: result => {
+ showToast.success(
+ `Unpaid rewards reclaimed: ${result.reclaimedStroops.toLocaleString()} stroops`
+ );
+ invalidate();
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not reclaim rewards')),
+ });
+}
diff --git a/src/hooks/useConviction.ts b/src/hooks/useConviction.ts
new file mode 100644
index 00000000..7e8d9745
--- /dev/null
+++ b/src/hooks/useConviction.ts
@@ -0,0 +1,181 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { queryKeys } from '@/lib/queryKeys';
+import { convictionService } from '@/services/conviction.service';
+import type {
+ ConvictionBalances,
+ ConvictionProjection,
+ ConvictionProposal,
+} from '@/types/conviction';
+import {
+ calculateConvictionProjection,
+ getMaxStakeForProposal,
+} from '@/utils/conviction.utils';
+import showToast from '@/utils/toast.util';
+
+export interface UseConvictionResult {
+ /** Current accumulated conviction. */
+ conviction: number;
+ /** Conviction threshold required to pass. */
+ threshold: number;
+ /** User's currently allocated stake to this proposal. */
+ stake: number;
+ /** Total stake across all users. */
+ totalStake: number;
+ /** Full proposal data. */
+ proposal: ConvictionProposal | undefined;
+ /** User balances. */
+ balances: ConvictionBalances | undefined;
+ /** Unallocated balance across all active proposals. */
+ unallocatedBalance: number;
+ /** Max stake the user could allocate to this proposal. */
+ maxStake: number;
+ /** Conviction growth & crossing projection. */
+ projection: ConvictionProjection;
+ /** Whether the threshold has been crossed. */
+ isThresholdCrossed: boolean;
+ /** Whether the proposal is executed. */
+ isExecuted: boolean;
+ /** Allocate stake mutation. */
+ allocateStake: (amount: number) => Promise;
+ /** Withdraw stake mutation. */
+ withdrawStake: (amount?: number) => Promise;
+ /** Execute proposal mutation. */
+ executeProposal: () => Promise;
+ /** Loading state. */
+ isLoading: boolean;
+ /** Mutation pending state. */
+ isMutating: boolean;
+ /** Query error if any. */
+ error: Error | null;
+}
+
+export function useConviction(
+ proposalId: string,
+ userAddress?: string
+): UseConvictionResult {
+ const queryClient = useQueryClient();
+
+ const proposalQuery = useQuery({
+ queryKey: queryKeys.conviction.proposal(proposalId),
+ queryFn: () => convictionService.getProposal(proposalId),
+ enabled: Boolean(proposalId),
+ });
+
+ const balancesQuery = useQuery({
+ queryKey: queryKeys.conviction.balances(userAddress),
+ queryFn: () => convictionService.getUserBalances(userAddress),
+ });
+
+ const allocateMutation = useMutation({
+ mutationFn: (amount: number) =>
+ convictionService.allocateStake(proposalId, amount, userAddress),
+ onSuccess: updated => {
+ showToast.success(`Allocated ${updated.userStake} stake to proposal`);
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.conviction.all(),
+ });
+ },
+ onError: (err: Error) => {
+ showToast.error(err.message || 'Failed to allocate stake');
+ },
+ });
+
+ const withdrawMutation = useMutation({
+ mutationFn: (amount?: number) =>
+ convictionService.withdrawStake(proposalId, amount, userAddress),
+ onSuccess: _updated => {
+ showToast.success(
+ `Withdrawn stake. Note: conviction decays gradually after withdrawal.`
+ );
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.conviction.all(),
+ });
+ },
+ onError: (err: Error) => {
+ showToast.error(err.message || 'Failed to withdraw stake');
+ },
+ });
+
+ const executeMutation = useMutation({
+ mutationFn: () =>
+ convictionService.executeProposal(proposalId, userAddress),
+ onSuccess: () => {
+ showToast.success('Proposal executed successfully!');
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.conviction.all(),
+ });
+ },
+ onError: (err: Error) => {
+ showToast.error(err.message || 'Failed to execute proposal');
+ },
+ });
+
+ const proposal = proposalQuery.data ?? undefined;
+ const balances = balancesQuery.data;
+
+ const conviction = proposal?.currentConviction ?? 0;
+ const threshold = proposal?.threshold ?? 0;
+ const stake = proposal?.userStake ?? 0;
+ const totalStake = proposal?.totalStake ?? 0;
+ const unallocatedBalance = balances?.unallocatedBalance ?? 0;
+ const maxStake = getMaxStakeForProposal(unallocatedBalance, stake);
+
+ const projection = calculateConvictionProjection(
+ conviction,
+ threshold,
+ totalStake,
+ proposal?.alpha
+ );
+
+ const isThresholdCrossed = conviction >= threshold && threshold > 0;
+ const isExecuted = proposal?.status === 'executed';
+
+ return {
+ conviction,
+ threshold,
+ stake,
+ totalStake,
+ proposal,
+ balances,
+ unallocatedBalance,
+ maxStake,
+ projection,
+ isThresholdCrossed,
+ isExecuted,
+ allocateStake: allocateMutation.mutateAsync,
+ withdrawStake: withdrawMutation.mutateAsync,
+ executeProposal: executeMutation.mutateAsync,
+ isLoading: proposalQuery.isLoading || balancesQuery.isLoading,
+ isMutating:
+ allocateMutation.isPending ||
+ withdrawMutation.isPending ||
+ executeMutation.isPending,
+ error: (proposalQuery.error as Error) || null,
+ };
+}
+
+/**
+ * Hook to fetch all conviction proposals.
+ */
+export function useConvictionProposals(userAddress?: string) {
+ const queryClient = useQueryClient();
+
+ const proposalsQuery = useQuery({
+ queryKey: queryKeys.conviction.proposals(),
+ queryFn: () => convictionService.getProposals(),
+ });
+
+ const balancesQuery = useQuery({
+ queryKey: queryKeys.conviction.balances(userAddress),
+ queryFn: () => convictionService.getUserBalances(userAddress),
+ });
+
+ return {
+ proposals: proposalsQuery.data ?? [],
+ balances: balancesQuery.data,
+ isLoading: proposalsQuery.isLoading || balancesQuery.isLoading,
+ error: proposalsQuery.error as Error | null,
+ refetch: () =>
+ queryClient.invalidateQueries({ queryKey: queryKeys.conviction.all() }),
+ };
+}
diff --git a/src/hooks/useEvents.ts b/src/hooks/useEvents.ts
new file mode 100644
index 00000000..f7f1b6ff
--- /dev/null
+++ b/src/hooks/useEvents.ts
@@ -0,0 +1,93 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { queryKeys } from '@/lib/queryKeys';
+import {
+ closeEvent,
+ createEvent,
+ getRedemptionEligibility,
+ getWalletRedemption,
+ listEvents,
+ redeemPass,
+ type CreateEventInput,
+} from '@/services/events.service';
+import showToast from '@/utils/toast.util';
+
+function message(error: unknown, fallback: string): string {
+ return error instanceof Error ? error.message : fallback;
+}
+
+export function useEvents(creator?: string) {
+ return useQuery({
+ queryKey: queryKeys.events.list(creator),
+ queryFn: () => listEvents(creator),
+ staleTime: 10_000,
+ });
+}
+
+export function useEventRedemption(
+ eventId: string,
+ wallet: string | undefined,
+ heldKeyIds: string[]
+) {
+ const query = useQuery({
+ queryKey: queryKeys.events.redemption(eventId, wallet ?? ''),
+ queryFn: () => getWalletRedemption(eventId, wallet),
+ enabled: Boolean(eventId),
+ staleTime: 10_000,
+ });
+ const eligibility = getRedemptionEligibility(eventId, wallet, heldKeyIds);
+
+ return { ...query, eligibility };
+}
+
+export function useCreateEvent() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationKey: ['events', 'create'],
+ mutationFn: async (input: CreateEventInput) => createEvent(input),
+ onSuccess: () => {
+ showToast.success('Event created');
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.events.all(),
+ });
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not create event')),
+ });
+}
+
+export function useRedeemPass() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationKey: ['events', 'redeem'],
+ mutationFn: async (input: {
+ eventId: string;
+ wallet: string;
+ heldKeyIds: string[];
+ }) => redeemPass(input.eventId, input.wallet, input.heldKeyIds),
+ onSuccess: () => {
+ showToast.success('Pass redeemed');
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.events.all(),
+ });
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not redeem pass')),
+ });
+}
+
+export function useCloseEvent() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationKey: ['events', 'close'],
+ mutationFn: async (input: { eventId: string; creator: string }) =>
+ closeEvent(input.eventId, input.creator),
+ onSuccess: () => {
+ showToast.success('Event closed');
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.events.all(),
+ });
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not close event')),
+ });
+}
diff --git a/src/hooks/useFeeChange.ts b/src/hooks/useFeeChange.ts
new file mode 100644
index 00000000..a57bd6d1
--- /dev/null
+++ b/src/hooks/useFeeChange.ts
@@ -0,0 +1,48 @@
+import { create } from 'zustand';
+import {
+ cancelFeeChange,
+ executeFeeChange,
+ getFeeChangeState,
+ queueFeeChange,
+ resetFeeChangeStore,
+ type FeeChangeState,
+ type QueueFeeChangeInput,
+} from '@/services/feeChange.service';
+
+interface FeeChangeStore {
+ state: FeeChangeState;
+ refresh: () => void;
+ queue: (input: QueueFeeChangeInput) => FeeChangeState;
+ cancel: () => FeeChangeState;
+ execute: () => FeeChangeState;
+ reset: () => void;
+}
+
+export const useFeeChangeStore = create(set => ({
+ state: getFeeChangeState(),
+ refresh: () => set({ state: getFeeChangeState() }),
+ queue: input => {
+ const state = queueFeeChange(input);
+ set({ state });
+ return state;
+ },
+ cancel: () => {
+ const state = cancelFeeChange();
+ set({ state });
+ return state;
+ },
+ execute: () => {
+ const state = executeFeeChange();
+ set({ state });
+ return state;
+ },
+ reset: () => {
+ resetFeeChangeStore();
+ set({ state: getFeeChangeState() });
+ },
+}));
+
+export function usePendingFeeChange(): FeeChangeState | null {
+ const state = useFeeChangeStore(store => store.state);
+ return state.status === 'pending' ? state : null;
+}
diff --git a/src/hooks/useGrants.ts b/src/hooks/useGrants.ts
new file mode 100644
index 00000000..55ac7f50
--- /dev/null
+++ b/src/hooks/useGrants.ts
@@ -0,0 +1,116 @@
+import {
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query';
+import { queryKeys } from '@/lib/queryKeys';
+import {
+ getGrant,
+ listGrants,
+ reviewMilestone,
+ submitEvidence,
+ type Grant,
+ type GrantFilters,
+ type ReviewMilestoneInput,
+ type SubmitEvidenceInput,
+} from '@/services/grants.service';
+import showToast from '@/utils/toast.util';
+
+function message(error: unknown, fallback: string): string {
+ return error instanceof Error ? error.message : fallback;
+}
+
+export function useGrants(filters: Omit = {}) {
+ return useInfiniteQuery({
+ queryKey: queryKeys.grants.pages(filters as Record),
+ queryFn: ({ pageParam }) =>
+ listGrants({ ...filters, cursor: pageParam ?? null }),
+ initialPageParam: null as string | null,
+ getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
+ staleTime: 20_000,
+ });
+}
+
+export function useGrant(grantId: string | undefined) {
+ return useQuery({
+ queryKey: queryKeys.grants.detail(grantId ?? ''),
+ queryFn: () => getGrant(grantId ?? ''),
+ enabled: Boolean(grantId),
+ staleTime: 10_000,
+ });
+}
+
+export function useSubmitEvidence() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationKey: ['grant', 'submit-evidence'],
+ mutationFn: async (input: SubmitEvidenceInput) => submitEvidence(input),
+ onSuccess: () => {
+ showToast.success('Evidence submitted for review');
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.grants.all(),
+ });
+ },
+ onError: error =>
+ showToast.error(message(error, 'Could not submit evidence')),
+ });
+}
+
+export function useReviewMilestone() {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationKey: ['grant', 'review-milestone'],
+ mutationFn: async (input: ReviewMilestoneInput) => reviewMilestone(input),
+ onMutate: async input => {
+ await queryClient.cancelQueries({ queryKey: queryKeys.grants.all() });
+ const grant = queryClient.getQueryData(
+ queryKeys.grants.detail(input.grantId)
+ );
+ const previous = grant;
+ if (!grant || input.decision !== 'approve') return { previous };
+
+ const target = grant.milestones.find(m => m.id === input.milestoneId);
+ const releasedStroops =
+ grant.releasedStroops + (target?.amountStroops ?? 0);
+ queryClient.setQueryData(
+ queryKeys.grants.detail(grant.id),
+ current =>
+ current
+ ? {
+ ...current,
+ releasedStroops,
+ milestones: current.milestones.map(m =>
+ m.id === input.milestoneId
+ ? { ...m, state: 'approved' }
+ : m
+ ),
+ }
+ : current
+ );
+ return { previous };
+ },
+ onSuccess: (_result, input) => {
+ showToast.success(
+ input.decision === 'approve'
+ ? 'Milestone approved and funds released'
+ : 'Evidence returned to pending'
+ );
+ },
+ onError: (error, _input, context) => {
+ if (context?.previous) {
+ queryClient.setQueryData(
+ queryKeys.grants.detail(context.previous.id),
+ context.previous
+ );
+ }
+ showToast.error(message(error, 'Could not review milestone'));
+ },
+ onSettled: () => {
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.grants.all(),
+ });
+ },
+ });
+}
diff --git a/src/hooks/useOracleStatus.ts b/src/hooks/useOracleStatus.ts
new file mode 100644
index 00000000..4d121b3b
--- /dev/null
+++ b/src/hooks/useOracleStatus.ts
@@ -0,0 +1,118 @@
+import { useEffect, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import { queryKeys } from '@/lib/queryKeys';
+import { oracleService } from '@/services/oracle.service';
+import type {
+ OracleHealthState,
+ OracleSource,
+ OracleStatus,
+} from '@/types/oracle';
+import { formatLiveRelativeTime } from '@/utils/oracleRelativeTime.utils';
+
+export interface UseOracleStatusResult {
+ /** Underlying contract status data. */
+ data: OracleStatus | undefined;
+ /** Contract reported status: 'healthy' | 'fallback' | 'stale'. */
+ status: OracleHealthState;
+ /** Price source: 'primary' | 'fallback'. */
+ source: OracleSource;
+ /** Human-readable source name. */
+ sourceName: string;
+ /** Reference price in XLM. */
+ priceXlm: number;
+ /** Reference price in stroops. */
+ priceStroops: number;
+ /** Epoch timestamp in ms of last oracle report. */
+ updatedAt: number;
+ /** Current age in milliseconds (live updated). */
+ ageMs: number;
+ /** Live formatted relative time string (e.g. '12s ago', 'just now'). */
+ relativeTime: string;
+ /** Absolute deviation percentage from spot/reference. */
+ deviationPercent: number;
+ /** Deviation in basis points. */
+ deviationBps: number;
+ /** Whether the price is stale. */
+ isStale: boolean;
+ /** Whether the source is fallback. */
+ isFallback: boolean;
+ /** Whether the oracle is healthy. */
+ isHealthy: boolean;
+ /** Explanation reason when actions are blocked or degraded. */
+ staleReason: string | null;
+ /** Loading state. */
+ isLoading: boolean;
+ /** Error state. */
+ error: Error | null;
+}
+
+export function useOracleStatus(
+ asset: string = 'XLM',
+ options?: { enabled?: boolean; pollIntervalMs?: number }
+): UseOracleStatusResult {
+ const enabled = options?.enabled ?? Boolean(asset);
+ const pollIntervalMs = options?.pollIntervalMs ?? 15_000;
+
+ const {
+ data,
+ isLoading,
+ error,
+ } = useQuery({
+ queryKey: queryKeys.oracle.status(asset),
+ queryFn: () => oracleService.getOracleStatus(asset),
+ enabled,
+ refetchInterval: pollIntervalMs,
+ });
+
+ // Live relative time ticking every second so age updates without page reload
+ const [currentTime, setCurrentTime] = useState(Date.now());
+
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setCurrentTime(Date.now());
+ }, 1000);
+ return () => clearInterval(interval);
+ }, []);
+
+ const updatedAt = data?.updatedAt ?? currentTime;
+ const ageMs = Math.max(0, currentTime - updatedAt);
+ const relativeTime = formatLiveRelativeTime(ageMs);
+
+ const isStale =
+ Boolean(data?.isStale) ||
+ (data?.maxStaleAgeMs ? ageMs > data.maxStaleAgeMs : false) ||
+ data?.status === 'stale';
+
+ const isFallback =
+ !isStale && (data?.isFallback || data?.source === 'fallback' || data?.status === 'fallback');
+
+ const effectiveStatus: OracleHealthState = isStale
+ ? 'stale'
+ : isFallback
+ ? 'fallback'
+ : 'healthy';
+
+ const staleReason = isStale
+ ? `Oracle price is stale (last update ${relativeTime}). Dependent actions are temporarily paused to protect against price manipulation.`
+ : null;
+
+ return {
+ data,
+ status: effectiveStatus,
+ source: isFallback ? 'fallback' : 'primary',
+ sourceName: data?.sourceName ?? (isFallback ? 'Fallback Oracle' : 'Primary Oracle'),
+ priceXlm: data?.priceXlm ?? 0,
+ priceStroops: data?.priceStroops ?? 0,
+ updatedAt,
+ ageMs,
+ relativeTime,
+ deviationPercent: data?.deviationPercent ?? 0,
+ deviationBps: data?.deviationBps ?? 0,
+ isStale,
+ isFallback,
+ isHealthy: effectiveStatus === 'healthy',
+ staleReason,
+ isLoading,
+ error: (error as Error) || null,
+ };
+}
diff --git a/src/hooks/useRagequit.ts b/src/hooks/useRagequit.ts
new file mode 100644
index 00000000..ec9040fe
--- /dev/null
+++ b/src/hooks/useRagequit.ts
@@ -0,0 +1,149 @@
+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/hooks/useStream.ts b/src/hooks/useStream.ts
new file mode 100644
index 00000000..f4fc0ad3
--- /dev/null
+++ b/src/hooks/useStream.ts
@@ -0,0 +1,104 @@
+import { useEffect, useState } from 'react';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { queryKeys } from '@/lib/queryKeys';
+import { creatorStreamContractService } from '@/services/creatorStreamContract.service';
+import type { EarningsStream, StreamWithdrawal } from '@/types/stream';
+import { calculateClaimableBalance } from '@/utils/stream.utils';
+import showToast from '@/utils/toast.util';
+
+export interface UseStreamResult {
+ stream: EarningsStream | undefined;
+ funded: number;
+ withdrawn: number;
+ rate: number;
+ claimable: number;
+ isPaused: boolean;
+ withdrawals: StreamWithdrawal[];
+ withdraw: (amount: number) => Promise;
+ isLoading: boolean;
+ isWithdrawing: boolean;
+ error: Error | null;
+}
+
+export function useStream(streamId: string): UseStreamResult {
+ const queryClient = useQueryClient();
+
+ const {
+ data: stream,
+ isLoading,
+ error,
+ } = useQuery({
+ queryKey: queryKeys.stream.detail(streamId),
+ queryFn: () => creatorStreamContractService.getStream(streamId),
+ enabled: Boolean(streamId),
+ });
+
+ // Live ticker updates claimable balance each second
+ const [now, setNow] = useState(Date.now());
+
+ useEffect(() => {
+ if (!stream || stream.isPaused) return;
+ const interval = setInterval(() => {
+ setNow(Date.now());
+ }, 1000);
+ return () => clearInterval(interval);
+ }, [stream]);
+
+ const mutation = useMutation({
+ mutationFn: (amount: number) =>
+ creatorStreamContractService.withdraw(streamId, amount),
+ onSuccess: res => {
+ showToast.success(
+ `Successfully withdrew ${res.amountXlm.toFixed(2)} XLM from stream!`
+ );
+ void queryClient.invalidateQueries({
+ queryKey: queryKeys.stream.all(),
+ });
+ },
+ onError: (err: Error) => {
+ showToast.error(err.message || 'Withdrawal failed');
+ },
+ });
+
+ const funded = stream?.fundedAmount ?? 0;
+ const withdrawn = stream?.withdrawnAmount ?? 0;
+ const rate = stream?.ratePerSecond ?? 0;
+ const isPaused = Boolean(stream?.isPaused);
+ const claimable = stream ? calculateClaimableBalance(stream, now) : 0;
+ const withdrawals = stream?.withdrawals ?? [];
+
+ return {
+ stream: stream ?? undefined,
+ funded,
+ withdrawn,
+ rate,
+ claimable,
+ isPaused,
+ withdrawals,
+ withdraw: mutation.mutateAsync,
+ isLoading,
+ isWithdrawing: mutation.isPending,
+ error: (error as Error) || null,
+ };
+}
+
+export function useCreatorStreams(creatorAddress?: string) {
+ const queryClient = useQueryClient();
+
+ const {
+ data: streams,
+ isLoading,
+ error,
+ } = useQuery({
+ queryKey: queryKeys.stream.list(creatorAddress),
+ queryFn: () => creatorStreamContractService.getStreams(creatorAddress),
+ });
+
+ return {
+ streams: streams ?? [],
+ isLoading,
+ error: (error as Error) || null,
+ refetch: () =>
+ queryClient.invalidateQueries({ queryKey: queryKeys.stream.all() }),
+ };
+}
diff --git a/src/lib/queryKeys.ts b/src/lib/queryKeys.ts
index 36e19aca..447c080a 100644
--- a/src/lib/queryKeys.ts
+++ b/src/lib/queryKeys.ts
@@ -222,6 +222,28 @@ export const queryKeys = {
['governance', 'events', type ?? 'all'] as const,
admin: () => ['governance', 'admin'] as const,
},
+ conviction: {
+ all: () => ['conviction'] as const,
+ proposals: () => ['conviction', 'proposals'] as const,
+ proposal: (id: string) => ['conviction', 'proposal', id] as const,
+ balances: (userAddress?: string) =>
+ ['conviction', 'balances', userAddress ?? 'default'] as const,
+ },
+ oracle: {
+ all: () => ['oracle'] as const,
+ status: (asset: string) => ['oracle', 'status', asset.toUpperCase()] as const,
+ },
+ ragequit: {
+ all: () => ['ragequit'] as const,
+ state: (proposalId: string, userAddress?: string) =>
+ ['ragequit', proposalId, userAddress ?? 'default'] as const,
+ },
+ stream: {
+ all: () => ['stream'] as const,
+ list: (creatorAddress?: string) =>
+ ['stream', 'list', creatorAddress ?? 'default'] as const,
+ detail: (streamId: string) => ['stream', 'detail', streamId] as const,
+ },
mergeProposal: {
bySourceKey: (sourceKeyId: string) =>
['mergeProposal', 'source', sourceKeyId] as const,
@@ -361,4 +383,28 @@ export const queryKeys = {
sessions: () => ['sessions'] as const,
alerts: () => ['alerts'] as const,
},
+ bounties: {
+ all: () => ['bounties'] as const,
+ list: (filters?: Record) =>
+ ['bounties', 'list', filters ?? null] as const,
+ detail: (bountyId: string) => ['bounties', 'detail', bountyId] as const,
+ submissions: (bountyId: string) =>
+ ['bounties', 'submissions', bountyId] as const,
+ },
+ grants: {
+ all: () => ['grants'] as const,
+ pages: (filters?: Record) =>
+ ['grants', 'pages', filters ?? null] as const,
+ detail: (grantId: string) => ['grants', 'detail', grantId] as const,
+ },
+ events: {
+ all: () => ['events'] as const,
+ list: (creator?: string) => ['events', 'list', creator ?? ''] as const,
+ redemption: (eventId: string, wallet: string) =>
+ ['events', 'redemption', eventId, wallet] as const,
+ },
+ feeChange: {
+ all: () => ['fee-change'] as const,
+ pending: () => ['fee-change', 'pending'] as const,
+ },
} as const;
diff --git a/src/pages/AdminDashboardPage.tsx b/src/pages/AdminDashboardPage.tsx
index 8b104d9e..33af9a4c 100644
--- a/src/pages/AdminDashboardPage.tsx
+++ b/src/pages/AdminDashboardPage.tsx
@@ -5,6 +5,7 @@ import AclWhitelistPanel from '@/components/admin/AclWhitelistPanel';
import UpgradeProxyPanel from '@/components/admin/UpgradeProxyPanel';
import TreasuryPanel from '@/components/admin/TreasuryPanel';
import TreasuryManagementDashboard from '@/components/admin/TreasuryManagementDashboard';
+import FeeChangeAdminPanel from '@/components/admin/FeeChangeAdminPanel';
import { useNavigationTiming } from '@/hooks/useNavigationTiming';
import { useStellarWallet } from '@/hooks/useStellarWallet';
import { isAdminWallet } from '@/utils/adminAccess';
@@ -32,8 +33,8 @@ export default function AdminDashboardPage() {
Access denied
- Your connected wallet is not in the protocol signer set and cannot
- view or approve multi-sig actions.
+ Your connected wallet is not in the protocol signer set and
+ cannot view or approve multi-sig actions.