diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx index 2304d8a..faaf557 100644 --- a/src/components/CashuWallet.tsx +++ b/src/components/CashuWallet.tsx @@ -1,7 +1,6 @@ import { useState, useEffect, useCallback } from 'react'; import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; import { useNpubCash } from '@/hooks/useNpubCash'; -import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLightningAddress } from '@/hooks/useLightningAddress'; import { useToast } from '@/hooks/useToast'; import { Button } from '@/components/ui/button'; @@ -9,7 +8,8 @@ import { Input } from '@/components/ui/input'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu'; -import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode } from 'lucide-react'; +import { QRModal } from '@/components/ui/qr-modal'; +import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode, AlertTriangle } from 'lucide-react'; import QRCode from 'qrcode'; export function CashuWallet() { @@ -27,6 +27,7 @@ export function CashuWallet() { send, getProofs, addMint, + removeMint, createMintQuote, createMeltQuote, payMeltQuote, @@ -115,6 +116,12 @@ export function CashuWallet() { invoice: string; qrCodeUrl: string; } | null>(null); + + const [showRemoveMintModal, setShowRemoveMintModal] = useState(false); + const [mintToRemove, setMintToRemove] = useState<{ + url: string; + name?: string; + } | null>(null); // ============================================================================ // COMPUTED VALUES @@ -162,39 +169,13 @@ export function CashuWallet() { } }; - // Generate QR code for Lightning address - const generateLightningQRCode = async () => { - if (!lightningAddress) return; - - try { - const qrCodeUrl = await QRCode.toDataURL(lightningAddress, { - width: 256, - margin: 2, - color: { - dark: '#000000', - light: '#FFFFFF', - }, - }); - setLightningQRCode(qrCodeUrl); - setShowLightningQR(true); - } catch (err) { - console.error('Failed to generate Lightning address QR code:', err); - toast({ - variant: "destructive", - title: "QR Code Failed", - description: "Failed to generate QR code for Lightning address", - }); - } - }; - - // ============================================================================ - // HELPER FUNCTIONS - QR Code + // HELPER FUNCTIONS - QR Code Generation // ============================================================================ - const generateQRCodeForQuote = async (invoice: string): Promise => { + const generateQRCode = async (text: string): Promise => { try { - return await QRCode.toDataURL(invoice, { + return await QRCode.toDataURL(text, { width: 256, margin: 2, color: { @@ -204,10 +185,28 @@ export function CashuWallet() { }); } catch (err) { console.error('Failed to generate QR code:', err); + toast({ + variant: "destructive", + title: "QR Code Failed", + description: "Failed to generate QR code", + }); return ''; } }; + // Generate QR code for Lightning address + const generateLightningQRCode = async () => { + if (!lightningAddress) return; + + try { + const qrCodeUrl = await generateQRCode(lightningAddress); + setLightningQRCode(qrCodeUrl); + setShowLightningQR(true); + } catch (err) { + console.error('Failed to generate Lightning address QR code:', err); + } + }; + // ============================================================================ // HELPER FUNCTIONS - Mint Management // ============================================================================ @@ -332,7 +331,7 @@ export function CashuWallet() { const quote = await createMintQuote(activeMintUrl, amount); // Generate QR code for the Lightning invoice - const qrCodeUrl = await generateQRCodeForQuote(quote.request); + const qrCodeUrl = await generateQRCode(quote.request); // Set the invoice data and show modal setCurrentInvoice({ @@ -514,6 +513,47 @@ export function CashuWallet() { } }; + const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => { + setMintToRemove(mint); + setShowRemoveMintModal(true); + }, []); + + const handleConfirmRemoveMint = useCallback(async () => { + if (!mintToRemove) return; + + try { + await removeMint(mintToRemove.url); + + // Manually refresh mints since there's no mint:removed event + await refreshMints(); + + // If the removed mint was the active mint, select the first available mint + if (activeMintUrl === mintToRemove.url) { + const remainingMints = mints.filter(m => m.url !== mintToRemove.url); + if (remainingMints.length > 0) { + setActiveMintUrl(remainingMints[0].url); + } else { + setActiveMintUrl(null); + } + } + + toast({ + title: "Mint Removed", + description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`, + }); + + setShowRemoveMintModal(false); + setMintToRemove(null); + } catch (err) { + console.error('Failed to remove mint:', err); + toast({ + variant: "destructive", + title: "Remove Failed", + description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`, + }); + } + }, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]); + // ============================================================================ // EVENT HANDLERS - Mint Management // ============================================================================ @@ -685,48 +725,57 @@ export function CashuWallet() { // ============================================================================ - // RENDER - Loading State + // RENDER - Loading Modal // ============================================================================ - if (isLoading) { + const LoadingModal = () => { + if (!isLoading) return null; + return ( -
- +
+ - - Initializing... + + Loading
); - } + }; // ============================================================================ - // RENDER - Uninitialized State + // RENDER - Uninitialized State Modal // ============================================================================ - if (!isInitialized) { + const UninitializedModal = () => { + if (isInitialized) return null; + return ( - - - - - Cashu Wallet - - - Failed to initialize wallet. Please check the console for errors. - - - +
+ + + + + Cashu Wallet + + + Failed to initialize wallet. Please check the console for errors. + + + +
); - } + }; // ============================================================================ // RENDER - Main UI // ============================================================================ return ( -
+ <> + + +
{/* ======================================================================== SECTION: Balance Display @@ -792,8 +841,6 @@ export function CashuWallet() { - Connected Mints - {mints.length === 0 && ( No mints connected )} @@ -808,6 +855,17 @@ export function CashuWallet() {
{getCleanMintLabel(mint)}
+ ))} @@ -845,21 +903,21 @@ export function CashuWallet() { {/* Lightning Address */} {lightningAddress && (
- - {lightningAddress} - - + + {lightningAddress} + + {unclaimedAmount > 0 && ( - + )}
)} @@ -895,8 +953,8 @@ export function CashuWallet() { - - Receive + + Receive {mode === 'tokens' @@ -947,8 +1005,8 @@ export function CashuWallet() { - - Send + + Send {mode === 'tokens' @@ -1355,60 +1413,44 @@ export function CashuWallet() { {/* ======================================================================== SECTION: Lightning Address QR Code Modal ======================================================================== */} - {showLightningQR && lightningQRCode && ( -
- - - - - - Lightning Address QR Code - - - Scan to send Lightning payments - - - -
-
- Lightning Address QR Code -
-
- -
-
- {lightningAddress} -
-
- -
- 💡 Share this QR code or address to receive Lightning payments -
-
-
-
- )} + setShowLightningQR(false)} + title="Lightning Address QR Code" + description="Scan to send Lightning payments" + qrCodeUrl={lightningQRCode} + content={lightningAddress || ''} + icon="qr" + helpText="💡 Share this QR code or address to receive Lightning payments" + /> {/* ======================================================================== SECTION: Lightning Invoice Modal ======================================================================== */} - {showInvoiceModal && currentInvoice && ( -
+ setShowInvoiceModal(false)} + title="Lightning Invoice" + description={currentInvoice ? `Pay this invoice to receive ${currentInvoice.amount} sats` : ''} + qrCodeUrl={currentInvoice?.qrCodeUrl || ''} + content={currentInvoice?.invoice || ''} + icon="zap" + showCopyButton={true} + copiedText={copiedInvoice} + onCopy={() => currentInvoice && handleCopy(currentInvoice.invoice, 'invoice')} + copyButtonText="Copy Invoice" + helpText="💡 Coco will automatically claim your tokens when payment is detected" + /> + + {/* ======================================================================== + SECTION: Remove Mint Confirmation Modal + ======================================================================== */} + {showRemoveMintModal && mintToRemove && ( +
- - Lightning Invoice + + Remove Mint - Pay this invoice to receive {currentInvoice.amount} sats + Are you sure you want to remove this mint from your wallet? -
-
- Lightning Invoice QR Code +
+
{mintToRemove.name || new URL(mintToRemove.url).hostname}
+
+ {mintToRemove.url}
-
-
- {currentInvoice.invoice} -
+
+
⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.
+
💡 You can always add this mint back later if needed.
-
+
+
- -
- 💡 Coco will automatically claim your tokens when payment is detected -
)} -
+
+ ); } diff --git a/src/components/ui/qr-modal.tsx b/src/components/ui/qr-modal.tsx new file mode 100644 index 0000000..88c4966 --- /dev/null +++ b/src/components/ui/qr-modal.tsx @@ -0,0 +1,106 @@ +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { X, Copy, Check, QrCode, Zap } from 'lucide-react'; + +interface QRModalProps { + isOpen: boolean; + onClose: () => void; + title: string; + description: string; + qrCodeUrl: string; + content: string; + icon?: 'qr' | 'zap'; + showCopyButton?: boolean; + copiedText?: string | null; + onCopy?: () => void; + copyButtonText?: string; + helpText?: string; +} + +export function QRModal({ + isOpen, + onClose, + title, + description, + qrCodeUrl, + content, + icon = 'qr', + showCopyButton = false, + copiedText, + onCopy, + copyButtonText = 'Copy', + helpText, +}: QRModalProps) { + if (!isOpen) return null; + + const IconComponent = icon === 'zap' ? Zap : QrCode; + + return ( +
+ + + + + + {title} + + + {description} + + + +
+
+ {`${title} +
+
+ +
+
+ {content} +
+
+ + {showCopyButton && onCopy && ( +
+ +
+ )} + + {helpText && ( +
+ {helpText} +
+ )} +
+
+
+ ); +} diff --git a/src/hooks/cashu/useCashuBalances.ts b/src/hooks/cashu/useCashuBalances.ts index 1f2c98e..8d8d456 100644 --- a/src/hooks/cashu/useCashuBalances.ts +++ b/src/hooks/cashu/useCashuBalances.ts @@ -17,7 +17,7 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur // Throttling refs const lastRefreshTimeRef = useRef(0); const isRefreshingRef = useRef(false); - const REFRESH_THROTTLE_MS = 500; + const REFRESH_THROTTLE_MS = 200; const refreshBalances = useCallback(async () => { if (!manager) return; @@ -102,10 +102,46 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur refreshBalances(); }); + const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('send:created', () => { + console.log('📤 Send created, refreshing balances...'); + // Bypass throttling for send operations to ensure immediate balance update + setTimeout(async () => { + if (!manager) return; + try { + console.log('🔄 send:created: Getting balances from wallet...'); + const newBalances = await (manager as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); + console.log('💰 send:created: Raw balances from wallet:', newBalances); + + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ send:created: Balances unchanged, skipping state update'); + return prevBalances; + } + }); + } catch (err) { + console.error('❌ send:created: Failed to refresh balances:', err); + } + }, 100); + }); + + const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('receive:created', () => { + console.log('📥 Receive created, refreshing balances...'); + refreshBalances(); + }); + return () => { unsubscribeProofsSaved(); unsubscribeProofsStateChanged(); unsubscribeMintQuoteRedeemed(); + unsubscribeSendCreated(); + unsubscribeReceiveCreated(); }; }, [manager, refreshBalances]); diff --git a/src/hooks/cashu/useCashuMints.ts b/src/hooks/cashu/useCashuMints.ts index 962cfe1..5a55d3a 100644 --- a/src/hooks/cashu/useCashuMints.ts +++ b/src/hooks/cashu/useCashuMints.ts @@ -78,13 +78,33 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn { } }, [manager]); - const removeMint = useCallback(async (_mintUrl: string) => { - // Note: coco-cashu doesn't have a direct remove mint method - // This would need to be implemented at the repository level - const error = new CashuWalletError('Remove mint functionality not yet implemented', 'REMOVE_MINT_NOT_IMPLEMENTED'); - setError(error); - throw error; - }, []); + const removeMint = useCallback(async (mintUrl: string) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + + // Access the mintService directly through the manager to use deleteMint + // The manager has a private mintService property that we can access + const mintService = (manager as any).mintService; + if (!mintService || typeof mintService.deleteMint !== 'function') { + throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR'); + } + + await mintService.deleteMint(mintUrl); + + // No need to manually refresh - events will handle it automatically + console.log('✅ Mint removed successfully:', mintUrl); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint'; + const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); // Set up event listeners for automatic mint updates using coco events useEffect(() => {