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 } 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 { 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 } 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 } = useQRCode(); const { copy: copyToClipboard } = useCopyToClipboard(); // 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); // 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]); // ============================================================================ // EFFECTS - Cleanup // ============================================================================ useEffect(() => { return () => { if (mintQuoteUnsubscribeRef.current) { mintQuoteUnsubscribeRef.current(); mintQuoteUnsubscribeRef.current = null; } }; }, [mintQuoteUnsubscribeRef]); // ============================================================================ // 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} 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={() => {}} />
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" />
); }