import { useState, useEffect, useCallback, useRef } from 'react'; import { useLocalStorage } from './useLocalStorage'; import * as bip39 from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; // 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; } 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 refreshBalances = useCallback(async () => { if (!managerRef.current) return; 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); setBalances(newBalances); console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); } }, []); 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); setBalances(newBalances); console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); } 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); setBalances(newBalances); console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); } 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); setBalances(newBalances); console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); } 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); 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) { const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote'; setError(errorMessage); throw err; } }, [refreshBalances]); 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, }; }