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 { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Alert, AlertDescription } from '@/components/ui/alert'; 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, CreditCard } from 'lucide-react'; import QRCode from 'qrcode'; export function CashuWallet() { // ============================================================================ // HOOKS // ============================================================================ const { isInitialized, isLoading, error, balances, mints, receive, send, getProofs, addMint, createMintQuote, createMeltQuote, payMeltQuote, redeemMintQuote, addMintQuote, refreshBalances, refreshMints, checkAndRedeemPendingQuotes, clearError, getHistory, } = useCashu(); const { lightningAddress, unclaimedAmount, quotes, isLoading: isNpubCashLoading, error: npubCashError, fetchQuotes, refresh: refreshNpubCash, retryAuth, setMint, } = useNpubCash(); const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); // ============================================================================ // STATE - Input Values // ============================================================================ const [tokenInput, setTokenInput] = useState(''); const [mintUrl, setMintUrl] = useState(''); const [sendAmount, setSendAmount] = useState(''); const [quoteAmount, setQuoteAmount] = useState(''); const [lightningInvoice, setLightningInvoice] = useState(''); const [lightningAddressInput, setLightningAddressInput] = useState(''); const [lightningAddressAmount, setLightningAddressAmount] = useState(''); // ============================================================================ // STATE - UI State // ============================================================================ const [showSats, setShowSats] = useState(true); const [receiveMode, setReceiveMode] = useState<'tokens' | 'lightning'>('tokens'); const [sendMode, setSendMode] = useState<'tokens' | 'lightning'>('tokens'); const [activeMintUrl, setActiveMintUrl] = useState(null); // ============================================================================ // STATE - Transaction State // ============================================================================ const [sentToken, setSentToken] = useState(null); const [pendingLightningAddress, setPendingLightningAddress] = useState(null); const [pendingQuotes, setPendingQuotes] = useLocalStorage>('cashu-pending-quotes', []); // ============================================================================ // STATE - Copy Feedback // ============================================================================ const [copiedToken, setCopiedToken] = useState(false); const [copiedInvoice, setCopiedInvoice] = useState(null); const [copiedLightningAddress, setCopiedLightningAddress] = useState(false); // ============================================================================ // STATE - History // ============================================================================ const [historyEntries, setHistoryEntries] = useState([]); const [isLoadingHistory, setIsLoadingHistory] = useState(false); const [isHistoryExpanded, setIsHistoryExpanded] = useState(false); const [showProofBreakdown, setShowProofBreakdown] = useState(false); const [proofBreakdown, setProofBreakdown] = useState<{ mintUrl: string; denominations: { [key: number]: number }; totalBalance: number; } | null>(null); // ============================================================================ // COMPUTED VALUES // ============================================================================ const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0); // ============================================================================ // HELPER FUNCTIONS - Display // ============================================================================ const getCleanMintLabel = (mint: { name?: string; url: string }) => { if (mint.name && mint.name.trim().length > 0) { // If name looks like a URL, strip protocol as well return mint.name.replace(/^https?:\/\//, ''); } try { return new URL(mint.url).host; // host excludes protocol and preserves port if any } catch { // Fallback: manual strip return mint.url.replace(/^https?:\/\//, ''); } }; const formatAmount = (sats: number): string => { if (showSats) { return `${sats.toLocaleString()} sats`; } else { // Simple USD conversion (you can enhance this with real BTC price) const usd = sats * 0.0001; // Rough approximation return `$${usd.toFixed(2)}`; } }; // Copy Lightning address to clipboard const copyLightningAddress = async () => { if (!lightningAddress) return; try { await navigator.clipboard.writeText(lightningAddress); setCopiedLightningAddress(true); setTimeout(() => setCopiedLightningAddress(false), 2000); } catch (err) { console.error('Failed to copy Lightning address:', err); } }; // ============================================================================ // HELPER FUNCTIONS - QR Code // ============================================================================ const generateQRCodeForQuote = async (invoice: string): Promise => { try { return await QRCode.toDataURL(invoice, { width: 256, margin: 2, color: { dark: '#000000', light: '#FFFFFF', }, }); } catch (err) { console.error('Failed to generate QR code:', err); return ''; } }; // ============================================================================ // HELPER FUNCTIONS - Mint Management // ============================================================================ /** * Set active mint and sync with npubx.cash */ const handleSetActiveMint = useCallback(async (mintUrl: string | null) => { // Set the active mint locally setActiveMintUrl(mintUrl); // If we have a mint URL, also update npubx.cash preference if (mintUrl) { try { await setMint(mintUrl); console.log(`✅ Updated npubx.cash mint preference to: ${mintUrl}`); } catch (error) { console.error('❌ Failed to update npubx.cash mint preference:', error); // Don't throw - we still want to set the local mint even if npubx.cash fails } } }, [setMint]); // ============================================================================ // HELPER FUNCTIONS - History // ============================================================================ const loadHistory = useCallback(async () => { try { setIsLoadingHistory(true); const entries = await getHistory(50, 0); setHistoryEntries(entries); } catch (err) { console.error('Failed to load history:', err); } finally { setIsLoadingHistory(false); } }, [getHistory]); const getHistoryIcon = (type: string) => { switch (type) { case 'mint': return ; case 'melt': return ; case 'send': return ; case 'receive': return ; default: return ; } }; const getHistoryLabel = (type: string) => { switch (type) { case 'mint': return 'Mint (Lightning → Tokens)'; case 'melt': return 'Melt (Tokens → Lightning)'; case 'send': return 'Send Tokens'; case 'receive': return 'Receive Tokens'; default: return type; } }; const getHistoryStateColor = (state?: string) => { if (!state) return 'bg-gray-500'; switch (state) { case 'PAID': return 'bg-green-500'; case 'UNPAID': return 'bg-yellow-500'; case 'PENDING': return 'bg-blue-500'; default: return 'bg-gray-500'; } }; // ============================================================================ // EVENT HANDLERS - Receive // ============================================================================ const handleReceive = async () => { if (receiveMode === 'tokens') { if (!tokenInput.trim()) return; try { await receive(tokenInput); setTokenInput(''); const message = 'Token received successfully!'; console.log('✅', message); alert(message); } catch (err) { const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } } else { // Lightning mode - create mint quote if (!quoteAmount || !activeMintUrl) return; try { const amount = parseInt(quoteAmount); if (isNaN(amount) || amount <= 0) { const message = 'Please enter a valid amount'; console.warn('⚠️', message); alert(message); return; } const quote = await createMintQuote(activeMintUrl, amount); // Generate QR code for the Lightning invoice const qrCodeUrl = await generateQRCodeForQuote(quote.request); // Save the pending quote with QR code setPendingQuotes(prev => [...prev, { quoteId: quote.quote, mintUrl: activeMintUrl, amount, invoice: quote.request, timestamp: Date.now(), qrCodeUrl }]); const message = `Mint quote created! Request: ${quote.request}`; console.log('✅', message); console.log('💰 Quote object:', quote); console.log('🔗 Lightning Invoice:', quote.request); alert('Lightning invoice created! After paying, click the refresh button (🔄) to claim your tokens.'); setQuoteAmount(''); } catch (err) { const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } } }; // ============================================================================ // EVENT HANDLERS - Send // ============================================================================ const handleSend = async () => { if (sendMode === 'tokens') { if (!sendAmount || !activeMintUrl) return; try { const amount = parseInt(sendAmount); if (isNaN(amount) || amount <= 0) { const message = 'Please enter a valid amount'; console.warn('⚠️', message); alert(message); return; } const encodedToken = await send(activeMintUrl, amount); setSentToken(encodedToken); console.log('✅ Token sent successfully!'); console.log('📤 Encoded token:', encodedToken); setSendAmount(''); } catch (err) { const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } } else { // Lightning mode if (!activeMintUrl) return; // Step 1: Check if we have a pending Lightning address awaiting amount if (pendingLightningAddress) { // Step 2: User entered amount, now resolve address and pay if (!lightningAddressAmount) return; try { const amount = parseInt(lightningAddressAmount); if (isNaN(amount) || amount <= 0) { alert('Please enter a valid amount'); return; } console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount); const invoice = await getLightningInvoice({ lightningAddress: pendingLightningAddress, amountSats: amount, }); console.log('🔄 Creating melt quote for invoice:', invoice); const meltQuote = await createMeltQuote(activeMintUrl, invoice); console.log('🔄 Paying melt quote:', meltQuote.quote); await payMeltQuote(activeMintUrl, meltQuote.quote); console.log('✅ Lightning payment sent successfully!'); alert(`Successfully sent ${amount} sats to ${pendingLightningAddress}!`); // Reset state setPendingLightningAddress(null); setLightningAddressInput(''); setLightningAddressAmount(''); // Refresh balances await refreshBalances(); } catch (err) { const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } } else { // Step 1: Check if input is a Lightning address or invoice const input = lightningInvoice.trim() || lightningAddressInput.trim(); if (!input) return; // Check if it's a Lightning address (contains @) if (input.includes('@')) { console.log('📧 Detected Lightning address:', input); setPendingLightningAddress(input); setLightningAddressInput(''); } else { // It's a regular Lightning invoice try { console.log('🔄 Creating melt quote for invoice:', input); const meltQuote = await createMeltQuote(activeMintUrl, input); console.log('🔄 Paying melt quote:', meltQuote.quote); await payMeltQuote(activeMintUrl, meltQuote.quote); console.log('✅ Lightning invoice paid successfully!'); alert('Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.'); setLightningInvoice(''); // Refresh balances to show updated amounts await refreshBalances(); } catch (err) { const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } } } } }; // ============================================================================ // EVENT HANDLERS - Utility // ============================================================================ const handleCopy = async (text: string, type: 'token' | 'invoice') => { try { await navigator.clipboard.writeText(text); if (type === 'token') { setCopiedToken(true); setTimeout(() => setCopiedToken(false), 2000); } else { setCopiedInvoice(text); setTimeout(() => setCopiedInvoice(null), 2000); } } catch (err) { console.error('Failed to copy to clipboard:', err); alert('Failed to copy to clipboard'); } }; // ============================================================================ // EVENT HANDLERS - Mint Management // ============================================================================ const handleAddMint = async () => { if (!mintUrl.trim()) return; try { // Normalize URL - add https:// if not present let normalizedUrl = mintUrl.trim(); if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) { normalizedUrl = `https://${normalizedUrl}`; } await addMint(normalizedUrl); setMintUrl(''); // Explicitly refresh mints and balances await refreshMints(); await refreshBalances(); const message = `Mint added successfully: ${normalizedUrl}`; console.log('✅', message); alert('Mint added successfully!'); } catch (err) { const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } }; // ============================================================================ // EVENT HANDLERS - Quote Management // ============================================================================ const handleClaimQuote = async (quoteId: string, mintUrl: string) => { try { console.log('🎯 Attempting to claim quote:', quoteId, 'from mint:', mintUrl); await redeemMintQuote(mintUrl, quoteId); // Remove from pending quotes setPendingQuotes(prev => prev.filter(q => q.quoteId !== quoteId)); // Refresh balances await refreshBalances(); console.log('✅ Quote claimed successfully!'); alert('Tokens claimed successfully! Your balance has been updated.'); } catch (err) { const errorMessage = `Failed to claim tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); alert(errorMessage); } }; // Claim npub.cash quotes const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => { try { console.log('🎯 Claiming npubx.cash quote:', quote); console.log('📋 Quote details:', { quote_id: quote.quoteId, mint_url: quote.mintUrl, amount: quote.amount, state: quote.state, }); // Add mint if not already added const hasMint = mints.some(m => m.url === quote.mintUrl); if (!hasMint) { console.log('➕ Adding mint:', quote.mintUrl); await addMint(quote.mintUrl); } // Use coco-cashu's addMintQuote API instead of calling mint directly console.log('🔄 Adding mint quote to coco-cashu:', quote.quoteId); await addMintQuote(quote.mintUrl, quote.quoteId); console.log('✅ Quote added to coco-cashu successfully'); console.log('💡 Coco will automatically redeem when mint processor runs'); // Trigger the mint processor to check and redeem the quote await checkAndRedeemPendingQuotes(); // Refresh quotes and balances await fetchQuotes(); await refreshBalances(); alert(`Successfully claimed ${quote.amount} sats!`); } catch (err) { console.error('Failed to claim npub.cash quote:', err); alert(`Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`); } }; const handleShowDenominations = async (mintUrl: string) => { try { console.log('🔍 Getting token denominations for mint:', mintUrl); // Get proofs from the wallet for this specific mint const proofs = await getProofs(mintUrl); console.log('💰 Raw proofs for mint:', proofs); if (!proofs || proofs.length === 0) { alert('No tokens found for this mint'); return; } // Group proofs by denomination const denominations: { [key: number]: number } = {}; proofs.forEach((proof: { amount?: number }) => { const amount = proof.amount || 0; denominations[amount] = (denominations[amount] || 0) + 1; }); const totalBalance = Object.entries(denominations) .reduce((sum, [amount, count]) => sum + (parseInt(amount) * count), 0); // Set the breakdown data and show the modal setProofBreakdown({ mintUrl, denominations, totalBalance }); setShowProofBreakdown(true); } catch (err) { console.error('Failed to get denominations:', err); alert('Failed to get token denominations. Check console for details.'); } }; // ============================================================================ // EFFECTS // ============================================================================ // Auto-select active mint when mints or balances change useEffect(() => { if (mints.length > 0 && !activeMintUrl) { // Find mint with highest balance, or first mint if balances are equal const mintWithHighestBalance = mints.reduce((highest, current) => { const currentBalance = balances[current.url] || 0; const highestBalance = balances[highest.url] || 0; return currentBalance > highestBalance ? current : highest; }); handleSetActiveMint(mintWithHighestBalance.url); } }, [mints, activeMintUrl, balances, handleSetActiveMint]); // Load transaction history when wallet is initialized useEffect(() => { if (isInitialized && historyEntries.length === 0) { loadHistory(); } }, [isInitialized, historyEntries.length, loadHistory]); // Generate QR codes for existing pending quotes that don't have them useEffect(() => { const generateMissingQRCodes = async () => { const quotesNeedingQR = pendingQuotes.filter(quote => !quote.qrCodeUrl); if (quotesNeedingQR.length === 0) return; const updatedQuotes = await Promise.all( pendingQuotes.map(async (quote) => { if (!quote.qrCodeUrl) { const qrCodeUrl = await generateQRCodeForQuote(quote.invoice); return { ...quote, qrCodeUrl }; } return quote; }) ); setPendingQuotes(updatedQuotes); }; generateMissingQRCodes(); }, []); // Only run once on mount // ============================================================================ // RENDER - Loading State // ============================================================================ if (isLoading) { return (
Initializing...
); } // ============================================================================ // RENDER - Uninitialized State // ============================================================================ if (!isInitialized) { return ( Cashu Wallet Failed to initialize wallet. Please check the console for errors. ); } // ============================================================================ // RENDER - Main UI // ============================================================================ return (
{/* ======================================================================== SECTION: Balance Display ======================================================================== */} {isInitialized && (
{/* Active Mint Dropdown and Balance */}
Connected Mints {mints.length === 0 && ( No mints connected )} {mints .filter((mint) => mint.url) .map((mint, index) => ( handleSetActiveMint(mint.url)} >
{getCleanMintLabel(mint)}
))}
setMintUrl(e.target.value)} className="h-8" />
{/* Active Mint Balance */} {activeMintUrl && (
)}
{/* npub.cash Lightning Address */} {lightningAddress && (
Your Lightning Address
{lightningAddress}
{unclaimedAmount > 0 && (
{unclaimedAmount} sats unclaimed
)}
)}
)} {/* ======================================================================== SECTION: Error Display ======================================================================== */} {(error || npubCashError) && (
{error || npubCashError} {npubCashError && npubCashError.includes('Authorization') && (
Try refreshing the page or check your Nostr extension
)}
{npubCashError && ( )}
)} {/* ======================================================================== SECTION: Receive & Send Cards ======================================================================== */}
{/* Receive Card */}
Receive
{receiveMode === 'tokens' ? 'Enter Cashu token to redeem' : 'Deposit funds with Lightning' }
{receiveMode === 'tokens' ? (
setTokenInput(e.target.value)} className="flex-1" />
) : ( <> {!activeMintUrl && (
Select a mint from "Connected Mints" to create Lightning invoice
)}
setQuoteAmount(e.target.value)} />
)}
{/* Send Card */}
Send
{sendMode === 'tokens' ? 'Generate Cashu token to send' : pendingLightningAddress ? 'Enter the amount to send' : 'Pay Lightning invoices or addresses from balance' }
{sendMode === 'tokens' ? ( <> {!activeMintUrl && (
Select a mint from "Connected Mints" to send tokens
)}
setSendAmount(e.target.value)} />
) : ( <> {!activeMintUrl && (
Select a mint from "Connected Mints" to pay Lightning invoices
)} {pendingLightningAddress ? ( // Step 2: Show amount input for Lightning address
Sending to: {pendingLightningAddress}
Enter amount to send
setLightningAddressAmount(e.target.value)} autoFocus />
) : ( // Step 1: Show invoice/address input
{ const value = e.target.value; if (value.includes('@')) { setLightningAddressInput(value); setLightningInvoice(''); } else { setLightningInvoice(value); setLightningAddressInput(''); } }} className="flex-1" />
)} )}
{/* ======================================================================== SECTION: Sent Token Display ======================================================================== */} {sentToken && ( Token Created Successfully Share this token with the recipient to send them your sats
{sentToken.length > 20 ? `${sentToken.substring(0, 20)}...` : sentToken}
)} {/* ======================================================================== SECTION: Pending Lightning Payments ======================================================================== */} {pendingQuotes.length > 0 && ( Pending Lightning Payments Click "Check Payment" after paying the Lightning invoice
{pendingQuotes.map((quote) => (
{quote.amount} sats
{new URL(quote.mintUrl).hostname}
Created: {new Date(quote.timestamp).toLocaleTimeString()}
{/* QR Code */} {quote.qrCodeUrl && (
Lightning Invoice QR Code
)}
{quote.invoice.length > 20 ? `${quote.invoice.substring(0, 20)}...` : quote.invoice}
))}
)} {/* ======================================================================== SECTION: npub.cash Received Payments ======================================================================== */} {quotes.length > 0 && (
Received Payments (npub.cash)
Lightning payments received to your npub.cash address
{quotes && quotes.length > 0 ? quotes.map(quote => { const isExpired = quote.expiresAt < Date.now() / 1000; const isPaid = quote.state === 'PAID'; return (

{quote.amount} sats

{quote.paidAt ? new Date(quote.paidAt * 1000).toLocaleString() : 'Unknown date'}

{quote.state} {isPaid && !isExpired && ( )}

Mint: {quote.mintUrl}

{isExpired && (

Expired: {new Date(quote.expiresAt * 1000).toLocaleString()}

)} {quote.locked && ( 🔒 Locked to your pubkey )}
); }) : null}
)} {/* ======================================================================== SECTION: Transaction History ======================================================================== */}
Transaction History
{historyEntries.length > 3 && ( )}
View your recent transactions
{isLoadingHistory ? (
Loading history...
) : historyEntries.length === 0 ? (
No transaction history yet
) : (
{(isHistoryExpanded ? historyEntries : historyEntries.slice(0, 3)).map((entry) => (
{getHistoryIcon(entry.type)}
{getHistoryLabel(entry.type)} {entry.state && ( {entry.state} )}
{new URL(entry.mintUrl).hostname}
{new Date(entry.createdAt).toLocaleString()}
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'} {entry.amount.toLocaleString()} {entry.unit}
))}
)}
{/* ======================================================================== SECTION: Proof Breakdown Modal ======================================================================== */} {showProofBreakdown && proofBreakdown && (
Token Breakdown {new URL(proofBreakdown.mintUrl).hostname}
{formatAmount(proofBreakdown.totalBalance)}
Total Balance
Denominations:
{Object.entries(proofBreakdown.denominations) .sort(([a], [b]) => parseInt(a) - parseInt(b)) .map(([amount, count]) => (
{parseInt(amount).toLocaleString()} sats
× {count}
))}
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
)}
); }