code cleanup

This commit is contained in:
lemonknowsall committed 2025-10-13 16:52:25 -07:00
1 parent dd3f4465c5
commit 5ce402105c
13 files changed
+277 -1042

No files matched your search

+11 -80
View File
@@ -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",
+21 -3
View File
@@ -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<number | null>(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 (
<div className="text-center py-2">
@@ -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
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{convertCurrency(breakdown.totalBalance)}
{breakdown.totalBalance.toLocaleString()} sats
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
+223 -78
View File
@@ -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<CashuBalance>({});
const [mints, setMints] = useState<CashuMint[]>([]);
// 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,
};
}
-204
View File
@@ -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<void>;
getBalances: () => Promise<CashuBalance>;
convertCurrency: (sats: number, showSats?: boolean) => string;
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
}
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
const [balances, setBalances] = useState<CashuBalance>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(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<CashuBalance> } }).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<CashuBalance> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
return await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).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>) => () => void }).on('proofs:saved', () => {
console.log('📨 Proofs saved, refreshing balances...');
refreshBalances();
});
const unsubscribeProofsStateChanged = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => 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>) => () => 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<CashuBalance> } }).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>) => () => 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<string> => {
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,
};
}
-42
View File
@@ -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<HistoryEntry[]>;
}
export function useCashuHistory(manager: unknown | null): UseCashuHistoryReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise<HistoryEntry[]> => {
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<unknown[]> } }).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,
};
}
-3
View File
@@ -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);
}
@@ -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<void>;
disableMintQuoteWatcher: () => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
disableMintQuoteProcessor: () => Promise<void>;
waitForMintQuoteProcessor: () => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
disableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => 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<void> }).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<void> }).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<void> }).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<void> }).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<void> }).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<void> }).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<void> }).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<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => 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<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return (manager as { once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => 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<void>) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
(manager as { off: (event: string, handler: (payload: unknown) => void | Promise<void>) => 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,
};
}
-174
View File
@@ -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<void>;
getMints: () => Promise<CashuMint[]>;
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
}
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
const [mints, setMints] = useState<CashuMint[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const refreshMints = useCallback(async () => {
if (!manager) return;
try {
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).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<string, unknown> }) => ({
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<unknown> } }).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<CashuMint[]> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
const mintList = await (manager as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).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<string, unknown> }) => ({
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<unknown> } }).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>) => () => void }).on('mint:added', () => {
console.log('➕ Mint added, refreshing mints...');
refreshMints();
});
const unsubscribeMintUpdated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => 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,
};
}
-156
View File
@@ -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<CashuMintQuote>;
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
}
export function useCashuQuotes(manager: unknown | null, repositories: unknown | null): UseCashuQuotesReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
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<CashuMintQuote> } }).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<void> } }).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<void>
}
})?.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<CashuMeltQuote> => {
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<CashuMeltQuote> } }).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<void> } }).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,
};
}
-43
View File
@@ -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<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
}
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<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).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<unknown> => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
return await (manager as { subscription: { awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown> } }).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,
};
}
-108
View File
@@ -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<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
}
export function useCashuWallet(manager: unknown | null, repositories: unknown | null): UseCashuWalletReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(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<void> } }).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<string> => {
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<CashuToken> } }).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<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
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<Array<Record<string, unknown>>> } })?.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,
};
}
+21
View File
@@ -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?:\/\//, '');
}
}