From 28e50a9d7ae36dad77daad55e0242f18ea22ba39 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sun, 2 Nov 2025 18:31:57 -0800 Subject: [PATCH] separate cashu and bitcoin wallets --- src/AppRouter.tsx | 4 +- src/components/wallet/BitcoinWallet.tsx | 412 ++++++++++++++++++ src/components/wallet/CashuWallet.tsx | 483 ++++++++-------------- src/components/wallet/QRScanner.tsx | 112 +++++ src/components/wallet/QRScannerModal.tsx | 63 --- src/components/wallet/WalletContainer.tsx | 232 +++++++++++ src/hooks/cashu/useCashu.ts | 4 +- src/hooks/cashu/useMintManager.ts | 30 +- src/hooks/cashu/useTokenOperations.ts | 16 +- src/hooks/useNpubCash.ts | 40 +- 10 files changed, 1003 insertions(+), 393 deletions(-) create mode 100644 src/components/wallet/BitcoinWallet.tsx create mode 100644 src/components/wallet/QRScanner.tsx delete mode 100644 src/components/wallet/QRScannerModal.tsx create mode 100644 src/components/wallet/WalletContainer.tsx diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index e6ad301..21a061a 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -4,7 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop"; import Index from "./pages/Index"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; -import { CashuWallet } from "./components/wallet/CashuWallet"; +import { WalletContainer } from "./components/wallet/WalletContainer"; export function AppRouter() { return ( @@ -12,7 +12,7 @@ export function AppRouter() { } /> - } /> + } /> {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} } /> {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} diff --git a/src/components/wallet/BitcoinWallet.tsx b/src/components/wallet/BitcoinWallet.tsx new file mode 100644 index 0000000..5625ba3 --- /dev/null +++ b/src/components/wallet/BitcoinWallet.tsx @@ -0,0 +1,412 @@ +import { useState, useEffect, useRef } from 'react'; +import { nip19 } from 'nostr-tools'; +import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance'; +import { useNsecAccess } from '@/hooks/useNsecAccess'; +import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; +import { QRModal } from '@/components/ui/qr-modal'; +import { TransactionCard } from './PaymentCard'; +import { ConsolidationModal } from './ConsolidationModal'; +import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; +import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; +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'; +import type { QRScanResult } from '@/hooks/useQRCode'; + +interface BitcoinWalletProps { + toast: ReturnType['toast']; + generateQRCode: (text: string) => Promise; + copyToClipboard: (text: string) => Promise; + user?: { pubkey: string }; + onRequestQRScanner: () => void; + onQRResult?: (result: QRScanResult) => void; + onWalletHeaderPropsChange?: (props: any) => void; +} + +export function BitcoinWallet({ + toast, + generateQRCode, + copyToClipboard, + user, + onRequestQRScanner, + onQRResult, + onWalletHeaderPropsChange, +}: BitcoinWalletProps) { + const { hasNsecAccess } = useNsecAccess(); + const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; + const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress); + + const { + utxos, + isConsolidating, + bitcoinMaxAmount, + fetchBitcoinUtxos, + handleSendMax, + handleBitcoinSend, + handleBitcoinReceive, + handleConsolidateUtxos, + } = useBitcoinOperations(bitcoinAddress); + + const { + data: bitcoinTransactions = [], + isLoading: isBitcoinTransactionsLoading + } = useBitcoinTransactionHistory(bitcoinAddress); + + // 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 [showConsolidationModal, setShowConsolidationModal] = useState(false); + const [showSendModal, setShowSendModal] = useState(false); + const [showReceiveModal, setShowReceiveModal] = useState(false); + const [showHistoryModal, setShowHistoryModal] = useState(false); + + // UTXO state + const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false); + + // Fetch UTXOs when component mounts + useEffect(() => { + if (bitcoinAddress) { + fetchBitcoinUtxos(); + } + }, [bitcoinAddress, fetchBitcoinUtxos]); + + // Handle drawer close with state reset + const handleSendDrawerClose = (open: boolean) => { + setShowSendModal(open); + if (!open) { + setBitcoinAmount(''); + setBitcoinRecipient(''); + setPendingBitcoinRecipient(null); + } + }; + + const handleReceiveDrawerClose = (open: boolean) => { + setShowReceiveModal(open); + }; + + // Handle focus management when drawers open + useEffect(() => { + if (showSendModal || showReceiveModal || showHistoryModal) { + const activeElement = document.activeElement as HTMLElement; + if (activeElement && activeElement.blur) { + activeElement.blur(); + } + } + }, [showSendModal, showReceiveModal, showHistoryModal]); + + // Handle QR scan results (called from parent WalletContainer) + useEffect(() => { + if (!onQRResult) return; + + const handleQRResult = (result: QRScanResult) => { + if (result.type === 'bitcoin_address') { + setBitcoinRecipient(result.value); + setPendingBitcoinRecipient(result.value); + setShowSendModal(true); + toast({ + title: "Bitcoin Address Scanned", + description: "Enter amount to send", + }); + } else if (result.type === 'npub') { + try { + const decoded = nip19.decode(result.value); + if (decoded.type === 'npub') { + const address = nostrPubkeyToBitcoinAddress(decoded.data); + 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", + }); + } + } + }; + + // Store handler for parent to call + (window as any).__bitcoinWalletQRHandler = handleQRResult; + return () => { + delete (window as any).__bitcoinWalletQRHandler; + }; + }, [onQRResult, toast]); + + const totalBalance = bitcoinBalanceData?.balance || 0; + + // Expose WalletHeader props to parent WalletContainer + // Use ref to track previous values and prevent infinite loops + const prevPropsRef = useRef<{ + utxosLength?: number; + utxoDropdownOpen?: boolean; + isConsolidating?: boolean; + }>({}); + + useEffect(() => { + if (!onWalletHeaderPropsChange) return; + + // Check if values actually changed + const currentProps = { + utxosLength: utxos?.length, + utxoDropdownOpen, + isConsolidating, + }; + + const prevProps = prevPropsRef.current; + const hasChanged = + prevProps.utxosLength !== currentProps.utxosLength || + prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen || + prevProps.isConsolidating !== currentProps.isConsolidating; + + if (!hasChanged && Object.keys(prevProps).length > 0) { + // Values haven't changed, skip update + return; + } + + // Update ref + prevPropsRef.current = currentProps; + + // Send updated props + onWalletHeaderPropsChange({ + utxos, + utxoDropdownOpen, + setUtxoDropdownOpen, + onShowConsolidationModal: () => setShowConsolidationModal(true), + isConsolidating, + onShowBitcoinAddressQR: async (qr: string) => { + setBitcoinAddressQRCode(qr); + setShowBitcoinAddressQR(true); + }, + }); + }, [ + onWalletHeaderPropsChange, + utxos?.length, + utxoDropdownOpen, + isConsolidating, + // Note: Functions (setUtxoDropdownOpen, etc.) are not in deps + // because they're stable setters or we accept they may change + // The ref-based change detection ensures we only update when primitives change + ]); + + return ( + <> + {/* Action Buttons and Transaction History Container */} +
+ {/* Action Buttons */} +
+ + + + + +
+ + {/* Transaction History Button */} +
+ +
+
+ + {/* Modals */} + <> + {/* Consolidation Modal */} + setShowConsolidationModal(false)} + utxos={utxos} + onConfirm={handleConsolidateUtxos} + isConsolidating={isConsolidating} + /> + + {/* 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" + /> + + {/* Bottom Drawer Modals */} + + + + Send + + + Send Bitcoin on-chain + + + +
+ {}} + lightningInvoice="" + setLightningInvoice={() => {}} + lightningAddressInput="" + setLightningAddressInput={() => {}} + lightningAddressAmount="" + setLightningAddressAmount={() => {}} + pendingLightningAddress={null} + setPendingLightningAddress={() => {}} + decodedInvoiceAmount={null} + setDecodedInvoiceAmount={() => {}} + pendingInvoice={null} + setPendingInvoice={() => {}} + tokenInput="" + setTokenInput={() => {}} + quoteAmount="" + setQuoteAmount={() => {}} + activeMintUrl={null} + onSend={() => { + handleBitcoinSend( + bitcoinAmount, + pendingBitcoinRecipient, + setBitcoinAmount, + setBitcoinRecipient, + setPendingBitcoinRecipient, + setShowSendModal + ); + }} + onReceive={() => {}} + isResolvingAddress={false} + isLoading={isBitcoinBalanceLoading} + bitcoinAddress={bitcoinAddress || ''} + bitcoinAmount={bitcoinAmount} + setBitcoinAmount={setBitcoinAmount} + bitcoinRecipient={bitcoinRecipient} + setBitcoinRecipient={setBitcoinRecipient} + pendingBitcoinRecipient={pendingBitcoinRecipient} + setPendingBitcoinRecipient={setPendingBitcoinRecipient} + hasNsecAccess={hasNsecAccess} + bitcoinMaxAmount={bitcoinMaxAmount} + onSendMax={() => handleSendMax(setBitcoinAmount)} + /> +
+
+
+ + + + + Receive + + + Receive Bitcoin on-chain + + + +
+ {}} + lightningInvoice="" + setLightningInvoice={() => {}} + lightningAddressInput="" + setLightningAddressInput={() => {}} + lightningAddressAmount="" + setLightningAddressAmount={() => {}} + pendingLightningAddress={null} + setPendingLightningAddress={() => {}} + decodedInvoiceAmount={null} + setDecodedInvoiceAmount={() => {}} + pendingInvoice={null} + setPendingInvoice={() => {}} + tokenInput="" + setTokenInput={() => {}} + quoteAmount="" + setQuoteAmount={() => {}} + activeMintUrl={null} + onSend={() => {}} + onReceive={() => { + handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR); + setShowReceiveModal(false); + }} + isResolvingAddress={false} + isLoading={isBitcoinBalanceLoading} + bitcoinAddress={bitcoinAddress || ''} + bitcoinAmount="" + setBitcoinAmount={() => {}} + bitcoinRecipient="" + setBitcoinRecipient={() => {}} + pendingBitcoinRecipient={null} + setPendingBitcoinRecipient={() => {}} + hasNsecAccess={hasNsecAccess} + /> +
+
+
+ + + + + Transactions + + + View your Bitcoin transaction history + + + + + + + + + + + ); +} + + diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index 96a7c0f..15b19ed 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -3,27 +3,18 @@ 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 type { QRScanResult } from '@/hooks/useQRCode'; import { useMintManager } from '@/hooks/cashu/useMintManager'; import { useTokenOperations } from '@/hooks/cashu/useTokenOperations'; import { useLightningOperations } from '@/hooks/cashu/useLightningOperations'; import { useReverseSwapOperations } from '@/hooks/cashu/useReverseSwapOperations'; import { useSeedPhraseRestore } from '@/hooks/cashu/useSeedPhraseRestore'; 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 { ProofBreakdownModal } from './ProofBreakdownModal'; import { RemoveMintModal } from './RemoveMintModal'; -import { ConsolidationModal } from './ConsolidationModal'; -import { QRScannerModal } from './QRScannerModal'; import { SeedPhraseModal } from './SeedPhraseModal'; import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; @@ -32,7 +23,25 @@ import { ScrollArea } from '@/components/ui/scroll-area'; import { ChevronUp, Send, Download, ScanLine } from 'lucide-react'; import { Button } from '@/components/ui/button'; -export function CashuWallet() { +interface CashuWalletProps { + mode: 'tokens' | 'lightning'; + toast: ReturnType['toast']; + generateQRCode: (text: string) => Promise; + copyToClipboard: (text: string) => Promise; + user?: { pubkey: string }; + onRequestQRScanner: () => void; + onWalletHeaderPropsChange?: (props: any) => void; +} + +export function CashuWallet({ + mode, + toast, + generateQRCode, + copyToClipboard, + user, + onRequestQRScanner, + onWalletHeaderPropsChange, +}: CashuWalletProps) { // ============================================================================ // CORE HOOKS // ============================================================================ @@ -50,28 +59,7 @@ export function CashuWallet() { 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, @@ -238,18 +226,11 @@ export function CashuWallet() { 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; @@ -262,19 +243,7 @@ export function CashuWallet() { 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 @@ -292,10 +261,6 @@ export function CashuWallet() { // Reset reverse swap state setPendingBitcoinSwapAddress(null); setBitcoinSwapAmount(''); - // Reset Bitcoin state - setBitcoinAmount(''); - setBitcoinRecipient(''); - setPendingBitcoinRecipient(null); } }; @@ -315,9 +280,7 @@ export function CashuWallet() { // COMPUTED VALUES // ============================================================================ - const totalBalance: number = mode === 'bitcoin' - ? (bitcoinBalanceData?.balance || 0) - : (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); + const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); // ============================================================================ // EFFECTS - Error Handling @@ -371,7 +334,20 @@ export function CashuWallet() { if (!mintExists && coco) { try { - await coco.mint.addMint(userInfo.mint_url); + // Check if mint exists (known) by checking all mints + const allMints = await coco.mint.getAllMints(); + const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mint_url.toLowerCase()); + + if (isKnown) { + // Mint exists but may not be trusted, ensure it's trusted + const isTrusted = await coco.mint.isTrustedMint(userInfo.mint_url); + if (!isTrusted) { + await coco.mint.trustMint(userInfo.mint_url); + } + } else { + // Add mint from npub.cash and automatically trust it + await coco.mint.addMint(userInfo.mint_url, { trusted: true }); + } setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500); } catch { // Silent failure - user can manually add mint if needed @@ -404,27 +380,6 @@ export function CashuWallet() { }; }, [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]); // Handle focus management when drawers open to prevent aria-hidden warnings useEffect(() => { @@ -450,170 +405,139 @@ export function CashuWallet() { }; }, [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()) { + // Handle QR scan results (called from parent WalletContainer) + const handleQRResult = (result: QRScanResult) => { + switch (result.type) { + case 'lightning_invoice': { + setLightningInvoice(result.value); + setPendingInvoice(result.value); + // Decode invoice amount + const amount = decodeBolt11Amount(result.value); + setDecodedInvoiceAmount(amount); + setShowSendModal(true); toast({ - variant: "destructive", - title: "Clipboard Empty", - description: "No text found in clipboard", + title: "Lightning Invoice Scanned", + description: amount ? `${amount} sats` : "Invoice ready to pay", }); - return; + break; + } + case 'lightning_address': { + setLightningAddressInput(result.value); + setPendingLightningAddress(result.value); + setShowSendModal(true); + toast({ + title: "Lightning Address Scanned", + description: "Enter amount to send", + }); + break; + } + case 'cashu_token': { + setTokenInput(result.value); + setShowReceiveModal(true); + toast({ + title: "Cashu Token Scanned", + description: "Token ready to redeem", + }); + break; + } + default: { + // Bitcoin addresses and npubs are handled by BitcoinWallet + break; } - - 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); } }; + // Expose handler to parent via window (temporary, will be improved) + useEffect(() => { + (window as any).__cashuWalletQRHandler = handleQRResult; + return () => { + delete (window as any).__cashuWalletQRHandler; + }; + }, [mode, setLightningInvoice, setPendingInvoice, setDecodedInvoiceAmount, setShowSendModal, setLightningAddressInput, setPendingLightningAddress, setTokenInput, setShowReceiveModal, toast]); // Re-setup when mode changes + // ============================================================================ // RENDER // ============================================================================ + // Expose WalletHeader props to parent WalletContainer + // Use ref to track previous values and prevent infinite loops + const prevPropsRef = useRef<{ + activeMintUrl?: string | null; + mintsLength?: number; + firstMintUrl?: string; + mintUrl?: string; + mintDropdownOpen?: boolean; + npubCashUsername?: string; + }>({}); + + useEffect(() => { + if (!onWalletHeaderPropsChange) return; + + const npubCashUsername = user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined; + + // Check if values actually changed + const currentProps = { + activeMintUrl, + mintsLength: mints?.length, + firstMintUrl: mints?.[0]?.url, + mintUrl, + mintDropdownOpen, + npubCashUsername, + }; + + const prevProps = prevPropsRef.current; + const hasChanged = + prevProps.activeMintUrl !== currentProps.activeMintUrl || + prevProps.mintsLength !== currentProps.mintsLength || + prevProps.firstMintUrl !== currentProps.firstMintUrl || + prevProps.mintUrl !== currentProps.mintUrl || + prevProps.mintDropdownOpen !== currentProps.mintDropdownOpen || + prevProps.npubCashUsername !== currentProps.npubCashUsername; + + if (!hasChanged && Object.keys(prevProps).length > 0) { + // Values haven't changed, skip update + return; + } + + // Update ref + prevPropsRef.current = currentProps; + + // Send updated props + onWalletHeaderPropsChange({ + activeMintUrl, + setActiveMintUrl: handleSetActiveMintSync, + mints, + mintUrl, + setMintUrl, + onAddMint: handleAddMint, + onRemoveMint: handleRemoveMintClick, + onShowDenominations: (mintUrl: string) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown), + getCleanMintLabel, + mintDropdownOpen, + setMintDropdownOpen, + npubCashUsername, + onShowLightningAddressQR: async (qr: string) => { + setLightningAddressQRCode(qr); + setShowLightningAddressQR(true); + }, + onShowSeedPhraseInfo: () => setShowSeedPhraseInfo(true), + }); + }, [ + onWalletHeaderPropsChange, + activeMintUrl, + mints?.length, + mints?.[0]?.url, + mintUrl, + mintDropdownOpen, + npubCashUserInfo?.name, + user?.pubkey, + // Note: Functions (handleSetActiveMintSync, handleAddMint, etc.) are not in deps + // because they're stable from hooks or we accept they may change + // The ref-based change detection ensures we only update when primitives change + ]); + 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 */} @@ -633,7 +557,7 @@ export function CashuWallet() {
@@ -917,28 +787,17 @@ export function CashuWallet() { - {/* 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" - /> - ); } diff --git a/src/components/wallet/QRScanner.tsx b/src/components/wallet/QRScanner.tsx new file mode 100644 index 0000000..5d0a4a9 --- /dev/null +++ b/src/components/wallet/QRScanner.tsx @@ -0,0 +1,112 @@ +import { useEffect } from 'react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; +import { useToast } from '@/hooks/useToast'; +import type { QRScanResult } from '@/hooks/useQRCode'; + +interface QRScannerProps { + isOpen: boolean; + onClose: () => Promise; + onResult: (result: QRScanResult) => void; + classifyQRCode: (text: string) => QRScanResult; + startScanning: (onResult: (result: QRScanResult) => void) => Promise; + stopScanning: () => Promise; + setModalOpen?: (isOpen: boolean) => void; + qrError: string | null; +} + +export function QRScanner({ + isOpen, + onClose, + onResult, + classifyQRCode, + startScanning, + stopScanning, + setModalOpen, + qrError, +}: QRScannerProps) { + const { toast } = useToast(); + + // 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()); + onResult(result); + await stopScanning(); + await onClose(); + } catch (err) { + toast({ + variant: "destructive", + title: "Paste Failed", + description: "Could not read from clipboard", + }); + console.error('Error pasting from clipboard:', err); + } + }; + + // Start/stop scanning based on isOpen + useEffect(() => { + if (isOpen) { + setModalOpen?.(true); + startScanning(onResult); + } else { + setModalOpen?.(false); + stopScanning(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen, startScanning, stopScanning, setModalOpen]); + + return ( + { + if (!open) { + await onClose(); + } + }}> + + + Scan QR Code + + + Position the QR code within the camera view to scan + + + + +
+
+ + {qrError && ( +
+ {qrError} +
+ )} +
+ +
+ +
+ +
+ ); +} + diff --git a/src/components/wallet/QRScannerModal.tsx b/src/components/wallet/QRScannerModal.tsx deleted file mode 100644 index 0a99d62..0000000 --- a/src/components/wallet/QRScannerModal.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { Button } from '@/components/ui/button'; -import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; -import * as VisuallyHidden from '@radix-ui/react-visually-hidden'; - -interface QRScannerModalProps { - isOpen: boolean; - onClose: () => Promise; - qrError: string | null; - onPasteQRCode?: () => Promise; -} - -export function QRScannerModal({ - isOpen, - onClose, - qrError, - onPasteQRCode, -}: QRScannerModalProps) { - return ( - { - if (!open) { - await onClose(); - } - }}> - - - Scan QR Code - - - Position the QR code within the camera view to scan - - - - -
-
- - {qrError && ( -
- {qrError} -
- )} -
- -
- -
- -
- ); -} diff --git a/src/components/wallet/WalletContainer.tsx b/src/components/wallet/WalletContainer.tsx new file mode 100644 index 0000000..cf69d59 --- /dev/null +++ b/src/components/wallet/WalletContainer.tsx @@ -0,0 +1,232 @@ +import { useState, useEffect, useRef, useCallback } from 'react'; +import { nip19 } from 'nostr-tools'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useToast } from '@/hooks/useToast'; +import { useQRCode, type QRScanResult } from '@/hooks/useQRCode'; +import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; +import { useCashu } from '@/hooks/cashu/useCashu'; +import { useBitcoinBalance } from '@/hooks/useBitcoinBalance'; +import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin'; +import { WalletHeader } from './WalletHeader'; +import { CashuWallet } from './CashuWallet'; +import { BitcoinWallet } from './BitcoinWallet'; +import { QRScanner } from './QRScanner'; +import { decodeBolt11Amount } from '@/lib/bolt11Decoder'; + +export function WalletContainer() { + const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning'); + const [showSats, setShowSats] = useState(true); + const [showQRScanner, setShowQRScanner] = useState(false); + + // Shared hooks + const { user } = useCurrentUser(); + const { toast } = useToast(); + const { generateQRCode, classifyQRCode, startScanning, stopScanning, setModalOpen, error: qrError } = useQRCode(); + const { copy: copyToClipboard } = useCopyToClipboard(); + + // Get balance data for WalletHeader + const { balances, mnemonic } = useCashu(); + const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; + const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress); + + // Calculate total balance based on mode + const totalBalance: number = mode === 'bitcoin' + ? (bitcoinBalanceData?.balance || 0) + : (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); + + // Refs to call wallet QR handlers + const cashuWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null); + const bitcoinWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null); + + // Handle QR scanner results and route to appropriate wallet + const handleQRScanResult = async (result: QRScanResult) => { + try { + await stopScanning(); + setShowQRScanner(false); + + switch (result.type) { + case 'cashu_token': { + setMode('tokens'); + // Call CashuWallet handler if available + if (cashuWalletQRHandlerRef.current) { + cashuWalletQRHandlerRef.current(result); + } + break; + } + case 'lightning_invoice': { + setMode('lightning'); + // Call CashuWallet handler if available + if (cashuWalletQRHandlerRef.current) { + cashuWalletQRHandlerRef.current(result); + } + break; + } + case 'lightning_address': { + setMode('lightning'); + // Call CashuWallet handler if available + if (cashuWalletQRHandlerRef.current) { + cashuWalletQRHandlerRef.current(result); + } + break; + } + case 'bitcoin_address': { + setMode('bitcoin'); + // Call BitcoinWallet handler if available + if (bitcoinWalletQRHandlerRef.current) { + bitcoinWalletQRHandlerRef.current(result); + } + break; + } + case 'npub': { + setMode('bitcoin'); + // Call BitcoinWallet handler if available + if (bitcoinWalletQRHandlerRef.current) { + bitcoinWalletQRHandlerRef.current(result); + } + break; + } + default: { + toast({ + variant: "destructive", + title: "Unknown QR Code", + description: result.value, + }); + } + } + } catch (err) { + console.error('Error handling QR scan:', err); + } + }; + + // Set up refs to wallet QR handlers + useEffect(() => { + const checkHandlers = () => { + if ((window as any).__cashuWalletQRHandler) { + cashuWalletQRHandlerRef.current = (window as any).__cashuWalletQRHandler; + } + if ((window as any).__bitcoinWalletQRHandler) { + bitcoinWalletQRHandlerRef.current = (window as any).__bitcoinWalletQRHandler; + } + }; + + // Check periodically for handlers (wallets set them up asynchronously) + const interval = setInterval(checkHandlers, 100); + checkHandlers(); // Initial check + + return () => clearInterval(interval); + }, []); + + // WalletHeader props - these will be passed from wallets via callbacks + const [walletHeaderProps, setWalletHeaderProps] = useState<{ + activeMintUrl?: string | null; + mints?: Array<{ url: string; name?: string }>; + mintUrl?: string; + setMintUrl?: (url: string) => void; + onAddMint?: () => void; + onRemoveMint?: (mint: { url: string; name?: string }) => void; + onShowDenominations?: (mintUrl: string) => void; + getCleanMintLabel?: (mint: { name?: string; url: string }) => string; + mintDropdownOpen?: boolean; + setMintDropdownOpen?: (open: boolean) => void; + npubCashUsername?: string; + utxos?: Array; + utxoDropdownOpen?: boolean; + setUtxoDropdownOpen?: (open: boolean) => void; + onShowConsolidationModal?: () => void; + isConsolidating?: boolean; + onShowLightningAddressQR?: (qr: string) => void; + onShowBitcoinAddressQR?: (qr: string) => void; + onShowSeedPhraseInfo?: () => void; + setActiveMintUrl?: (url: string | null) => void; + }>({}); + + // Memoize the callback to prevent infinite loops + const handleWalletHeaderPropsChange = useCallback((props: typeof walletHeaderProps) => { + setWalletHeaderProps(props); + }, []); + + return ( + <> +
+ {/* Wallet Header */} + {})} + onShowBitcoinAddressQR={walletHeaderProps.onShowBitcoinAddressQR || (() => {})} + onShowSeedPhraseInfo={walletHeaderProps.onShowSeedPhraseInfo || (() => {})} + generateQRCode={generateQRCode} + // MintSelector props (only for tokens/lightning) + activeMintUrl={mode !== 'bitcoin' ? (walletHeaderProps.activeMintUrl ?? null) : null} + setActiveMintUrl={walletHeaderProps.setActiveMintUrl || (() => {})} + mints={mode !== 'bitcoin' ? (walletHeaderProps.mints || []) : []} + mintUrl={walletHeaderProps.mintUrl || ''} + setMintUrl={walletHeaderProps.setMintUrl || (() => {})} + onAddMint={walletHeaderProps.onAddMint || (() => {})} + onRemoveMint={walletHeaderProps.onRemoveMint || (() => {})} + onShowDenominations={walletHeaderProps.onShowDenominations || (() => {})} + getCleanMintLabel={walletHeaderProps.getCleanMintLabel || (() => '')} + dropdownOpen={walletHeaderProps.mintDropdownOpen || false} + setDropdownOpen={walletHeaderProps.setMintDropdownOpen || (() => {})} + // UTXOSelector props (only for bitcoin) + utxos={mode === 'bitcoin' ? (walletHeaderProps.utxos || []) : []} + utxoDropdownOpen={walletHeaderProps.utxoDropdownOpen || false} + setUtxoDropdownOpen={walletHeaderProps.setUtxoDropdownOpen || (() => {})} + onShowConsolidationModal={walletHeaderProps.onShowConsolidationModal} + isConsolidating={walletHeaderProps.isConsolidating} + /> + + {/* Render appropriate wallet based on mode */} + {mode === 'tokens' || mode === 'lightning' ? ( + setShowQRScanner(true)} + onWalletHeaderPropsChange={handleWalletHeaderPropsChange} + /> + ) : ( + setShowQRScanner(true)} + onQRResult={(result) => { + if (bitcoinWalletQRHandlerRef.current) { + bitcoinWalletQRHandlerRef.current(result); + } + }} + onWalletHeaderPropsChange={handleWalletHeaderPropsChange} + /> + )} +
+ + {/* Shared QR Scanner */} + { + await stopScanning(); + setShowQRScanner(false); + }} + onResult={handleQRScanResult} + classifyQRCode={classifyQRCode} + startScanning={startScanning} + stopScanning={stopScanning} + setModalOpen={setModalOpen} + qrError={qrError} + /> + + ); +} + diff --git a/src/hooks/cashu/useCashu.ts b/src/hooks/cashu/useCashu.ts index e9a147f..a1c1fcb 100644 --- a/src/hooks/cashu/useCashu.ts +++ b/src/hooks/cashu/useCashu.ts @@ -71,7 +71,8 @@ export function useCashu(): UseCashuReturn { if (!coco) return; try { - const mintList = await coco.mint.getAllMints(); + // Only show trusted mints in the UI + const mintList = await coco.mint.getAllTrustedMints(); setMints(mintList.map((m: Mint) => ({ url: m.mintUrl, name: m.name, @@ -101,7 +102,6 @@ export function useCashu(): UseCashuReturn { try { // Use singleton pattern to prevent multiple initializations if (globalCocoInstance && globalRepositories) { - console.log('Using existing coco instance (singleton)'); cocoRef.current = globalCocoInstance; repositoriesRef.current = globalRepositories; setIsInitialized(true); diff --git a/src/hooks/cashu/useMintManager.ts b/src/hooks/cashu/useMintManager.ts index 0895c95..f0015a7 100644 --- a/src/hooks/cashu/useMintManager.ts +++ b/src/hooks/cashu/useMintManager.ts @@ -1,4 +1,4 @@ -import { useState, useCallback, useEffect } from 'react'; +import { useState, useCallback, useEffect, useRef } from 'react'; import { getCleanMintLabel } from './walletUtils'; import type { Manager, Repositories } from 'coco-cashu-core'; import { toast } from '@/hooks/useToast'; @@ -30,6 +30,7 @@ export function useMintManager({ const [mintUrl, setMintUrl] = useState(''); const [mintToRemove, setMintToRemove] = useState(null); const [showRemoveMintModal, setShowRemoveMintModal] = useState(false); + const isAddingDefaultMintRef = useRef(false); // Set active mint and optionally sync to npub.cash const handleSetActiveMint = useCallback( @@ -75,12 +76,13 @@ export function useMintManager({ return; } - await coco.mint.addMint(normalizedUrl); + // Add mint and automatically trust it + await coco.mint.addMint(normalizedUrl, { trusted: true }); setMintUrl(''); toast({ title: 'Mint Added', - description: 'Mint added successfully!', + description: 'Mint added and trusted successfully!', }); } catch (err) { toast({ @@ -209,14 +211,32 @@ export function useMintManager({ // Select first mint initially - user can change via dropdown // Don't sync to npub.cash on auto-select, only on manual changes handleSetActiveMint(mints[0].url, false); - } else if (mints.length === 0 && !activeMintUrl && coco) { + } else if (mints.length === 0 && !activeMintUrl && coco && !isAddingDefaultMintRef.current) { // Add default mint if no mints exist + // Use ref guard to prevent multiple simultaneous additions + isAddingDefaultMintRef.current = true; const addDefaultMint = async () => { try { - await coco.mint.addMint('https://mint.chorus.community'); + const defaultMintUrl = 'https://mint.chorus.community'; + + // Check if mint already exists (check trusted mints since that's what we display) + const trustedMints = await coco.mint.getAllTrustedMints(); + const mintExists = trustedMints.some((mint: { mintUrl: string }) => + mint.mintUrl.toLowerCase() === defaultMintUrl.toLowerCase() + ); + + if (!mintExists) { + // Add default mint and automatically trust it + await coco.mint.addMint(defaultMintUrl, { trusted: true }); // The mint will be added and refreshMints will be called via event listeners + } } catch (err) { console.error('Failed to add default mint:', err); + } finally { + // Reset the guard after a short delay to allow mints to update + setTimeout(() => { + isAddingDefaultMintRef.current = false; + }, 1000); } }; addDefaultMint(); diff --git a/src/hooks/cashu/useTokenOperations.ts b/src/hooks/cashu/useTokenOperations.ts index bdf4bd2..d93fe55 100644 --- a/src/hooks/cashu/useTokenOperations.ts +++ b/src/hooks/cashu/useTokenOperations.ts @@ -47,8 +47,20 @@ export function useTokenOperations({ try { console.log('Adding unknown mint:', mintUrl); - // Add the mint - await coco.mint.addMint(mintUrl); + // Check if mint exists (known) by checking all mints + const allMints = await coco.mint.getAllMints(); + const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase()); + + if (isKnown) { + // Mint exists but may not be trusted, ensure it's trusted + const isTrusted = await coco.mint.isTrustedMint(mintUrl); + if (!isTrusted) { + await coco.mint.trustMint(mintUrl); + } + } else { + // Add the mint and automatically trust it (user is explicitly receiving from it) + await coco.mint.addMint(mintUrl, { trusted: true }); + } // Retry receiving the token await coco.wallet.receive(tokenInput); diff --git a/src/hooks/useNpubCash.ts b/src/hooks/useNpubCash.ts index ad96a01..97879aa 100644 --- a/src/hooks/useNpubCash.ts +++ b/src/hooks/useNpubCash.ts @@ -138,10 +138,18 @@ export function useNpubCash() { // Process each mint's quotes for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) { try { - // Check if mint exists, add if not - const isKnown = await coco.mint.isKnownMint(mintUrl); + // Check if mint exists (known) by checking all mints + const allMints = await coco.mint.getAllMints(); + const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase()); + if (!isKnown) { - await coco.mint.addMint(mintUrl); + await coco.mint.addMint(mintUrl, { trusted: true }); + } else { + // Mint exists, ensure it's trusted + const isTrusted = await coco.mint.isTrustedMint(mintUrl); + if (!isTrusted) { + await coco.mint.trustMint(mintUrl); + } } // Add quotes to the wallet (matching main.ts format) @@ -203,9 +211,18 @@ export function useNpubCash() { let addedQuotes = 0; for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) { try { - const isKnown = await coco.mint.isKnownMint(mintUrl); + // Check if mint exists (known) by checking all mints + const allMints = await coco.mint.getAllMints(); + const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase()); + if (!isKnown) { - await coco.mint.addMint(mintUrl); + await coco.mint.addMint(mintUrl, { trusted: true }); + } else { + // Mint exists, ensure it's trusted + const isTrusted = await coco.mint.isTrustedMint(mintUrl); + if (!isTrusted) { + await coco.mint.trustMint(mintUrl); + } } coco.quotes.addMintQuote( @@ -250,9 +267,18 @@ export function useNpubCash() { for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) { try { - const isKnown = await coco.mint.isKnownMint(mintUrl); + // Check if mint exists (known) by checking all mints + const allMints = await coco.mint.getAllMints(); + const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase()); + if (!isKnown) { - await coco.mint.addMint(mintUrl); + await coco.mint.addMint(mintUrl, { trusted: true }); + } else { + // Mint exists, ensure it's trusted + const isTrusted = await coco.mint.isTrustedMint(mintUrl); + if (!isTrusted) { + await coco.mint.trustMint(mintUrl); + } } coco.quotes.addMintQuote(