import { useState, useEffect, useRef } from 'react'; import { nip19 } from 'nostr-tools'; import { useCashu } from '@/hooks/cashu/useCashu'; import { useLightningAddress } from '@/hooks/useLightningAddress'; import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useToast } from '@/hooks/useToast'; import { useQRCode, type QRScanResult } from '@/hooks/useQRCode'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; import { useMintManager } from '@/hooks/cashu/useMintManager'; import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions'; import { useHistoryManager } from '@/hooks/cashu/useHistoryManager'; import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance'; import { useNsecAccess } from '@/hooks/useNsecAccess'; import { decodeBolt11Amount } from '@/lib/bolt11Decoder'; import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; import { TransactionCard } from './PaymentCard'; import { WalletModals } from './WalletModals'; import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; import { TransactionHistory } from './TransactionHistory'; import { ScrollArea } from '@/components/ui/scroll-area'; import { ChevronUp, Send, Download, ScanLine } from 'lucide-react'; import { Button } from '@/components/ui/button'; export function CashuWallet() { // ============================================================================ // CORE HOOKS // ============================================================================ const { coco, repositories, isInitialized, isLoading, error, balances, mints, mnemonic, getEncodedToken, refreshMints, } = useCashu(); const { user } = useCurrentUser(); const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); const { toast } = useToast(); const { generateQRCode, isScanning, startScanning, stopScanning, error: qrError, classifyQRCode, setModalOpen } = useQRCode(); const { copy: copyToClipboard } = useCopyToClipboard(); const { hasNsecAccess } = useNsecAccess(); // Bitcoin hooks - including balance and transaction history const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress); // Bitcoin operations hook const { utxos, isConsolidating, bitcoinMaxAmount, fetchBitcoinUtxos, handleSendMax, handleBitcoinSend, handleBitcoinReceive, handleConsolidateUtxos, } = useBitcoinOperations(bitcoinAddress); const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, syncQuotesWithWallet, isLoggedIn: isNpubCashLoggedIn, isLoading: isNpubCashLoading, error: npubCashError, clearError: clearNpubCashError } = useNpubCash(); // Wrapper to handle return type mismatch const handleSetNpubCashMint = (mintUrl: string): Promise => { return setNpubCashMint(mintUrl); }; // ============================================================================ // DOMAIN HOOKS // ============================================================================ const { activeMintUrl, setActiveMintUrl, mintUrl, setMintUrl, mintDropdownOpen, setMintDropdownOpen, handleAddMint, handleRemoveMintClick, handleConfirmRemoveMint, mintToRemove, showRemoveMintModal, setShowRemoveMintModal, getCleanMintLabel, handleShowDenominations, } = useMintManager({ coco, mints, repositories, isNpubCashLoggedIn, setNpubCashMint: handleSetNpubCashMint, refreshMints, }); // Wrapper for setActiveMintUrl to handle the async nature const handleSetActiveMintSync = (url: string | null) => { setActiveMintUrl(url); }; const { tokenInput, setTokenInput, quoteAmount, setQuoteAmount, sendAmount, setSendAmount, lightningInvoice, setLightningInvoice, lightningAddressInput, setLightningAddressInput, lightningAddressAmount, setLightningAddressAmount, pendingLightningAddress, setPendingLightningAddress, decodedInvoiceAmount, setDecodedInvoiceAmount, pendingInvoice, setPendingInvoice, sentToken, setSentToken, sentTokenQRCode, showInvoiceModal, setShowInvoiceModal, currentInvoice, handleReceive, handleSend, handleConfirmInvoicePayment, handleRestoreFromSeedPhrase, isRestoring, mintQuoteUnsubscribeRef, } = useWalletTransactions({ coco, activeMintUrl, generateQRCode, getEncodedToken, getLightningInvoice, }); const { historyEntries, isLoadingHistory, } = useHistoryManager({ coco, isInitialized, }); // Bitcoin transaction history const { data: bitcoinTransactions = [], isLoading: isBitcoinTransactionsLoading } = useBitcoinTransactionHistory(bitcoinAddress); // ============================================================================ // UI STATE // ============================================================================ const [showSats, setShowSats] = useState(true); const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning'); const [showProofBreakdown, setShowProofBreakdown] = useState(false); const [proofBreakdown, setProofBreakdown] = useState<{ mintUrl: string; denominations: { [key: number]: number }; totalBalance: number; } | null>(null); const [showLightningAddressQR, setShowLightningAddressQR] = useState(false); const [lightningAddressQRCode, setLightningAddressQRCode] = useState(''); const [npubCashUserInfo, setNpubCashUserInfo] = useState(null); const [showSendModal, setShowSendModal] = useState(false); const [showReceiveModal, setShowReceiveModal] = useState(false); const [showHistoryModal, setShowHistoryModal] = useState(false); const [showQRScanner, setShowQRScanner] = useState(false); // Bitcoin state const [bitcoinAmount, setBitcoinAmount] = useState(''); const [bitcoinRecipient, setBitcoinRecipient] = useState(''); const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState(null); const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false); const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState(''); const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false); const [showConsolidationModal, setShowConsolidationModal] = useState(false); // UTXO state const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false); // Handle drawer close with state reset const handleSendDrawerClose = (open: boolean) => { setShowSendModal(open); if (!open) { // Reset all send-related state when drawer closes setSendAmount(''); setLightningInvoice(''); setLightningAddressInput(''); setLightningAddressAmount(''); setPendingLightningAddress(null); setDecodedInvoiceAmount(null); setPendingInvoice(null); // Reset Bitcoin state setBitcoinAmount(''); setBitcoinRecipient(''); setPendingBitcoinRecipient(null); } }; const handleReceiveDrawerClose = (open: boolean) => { setShowReceiveModal(open); if (!open) { // Reset all receive-related state when drawer closes setTokenInput(''); setQuoteAmount(''); } }; // Ref to track if we've fetched npub.cash user info const hasCheckedNpubCashRef = useRef(false); // ============================================================================ // COMPUTED VALUES // ============================================================================ const totalBalance: number = mode === 'bitcoin' ? (bitcoinBalanceData?.balance || 0) : (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); // ============================================================================ // EFFECTS - Error Handling // ============================================================================ useEffect(() => { if (error) { toast({ variant: "destructive", title: "Wallet Error", description: error.message, }); } }, [error, toast]); useEffect(() => { if (npubCashError) { toast({ variant: "destructive", title: "Npub.cash Error", description: npubCashError, }); clearNpubCashError(); } }, [npubCashError, clearNpubCashError, toast]); // ============================================================================ // EFFECTS - NPub.cash Integration // ============================================================================ useEffect(() => { if (!isNpubCashLoggedIn) { hasCheckedNpubCashRef.current = false; setNpubCashUserInfo(null); return; } if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return; const fetchUserInfo = async () => { hasCheckedNpubCashRef.current = true; const userInfo = await getNpubCashUserInfo(); if (!userInfo) return; setNpubCashUserInfo(userInfo); // Sync mint from npub.cash if different from active mint if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) { const mintExists = mints.some(m => m.url === userInfo.mint_url); if (!mintExists && coco) { try { await coco.mint.addMint(userInfo.mint_url); setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500); } catch { // Silent failure - user can manually add mint if needed } } else if (mintExists) { setActiveMintUrl(userInfo.mint_url, false); } } }; fetchUserInfo(); }, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]); // Set up automatic quote sync subscription when logged into npub.cash useEffect(() => { if (!isNpubCashLoggedIn || !coco || !isInitialized) return; let unsubscribe: (() => void) | null = null; const setupSync = async () => { unsubscribe = await syncQuotesWithWallet(coco); }; setupSync(); return () => { if (unsubscribe) { unsubscribe(); } }; }, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]); // ============================================================================ // EFFECTS - UTXO Fetching // ============================================================================ useEffect(() => { if (mode === 'bitcoin' && bitcoinAddress) { fetchBitcoinUtxos(); } }, [mode, bitcoinAddress, fetchBitcoinUtxos]); // Start/stop QR scanner when modal opens/closes useEffect(() => { if (showQRScanner) { setModalOpen?.(true); startScanning(handleQRScanResult); } else { setModalOpen?.(false); stopScanning(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [showQRScanner, startScanning, stopScanning, setModalOpen]); // ============================================================================ // EFFECTS - Cleanup // ============================================================================ useEffect(() => { return () => { if (mintQuoteUnsubscribeRef.current) { mintQuoteUnsubscribeRef.current(); mintQuoteUnsubscribeRef.current = null; } }; }, [mintQuoteUnsubscribeRef]); // Handle QR scanner results const handleQRScanResult = async (result: QRScanResult) => { try { await stopScanning(); setShowQRScanner(false); switch (result.type) { case 'lightning_invoice': { setMode('lightning'); setLightningInvoice(result.value); setPendingInvoice(result.value); // Decode invoice amount const amount = decodeBolt11Amount(result.value); setDecodedInvoiceAmount(amount); setShowSendModal(true); toast({ title: "Lightning Invoice Scanned", description: amount ? `${amount} sats` : "Invoice ready to pay", }); break; } case 'lightning_address': { setMode('lightning'); setLightningAddressInput(result.value); setPendingLightningAddress(result.value); setShowSendModal(true); toast({ title: "Lightning Address Scanned", description: "Enter amount to send", }); break; } case 'cashu_token': { setMode('tokens'); setTokenInput(result.value); setShowReceiveModal(true); toast({ title: "Cashu Token Scanned", description: "Token ready to redeem", }); break; } case 'bitcoin_address': { setMode('bitcoin'); setBitcoinRecipient(result.value); setPendingBitcoinRecipient(result.value); setShowSendModal(true); toast({ title: "Bitcoin Address Scanned", description: "Enter amount to send", }); break; } case 'npub': { // Convert npub to bitcoin address try { const decoded = nip19.decode(result.value); if (decoded.type === 'npub') { const address = nostrPubkeyToBitcoinAddress(decoded.data); setMode('bitcoin'); setBitcoinRecipient(address); setPendingBitcoinRecipient(address); setShowSendModal(true); toast({ title: "Nostr npub Scanned", description: "Enter amount to send", }); } } catch (err) { toast({ variant: "destructive", title: "Invalid npub", description: "Could not decode npub", }); } break; } default: { toast({ variant: "destructive", title: "Unknown QR Code", description: result.value, }); } } } catch (err) { console.error('Error handling QR scan:', err); } }; // Handle paste from clipboard const handlePasteQRCode = async () => { try { const text = await navigator.clipboard.readText(); if (!text || !text.trim()) { toast({ variant: "destructive", title: "Clipboard Empty", description: "No text found in clipboard", }); return; } const result = classifyQRCode(text.trim()); await handleQRScanResult(result); } catch (err) { toast({ variant: "destructive", title: "Paste Failed", description: "Could not read from clipboard", }); console.error('Error pasting from clipboard:', err); } }; // ============================================================================ // RENDER // ============================================================================ return ( <>
{/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */} { setLightningAddressQRCode(qr); setShowLightningAddressQR(true); }} onShowBitcoinAddressQR={(qr) => { setBitcoinAddressQRCode(qr); setShowBitcoinAddressQR(true); }} onShowSeedPhraseInfo={() => setShowSeedPhraseInfo(true)} generateQRCode={generateQRCode} // MintSelector props activeMintUrl={activeMintUrl} setActiveMintUrl={handleSetActiveMintSync} mints={mints} mintUrl={mintUrl} setMintUrl={setMintUrl} onAddMint={handleAddMint} onRemoveMint={handleRemoveMintClick} onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)} getCleanMintLabel={getCleanMintLabel} dropdownOpen={mintDropdownOpen} setDropdownOpen={setMintDropdownOpen} // UTXOSelector props utxos={utxos} utxoDropdownOpen={utxoDropdownOpen} setUtxoDropdownOpen={setUtxoDropdownOpen} onShowConsolidationModal={() => setShowConsolidationModal(true)} isConsolidating={isConsolidating} /> {/* Action Buttons and Transaction History Container */}
{/* Action Buttons */}
{/* Transaction History Button */}
{/* Modals */} <> {/* Bottom Drawer Modals */} Send
{}} quoteAmount="" setQuoteAmount={() => {}} activeMintUrl={activeMintUrl} onSend={() => { if (mode === 'bitcoin') { handleBitcoinSend( bitcoinAmount, pendingBitcoinRecipient, setBitcoinAmount, setBitcoinRecipient, setPendingBitcoinRecipient, setShowSendModal ); } else { const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== ''; handleSend(); if (mode === 'tokens' || wasPendingBefore) { setShowSendModal(false); } } }} onReceive={() => {}} onConfirmInvoice={() => { handleConfirmInvoicePayment(); setShowSendModal(false); }} isResolvingAddress={isResolvingAddress} isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading} // Bitcoin props bitcoinAddress={bitcoinAddress || ''} bitcoinAmount={bitcoinAmount} setBitcoinAmount={setBitcoinAmount} bitcoinRecipient={bitcoinRecipient} setBitcoinRecipient={setBitcoinRecipient} pendingBitcoinRecipient={pendingBitcoinRecipient} setPendingBitcoinRecipient={setPendingBitcoinRecipient} hasNsecAccess={hasNsecAccess} bitcoinMaxAmount={bitcoinMaxAmount} onSendMax={() => handleSendMax(setBitcoinAmount)} />
Receive
{}} lightningInvoice="" setLightningInvoice={() => {}} lightningAddressInput="" setLightningAddressInput={() => {}} lightningAddressAmount="" setLightningAddressAmount={() => {}} pendingLightningAddress={null} setPendingLightningAddress={() => {}} decodedInvoiceAmount={null} setDecodedInvoiceAmount={() => {}} pendingInvoice={null} setPendingInvoice={() => {}} tokenInput={tokenInput} setTokenInput={setTokenInput} quoteAmount={quoteAmount} setQuoteAmount={setQuoteAmount} activeMintUrl={activeMintUrl} onSend={() => {}} onReceive={() => { if (mode === 'bitcoin') { handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR); setShowReceiveModal(false); } else { handleReceive(); setShowReceiveModal(false); } }} isResolvingAddress={false} isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading} // Bitcoin props bitcoinAddress={bitcoinAddress || ''} bitcoinAmount="" setBitcoinAmount={() => {}} bitcoinRecipient="" setBitcoinRecipient={() => {}} pendingBitcoinRecipient={null} setPendingBitcoinRecipient={() => {}} hasNsecAccess={hasNsecAccess} />
Transactions {/* Bitcoin Address QR Modal */} setShowBitcoinAddressQR(false)} title="Bitcoin Address" description="Scan this QR code to send Bitcoin to your address" qrCodeUrl={bitcoinAddressQRCode} content={bitcoinAddress || ''} icon="qr" />
); }