From 22d3675f2b4f4ac1b0bf5f75e0fbbb47e92956e4 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Wed, 8 Oct 2025 00:23:26 -0700 Subject: [PATCH] modular cashu hooks, wallet toggle, qr code modals --- src/components/CashuWallet.tsx | 679 +++++++++-------- src/hooks/cashu/index.ts | 102 +++ src/hooks/cashu/types.ts | 142 ++++ src/hooks/cashu/useCashuBalances.ts | 126 ++++ src/hooks/cashu/useCashuHistory.ts | 42 ++ src/hooks/cashu/useCashuManager.ts | 167 +++++ src/hooks/cashu/useCashuManagerOperations.ts | 147 ++++ src/hooks/cashu/useCashuMints.ts | 125 +++ src/hooks/cashu/useCashuQuotes.ts | 156 ++++ src/hooks/cashu/useCashuSubscriptions.ts | 43 ++ src/hooks/cashu/useCashuWallet.ts | 108 +++ src/hooks/useCashu.ts | 751 +------------------ 12 files changed, 1537 insertions(+), 1051 deletions(-) create mode 100644 src/hooks/cashu/index.ts create mode 100644 src/hooks/cashu/types.ts create mode 100644 src/hooks/cashu/useCashuBalances.ts create mode 100644 src/hooks/cashu/useCashuHistory.ts create mode 100644 src/hooks/cashu/useCashuManager.ts create mode 100644 src/hooks/cashu/useCashuManagerOperations.ts create mode 100644 src/hooks/cashu/useCashuMints.ts create mode 100644 src/hooks/cashu/useCashuQuotes.ts create mode 100644 src/hooks/cashu/useCashuSubscriptions.ts create mode 100644 src/hooks/cashu/useCashuWallet.ts diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx index 6f8f1ca..2304d8a 100644 --- a/src/components/CashuWallet.tsx +++ b/src/components/CashuWallet.tsx @@ -3,13 +3,13 @@ import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; import { useNpubCash } from '@/hooks/useNpubCash'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLightningAddress } from '@/hooks/useLightningAddress'; +import { useToast } from '@/hooks/useToast'; import { Button } from '@/components/ui/button'; 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 { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode } from 'lucide-react'; import QRCode from 'qrcode'; export function CashuWallet() { @@ -34,7 +34,6 @@ export function CashuWallet() { addMintQuote, refreshBalances, refreshMints, - checkAndRedeemPendingQuotes, clearError, getHistory, } = useCashu(); @@ -52,6 +51,8 @@ export function CashuWallet() { } = useNpubCash(); const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); + + const { toast } = useToast(); // ============================================================================ // STATE - Input Values @@ -70,8 +71,7 @@ export function CashuWallet() { // ============================================================================ const [showSats, setShowSats] = useState(true); - const [receiveMode, setReceiveMode] = useState<'tokens' | 'lightning'>('tokens'); - const [sendMode, setSendMode] = useState<'tokens' | 'lightning'>('tokens'); + const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens'); const [activeMintUrl, setActiveMintUrl] = useState(null); // ============================================================================ @@ -80,14 +80,6 @@ export function CashuWallet() { const [sentToken, setSentToken] = useState(null); const [pendingLightningAddress, setPendingLightningAddress] = useState(null); - const [pendingQuotes, setPendingQuotes] = useLocalStorage>('cashu-pending-quotes', []); // ============================================================================ // STATE - Copy Feedback @@ -111,12 +103,24 @@ export function CashuWallet() { denominations: { [key: number]: number }; totalBalance: number; } | null>(null); + + const [showLightningQR, setShowLightningQR] = useState(false); + const [lightningQRCode, setLightningQRCode] = useState(''); + + const [showInvoiceModal, setShowInvoiceModal] = useState(false); + const [currentInvoice, setCurrentInvoice] = useState<{ + quoteId: string; + mintUrl: string; + amount: number; + invoice: string; + qrCodeUrl: string; + } | null>(null); // ============================================================================ // COMPUTED VALUES // ============================================================================ - const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0); + const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); // ============================================================================ // HELPER FUNCTIONS - Display @@ -158,6 +162,31 @@ export function CashuWallet() { } }; + // Generate QR code for Lightning address + const generateLightningQRCode = async () => { + if (!lightningAddress) return; + + try { + const qrCodeUrl = await QRCode.toDataURL(lightningAddress, { + width: 256, + margin: 2, + color: { + dark: '#000000', + light: '#FFFFFF', + }, + }); + setLightningQRCode(qrCodeUrl); + setShowLightningQR(true); + } catch (err) { + console.error('Failed to generate Lightning address QR code:', err); + toast({ + variant: "destructive", + title: "QR Code Failed", + description: "Failed to generate QR code for Lightning address", + }); + } + }; + // ============================================================================ // HELPER FUNCTIONS - QR Code @@ -267,18 +296,24 @@ export function CashuWallet() { // ============================================================================ const handleReceive = async () => { - if (receiveMode === 'tokens') { + if (mode === 'tokens') { if (!tokenInput.trim()) return; try { await receive(tokenInput); setTokenInput(''); - const message = 'Token received successfully!'; - console.log('✅', message); - alert(message); + console.log('✅ Token received successfully!'); + toast({ + title: "Token Received", + description: "Cashu token redeemed successfully!", + }); } catch (err) { const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Receive Failed", + description: errorMessage, + }); } } else { // Lightning mode - create mint quote @@ -286,9 +321,12 @@ export function CashuWallet() { try { const amount = parseInt(quoteAmount); if (isNaN(amount) || amount <= 0) { - const message = 'Please enter a valid amount'; - console.warn('⚠️', message); - alert(message); + console.warn('⚠️ Invalid amount'); + toast({ + variant: "destructive", + title: "Invalid Amount", + description: "Please enter a valid amount", + }); return; } const quote = await createMintQuote(activeMintUrl, amount); @@ -296,26 +334,32 @@ export function CashuWallet() { // Generate QR code for the Lightning invoice const qrCodeUrl = await generateQRCodeForQuote(quote.request); - // Save the pending quote with QR code - setPendingQuotes(prev => [...prev, { + // Set the invoice data and show modal + setCurrentInvoice({ quoteId: quote.quote, mintUrl: activeMintUrl, amount, invoice: quote.request, - timestamp: Date.now(), qrCodeUrl - }]); + }); + setShowInvoiceModal(true); - const message = `Mint quote created! Request: ${quote.request}`; - console.log('✅', message); - console.log('💰 Quote object:', quote); + console.log('✅ Mint quote created:', quote); console.log('🔗 Lightning Invoice:', quote.request); - alert('Lightning invoice created! After paying, click the refresh button (🔄) to claim your tokens.'); + console.log('💡 Coco will automatically redeem when payment is detected'); + toast({ + title: "Lightning Invoice Created", + description: "Coco will automatically claim your tokens when payment is detected.", + }); setQuoteAmount(''); } catch (err) { const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Quote Creation Failed", + description: errorMessage, + }); } } }; @@ -325,14 +369,17 @@ export function CashuWallet() { // ============================================================================ const handleSend = async () => { - if (sendMode === 'tokens') { + if (mode === '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); + console.warn('⚠️ Invalid amount'); + toast({ + variant: "destructive", + title: "Invalid Amount", + description: "Please enter a valid amount", + }); return; } const encodedToken = await send(activeMintUrl, amount); @@ -343,7 +390,11 @@ export function CashuWallet() { } catch (err) { const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Send Failed", + description: errorMessage, + }); } } else { // Lightning mode @@ -357,7 +408,11 @@ export function CashuWallet() { try { const amount = parseInt(lightningAddressAmount); if (isNaN(amount) || amount <= 0) { - alert('Please enter a valid amount'); + toast({ + variant: "destructive", + title: "Invalid Amount", + description: "Please enter a valid amount", + }); return; } @@ -374,19 +429,25 @@ export function CashuWallet() { await payMeltQuote(activeMintUrl, meltQuote.quote); console.log('✅ Lightning payment sent successfully!'); - alert(`Successfully sent ${amount} sats to ${pendingLightningAddress}!`); + toast({ + title: "Payment Sent", + description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`, + }); // Reset state setPendingLightningAddress(null); setLightningAddressInput(''); setLightningAddressAmount(''); - // Refresh balances - await refreshBalances(); + // No need to manually refresh balances - events will handle it automatically } catch (err) { const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Payment Failed", + description: errorMessage, + }); } } else { // Step 1: Check if input is a Lightning address or invoice @@ -408,15 +469,21 @@ export function CashuWallet() { await payMeltQuote(activeMintUrl, meltQuote.quote); console.log('✅ Lightning invoice paid successfully!'); - alert('Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.'); + toast({ + title: "Invoice Paid", + description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.", + }); setLightningInvoice(''); - // Refresh balances to show updated amounts - await refreshBalances(); + // No need to manually refresh balances - events will handle it automatically } catch (err) { const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Invoice Payment Failed", + description: errorMessage, + }); } } } @@ -439,7 +506,11 @@ export function CashuWallet() { } } catch (err) { console.error('Failed to copy to clipboard:', err); - alert('Failed to copy to clipboard'); + toast({ + variant: "destructive", + title: "Copy Failed", + description: "Failed to copy to clipboard", + }); } }; @@ -459,17 +530,20 @@ export function CashuWallet() { 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!'); + // No need to manually refresh - events will handle it automatically + console.log('✅ Mint added successfully:', normalizedUrl); + toast({ + title: "Mint Added", + description: "Mint added successfully!", + }); } catch (err) { const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`; console.error('❌', errorMessage, err); - alert(errorMessage); + toast({ + variant: "destructive", + title: "Add Mint Failed", + description: errorMessage, + }); } }; @@ -477,25 +551,6 @@ export function CashuWallet() { // 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]) => { @@ -522,17 +577,20 @@ export function CashuWallet() { 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 + // Refresh quotes (balances will be updated automatically via events) await fetchQuotes(); - await refreshBalances(); - alert(`Successfully claimed ${quote.amount} sats!`); + toast({ + title: "Quote Claimed", + description: `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'}`); + toast({ + variant: "destructive", + title: "Claim Failed", + description: `Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`, + }); } }; const handleShowDenominations = async (mintUrl: string) => { @@ -544,7 +602,11 @@ export function CashuWallet() { console.log('💰 Raw proofs for mint:', proofs); if (!proofs || proofs.length === 0) { - alert('No tokens found for this mint'); + toast({ + variant: "destructive", + title: "No Tokens", + description: "No tokens found for this mint", + }); return; } @@ -568,7 +630,11 @@ export function CashuWallet() { } catch (err) { console.error('Failed to get denominations:', err); - alert('Failed to get token denominations. Check console for details.'); + toast({ + variant: "destructive", + title: "Failed to Get Denominations", + description: "Failed to get token denominations. Check console for details.", + }); } }; @@ -576,18 +642,39 @@ export function CashuWallet() { // EFFECTS // ============================================================================ - // Auto-select active mint when mints or balances change + // Show error toasts when errors occur + 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, + action: npubCashError.includes('Authorization') ? ( + + ) : undefined, + }); + } + }, [npubCashError, toast, retryAuth]); + + // Auto-select active mint when mints change (balances will update automatically via events) 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); + // Select first mint initially - user can change via dropdown + handleSetActiveMint(mints[0].url); } - }, [mints, activeMintUrl, balances, handleSetActiveMint]); + }, [mints, activeMintUrl, handleSetActiveMint]); // Load transaction history when wallet is initialized useEffect(() => { @@ -596,27 +683,6 @@ export function CashuWallet() { } }, [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 @@ -680,18 +746,41 @@ export function CashuWallet() { size="icon" onClick={async () => { console.log('🔄 Manual refresh triggered'); - await checkAndRedeemPendingQuotes(); - await refreshBalances(); await loadHistory(); await refreshNpubCash(); - console.log('💰 Current balances after manual refresh:', balances); + console.log('💰 Current balances (auto-updated via events):', balances); }} className="mt-2" - title="Check for paid invoices and refresh balances and history" + title="Refresh history and npub.cash data" > + + {/* Main Mode Toggle */} +
+
+ + +
+
+ {/* Active Mint Dropdown and Balance */}
@@ -753,82 +842,49 @@ export function CashuWallet() { )}
- {/* npub.cash Lightning Address */} + {/* Lightning Address */} {lightningAddress && ( -
-
- - Your Lightning Address -
-
- - {lightningAddress} - +
+ + {lightningAddress} + + + + {unclaimedAmount > 0 && ( -
- {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 @@ -838,39 +894,19 @@ export function CashuWallet() { {/* Receive Card */} - -
- - Receive -
-
- - -
+ + + Receive - {receiveMode === 'tokens' + {mode === 'tokens' ? 'Enter Cashu token to redeem' : 'Deposit funds with Lightning' }
- {receiveMode === 'tokens' ? ( + {mode === 'tokens' ? (
- -
- - Send -
-
- - -
+ + + Send - {sendMode === 'tokens' + {mode === 'tokens' ? 'Generate Cashu token to send' : pendingLightningAddress ? 'Enter the amount to send' @@ -944,7 +960,7 @@ export function CashuWallet() {
- {sendMode === 'tokens' ? ( + {mode === 'tokens' ? ( <> {!activeMintUrl && (
@@ -1102,91 +1118,6 @@ export function CashuWallet() { )} - {/* ======================================================================== - 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 @@ -1196,7 +1127,7 @@ export function CashuWallet() {
- + Received Payments (npub.cash)
)} + + {/* ======================================================================== + SECTION: Lightning Address QR Code Modal + ======================================================================== */} + {showLightningQR && lightningQRCode && ( +
+ + + + + + Lightning Address QR Code + + + Scan to send Lightning payments + + + +
+
+ Lightning Address QR Code +
+
+ +
+
+ {lightningAddress} +
+
+ +
+ 💡 Share this QR code or address to receive Lightning payments +
+
+
+
+ )} + + {/* ======================================================================== + SECTION: Lightning Invoice Modal + ======================================================================== */} + {showInvoiceModal && currentInvoice && ( +
+ + + + + + Lightning Invoice + + + Pay this invoice to receive {currentInvoice.amount} sats + + + +
+
+ Lightning Invoice QR Code +
+
+ +
+
+ {currentInvoice.invoice} +
+
+ +
+ +
+ +
+ 💡 Coco will automatically claim your tokens when payment is detected +
+
+
+
+ )}
); } diff --git a/src/hooks/cashu/index.ts b/src/hooks/cashu/index.ts new file mode 100644 index 0000000..47de08f --- /dev/null +++ b/src/hooks/cashu/index.ts @@ -0,0 +1,102 @@ +import { useMemo } from 'react'; +import { useCashuManager } from './useCashuManager'; +import { useCashuBalances } from './useCashuBalances'; +import { useCashuMints } from './useCashuMints'; +import { useCashuQuotes } from './useCashuQuotes'; +import { useCashuWallet } from './useCashuWallet'; +import { useCashuHistory } from './useCashuHistory'; +import { useCashuSubscriptions } from './useCashuSubscriptions'; +import { useCashuManagerOperations } from './useCashuManagerOperations'; +import { UseCashuReturn, CashuWalletError } from './types'; + +export function useCashu(): UseCashuReturn { + const manager = useCashuManager(); + const balances = useCashuBalances(manager.manager); + const mints = useCashuMints(manager.manager); + const quotes = useCashuQuotes(manager.manager, manager.repositories); + const wallet = useCashuWallet(manager.manager, manager.repositories); + const history = useCashuHistory(manager.manager); + const subscriptions = useCashuSubscriptions(manager.manager); + const managerOperations = useCashuManagerOperations(manager.manager); + + // Combine all errors into a single error state + const combinedError = useMemo(() => { + const errors = [ + manager.error, + balances.error, + mints.error, + quotes.error, + wallet.error, + history.error, + subscriptions.error, + managerOperations.error, + ].filter(Boolean) as CashuWalletError[]; + + return errors.length > 0 ? errors[0] : null; + }, [manager.error, balances.error, mints.error, quotes.error, wallet.error, history.error, subscriptions.error, managerOperations.error]); + + // Combine all loading states + const combinedIsLoading = useMemo(() => { + return manager.isLoading || balances.isLoading || mints.isLoading || quotes.isLoading || wallet.isLoading || history.isLoading || subscriptions.isLoading || managerOperations.isLoading; + }, [manager.isLoading, balances.isLoading, mints.isLoading, quotes.isLoading, wallet.isLoading, history.isLoading, subscriptions.isLoading, managerOperations.isLoading]); + + return { + // State + isInitialized: manager.isInitialized, + isLoading: combinedIsLoading, + error: combinedError, + balances: balances.balances, + mints: mints.mints, + mnemonic: manager.mnemonic, + + // Actions + // Wallet operations + receive: wallet.receive, + send: wallet.send, + getBalances: balances.getBalances, + getProofs: wallet.getProofs, + + // Mint operations + addMint: mints.addMint, + removeMint: mints.removeMint, + getMints: mints.getMints, + + // Quote operations + createMintQuote: quotes.createMintQuote, + redeemMintQuote: quotes.redeemMintQuote, + createMeltQuote: quotes.createMeltQuote, + payMeltQuote: quotes.payMeltQuote, + addMintQuote: quotes.addMintQuote, + + // Subscription operations + awaitMintQuotePaid: subscriptions.awaitMintQuotePaid, + awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid, + + // Manager operations + enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher, + disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher, + enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor, + disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor, + waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor, + enableProofStateWatcher: managerOperations.enableProofStateWatcher, + disableProofStateWatcher: managerOperations.disableProofStateWatcher, + + // Event operations + on: managerOperations.on, + once: managerOperations.once, + off: managerOperations.off, + + // Mnemonic operations + setMnemonic: manager.setMnemonic, + generateMnemonic: manager.generateMnemonic, + getMnemonic: manager.getMnemonic, + + // History operations + getHistory: history.getHistory, + + // Utility operations + refreshBalances: balances.refreshBalances, + refreshMints: mints.refreshMints, + clearError: manager.clearError, + }; +} diff --git a/src/hooks/cashu/types.ts b/src/hooks/cashu/types.ts new file mode 100644 index 0000000..c9e06a1 --- /dev/null +++ b/src/hooks/cashu/types.ts @@ -0,0 +1,142 @@ +// Error types that align with coco-cashu patterns +export class CashuWalletError extends Error { + constructor(message: string, public code: string, public details?: unknown) { + super(message); + this.name = 'CashuWalletError'; + } +} + +export class CashuInitializationError extends CashuWalletError { + constructor(message: string, details?: unknown) { + super(message, 'INITIALIZATION_ERROR', details); + } +} + +export class CashuMintError extends CashuWalletError { + constructor(message: string, mintUrl: string, details?: unknown) { + super(message, 'MINT_ERROR', details); + this.mintUrl = mintUrl; + } + public mintUrl: string; +} + +export class CashuQuoteError extends CashuWalletError { + constructor(message: string, quoteId: string, details?: unknown) { + super(message, 'QUOTE_ERROR', details); + this.quoteId = quoteId; + } + public quoteId: string; +} + +export class CashuTokenError extends CashuWalletError { + constructor(message: string, token?: string, details?: unknown) { + super(message, 'TOKEN_ERROR', details); + this.token = token; + } + public token?: string; +} + +// Core types +export interface CashuBalance { + [mintUrl: string]: number; +} + +export interface CashuMint { + url: string; + name?: string; + info?: Record; +} + +export interface CashuMintQuote { + quote: string; + request: string; + expiry: number; +} + +export interface CashuMeltQuote { + quote: string; + request: string; + expiry: number; +} + +export interface CashuToken { + mint: string; + proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>; +} + +export interface HistoryEntry { + id: string; + type: 'mint' | 'melt' | 'send' | 'receive'; + mintUrl: string; + amount: number; + unit: string; + createdAt: number; + metadata?: Record; + quoteId?: string; + state?: string; + paymentRequest?: string; + token?: CashuToken; +} + +// Hook state types +export interface CashuState { + isInitialized: boolean; + isLoading: boolean; + error: CashuWalletError | null; + balances: CashuBalance; + mints: CashuMint[]; + mnemonic: string | null; +} + +export interface CashuActions { + // Wallet operations + receive: (token: string | CashuToken) => Promise; + send: (mintUrl: string, amount: number) => Promise; + getBalances: () => Promise; + getProofs: (mintUrl: string) => Promise>; + + // Mint operations + addMint: (mintUrl: string) => Promise; + removeMint: (mintUrl: string) => Promise; + getMints: () => Promise; + + // Quote operations + createMintQuote: (mintUrl: string, amount: number) => Promise; + redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; + createMeltQuote: (mintUrl: string, invoice: string) => Promise; + payMeltQuote: (mintUrl: string, quoteId: string) => Promise; + addMintQuote: (mintUrl: string, quoteId: string) => Promise; + + // Subscription operations (NEW) + awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise; + awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise; + + // Manager operations (NEW) + enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise; + disableMintQuoteWatcher: () => Promise; + enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise; + disableMintQuoteProcessor: () => Promise; + waitForMintQuoteProcessor: () => Promise; + enableProofStateWatcher: () => Promise; + disableProofStateWatcher: () => Promise; + + // Event operations (NEW) + on: (event: string, handler: (payload: unknown) => void | Promise) => () => void; + once: (event: string, handler: (payload: unknown) => void | Promise) => () => void; + off: (event: string, handler: (payload: unknown) => void | Promise) => void; + + // Mnemonic operations + setMnemonic: (mnemonic: string) => void; + generateMnemonic: () => string; + getMnemonic: () => string | null; + + // History operations + getHistory: (limit?: number, offset?: number) => Promise; + + // Utility operations + refreshBalances: () => Promise; + refreshMints: () => Promise; + clearError: () => void; +} + +export type UseCashuReturn = CashuState & CashuActions; diff --git a/src/hooks/cashu/useCashuBalances.ts b/src/hooks/cashu/useCashuBalances.ts new file mode 100644 index 0000000..1f2c98e --- /dev/null +++ b/src/hooks/cashu/useCashuBalances.ts @@ -0,0 +1,126 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { CashuBalance, CashuWalletError } from './types'; + +export interface UseCashuBalancesReturn { + balances: CashuBalance; + isLoading: boolean; + error: CashuWalletError | null; + refreshBalances: () => Promise; + getBalances: () => Promise; +} + +export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn { + const [balances, setBalances] = useState({}); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + // Throttling refs + const lastRefreshTimeRef = useRef(0); + const isRefreshingRef = useRef(false); + const REFRESH_THROTTLE_MS = 500; + + const refreshBalances = useCallback(async () => { + if (!manager) return; + + // Prevent concurrent calls + if (isRefreshingRef.current) { + console.log('⏭️ refreshBalances: Skipping (already in progress)'); + return; + } + + // Throttle rapid successive calls + const now = Date.now(); + if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) { + console.log('⏭️ refreshBalances: Skipping (throttled)'); + return; + } + + isRefreshingRef.current = true; + lastRefreshTimeRef.current = now; + + try { + console.log('🔄 refreshBalances: Getting balances from wallet...'); + const newBalances = await (manager as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); + console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); + + // Only update state if balances actually changed (deep comparison) + setBalances(prevBalances => { + const hasChanged = + Object.keys(newBalances).length !== Object.keys(prevBalances).length || + Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); + + if (hasChanged) { + console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); + return newBalances; + } else { + console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); + return prevBalances; + } + }); + } catch (err) { + console.error('❌ refreshBalances: Failed to refresh balances:', err); + const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balances'; + setError(new CashuWalletError(errorMessage, 'BALANCE_REFRESH_ERROR', { originalError: err })); + } finally { + isRefreshingRef.current = false; + } + }, [manager]); + + const getBalances = useCallback(async (): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + return await (manager as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get balances'; + const cashuError = new CashuWalletError(errorMessage, 'GET_BALANCES_ERROR', { originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + // Set up event listeners for automatic balance updates using coco events + useEffect(() => { + if (!manager) return; + + const unsubscribeProofsSaved = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('proofs:saved', () => { + console.log('📨 Proofs saved, refreshing balances...'); + refreshBalances(); + }); + + const unsubscribeProofsStateChanged = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('proofs:state-changed', () => { + console.log('🔄 Proofs state changed, refreshing balances...'); + refreshBalances(); + }); + + const unsubscribeMintQuoteRedeemed = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('mintQuote:redeemed', () => { + console.log('💰 Mint quote redeemed, refreshing balances...'); + refreshBalances(); + }); + + return () => { + unsubscribeProofsSaved(); + unsubscribeProofsStateChanged(); + unsubscribeMintQuoteRedeemed(); + }; + }, [manager, refreshBalances]); + + // Initial balance load + useEffect(() => { + if (manager && Object.keys(balances).length === 0) { + refreshBalances(); + } + }, [manager, balances, refreshBalances]); + + return { + balances, + isLoading, + error, + refreshBalances, + getBalances, + }; +} diff --git a/src/hooks/cashu/useCashuHistory.ts b/src/hooks/cashu/useCashuHistory.ts new file mode 100644 index 0000000..277d44c --- /dev/null +++ b/src/hooks/cashu/useCashuHistory.ts @@ -0,0 +1,42 @@ +import { useState, useCallback } from 'react'; +import { HistoryEntry, CashuWalletError } from './types'; + +export interface UseCashuHistoryReturn { + isLoading: boolean; + error: CashuWalletError | null; + getHistory: (limit?: number, offset?: number) => Promise; +} + +export function useCashuHistory(manager: unknown | null): UseCashuHistoryReturn { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + console.log('📜 Getting transaction history...'); + + const entries = await (manager as { history: { getPaginatedHistory: (offset: number, limit: number) => Promise } }).history.getPaginatedHistory(offset, limit); + console.log(`✅ Found ${entries.length} history entries`); + + return entries as unknown as HistoryEntry[]; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get history'; + console.error('❌ Error getting history:', err); + const cashuError = new CashuWalletError(errorMessage, 'GET_HISTORY_ERROR', { limit, offset, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + return { + isLoading, + error, + getHistory, + }; +} diff --git a/src/hooks/cashu/useCashuManager.ts b/src/hooks/cashu/useCashuManager.ts new file mode 100644 index 0000000..b8842e3 --- /dev/null +++ b/src/hooks/cashu/useCashuManager.ts @@ -0,0 +1,167 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { useLocalStorage } from '../useLocalStorage'; +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; +import { CashuInitializationError, CashuWalletError } from './types'; + +// Dynamic imports for coco-cashu packages +let Manager: unknown = null; +let IndexedDbRepositories: unknown = null; +let ConsoleLogger: unknown = null; +let getEncodedToken: unknown = null; +let _getDecodedToken: unknown = null; + +// Lazy load coco-cashu packages +const loadCocoCashu = async () => { + if (Manager) return; // Already loaded + + try { + const coreModule = await import('coco-cashu-core'); + const indexedDbModule = await import('coco-cashu-indexeddb'); + + Manager = coreModule.Manager; + ConsoleLogger = coreModule.ConsoleLogger; + getEncodedToken = coreModule.getEncodedToken; + _getDecodedToken = coreModule.getDecodedToken; + IndexedDbRepositories = indexedDbModule.IndexedDbRepositories; + } catch (error) { + console.error('Failed to load coco-cashu packages:', error); + throw new CashuInitializationError( + 'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb', + { error } + ); + } +}; + +export interface UseCashuManagerReturn { + manager: unknown | null; + repositories: unknown | null; + isInitialized: boolean; + isLoading: boolean; + error: CashuWalletError | null; + mnemonic: string | null; + setMnemonic: (mnemonic: string) => void; + generateMnemonic: () => string; + getMnemonic: () => string | null; + clearError: () => void; +} + +export function useCashuManager(): UseCashuManagerReturn { + const [isInitialized, setIsInitialized] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + // Mnemonic management with localStorage + const [mnemonic, setMnemonicState] = useLocalStorage('cashu-mnemonic', null); + + // Manager instance refs + const managerRef = useRef(null); + const repositoriesRef = useRef(null); + + const clearError = useCallback(() => { + setError(null); + }, []); + + const generateMnemonic = useCallback(() => { + return bip39.generateMnemonic(wordlist); + }, []); + + const getMnemonic = useCallback(() => { + return mnemonic; + }, [mnemonic]); + + const setMnemonic = useCallback((newMnemonic: string) => { + if (!bip39.validateMnemonic(newMnemonic, wordlist)) { + throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC'); + } + setMnemonicState(newMnemonic); + // Reinitialize manager with new mnemonic + setIsInitialized(false); + }, [setMnemonicState]); + + // Initialize the manager + const initializeManager = useCallback(async () => { + if (isInitialized || isLoading) return; + + setIsLoading(true); + setError(null); + + try { + await loadCocoCashu(); + + // Generate or retrieve mnemonic + let currentMnemonic = mnemonic; + if (!currentMnemonic) { + currentMnemonic = bip39.generateMnemonic(wordlist); + setMnemonicState(currentMnemonic); + } + + // Create seed from mnemonic + const seed = bip39.mnemonicToSeedSync(currentMnemonic); + + // Initialize repositories + const repositories = new (IndexedDbRepositories as new (options: Record) => { init: () => Promise })({}); + await repositories.init(); + repositoriesRef.current = repositories; + + // Initialize manager + const manager = new (Manager as new ( + repositories: unknown, + seedGetter: () => Promise, + logger?: unknown + ) => { + wallet: { getBalances: () => Promise>; receive: (token: string | unknown) => Promise; send: (mintUrl: string, amount: number) => Promise }; + mint: { addMint: (mintUrl: string) => Promise; getAllMints: () => Promise }>> }; + quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; createMeltQuote: (mintUrl: string, invoice: string) => Promise; payMeltQuote: (mintUrl: string, quoteId: string) => Promise }; + history: { getPaginatedHistory: (offset: number, limit: number) => Promise }; + enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise; + enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise; + enableProofStateWatcher: () => Promise; + on: (event: string, handler: (payload: unknown) => void | Promise) => () => void; + })( + repositories, + async () => seed, + new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' }) + ); + managerRef.current = manager; + + // Enable built-in services for automatic quote processing and state watching + try { + await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true }); + await manager.enableMintQuoteProcessor(); + await manager.enableProofStateWatcher(); + console.log('✅ Enabled coco-cashu watcher services'); + } catch (err) { + console.warn('⚠️ Failed to enable some watcher services:', err); + // Don't fail initialization if watchers can't be enabled + } + + setIsInitialized(true); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet'; + const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err }); + setError(cashuError); + console.error('Cashu initialization error:', err); + } finally { + setIsLoading(false); + } + }, [isInitialized, isLoading, mnemonic, setMnemonicState]); + + // Initialize on mount and when mnemonic changes + useEffect(() => { + initializeManager(); + }, [initializeManager]); + + return { + manager: managerRef.current, + repositories: repositoriesRef.current, + isInitialized, + isLoading, + error, + mnemonic, + setMnemonic, + generateMnemonic, + getMnemonic, + clearError, + }; +} diff --git a/src/hooks/cashu/useCashuManagerOperations.ts b/src/hooks/cashu/useCashuManagerOperations.ts new file mode 100644 index 0000000..b293825 --- /dev/null +++ b/src/hooks/cashu/useCashuManagerOperations.ts @@ -0,0 +1,147 @@ +import { useCallback } from 'react'; +import { CashuWalletError } from './types'; + +export interface UseCashuManagerOperationsReturn { + isLoading: boolean; + error: CashuWalletError | null; + enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise; + disableMintQuoteWatcher: () => Promise; + enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise; + disableMintQuoteProcessor: () => Promise; + waitForMintQuoteProcessor: () => Promise; + enableProofStateWatcher: () => Promise; + disableProofStateWatcher: () => Promise; + on: (event: string, handler: (payload: unknown) => void | Promise) => () => void; + once: (event: string, handler: (payload: unknown) => void | Promise) => () => void; + off: (event: string, handler: (payload: unknown) => void | Promise) => void; +} + +export function useCashuManagerOperations(manager: unknown | null): UseCashuManagerOperationsReturn { + const isLoading = false; // Manager operations are typically async but don't have loading states + const error = null; // Errors are handled per-operation + + const enableMintQuoteWatcher = useCallback(async (options?: { watchExistingPendingOnStart?: boolean }) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise }).enableMintQuoteWatcher(options); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote watcher'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteWatcher', originalError: err }); + } + }, [manager]); + + const disableMintQuoteWatcher = useCallback(async () => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { disableMintQuoteWatcher: () => Promise }).disableMintQuoteWatcher(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote watcher'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteWatcher', originalError: err }); + } + }, [manager]); + + const enableMintQuoteProcessor = useCallback(async (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise }).enableMintQuoteProcessor(options); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to enable mint quote processor'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableMintQuoteProcessor', originalError: err }); + } + }, [manager]); + + const disableMintQuoteProcessor = useCallback(async () => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { disableMintQuoteProcessor: () => Promise }).disableMintQuoteProcessor(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to disable mint quote processor'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableMintQuoteProcessor', originalError: err }); + } + }, [manager]); + + const waitForMintQuoteProcessor = useCallback(async () => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { waitForMintQuoteProcessor: () => Promise }).waitForMintQuoteProcessor(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to wait for mint quote processor'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'waitForMintQuoteProcessor', originalError: err }); + } + }, [manager]); + + const enableProofStateWatcher = useCallback(async () => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { enableProofStateWatcher: () => Promise }).enableProofStateWatcher(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to enable proof state watcher'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'enableProofStateWatcher', originalError: err }); + } + }, [manager]); + + const disableProofStateWatcher = useCallback(async () => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + await (manager as { disableProofStateWatcher: () => Promise }).disableProofStateWatcher(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to disable proof state watcher'; + throw new CashuWalletError(errorMessage, 'MANAGER_OPERATION_ERROR', { operation: 'disableProofStateWatcher', originalError: err }); + } + }, [manager]); + + const on = useCallback((event: string, handler: (payload: unknown) => void | Promise) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + return (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on(event, handler); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to add event listener'; + throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'on', event, originalError: err }); + } + }, [manager]); + + const once = useCallback((event: string, handler: (payload: unknown) => void | Promise) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + return (manager as { once: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).once(event, handler); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to add one-time event listener'; + throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'once', event, originalError: err }); + } + }, [manager]); + + const off = useCallback((event: string, handler: (payload: unknown) => void | Promise) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + (manager as { off: (event: string, handler: (payload: unknown) => void | Promise) => void }).off(event, handler); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to remove event listener'; + throw new CashuWalletError(errorMessage, 'EVENT_ERROR', { operation: 'off', event, originalError: err }); + } + }, [manager]); + + return { + isLoading, + error, + enableMintQuoteWatcher, + disableMintQuoteWatcher, + enableMintQuoteProcessor, + disableMintQuoteProcessor, + waitForMintQuoteProcessor, + enableProofStateWatcher, + disableProofStateWatcher, + on, + once, + off, + }; +} diff --git a/src/hooks/cashu/useCashuMints.ts b/src/hooks/cashu/useCashuMints.ts new file mode 100644 index 0000000..962cfe1 --- /dev/null +++ b/src/hooks/cashu/useCashuMints.ts @@ -0,0 +1,125 @@ +import { useState, useEffect, useCallback } from 'react'; +import { CashuMint, CashuWalletError } from './types'; + +export interface UseCashuMintsReturn { + mints: CashuMint[]; + isLoading: boolean; + error: CashuWalletError | null; + refreshMints: () => Promise; + getMints: () => Promise; + addMint: (mintUrl: string) => Promise; + removeMint: (mintUrl: string) => Promise; +} + +export function useCashuMints(manager: unknown | null): UseCashuMintsReturn { + const [mints, setMints] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const refreshMints = useCallback(async () => { + if (!manager) return; + + try { + const mintList = await (manager as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); + const formattedMints = mintList + .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url + .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ + url: mint.mintUrl, // Map mintUrl to url for consistency + name: mint.name, + info: mint.mintInfo + })); + setMints(formattedMints); + } catch (err) { + console.error('Failed to refresh mints:', err); + const errorMessage = err instanceof Error ? err.message : 'Failed to refresh mints'; + setError(new CashuWalletError(errorMessage, 'MINT_REFRESH_ERROR', { originalError: err })); + } + }, [manager]); + + const getMints = useCallback(async (): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + const mintList = await (manager as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); + return mintList + .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url + .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ + url: mint.mintUrl, // Map mintUrl to url for consistency + name: mint.name, + info: mint.mintInfo + })); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get mints'; + const cashuError = new CashuWalletError(errorMessage, 'GET_MINTS_ERROR', { originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const addMint = useCallback(async (mintUrl: string) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + await (manager as { mint: { addMint: (mintUrl: string) => Promise } }).mint.addMint(mintUrl); + // No need to manually refresh - events will handle it automatically + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to add mint'; + const cashuError = new CashuWalletError(errorMessage, 'ADD_MINT_ERROR', { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const removeMint = useCallback(async (_mintUrl: string) => { + // Note: coco-cashu doesn't have a direct remove mint method + // This would need to be implemented at the repository level + const error = new CashuWalletError('Remove mint functionality not yet implemented', 'REMOVE_MINT_NOT_IMPLEMENTED'); + setError(error); + throw error; + }, []); + + // Set up event listeners for automatic mint updates using coco events + useEffect(() => { + if (!manager) return; + + const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('mint:added', () => { + console.log('➕ Mint added, refreshing mints...'); + refreshMints(); + }); + + const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('mint:updated', () => { + console.log('🔄 Mint updated, refreshing mints...'); + refreshMints(); + }); + + return () => { + unsubscribeMintAdded(); + unsubscribeMintUpdated(); + }; + }, [manager, refreshMints]); + + // Initial mints load + useEffect(() => { + if (manager && mints.length === 0) { + refreshMints(); + } + }, [manager, mints.length, refreshMints]); + + return { + mints, + isLoading, + error, + refreshMints, + getMints, + addMint, + removeMint, + }; +} diff --git a/src/hooks/cashu/useCashuQuotes.ts b/src/hooks/cashu/useCashuQuotes.ts new file mode 100644 index 0000000..bc0282e --- /dev/null +++ b/src/hooks/cashu/useCashuQuotes.ts @@ -0,0 +1,156 @@ +import { useState, useCallback } from 'react'; +import { CashuMintQuote, CashuMeltQuote, CashuWalletError, CashuQuoteError } from './types'; + +export interface UseCashuQuotesReturn { + isLoading: boolean; + error: CashuWalletError | null; + createMintQuote: (mintUrl: string, amount: number) => Promise; + redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; + createMeltQuote: (mintUrl: string, invoice: string) => Promise; + payMeltQuote: (mintUrl: string, quoteId: string) => Promise; + addMintQuote: (mintUrl: string, quoteId: string) => Promise; +} + +export function useCashuQuotes(manager: unknown | null, repositories: unknown | null): UseCashuQuotesReturn { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + const quote = await (manager as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise } }).quotes.createMintQuote(mintUrl, amount); + return { + quote: quote.quote, + request: quote.request, + expiry: quote.expiry + }; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote'; + const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, amount, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId); + console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length); + console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl); + + await (manager as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise } }).quotes.redeemMintQuote(mintUrl, quoteId); + console.log('✅ redeemMintQuote: Quote redeemed successfully'); + } catch (err) { + console.error('❌ redeemMintQuote: Error details:', { + message: err instanceof Error ? err.message : 'Unknown error', + mintUrl, + quoteId, + quoteIdType: typeof quoteId, + quoteIdLength: quoteId.length + }); + const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote'; + const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => { + if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId }); + + // Access the mint quote repository + const mintQuoteRepo = (repositories as { + mintQuoteRepository?: { + addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise + } + })?.mintQuoteRepository; + + if (!mintQuoteRepo) { + throw new CashuWalletError('Mint quote repository not available', 'REPOSITORY_NOT_AVAILABLE'); + } + + // Add the quote to the repository with UNPAID state + // The mint processor will check and redeem it + await mintQuoteRepo.addMintQuote({ + quote: quoteId, + mintUrl: mintUrl, + state: 'UNPAID', // Mark as UNPAID so coco will check it + }); + + console.log('✅ Mint quote added to repository successfully'); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote'; + console.error('❌ Error adding mint quote:', err); + const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager, repositories]); + + const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + const quote = await (manager as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise } }).quotes.createMeltQuote(mintUrl, invoice); + return { + quote: quote.quote, + request: quote.request, + expiry: quote.expiry + }; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote'; + const cashuError = new CashuQuoteError(errorMessage, '', { mintUrl, invoice, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + await (manager as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise } }).quotes.payMeltQuote(mintUrl, quoteId); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote'; + const cashuError = new CashuQuoteError(errorMessage, quoteId, { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + return { + isLoading, + error, + createMintQuote, + redeemMintQuote, + createMeltQuote, + payMeltQuote, + addMintQuote, + }; +} diff --git a/src/hooks/cashu/useCashuSubscriptions.ts b/src/hooks/cashu/useCashuSubscriptions.ts new file mode 100644 index 0000000..8ce9a05 --- /dev/null +++ b/src/hooks/cashu/useCashuSubscriptions.ts @@ -0,0 +1,43 @@ +import { useCallback } from 'react'; +import { CashuWalletError } from './types'; + +export interface UseCashuSubscriptionsReturn { + isLoading: boolean; + error: CashuWalletError | null; + awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise; + awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise; +} + +export function useCashuSubscriptions(manager: unknown | null): UseCashuSubscriptionsReturn { + const isLoading = false; // Subscription operations are typically async but don't have loading states + const error = null; // Errors are handled per-operation + + const awaitMintQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + return await (manager as { subscription: { awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise } }).subscription.awaitMintQuotePaid(mintUrl, quoteId); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to await mint quote payment'; + throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err }); + } + }, [manager]); + + const awaitMeltQuotePaid = useCallback(async (mintUrl: string, quoteId: string): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + return await (manager as { subscription: { awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise } }).subscription.awaitMeltQuotePaid(mintUrl, quoteId); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to await melt quote payment'; + throw new CashuWalletError(errorMessage, 'SUBSCRIPTION_ERROR', { mintUrl, quoteId, originalError: err }); + } + }, [manager]); + + return { + isLoading, + error, + awaitMintQuotePaid, + awaitMeltQuotePaid, + }; +} diff --git a/src/hooks/cashu/useCashuWallet.ts b/src/hooks/cashu/useCashuWallet.ts new file mode 100644 index 0000000..b504765 --- /dev/null +++ b/src/hooks/cashu/useCashuWallet.ts @@ -0,0 +1,108 @@ +import { useState, useCallback } from 'react'; +import { CashuToken, CashuWalletError, CashuTokenError } from './types'; + +// Dynamic import for getEncodedToken +let getEncodedToken: unknown = null; + +const loadGetEncodedToken = async () => { + if (getEncodedToken) return; + try { + const coreModule = await import('coco-cashu-core'); + getEncodedToken = coreModule.getEncodedToken; + } catch (error) { + console.error('Failed to load getEncodedToken:', error); + } +}; + +export interface UseCashuWalletReturn { + isLoading: boolean; + error: CashuWalletError | null; + receive: (token: string | CashuToken) => Promise; + send: (mintUrl: string, amount: number) => Promise; + getProofs: (mintUrl: string) => Promise>; +} + +export function useCashuWallet(manager: unknown | null, repositories: unknown | null): UseCashuWalletReturn { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const receive = useCallback(async (token: string | CashuToken) => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + await (manager as { wallet: { receive: (token: string | CashuToken) => Promise } }).wallet.receive(token); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to receive token'; + const cashuError = new CashuTokenError(errorMessage, typeof token === 'string' ? token : undefined, { originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const send = useCallback(async (mintUrl: string, amount: number): Promise => { + if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + + // Load getEncodedToken if not already loaded + await loadGetEncodedToken(); + + const token = await (manager as { wallet: { send: (mintUrl: string, amount: number) => Promise } }).wallet.send(mintUrl, amount); + + // Encode the token into a Cashu token string + const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token); + return encodedToken; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens'; + const cashuError = new CashuWalletError(errorMessage, 'SEND_ERROR', { mintUrl, amount, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager]); + + const getProofs = useCallback(async (mintUrl: string): Promise> => { + if (!manager || !repositories) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); + + try { + setIsLoading(true); + setError(null); + console.log('🔍 Getting proofs from wallet for mint:', mintUrl); + + // Access the proof repository + const proofRepo = (repositories as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise>> } })?.proofRepository; + if (!proofRepo) { + throw new CashuWalletError('Proof repository not available', 'REPOSITORY_NOT_AVAILABLE'); + } + + // Get ready proofs for this mint (proofs available to spend) + const readyProofs = await proofRepo.getReadyProofs(mintUrl); + console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`); + + return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs'; + console.error('❌ Error getting proofs:', err); + const cashuError = new CashuWalletError(errorMessage, 'GET_PROOFS_ERROR', { mintUrl, originalError: err }); + setError(cashuError); + throw cashuError; + } finally { + setIsLoading(false); + } + }, [manager, repositories]); + + return { + isLoading, + error, + receive, + send, + getProofs, + }; +} diff --git a/src/hooks/useCashu.ts b/src/hooks/useCashu.ts index 550b663..08c13c8 100644 --- a/src/hooks/useCashu.ts +++ b/src/hooks/useCashu.ts @@ -1,736 +1,17 @@ -import { useState, useEffect, useCallback, useRef } from 'react'; -import { useLocalStorage } from './useLocalStorage'; -import * as bip39 from '@scure/bip39'; -import { wordlist } from '@scure/bip39/wordlists/english'; +// Re-export the new modular useCashu hook and types +export { useCashu } from './cashu/index'; +export type { + UseCashuReturn, + CashuBalance, + CashuMint, + CashuMintQuote, + CashuMeltQuote, + CashuToken, + HistoryEntry, + CashuWalletError, + CashuInitializationError, + CashuMintError, + CashuQuoteError, + CashuTokenError +} from './cashu/types'; -// Types for the hook interface -export interface CashuBalance { - [mintUrl: string]: number; -} - -export interface CashuMint { - url: string; - name?: string; - info?: Record; -} - -export interface CashuMintQuote { - quote: string; - request: string; - expiry: number; -} - -export interface CashuMeltQuote { - quote: string; - request: string; - expiry: number; -} - -export interface CashuToken { - mint: string; - proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>; -} - -export interface CashuState { - isInitialized: boolean; - isLoading: boolean; - error: string | null; - balances: CashuBalance; - mints: CashuMint[]; - mnemonic: string | null; -} - -export interface HistoryEntry { - id: string; - type: 'mint' | 'melt' | 'send' | 'receive'; - mintUrl: string; - amount: number; - unit: string; - createdAt: number; - metadata?: Record; - quoteId?: string; - state?: string; - paymentRequest?: string; - token?: CashuToken; -} - -export interface CashuActions { - // Wallet operations - receive: (token: string | CashuToken) => Promise; - send: (mintUrl: string, amount: number) => Promise; - getBalances: () => Promise; - getProofs: (mintUrl: string) => Promise>; - - // Mint operations - addMint: (mintUrl: string) => Promise; - removeMint: (mintUrl: string) => Promise; - getMints: () => Promise; - - // Quote operations - createMintQuote: (mintUrl: string, amount: number) => Promise; - redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; - createMeltQuote: (mintUrl: string, invoice: string) => Promise; - payMeltQuote: (mintUrl: string, quoteId: string) => Promise; - - // Mnemonic operations - setMnemonic: (mnemonic: string) => void; - generateMnemonic: () => string; - getMnemonic: () => string | null; - - // History operations - getHistory: (limit?: number, offset?: number) => Promise; - - // Utility operations - refreshBalances: () => Promise; - refreshMints: () => Promise; - checkAndRedeemPendingQuotes: () => Promise; - clearError: () => void; - - // Add mint quote (for external quotes like from npubx.cash) - addMintQuote: (mintUrl: string, quoteId: string) => Promise; -} - -export type UseCashuReturn = CashuState & CashuActions; - -// Dynamic imports for coco-cashu packages -let Manager: unknown = null; -let IndexedDbRepositories: unknown = null; -let ConsoleLogger: unknown = null; -let getEncodedToken: unknown = null; -let _getDecodedToken: unknown = null; - -// Lazy load coco-cashu packages -const loadCocoCashu = async () => { - if (Manager) return; // Already loaded - - try { - const coreModule = await import('coco-cashu-core'); - const indexedDbModule = await import('coco-cashu-indexeddb'); - - Manager = coreModule.Manager; - ConsoleLogger = coreModule.ConsoleLogger; - getEncodedToken = coreModule.getEncodedToken; - _getDecodedToken = coreModule.getDecodedToken; - IndexedDbRepositories = indexedDbModule.IndexedDbRepositories; - } catch (error) { - console.error('Failed to load coco-cashu packages:', error); - throw new Error('Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb'); - } -}; - -export function useCashu(): UseCashuReturn { - // State management - const [isInitialized, setIsInitialized] = useState(false); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - const [balances, setBalances] = useState({}); - const [mints, setMints] = useState([]); - - // Mnemonic management with localStorage - const [mnemonic, setMnemonicState] = useLocalStorage('cashu-mnemonic', null); - - // Manager instance ref - const managerRef = useRef(null); - const repositoriesRef = useRef(null); - - // Utility operations - defined first so they can be used in other callbacks - const lastRefreshTimeRef = useRef(0); - const isRefreshingRef = useRef(false); - const REFRESH_THROTTLE_MS = 500; // Prevent refreshing more than once every 500ms - - const refreshBalances = useCallback(async () => { - if (!managerRef.current) return; - - // Prevent concurrent calls - if (isRefreshingRef.current) { - console.log('⏭️ refreshBalances: Skipping (already in progress)'); - return; - } - - // Throttle rapid successive calls - const now = Date.now(); - if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) { - console.log('⏭️ refreshBalances: Skipping (throttled)'); - return; - } - - isRefreshingRef.current = true; - lastRefreshTimeRef.current = now; - - try { - console.log('🔄 refreshBalances: Getting balances from wallet...'); - const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); - console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - - // Only update state if balances actually changed (deep comparison) - setBalances(prevBalances => { - const hasChanged = - Object.keys(newBalances).length !== Object.keys(prevBalances).length || - Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); - - if (hasChanged) { - console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); - return newBalances; - } else { - console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); - return prevBalances; - } - }); - } catch (err) { - console.error('❌ refreshBalances: Failed to refresh balances:', err); - } finally { - isRefreshingRef.current = false; - } - }, []); - - const refreshMints = useCallback(async () => { - if (!managerRef.current) return; - - try { - const mintList = await (managerRef.current as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); - const formattedMints = mintList - .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url - .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ - url: mint.mintUrl, // Map mintUrl to url for consistency - name: mint.name, - info: mint.mintInfo - })); - setMints(formattedMints); - } catch (err) { - console.error('Failed to refresh mints:', err); - } - }, []); - - // Check and redeem all pending mint quotes - const checkAndRedeemPendingQuotes = useCallback(async () => { - if (!managerRef.current || !repositoriesRef.current) return; - - try { - console.log('🔍 Checking for pending mint quotes in IndexedDB...'); - - // Access the mint quotes repository directly - const mintQuotesRepo = (repositoriesRef.current as { mintQuoteRepository?: { getPendingMintQuotes: () => Promise>> } })?.mintQuoteRepository; - if (!mintQuotesRepo) { - console.log('⚠️ Mint quotes repository not available'); - return; - } - - // Get all pending mint quotes (non-ISSUED quotes) - const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes(); - console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`); - - // Filter for UNPAID quotes (these might have been paid but not redeemed) - const unpaidQuotes = pendingQuotes.filter((q: { state?: string }) => q.state === 'UNPAID'); - console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`); - - let claimedCount = 0; - - for (const quote of unpaidQuotes) { - try { - const q = quote as { quote: string; mintUrl: string; amount: number }; - console.log(`🔄 Attempting to redeem quote ${q.quote} from ${q.mintUrl}...`); - await (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise } }).quotes.redeemMintQuote(q.mintUrl, q.quote); - claimedCount++; - console.log(`✅ Successfully claimed ${q.amount} sats from quote ${q.quote}`); - } catch { - const q = quote as { quote: string }; - // Quote not paid yet or already claimed - this is expected, just skip - console.log(`⏭️ Quote ${q.quote} not ready yet (invoice not paid or already claimed)`); - } - } - - if (claimedCount > 0) { - console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`); - // Call refreshBalances directly without dependency to avoid circular dependency - try { - console.log('🔄 refreshBalances: Getting balances from wallet...'); - const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); - console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - - // Only update state if balances actually changed (deep comparison) - setBalances(prevBalances => { - const hasChanged = - Object.keys(newBalances).length !== Object.keys(prevBalances).length || - Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); - - if (hasChanged) { - console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); - return newBalances; - } else { - console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); - return prevBalances; - } - }); - } catch (err) { - console.error('❌ refreshBalances: Failed to refresh balances:', err); - } - } - } catch (err) { - console.error('❌ Error checking pending quotes:', err); - } - }, []); // Remove refreshBalances dependency to break the circular dependency - - // Initialize the manager - const initializeManager = useCallback(async () => { - if (isInitialized || isLoading) return; - - setIsLoading(true); - setError(null); - - try { - await loadCocoCashu(); - - // Generate or retrieve mnemonic - let currentMnemonic = mnemonic; - if (!currentMnemonic) { - currentMnemonic = bip39.generateMnemonic(wordlist); - setMnemonicState(currentMnemonic); - } - - // Create seed from mnemonic - const seed = bip39.mnemonicToSeedSync(currentMnemonic); - - // Initialize repositories - const repositories = new (IndexedDbRepositories as new (options: Record) => { init: () => Promise })({}); - await repositories.init(); - repositoriesRef.current = repositories; - - // Initialize manager - const manager = new (Manager as new ( - repositories: unknown, - seedGetter: () => Promise, - logger?: unknown - ) => { - wallet: { getBalances: () => Promise; receive: (token: string | CashuToken) => Promise; send: (mintUrl: string, amount: number) => Promise }; - mint: { addMint: (mintUrl: string) => Promise; getAllMints: () => Promise }>> }; - quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; createMeltQuote: (mintUrl: string, invoice: string) => Promise; payMeltQuote: (mintUrl: string, quoteId: string) => Promise }; - })( - repositories, - async () => seed, - new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' }) - ); - managerRef.current = manager; - - // Load initial data - call functions directly to avoid circular dependencies - try { - console.log('🔄 refreshBalances: Getting balances from wallet...'); - const newBalances = await manager.wallet.getBalances(); - console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - - // Only update state if balances actually changed (deep comparison) - setBalances(prevBalances => { - const hasChanged = - Object.keys(newBalances).length !== Object.keys(prevBalances).length || - Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); - - if (hasChanged) { - console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); - return newBalances; - } else { - console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); - return prevBalances; - } - }); - } catch (err) { - console.error('❌ refreshBalances: Failed to refresh balances:', err); - } - - try { - const mintList = await manager.mint.getAllMints(); - const formattedMints = mintList - .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url - .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ - url: mint.mintUrl, // Map mintUrl to url for consistency - name: mint.name, - info: mint.mintInfo - })); - setMints(formattedMints); - } catch (err) { - console.error('Failed to refresh mints:', err); - } - - // Check for any pending quotes that might have been paid - try { - console.log('🔍 Checking for pending mint quotes in IndexedDB...'); - - // Access the mint quotes repository directly - const mintQuotesRepo = (repositories as { mintQuoteRepository?: { getPendingMintQuotes: () => Promise>> } })?.mintQuoteRepository; - if (mintQuotesRepo) { - // Get all pending mint quotes (non-ISSUED quotes) - const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes(); - console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`); - - // Filter for UNPAID quotes (these might have been paid but not redeemed) - const unpaidQuotes = pendingQuotes.filter((q: { state?: string }) => q.state === 'UNPAID'); - console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`); - - let claimedCount = 0; - - for (const quote of unpaidQuotes) { - try { - const q = quote as { quote: string; mintUrl: string; amount: number }; - console.log(`🔄 Attempting to redeem quote ${q.quote} from ${q.mintUrl}...`); - await manager.quotes.redeemMintQuote(q.mintUrl, q.quote); - claimedCount++; - console.log(`✅ Successfully claimed ${q.amount} sats from quote ${q.quote}`); - } catch { - const q = quote as { quote: string }; - // Quote not paid yet or already claimed - this is expected, just skip - console.log(`⏭️ Quote ${q.quote} not ready yet (invoice not paid or already claimed)`); - } - } - - if (claimedCount > 0) { - console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`); - // Refresh balances after claiming quotes - try { - console.log('🔄 refreshBalances: Getting balances from wallet...'); - const newBalances = await manager.wallet.getBalances(); - console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); - - // Only update state if balances actually changed (deep comparison) - setBalances(prevBalances => { - const hasChanged = - Object.keys(newBalances).length !== Object.keys(prevBalances).length || - Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]); - - if (hasChanged) { - console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); - return newBalances; - } else { - console.log('⏭️ refreshBalances: Balances unchanged, skipping state update'); - return prevBalances; - } - }); - } catch (err) { - console.error('❌ refreshBalances: Failed to refresh balances:', err); - } - } - } else { - console.log('⚠️ Mint quotes repository not available'); - } - } catch (err) { - console.error('❌ Error checking pending quotes:', err); - } - - setIsInitialized(true); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet'; - setError(errorMessage); - console.error('Cashu initialization error:', err); - } finally { - setIsLoading(false); - } - }, [isInitialized, isLoading, mnemonic, setMnemonicState]); // Remove function dependencies to break circular dependency - - // Initialize on mount and when mnemonic changes - useEffect(() => { - initializeManager(); - }, [initializeManager]); - - // Wallet operations - const receive = useCallback(async (token: string | CashuToken) => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - await (managerRef.current as { wallet: { receive: (token: string | CashuToken) => Promise } }).wallet.receive(token); - await refreshBalances(); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to receive token'; - setError(errorMessage); - throw err; - } - }, [refreshBalances]); - - const send = useCallback(async (mintUrl: string, amount: number): Promise => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - const token = await (managerRef.current as { wallet: { send: (mintUrl: string, amount: number) => Promise } }).wallet.send(mintUrl, amount); - await refreshBalances(); - - // Encode the token into a Cashu token string - const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token); - return encodedToken; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens'; - setError(errorMessage); - throw err; - } - }, [refreshBalances]); - - const getBalances = useCallback(async (): Promise => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - return await (managerRef.current as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to get balances'; - setError(errorMessage); - throw err; - } - }, []); - - const getProofs = useCallback(async (mintUrl: string): Promise> => { - if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized'); - - try { - console.log('🔍 Getting proofs from wallet for mint:', mintUrl); - - // Access the proof repository - const proofRepo = (repositoriesRef.current as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise>> } })?.proofRepository; - if (!proofRepo) { - throw new Error('Proof repository not available'); - } - - // Get ready proofs for this mint (proofs available to spend) - const readyProofs = await proofRepo.getReadyProofs(mintUrl); - console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`); - - return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs'; - console.error('❌ Error getting proofs:', err); - setError(errorMessage); - throw err; - } - }, []); - - // Mint operations - const addMint = useCallback(async (mintUrl: string) => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - await (managerRef.current as { mint: { addMint: (mintUrl: string) => Promise } }).mint.addMint(mintUrl); - await refreshMints(); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to add mint'; - setError(errorMessage); - throw err; - } - }, [refreshMints]); - - const removeMint = useCallback(async (_mintUrl: string) => { - // Note: coco-cashu doesn't have a direct remove mint method - // This would need to be implemented at the repository level - setError('Remove mint functionality not yet implemented'); - throw new Error('Remove mint functionality not yet implemented'); - }, []); - - const getMints = useCallback(async (): Promise => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - const mintList = await (managerRef.current as { mint: { getAllMints: () => Promise }>> } }).mint.getAllMints(); - return mintList - .filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url - .map((mint: { mintUrl: string; name?: string; mintInfo?: Record }) => ({ - url: mint.mintUrl, // Map mintUrl to url for consistency - name: mint.name, - info: mint.mintInfo - })); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to get mints'; - setError(errorMessage); - throw err; - } - }, []); - - // Quote operations - const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - const quote = await (managerRef.current as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise } }).quotes.createMintQuote(mintUrl, amount); - return { - quote: quote.quote, - request: quote.request, - expiry: quote.expiry - }; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote'; - setError(errorMessage); - throw err; - } - }, []); - - const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId); - console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length); - console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl); - - await (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise } }).quotes.redeemMintQuote(mintUrl, quoteId); - console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...'); - await refreshBalances(); - } catch (err) { - console.error('❌ redeemMintQuote: Error details:', { - message: err instanceof Error ? err.message : 'Unknown error', - mintUrl, - quoteId, - quoteIdType: typeof quoteId, - quoteIdLength: quoteId.length - }); - const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote'; - setError(errorMessage); - throw err; - } - }, [refreshBalances]); - - // Add this implementation in the useCashu function - const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => { - if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId }); - - // Access the mint quote repository - const mintQuoteRepo = (repositoriesRef.current as { - mintQuoteRepository?: { - addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise - } - })?.mintQuoteRepository; - - if (!mintQuoteRepo) { - throw new Error('Mint quote repository not available'); - } - - // Add the quote to the repository with UNPAID state - // The mint processor will check and redeem it - await mintQuoteRepo.addMintQuote({ - quote: quoteId, - mintUrl: mintUrl, - state: 'UNPAID', // Mark as UNPAID so coco will check it - }); - - console.log('✅ Mint quote added to repository successfully'); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote'; - console.error('❌ Error adding mint quote:', err); - setError(errorMessage); - throw err; - } - }, []); - - const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - const quote = await (managerRef.current as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise } }).quotes.createMeltQuote(mintUrl, invoice); - return { - quote: quote.quote, - request: quote.request, - expiry: quote.expiry - }; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote'; - setError(errorMessage); - throw err; - } - }, []); - - const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => { - if (!managerRef.current) throw new Error('Wallet not initialized'); - - try { - setError(null); - await (managerRef.current as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise } }).quotes.payMeltQuote(mintUrl, quoteId); - await refreshBalances(); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote'; - setError(errorMessage); - throw err; - } - }, [refreshBalances]); - - // Mnemonic operations - const setMnemonic = useCallback((newMnemonic: string) => { - if (!bip39.validateMnemonic(newMnemonic, wordlist)) { - throw new Error('Invalid mnemonic'); - } - setMnemonicState(newMnemonic); - // Reinitialize manager with new mnemonic - setIsInitialized(false); - // Don't call initializeManager directly to avoid circular dependency - // The useEffect will handle reinitialization when isInitialized changes - }, [setMnemonicState]); - - const generateMnemonic = useCallback(() => { - return bip39.generateMnemonic(wordlist); - }, []); - - const getMnemonic = useCallback(() => { - return mnemonic; - }, [mnemonic]); - - const clearError = useCallback(() => { - setError(null); - }, []); - - // History operations - const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise => { - if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized'); - - try { - console.log('📜 Getting transaction history...'); - - // Access the history repository (correct property name is historyRepository) - const historyRepo = (repositoriesRef.current as { historyRepository?: { getPaginatedHistoryEntries: (limit: number, offset: number) => Promise>> } })?.historyRepository; - if (!historyRepo) { - throw new Error('History repository not available'); - } - - // Get paginated history entries - const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset); - console.log(`✅ Found ${entries.length} history entries`); - - return entries as unknown as HistoryEntry[]; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to get history'; - console.error('❌ Error getting history:', err); - setError(errorMessage); - throw err; - } - }, []); - - return { - // State - isInitialized, - isLoading, - error, - balances, - mints, - mnemonic, - - // Actions - receive, - send, - getBalances, - getProofs, - addMint, - removeMint, - getMints, - createMintQuote, - redeemMintQuote, - createMeltQuote, - payMeltQuote, - setMnemonic, - generateMnemonic, - getMnemonic, - getHistory, - refreshBalances, - refreshMints, - checkAndRedeemPendingQuotes, - clearError, - addMintQuote, - }; -}