import { useState, useCallback, useEffect } from 'react'; import type { HistoryEntry, Manager } from 'coco-cashu-core'; interface UseHistoryManagerProps { coco: Manager | null; isInitialized: boolean; } export function useHistoryManager({ coco, isInitialized, }: UseHistoryManagerProps) { const [historyEntries, setHistoryEntries] = useState([]); const [isLoadingHistory, setIsLoadingHistory] = useState(false); const [isHistoryExpanded, setIsHistoryExpanded] = useState(false); // Load history from wallet const loadHistory = useCallback(async () => { if (!coco) return; try { setIsLoadingHistory(true); const entries = await coco.history.getPaginatedHistory(0, 50); // TODO: show entire history // Filter out unpaid quotes: only show completed transactions // - Mint quotes: only show 'ISSUED' (completed) // - Melt quotes: only show 'PAID' (completed) // - Send/Receive: show all (no state field) const filteredEntries = entries.filter((entry) => { if (entry.type === 'mint') { return entry.state === 'ISSUED'; } if (entry.type === 'melt') { return entry.state === 'PAID'; } // Send and receive entries don't have a state field, show all return true; }); setHistoryEntries(filteredEntries); } catch (err) { console.error('Failed to load history:', err); } finally { setIsLoadingHistory(false); } }, [coco]); // Load history on wallet initialization useEffect(() => { if (isInitialized && historyEntries.length === 0) { loadHistory(); } }, [isInitialized, historyEntries.length, loadHistory]); // Auto-refresh on wallet events useEffect(() => { if (!isInitialized || !coco) return; // Listen for history updates (fires on send, receive transactions) const unsubscribeHistoryUpdated = coco.on('history:updated', () => { loadHistory(); }); // Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated) const unsubscribeMeltCreated = coco.on('melt-quote:created', () => { loadHistory(); }); // Listen for melt quote paid (backup, in case creation event missed) const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => { loadHistory(); }); // Listen for mint quote REDEEMED (only after invoice is paid, not created) const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => { loadHistory(); }); return () => { unsubscribeHistoryUpdated(); unsubscribeMeltCreated(); unsubscribeMeltPaid(); unsubscribeMintRedeemed(); }; }, [isInitialized, coco, loadHistory]); return { historyEntries, setHistoryEntries, isLoadingHistory, isHistoryExpanded, setIsHistoryExpanded, loadHistory, }; }