diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx index d6bd0a4..bf35794 100644 --- a/src/components/CashuWallet.tsx +++ b/src/components/CashuWallet.tsx @@ -1,8 +1,8 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { nip19 } from 'nostr-tools'; import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; -import { useCashuMints } from '@/hooks/cashu/useCashuMints'; import { useLightningAddress } from '@/hooks/useLightningAddress'; +import { getCleanMintLabel } from '@/lib/cashuUtils'; import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useToast } from '@/hooks/useToast'; @@ -46,8 +46,6 @@ export function CashuWallet() { getHistory, } = useCashu(); - const { getCleanMintLabel } = useCashuMints(null); - const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash(); const { user } = useCurrentUser(); @@ -163,7 +161,6 @@ export function CashuWallet() { // If user is logged in to npub.cash, a mint is selected, and we should sync if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) { - console.log('๐Ÿ”„ Syncing active mint with npub.cash:', mintUrl); const success = await setNpubCashMint(mintUrl); if (success) { @@ -171,10 +168,6 @@ export function CashuWallet() { title: "Mint Synced", description: "Your preferred mint has been updated on npub.cash", }); - } else { - // Don't show error toast - the hook already logs errors - // Just log that sync failed but local mint is still set - console.warn('โš ๏ธ Failed to sync mint with npub.cash, but local mint is still set'); } } }, [isNpubCashLoggedIn, setNpubCashMint, toast]); @@ -205,18 +198,15 @@ export function CashuWallet() { try { await receive(tokenInput); setTokenInput(''); - 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); toast({ variant: "destructive", title: "Receive Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } } else { @@ -225,7 +215,6 @@ export function CashuWallet() { try { const amount = parseInt(quoteAmount); if (isNaN(amount) || amount <= 0) { - console.warn('โš ๏ธ Invalid amount'); toast({ variant: "destructive", title: "Invalid Amount", @@ -249,9 +238,6 @@ export function CashuWallet() { }); setShowInvoiceModal(true); - console.log('โœ… Mint quote created:', quote); - console.log('๐Ÿ”— Lightning Invoice:', quote.request); - console.log('๐Ÿ’ก Wallet will automatically redeem when payment is detected'); toast({ title: "Lightning Invoice Created", description: "Wallet will automatically claim tokens when payment is detected.", @@ -264,18 +250,15 @@ export function CashuWallet() { mintQuoteUnsubscribeRef.current = null; } - // Listen for payment notification via mint-quote:redeemed event (note: hyphenated!) - console.log('๐Ÿ”” Setting up payment listener for quote:', quote.quote); + // Listen for payment notification via mint-quote:redeemed event const quoteId = quote.quote; const invoiceAmount = amount; const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => { const redeemedQuote = payload as { quoteId?: string }; - console.log('๐Ÿ”” Mint quote redeemed event received:', redeemedQuote); // Check if this is the quote we're waiting for if (redeemedQuote.quoteId === quoteId) { - console.log('โœ… Our quote was redeemed! Payment detected:', redeemedQuote); toast({ title: "Payment Received", description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`, @@ -292,12 +275,10 @@ export function CashuWallet() { // Store unsubscribe function for cleanup mintQuoteUnsubscribeRef.current = unsubscribe; } catch (err) { - const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`; - console.error('โŒ', errorMessage, err); toast({ variant: "destructive", title: "Quote Creation Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } } @@ -313,7 +294,6 @@ export function CashuWallet() { try { const amount = parseInt(sendAmount); if (isNaN(amount) || amount <= 0) { - console.warn('โš ๏ธ Invalid amount'); toast({ variant: "destructive", title: "Invalid Amount", @@ -324,16 +304,12 @@ export function CashuWallet() { const encodedToken = await send(activeMintUrl, amount); setSentToken(encodedToken); await generateSentTokenQRCode(encodedToken); - console.log('โœ… Token created successfully!'); - console.log('๐Ÿ“ค Encoded token:', encodedToken); setSendAmount(''); } catch (err) { - const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; - console.error('โŒ', errorMessage, err); toast({ variant: "destructive", title: "Send Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } } else { @@ -356,19 +332,14 @@ export function CashuWallet() { return; } - console.log('๐Ÿ”„ Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount); const invoice = await getLightningInvoice({ lightningAddress: pendingLightningAddress, amountSats: amount, }); - console.log('๐Ÿ”„ Creating melt quote for invoice:', invoice); const meltQuote = await createMeltQuote(activeMintUrl, invoice); - - console.log('๐Ÿ”„ Paying melt quote:', meltQuote.quote); await payMeltQuote(activeMintUrl, meltQuote.quote); - console.log('โœ… Lightning payment sent successfully!'); toast({ title: "Payment Sent", description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`, @@ -378,15 +349,11 @@ export function CashuWallet() { setPendingLightningAddress(null); setLightningAddressInput(''); setLightningAddressAmount(''); - - // 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); toast({ variant: "destructive", title: "Payment Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } } else { @@ -396,33 +363,24 @@ export function CashuWallet() { // Check if it's a Lightning address (contains @) if (input.includes('@')) { - console.log('๐Ÿ“ง Detected Lightning address:', input); setPendingLightningAddress(input); setLightningAddressInput(''); } else { // It's a regular Lightning invoice try { - console.log('๐Ÿ”„ Creating melt quote for invoice:', input); const meltQuote = await createMeltQuote(activeMintUrl, input); - - console.log('๐Ÿ”„ Paying melt quote:', meltQuote.quote); await payMeltQuote(activeMintUrl, meltQuote.quote); - console.log('โœ… Lightning invoice paid successfully!'); toast({ title: "Invoice Paid", description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.", }); setLightningInvoice(''); - - // 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); toast({ variant: "destructive", title: "Invoice Payment Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } } @@ -467,11 +425,10 @@ export function CashuWallet() { setShowRemoveMintModal(false); setMintToRemove(null); } catch (err) { - console.error('Failed to remove mint:', err); toast({ variant: "destructive", title: "Remove Failed", - description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`, + description: err instanceof Error ? err.message : 'Unknown error', }); } }, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]); @@ -492,19 +449,15 @@ export function CashuWallet() { await addMint(normalizedUrl); setMintUrl(''); - // 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); toast({ variant: "destructive", title: "Add Mint Failed", - description: errorMessage, + description: err instanceof Error ? err.message : 'Unknown error', }); } }; @@ -517,11 +470,7 @@ export function CashuWallet() { const handleShowDenominations = async (mintUrl: string) => { try { - console.log('๐Ÿ” Getting token denominations for mint:', mintUrl); - - // Get proofs from the wallet for this specific mint const proofs = await getProofs(mintUrl); - console.log('๐Ÿ’ฐ Raw proofs for mint:', proofs); if (!proofs || proofs.length === 0) { toast({ @@ -551,11 +500,10 @@ export function CashuWallet() { setShowProofBreakdown(true); } catch (err) { - console.error('Failed to get denominations:', err); toast({ variant: "destructive", title: "Failed to Get Denominations", - description: "Failed to get token denominations. Check console for details.", + description: err instanceof Error ? err.message : 'Unknown error', }); } }; @@ -590,23 +538,18 @@ export function CashuWallet() { // Mark that we've checked to prevent multiple fetches hasCheckedNpubCashRef.current = true; - console.log('๐Ÿ”„ Fetching npub.cash user info...'); const userInfo = await getNpubCashUserInfo(); if (!userInfo) return; setNpubCashUserInfo(userInfo); - console.log('๐Ÿ“‹ npub.cash user info:', userInfo); // Check if the mint from npub.cash is different from our active mint if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) { - console.log('๐Ÿ”„ npub.cash has a different preferred mint:', userInfo.mint_url); - // Check if we have this mint in our list const mintExists = mints.some(m => m.url === userInfo.mint_url); if (!mintExists) { - console.log('โž• Mint not in our list, adding it:', userInfo.mint_url); try { await addMint(userInfo.mint_url); // Wait a bit for the mint to be added @@ -614,14 +557,12 @@ export function CashuWallet() { handleSetActiveMint(userInfo.mint_url, false); }, 500); } catch (err) { - console.error('โŒ Failed to add mint from npub.cash:', err); + // Silent failure - user can manually add mint if needed } } else { // Mint exists, just set it as active (without syncing back to npub.cash) handleSetActiveMint(userInfo.mint_url, false); } - } else if (userInfo.mint_url === activeMintUrl) { - console.log('โœ… Active mint already matches npub.cash preferred mint'); } }; @@ -647,30 +588,24 @@ export function CashuWallet() { // Auto-refresh transaction history on new transactions useEffect(() => { if (!isInitialized) return; - - console.log('๐Ÿ“œ Setting up history auto-refresh listeners...'); // Listen for history updates (fires on send, receive transactions) const unsubscribeHistoryUpdated = on('history:updated', () => { - console.log('๐Ÿ“œ History updated event, refreshing...'); loadHistory(); }); // Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated) const unsubscribeMeltCreated = on('melt-quote:created', () => { - console.log('๐Ÿ“œ Melt quote created, refreshing history...'); loadHistory(); }); // Listen for melt quote paid (backup, in case creation event missed) const unsubscribeMeltPaid = on('melt-quote:paid', () => { - console.log('๐Ÿ“œ Melt quote paid, refreshing history...'); loadHistory(); }); // Listen for mint quote REDEEMED (only after invoice is paid, not created) const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => { - console.log('๐Ÿ“œ Mint quote redeemed (invoice paid), refreshing history...'); loadHistory(); }); @@ -686,7 +621,6 @@ export function CashuWallet() { useEffect(() => { return () => { if (mintQuoteUnsubscribeRef.current) { - console.log('๐Ÿงน Cleaning up mint quote listener (component unmount)'); mintQuoteUnsubscribeRef.current(); mintQuoteUnsubscribeRef.current = null; } @@ -835,7 +769,6 @@ export function CashuWallet() { onClose={() => { // Clean up event listener when modal is closed manually if (mintQuoteUnsubscribeRef.current) { - console.log('๐Ÿงน Cleaning up mint quote listener (modal closed)'); mintQuoteUnsubscribeRef.current(); mintQuoteUnsubscribeRef.current = null; } @@ -844,11 +777,9 @@ export function CashuWallet() { onExpiry={() => { // Clean up event listener when invoice expires if (mintQuoteUnsubscribeRef.current) { - console.log('๐Ÿงน Cleaning up mint quote listener (invoice expired)'); mintQuoteUnsubscribeRef.current(); mintQuoteUnsubscribeRef.current = null; } - // Show destructive toast toast({ variant: "destructive", title: "Invoice Expired", diff --git a/src/components/wallet/BalanceDisplay.tsx b/src/components/wallet/BalanceDisplay.tsx index b64adaa..b888f2f 100644 --- a/src/components/wallet/BalanceDisplay.tsx +++ b/src/components/wallet/BalanceDisplay.tsx @@ -3,8 +3,8 @@ import { Input } from '@/components/ui/input'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Wallet, ChevronDown, Plus, X, Zap, Coins, HelpCircle, QrCode, Copy, Check } from 'lucide-react'; -import { useCashuBalances } from '@/hooks/cashu/useCashuBalances'; -import { useState } from 'react'; +import { useState, useEffect } from 'react'; +import { exchangeRateService } from '@/lib/exchangeRateService'; interface CashuMint { url: string; @@ -57,8 +57,26 @@ export function BalanceDisplay({ onShowLightningAddressQR, generateQRCode, }: BalanceDisplayProps) { - const { convertCurrency } = useCashuBalances(null); const [lightningAddressCopied, setLightningAddressCopied] = useState(false); + const [btcUsdRate, setBtcUsdRate] = useState(null); + + useEffect(() => { + exchangeRateService.getBtcUsdRate() + .then(rate => setBtcUsdRate(rate)) + .catch(() => setBtcUsdRate(null)); + }, []); + + const convertCurrency = (sats: number, showSats: boolean): string => { + if (showSats) { + return `${sats.toLocaleString()} sats`; + } else if (btcUsdRate) { + const btcAmount = sats / 100000000; + const usd = btcAmount * btcUsdRate; + return `$${usd.toFixed(2)}`; + } else { + return `${sats.toLocaleString()} sats`; + } + }; return (
diff --git a/src/components/wallet/ProofBreakdownModal.tsx b/src/components/wallet/ProofBreakdownModal.tsx index 5d96df8..54ed818 100644 --- a/src/components/wallet/ProofBreakdownModal.tsx +++ b/src/components/wallet/ProofBreakdownModal.tsx @@ -2,7 +2,6 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { X, Coins } from 'lucide-react'; -import { useCashuBalances } from '@/hooks/cashu/useCashuBalances'; interface ProofBreakdown { mintUrl: string; @@ -17,8 +16,6 @@ interface ProofBreakdownModalProps { } export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) { - const { convertCurrency } = useCashuBalances(null); - if (!isOpen || !breakdown) return null; return ( @@ -50,7 +47,7 @@ export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdo
- {convertCurrency(breakdown.totalBalance)} + {breakdown.totalBalance.toLocaleString()} sats
Total Balance
diff --git a/src/hooks/cashu/index.ts b/src/hooks/cashu/index.ts index 47de08f..e1dd1a6 100644 --- a/src/hooks/cashu/index.ts +++ b/src/hooks/cashu/index.ts @@ -1,102 +1,247 @@ -import { useMemo } from 'react'; +import { useState, useEffect } 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'; +import type { UseCashuReturn, CashuBalance, CashuMint } 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[]; + const { + manager, + repositories, + isInitialized, + isLoading, + error, + mnemonic, + setMnemonic, + generateMnemonic, + getMnemonic, + clearError + } = useCashuManager(); + + const [balances, setBalances] = useState({}); + const [mints, setMints] = useState([]); + + // Auto-refresh balances and mints on manager events + useEffect(() => { + if (!manager) return; - 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]); - + const refreshBalances = async () => { + try { + const newBalances = await (manager as any).wallet.getBalances(); + setBalances(newBalances); + } catch (err) { + // Silent failure - errors are handled by the manager + } + }; + + const refreshMints = async () => { + try { + const mintList = await (manager as any).mint.getAllMints(); + setMints(mintList.map((m: any) => ({ + url: m.mintUrl, + name: m.name, + info: m.mintInfo + }))); + } catch (err) { + // Silent failure - errors are handled by the manager + } + }; + + // Initial load + refreshBalances(); + refreshMints(); + + // Listen to events + const unsubs = [ + (manager as any).on('proofs:saved', refreshBalances), + (manager as any).on('proofs:state-changed', refreshBalances), + (manager as any).on('send:created', refreshBalances), + (manager as any).on('receive:created', refreshBalances), + (manager as any).on('mint:added', refreshMints), + (manager as any).on('mint:updated', refreshMints), + ]; + + return () => unsubs.forEach(unsub => unsub()); + }, [manager]); + + // Helper to get getEncodedToken lazily + const getEncodedTokenFn = async () => { + const { getEncodedToken } = await import('coco-cashu-core'); + return getEncodedToken; + }; + + // Return direct manager access - no wrappers needed return { // State - isInitialized: manager.isInitialized, - isLoading: combinedIsLoading, - error: combinedError, - balances: balances.balances, - mints: mints.mints, - mnemonic: manager.mnemonic, + isInitialized, + isLoading, + error, + balances, + mints, + mnemonic, - // Actions - // Wallet operations - receive: wallet.receive, - send: wallet.send, - getBalances: balances.getBalances, - getProofs: wallet.getProofs, + // Wallet operations - direct manager API access + receive: async (token) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).wallet.receive(token); + }, + + send: async (mintUrl, amount) => { + if (!manager) throw new Error('Wallet not initialized'); + const token = await (manager as any).wallet.send(mintUrl, amount); + const getEncodedToken = await getEncodedTokenFn(); + return getEncodedToken(token); + }, + + getBalances: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).wallet.getBalances(); + }, + + getProofs: async (mintUrl) => { + if (!repositories) throw new Error('Wallet not initialized'); + return (repositories as any).proofRepository.getReadyProofs(mintUrl); + }, // Mint operations - addMint: mints.addMint, - removeMint: mints.removeMint, - getMints: mints.getMints, + addMint: async (mintUrl) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).mint.addMint(mintUrl); + }, + + removeMint: async (mintUrl) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).mintService.deleteMint(mintUrl); + }, + + getMints: async () => { + if (!manager) throw new Error('Wallet not initialized'); + const mintList = await (manager as any).mint.getAllMints(); + return mintList.map((m: any) => ({ + url: m.mintUrl, + name: m.name, + info: m.mintInfo + })); + }, // Quote operations - createMintQuote: quotes.createMintQuote, - redeemMintQuote: quotes.redeemMintQuote, - createMeltQuote: quotes.createMeltQuote, - payMeltQuote: quotes.payMeltQuote, - addMintQuote: quotes.addMintQuote, + createMintQuote: async (mintUrl, amount) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).quotes.createMintQuote(mintUrl, amount); + }, + + redeemMintQuote: async (mintUrl, quoteId) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).quotes.redeemMintQuote(mintUrl, quoteId); + }, + + createMeltQuote: async (mintUrl, invoice) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).quotes.createMeltQuote(mintUrl, invoice); + }, + + payMeltQuote: async (mintUrl, quoteId) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).quotes.payMeltQuote(mintUrl, quoteId); + }, + + addMintQuote: async (mintUrl, quoteId) => { + if (!repositories) throw new Error('Wallet not initialized'); + return (repositories as any).mintQuoteRepository.addMintQuote({ + quote: quoteId, + mintUrl: mintUrl, + state: 'UNPAID', + }); + }, // Subscription operations - awaitMintQuotePaid: subscriptions.awaitMintQuotePaid, - awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid, + awaitMintQuotePaid: async (mintUrl, quoteId) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).subscription.awaitMintQuotePaid(mintUrl, quoteId); + }, + + awaitMeltQuotePaid: async (mintUrl, quoteId) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).subscription.awaitMeltQuotePaid(mintUrl, quoteId); + }, // Manager operations - enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher, - disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher, - enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor, - disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor, - waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor, - enableProofStateWatcher: managerOperations.enableProofStateWatcher, - disableProofStateWatcher: managerOperations.disableProofStateWatcher, + enableMintQuoteWatcher: async (options) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).enableMintQuoteWatcher(options); + }, + + disableMintQuoteWatcher: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).disableMintQuoteWatcher(); + }, + + enableMintQuoteProcessor: async (options) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).enableMintQuoteProcessor(options); + }, + + disableMintQuoteProcessor: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).disableMintQuoteProcessor(); + }, + + waitForMintQuoteProcessor: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).waitForMintQuoteProcessor(); + }, + + enableProofStateWatcher: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).enableProofStateWatcher(); + }, + + disableProofStateWatcher: async () => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).disableProofStateWatcher(); + }, // Event operations - on: managerOperations.on, - once: managerOperations.once, - off: managerOperations.off, + on: (event, handler) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).on(event, handler); + }, - // Mnemonic operations - setMnemonic: manager.setMnemonic, - generateMnemonic: manager.generateMnemonic, - getMnemonic: manager.getMnemonic, + once: (event, handler) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).once(event, handler); + }, + + off: (event, handler) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).off(event, handler); + }, // History operations - getHistory: history.getHistory, + getHistory: async (limit = 50, offset = 0) => { + if (!manager) throw new Error('Wallet not initialized'); + return (manager as any).history.getPaginatedHistory(offset, limit); + }, // Utility operations - refreshBalances: balances.refreshBalances, - refreshMints: mints.refreshMints, - clearError: manager.clearError, + refreshBalances: async () => { + if (!manager) throw new Error('Wallet not initialized'); + const newBalances = await (manager as any).wallet.getBalances(); + setBalances(newBalances); + }, + + refreshMints: async () => { + if (!manager) throw new Error('Wallet not initialized'); + const mintList = await (manager as any).mint.getAllMints(); + setMints(mintList.map((m: any) => ({ + url: m.mintUrl, + name: m.name, + info: m.mintInfo + }))); + }, + + // Mnemonic operations + setMnemonic, + generateMnemonic, + getMnemonic, + clearError, }; } diff --git a/src/hooks/cashu/useCashuBalances.ts b/src/hooks/cashu/useCashuBalances.ts deleted file mode 100644 index da1ac53..0000000 --- a/src/hooks/cashu/useCashuBalances.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { useState, useEffect, useCallback, useRef } from 'react'; -import { CashuBalance, CashuWalletError } from './types'; -import { exchangeRateService } from '@/lib/exchangeRateService'; -import { toast } from '../useToast'; - -export interface UseCashuBalancesReturn { - balances: CashuBalance; - isLoading: boolean; - error: CashuWalletError | null; - refreshBalances: () => Promise; - getBalances: () => Promise; - convertCurrency: (sats: number, showSats?: boolean) => string; - convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise; -} - -export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn { - const [balances, setBalances] = useState({}); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - const [fallbackRate, setFallbackRate] = useState(null); - - // Throttling refs - const lastRefreshTimeRef = useRef(0); - const isRefreshingRef = useRef(false); - const REFRESH_THROTTLE_MS = 200; - - 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 unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('send:created', () => { - console.log('๐Ÿ“ค Send created, refreshing balances...'); - // Bypass throttling for send operations to ensure immediate balance update - setTimeout(async () => { - if (!manager) return; - try { - console.log('๐Ÿ”„ send:created: Getting balances from wallet...'); - const newBalances = await (manager as { wallet: { getBalances: () => Promise } }).wallet.getBalances(); - console.log('๐Ÿ’ฐ send:created: Raw balances from wallet:', newBalances); - - 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('โœ… send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints'); - return newBalances; - } else { - console.log('โญ๏ธ send:created: Balances unchanged, skipping state update'); - return prevBalances; - } - }); - } catch (err) { - console.error('โŒ send:created: Failed to refresh balances:', err); - } - }, 100); - }); - - const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise) => () => void }).on('receive:created', () => { - console.log('๐Ÿ“ฅ Receive created, refreshing balances...'); - refreshBalances(); - }); - - return () => { - unsubscribeProofsSaved(); - unsubscribeProofsStateChanged(); - unsubscribeSendCreated(); - unsubscribeReceiveCreated(); - }; - }, [manager, refreshBalances]); - - // Initial balance load - useEffect(() => { - if (manager && Object.keys(balances).length === 0) { - refreshBalances(); - } - }, [manager, balances, refreshBalances]); - - // Fetch exchange rate on mount for fallback - useEffect(() => { - exchangeRateService.getBtcUsdRate() - .then(rate => setFallbackRate(rate)) - .catch(error => { - console.warn('Failed to fetch initial exchange rate:', error); - // Keep fallbackRate as null to show sats instead of USD - }); - }, []); - - const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => { - if (showSats) { - return `${sats.toLocaleString()} sats`; - } else { - // Only show USD if we have a valid exchange rate - if (fallbackRate) { - const btcAmount = sats / 100000000; - const usd = btcAmount * fallbackRate; - return `$${usd.toFixed(2)}`; - } else { - // If no exchange rate available, show sats instead of incorrect USD - return `${sats.toLocaleString()} sats`; - } - } - }, [fallbackRate]); - - const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise => { - if (showSats) { - return `${sats.toLocaleString()} sats`; - } else { - try { - const usd = await exchangeRateService.satsToUsd(sats); - return `$${usd.toFixed(2)}`; - } catch (error) { - console.warn('Failed to fetch exchange rate:', error); - // If exchange rate fails, show sats instead of incorrect USD - return `${sats.toLocaleString()} sats`; - } - } - }, []); - - return { - balances, - isLoading, - error, - refreshBalances, - getBalances, - convertCurrency, - convertCurrencyAsync, - }; -} diff --git a/src/hooks/cashu/useCashuHistory.ts b/src/hooks/cashu/useCashuHistory.ts deleted file mode 100644 index 277d44c..0000000 --- a/src/hooks/cashu/useCashuHistory.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 index b8842e3..cc1e808 100644 --- a/src/hooks/cashu/useCashuManager.ts +++ b/src/hooks/cashu/useCashuManager.ts @@ -130,9 +130,7 @@ export function useCashuManager(): UseCashuManagerReturn { 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 } @@ -141,7 +139,6 @@ export function useCashuManager(): UseCashuManagerReturn { 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); } diff --git a/src/hooks/cashu/useCashuManagerOperations.ts b/src/hooks/cashu/useCashuManagerOperations.ts deleted file mode 100644 index b293825..0000000 --- a/src/hooks/cashu/useCashuManagerOperations.ts +++ /dev/null @@ -1,147 +0,0 @@ -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 deleted file mode 100644 index 3ede786..0000000 --- a/src/hooks/cashu/useCashuMints.ts +++ /dev/null @@ -1,174 +0,0 @@ -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; - getCleanMintLabel: (mint: { name?: string; url: string }) => string; -} - -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 - })); - - // If no mints exist, add the default mint - if (formattedMints.length === 0) { - console.log('๐Ÿ”ง No mints found, adding default mint: mint.chorus.community'); - try { - await (manager as { mint: { addMint: (mintUrl: string) => Promise } }).mint.addMint('https://mint.chorus.community'); - // The mint:added event will trigger refreshMints again, so we don't need to set mints here - return; - } catch (err) { - console.warn('โš ๏ธ Failed to add default mint:', err); - // Continue with empty mints if default mint fails - } - } - - 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) => { - if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED'); - - try { - setIsLoading(true); - setError(null); - - // Access the mintService directly through the manager to use deleteMint - // The manager has a private mintService property that we can access - const mintService = (manager as any).mintService; - if (!mintService || typeof mintService.deleteMint !== 'function') { - throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR'); - } - - await mintService.deleteMint(mintUrl); - - // No need to manually refresh - events will handle it automatically - console.log('โœ… Mint removed successfully:', mintUrl); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint'; - const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err }); - setError(cashuError); - throw cashuError; - } finally { - setIsLoading(false); - } - }, [manager]); - - // 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]); - - const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => { - if (mint.name && mint.name.trim().length > 0) { - // If name looks like a URL, strip protocol as well - return mint.name.replace(/^https?:\/\//, ''); - } - try { - return new URL(mint.url).host; // host excludes protocol and preserves port if any - } catch { - // Fallback: manual strip - return mint.url.replace(/^https?:\/\//, ''); - } - }, []); - - return { - mints, - isLoading, - error, - refreshMints, - getMints, - addMint, - removeMint, - getCleanMintLabel, - }; -} diff --git a/src/hooks/cashu/useCashuQuotes.ts b/src/hooks/cashu/useCashuQuotes.ts deleted file mode 100644 index bc0282e..0000000 --- a/src/hooks/cashu/useCashuQuotes.ts +++ /dev/null @@ -1,156 +0,0 @@ -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 deleted file mode 100644 index 8ce9a05..0000000 --- a/src/hooks/cashu/useCashuSubscriptions.ts +++ /dev/null @@ -1,43 +0,0 @@ -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 deleted file mode 100644 index b504765..0000000 --- a/src/hooks/cashu/useCashuWallet.ts +++ /dev/null @@ -1,108 +0,0 @@ -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/lib/cashuUtils.ts b/src/lib/cashuUtils.ts new file mode 100644 index 0000000..14df599 --- /dev/null +++ b/src/lib/cashuUtils.ts @@ -0,0 +1,21 @@ +/** + * Cashu wallet utility functions + */ + +/** + * Get a clean, readable label for a mint + * Strips protocol and uses hostname + */ +export function getCleanMintLabel(mint: { name?: string; url: string }): string { + if (mint.name && mint.name.trim().length > 0) { + // If name looks like a URL, strip protocol as well + return mint.name.replace(/^https?:\/\//, ''); + } + try { + return new URL(mint.url).host; // host excludes protocol and preserves port if any + } catch { + // Fallback: manual strip + return mint.url.replace(/^https?:\/\//, ''); + } +} +