modular cashu hooks, wallet toggle, qr code modals

This commit is contained in:
lemonknowsall committed 2025-10-08 00:23:26 -07:00
1 parent ec465d9892
commit 22d3675f2b
12 files changed
+1537 -1051

No files matched your search

+363 -316
View File
@@ -3,13 +3,13 @@ import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useNpubCash } from '@/hooks/useNpubCash';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, CreditCard } from 'lucide-react';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode } from 'lucide-react';
import QRCode from 'qrcode';
export function CashuWallet() {
@@ -34,7 +34,6 @@ export function CashuWallet() {
addMintQuote,
refreshBalances,
refreshMints,
checkAndRedeemPendingQuotes,
clearError,
getHistory,
} = useCashu();
@@ -52,6 +51,8 @@ export function CashuWallet() {
} = useNpubCash();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
// ============================================================================
// STATE - Input Values
@@ -70,8 +71,7 @@ export function CashuWallet() {
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [receiveMode, setReceiveMode] = useState<'tokens' | 'lightning'>('tokens');
const [sendMode, setSendMode] = useState<'tokens' | 'lightning'>('tokens');
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
// ============================================================================
@@ -80,14 +80,6 @@ export function CashuWallet() {
const [sentToken, setSentToken] = useState<string | null>(null);
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
const [pendingQuotes, setPendingQuotes] = useLocalStorage<Array<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
timestamp: number;
qrCodeUrl?: string;
}>>('cashu-pending-quotes', []);
// ============================================================================
// STATE - Copy Feedback
@@ -111,12 +103,24 @@ export function CashuWallet() {
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningQR, setShowLightningQR] = useState(false);
const [lightningQRCode, setLightningQRCode] = useState<string>('');
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
} | null>(null);
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// HELPER FUNCTIONS - Display
@@ -158,6 +162,31 @@ export function CashuWallet() {
}
};
// Generate QR code for Lightning address
const generateLightningQRCode = async () => {
if (!lightningAddress) return;
try {
const qrCodeUrl = await QRCode.toDataURL(lightningAddress, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
setLightningQRCode(qrCodeUrl);
setShowLightningQR(true);
} catch (err) {
console.error('Failed to generate Lightning address QR code:', err);
toast({
variant: "destructive",
title: "QR Code Failed",
description: "Failed to generate QR code for Lightning address",
});
}
};
// ============================================================================
// HELPER FUNCTIONS - QR Code
@@ -267,18 +296,24 @@ export function CashuWallet() {
// ============================================================================
const handleReceive = async () => {
if (receiveMode === 'tokens') {
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
await receive(tokenInput);
setTokenInput('');
const message = 'Token received successfully!';
console.log('✅', message);
alert(message);
console.log('✅ Token received successfully!');
toast({
title: "Token Received",
description: "Cashu token redeemed successfully!",
});
} catch (err) {
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Receive Failed",
description: errorMessage,
});
}
} else {
// Lightning mode - create mint quote
@@ -286,9 +321,12 @@ export function CashuWallet() {
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
const message = 'Please enter a valid amount';
console.warn('⚠️', message);
alert(message);
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const quote = await createMintQuote(activeMintUrl, amount);
@@ -296,26 +334,32 @@ export function CashuWallet() {
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCodeForQuote(quote.request);
// Save the pending quote with QR code
setPendingQuotes(prev => [...prev, {
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
timestamp: Date.now(),
qrCodeUrl
}]);
});
setShowInvoiceModal(true);
const message = `Mint quote created! Request: ${quote.request}`;
console.log('✅', message);
console.log('💰 Quote object:', quote);
console.log('✅ Mint quote created:', quote);
console.log('🔗 Lightning Invoice:', quote.request);
alert('Lightning invoice created! After paying, click the refresh button (🔄) to claim your tokens.');
console.log('💡 Coco will automatically redeem when payment is detected');
toast({
title: "Lightning Invoice Created",
description: "Coco will automatically claim your tokens when payment is detected.",
});
setQuoteAmount('');
} catch (err) {
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Quote Creation Failed",
description: errorMessage,
});
}
}
};
@@ -325,14 +369,17 @@ export function CashuWallet() {
// ============================================================================
const handleSend = async () => {
if (sendMode === 'tokens') {
if (mode === 'tokens') {
if (!sendAmount || !activeMintUrl) return;
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
const message = 'Please enter a valid amount';
console.warn('⚠️', message);
alert(message);
console.warn('⚠️ Invalid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const encodedToken = await send(activeMintUrl, amount);
@@ -343,7 +390,11 @@ export function CashuWallet() {
} catch (err) {
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Send Failed",
description: errorMessage,
});
}
} else {
// Lightning mode
@@ -357,7 +408,11 @@ export function CashuWallet() {
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
alert('Please enter a valid amount');
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
@@ -374,19 +429,25 @@ export function CashuWallet() {
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning payment sent successfully!');
alert(`Successfully sent ${amount} sats to ${pendingLightningAddress}!`);
toast({
title: "Payment Sent",
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
// Refresh balances
await refreshBalances();
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Payment Failed",
description: errorMessage,
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
@@ -408,15 +469,21 @@ export function CashuWallet() {
await payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('✅ Lightning invoice paid successfully!');
alert('Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.');
toast({
title: "Invoice Paid",
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
});
setLightningInvoice('');
// Refresh balances to show updated amounts
await refreshBalances();
// No need to manually refresh balances - events will handle it automatically
} catch (err) {
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Invoice Payment Failed",
description: errorMessage,
});
}
}
}
@@ -439,7 +506,11 @@ export function CashuWallet() {
}
} catch (err) {
console.error('Failed to copy to clipboard:', err);
alert('Failed to copy to clipboard');
toast({
variant: "destructive",
title: "Copy Failed",
description: "Failed to copy to clipboard",
});
}
};
@@ -459,17 +530,20 @@ export function CashuWallet() {
await addMint(normalizedUrl);
setMintUrl('');
// Explicitly refresh mints and balances
await refreshMints();
await refreshBalances();
const message = `Mint added successfully: ${normalizedUrl}`;
console.log('✅', message);
alert('Mint added successfully!');
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint added successfully:', normalizedUrl);
toast({
title: "Mint Added",
description: "Mint added successfully!",
});
} catch (err) {
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
toast({
variant: "destructive",
title: "Add Mint Failed",
description: errorMessage,
});
}
};
@@ -477,25 +551,6 @@ export function CashuWallet() {
// EVENT HANDLERS - Quote Management
// ============================================================================
const handleClaimQuote = async (quoteId: string, mintUrl: string) => {
try {
console.log('🎯 Attempting to claim quote:', quoteId, 'from mint:', mintUrl);
await redeemMintQuote(mintUrl, quoteId);
// Remove from pending quotes
setPendingQuotes(prev => prev.filter(q => q.quoteId !== quoteId));
// Refresh balances
await refreshBalances();
console.log('✅ Quote claimed successfully!');
alert('Tokens claimed successfully! Your balance has been updated.');
} catch (err) {
const errorMessage = `Failed to claim tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err);
alert(errorMessage);
}
};
// Claim npub.cash quotes
const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => {
@@ -522,17 +577,20 @@ export function CashuWallet() {
console.log('✅ Quote added to coco-cashu successfully');
console.log('💡 Coco will automatically redeem when mint processor runs');
// Trigger the mint processor to check and redeem the quote
await checkAndRedeemPendingQuotes();
// Refresh quotes and balances
// Refresh quotes (balances will be updated automatically via events)
await fetchQuotes();
await refreshBalances();
alert(`Successfully claimed ${quote.amount} sats!`);
toast({
title: "Quote Claimed",
description: `Successfully claimed ${quote.amount} sats!`,
});
} catch (err) {
console.error('Failed to claim npub.cash quote:', err);
alert(`Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`);
toast({
variant: "destructive",
title: "Claim Failed",
description: `Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`,
});
}
};
const handleShowDenominations = async (mintUrl: string) => {
@@ -544,7 +602,11 @@ export function CashuWallet() {
console.log('💰 Raw proofs for mint:', proofs);
if (!proofs || proofs.length === 0) {
alert('No tokens found for this mint');
toast({
variant: "destructive",
title: "No Tokens",
description: "No tokens found for this mint",
});
return;
}
@@ -568,7 +630,11 @@ export function CashuWallet() {
} catch (err) {
console.error('Failed to get denominations:', err);
alert('Failed to get token denominations. Check console for details.');
toast({
variant: "destructive",
title: "Failed to Get Denominations",
description: "Failed to get token denominations. Check console for details.",
});
}
};
@@ -576,18 +642,39 @@ export function CashuWallet() {
// EFFECTS
// ============================================================================
// Auto-select active mint when mints or balances change
// Show error toasts when errors occur
useEffect(() => {
if (error) {
toast({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "npub.cash Error",
description: npubCashError,
action: npubCashError.includes('Authorization') ? (
<Button variant="outline" size="sm" onClick={retryAuth}>
Retry Auth
</Button>
) : undefined,
});
}
}, [npubCashError, toast, retryAuth]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Find mint with highest balance, or first mint if balances are equal
const mintWithHighestBalance = mints.reduce((highest, current) => {
const currentBalance = balances[current.url] || 0;
const highestBalance = balances[highest.url] || 0;
return currentBalance > highestBalance ? current : highest;
});
handleSetActiveMint(mintWithHighestBalance.url);
// Select first mint initially - user can change via dropdown
handleSetActiveMint(mints[0].url);
}
}, [mints, activeMintUrl, balances, handleSetActiveMint]);
}, [mints, activeMintUrl, handleSetActiveMint]);
// Load transaction history when wallet is initialized
useEffect(() => {
@@ -596,27 +683,6 @@ export function CashuWallet() {
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Generate QR codes for existing pending quotes that don't have them
useEffect(() => {
const generateMissingQRCodes = async () => {
const quotesNeedingQR = pendingQuotes.filter(quote => !quote.qrCodeUrl);
if (quotesNeedingQR.length === 0) return;
const updatedQuotes = await Promise.all(
pendingQuotes.map(async (quote) => {
if (!quote.qrCodeUrl) {
const qrCodeUrl = await generateQRCodeForQuote(quote.invoice);
return { ...quote, qrCodeUrl };
}
return quote;
})
);
setPendingQuotes(updatedQuotes);
};
generateMissingQRCodes();
}, []); // Only run once on mount
// ============================================================================
// RENDER - Loading State
@@ -680,18 +746,41 @@ export function CashuWallet() {
size="icon"
onClick={async () => {
console.log('🔄 Manual refresh triggered');
await checkAndRedeemPendingQuotes();
await refreshBalances();
await loadHistory();
await refreshNpubCash();
console.log('💰 Current balances after manual refresh:', balances);
console.log('💰 Current balances (auto-updated via events):', balances);
}}
className="mt-2"
title="Check for paid invoices and refresh balances and history"
title="Refresh history and npub.cash data"
>
<RefreshCw className="h-5 w-5" />
</Button>
</div>
{/* Main Mode Toggle */}
<div className="mt-4 flex items-center justify-center">
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setMode('tokens')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-4 w-4" />
Cashu
</button>
<button
onClick={() => setMode('lightning')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-4 w-4" />
Lightning
</button>
</div>
</div>
{/* Active Mint Dropdown and Balance */}
<div className="mt-3 flex items-center justify-center gap-4">
<DropdownMenu>
@@ -753,82 +842,49 @@ export function CashuWallet() {
)}
</div>
{/* npub.cash Lightning Address */}
{/* Lightning Address */}
{lightningAddress && (
<div className="mt-4 p-4 bg-muted/30 rounded-lg">
<div className="flex items-center justify-center gap-2 mb-2">
<CreditCard className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium text-muted-foreground">Your Lightning Address</span>
</div>
<div className="flex items-center justify-center gap-2">
<code className="bg-background px-3 py-2 rounded text-sm font-mono border">
{lightningAddress}
</code>
<div className="mt-3 flex items-center justify-center gap-2">
<code className="bg-background px-3 py-2 rounded text-sm font-mono border">
{lightningAddress}
</code>
<Button
size="sm"
variant="outline"
onClick={copyLightningAddress}
className="h-8"
>
{copiedLightningAddress ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
<Button
size="sm"
variant="outline"
onClick={generateLightningQRCode}
className="h-8"
>
<QrCode className="h-3 w-3" />
</Button>
{unclaimedAmount > 0 && (
<Button
size="sm"
variant="outline"
onClick={copyLightningAddress}
className="h-8"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
className="h-8 text-xs"
>
{copiedLightningAddress ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
{unclaimedAmount} sats
</Button>
</div>
{unclaimedAmount > 0 && (
<div className="mt-2 flex items-center justify-center gap-2">
<Badge variant="secondary" className="text-sm">
{unclaimedAmount} sats unclaimed
</Badge>
<Button
size="sm"
variant="outline"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
className="h-6 text-xs"
>
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
)}
</div>
)}
</div>
)}
{/* ========================================================================
SECTION: Error Display
======================================================================== */}
{(error || npubCashError) && (
<Alert variant="destructive" className="mb-6">
<AlertDescription className="flex items-center justify-between">
<div className="flex-1">
{error || npubCashError}
{npubCashError && npubCashError.includes('Authorization') && (
<div className="text-xs mt-1 opacity-75">
Try refreshing the page or check your Nostr extension
</div>
)}
</div>
<div className="flex gap-2">
{npubCashError && (
<Button variant="outline" size="sm" onClick={retryAuth}>
Retry Auth
</Button>
)}
<Button variant="outline" size="sm" onClick={() => {
if (error) clearError();
// npub.cash errors are handled by retryAuth
}}>
Dismiss
</Button>
</div>
</AlertDescription>
</Alert>
)}
{/* ========================================================================
SECTION: Receive & Send Cards
@@ -838,39 +894,19 @@ export function CashuWallet() {
{/* Receive Card */}
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
</div>
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setReceiveMode('tokens')}
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
receiveMode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-3.5 w-3.5" />
</button>
<button
onClick={() => setReceiveMode('lightning')}
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
receiveMode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-3.5 w-3.5" />
</button>
</div>
<CardTitle className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
</CardTitle>
<CardDescription>
{receiveMode === 'tokens'
{mode === 'tokens'
? 'Enter Cashu token to redeem'
: 'Deposit funds with Lightning'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{receiveMode === 'tokens' ? (
{mode === 'tokens' ? (
<div className="flex gap-2">
<Input
placeholder="cashuBo2Ft..."
@@ -910,32 +946,12 @@ export function CashuWallet() {
{/* Send Card */}
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
</div>
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setSendMode('tokens')}
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
sendMode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-3.5 w-3.5" />
</button>
<button
onClick={() => setSendMode('lightning')}
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
sendMode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-3.5 w-3.5" />
</button>
</div>
<CardTitle className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
</CardTitle>
<CardDescription>
{sendMode === 'tokens'
{mode === 'tokens'
? 'Generate Cashu token to send'
: pendingLightningAddress
? 'Enter the amount to send'
@@ -944,7 +960,7 @@ export function CashuWallet() {
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{sendMode === 'tokens' ? (
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
@@ -1102,91 +1118,6 @@ export function CashuWallet() {
</Card>
)}
{/* ========================================================================
SECTION: Pending Lightning Payments
======================================================================== */}
{pendingQuotes.length > 0 && (
<Card className="mt-6">
<CardHeader className="relative">
<Button
onClick={() => setPendingQuotes([])}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Bitcoin className="h-5 w-5 mr-2" />
Pending Lightning Payments
</CardTitle>
<CardDescription>
Click "Check Payment" after paying the Lightning invoice
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{pendingQuotes.map((quote) => (
<div key={quote.quoteId} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div>
<div className="font-medium">{quote.amount} sats</div>
<div className="text-sm text-muted-foreground">
{new URL(quote.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
Created: {new Date(quote.timestamp).toLocaleTimeString()}
</div>
</div>
<Button
onClick={() => handleClaimQuote(quote.quoteId, quote.mintUrl)}
size="sm"
>
Check Payment
</Button>
</div>
{/* QR Code */}
{quote.qrCodeUrl && (
<div className="flex justify-center mb-3">
<div className="bg-white dark:bg-gray-100 p-3 rounded-lg border shadow-sm">
<img
src={quote.qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-28 h-28 sm:w-32 sm:h-32 object-contain"
/>
</div>
</div>
)}
<div className="relative">
<div className="bg-muted p-4 rounded-lg border font-mono text-sm">
{quote.invoice.length > 20 ? `${quote.invoice.substring(0, 20)}...` : quote.invoice}
</div>
<Button
onClick={() => handleCopy(quote.invoice, 'invoice')}
className="absolute top-2 right-2"
size="sm"
variant="secondary"
>
{copiedInvoice === quote.invoice ? (
<>
<Check className="h-4 w-4 mr-2" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4 mr-2" />
Copy Invoice
</>
)}
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
{/* ========================================================================
SECTION: npub.cash Received Payments
@@ -1196,7 +1127,7 @@ export function CashuWallet() {
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<CreditCard className="h-5 w-5 mr-2" />
<Zap className="h-5 w-5 mr-2" />
Received Payments (npub.cash)
</div>
<Button
@@ -1420,6 +1351,122 @@ export function CashuWallet() {
</Card>
</div>
)}
{/* ========================================================================
SECTION: Lightning Address QR Code Modal
======================================================================== */}
{showLightningQR && lightningQRCode && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={() => setShowLightningQR(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<QrCode className="h-5 w-5 mr-2" />
Lightning Address QR Code
</CardTitle>
<CardDescription>
Scan to send Lightning payments
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex justify-center">
<div className="bg-white dark:bg-gray-100 p-4 rounded-lg border shadow-sm">
<img
src={lightningQRCode}
alt="Lightning Address QR Code"
className="w-64 h-64 object-contain"
/>
</div>
</div>
<div className="text-center">
<div className="bg-muted p-3 rounded-lg border font-mono text-sm break-all">
{lightningAddress}
</div>
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded text-center">
💡 Share this QR code or address to receive Lightning payments
</div>
</CardContent>
</Card>
</div>
)}
{/* ========================================================================
SECTION: Lightning Invoice Modal
======================================================================== */}
{showInvoiceModal && currentInvoice && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={() => setShowInvoiceModal(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Zap className="h-5 w-5 mr-2" />
Lightning Invoice
</CardTitle>
<CardDescription>
Pay this invoice to receive {currentInvoice.amount} sats
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex justify-center">
<div className="bg-white dark:bg-gray-100 p-4 rounded-lg border shadow-sm">
<img
src={currentInvoice.qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-64 h-64 object-contain"
/>
</div>
</div>
<div className="text-center">
<div className="bg-muted p-3 rounded-lg border font-mono text-sm break-all">
{currentInvoice.invoice}
</div>
</div>
<div className="flex gap-2 justify-center">
<Button
variant="outline"
onClick={() => handleCopy(currentInvoice.invoice, 'invoice')}
className="flex items-center gap-2"
>
{copiedInvoice === currentInvoice.invoice ? (
<>
<Check className="h-4 w-4" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4" />
Copy Invoice
</>
)}
</Button>
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded text-center">
💡 Coco will automatically claim your tokens when payment is detected
</div>
</CardContent>
</Card>
</div>
)}
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import { useMemo } from 'react';
import { useCashuManager } from './useCashuManager';
import { useCashuBalances } from './useCashuBalances';
import { useCashuMints } from './useCashuMints';
import { useCashuQuotes } from './useCashuQuotes';
import { useCashuWallet } from './useCashuWallet';
import { useCashuHistory } from './useCashuHistory';
import { useCashuSubscriptions } from './useCashuSubscriptions';
import { useCashuManagerOperations } from './useCashuManagerOperations';
import { UseCashuReturn, CashuWalletError } from './types';
export function useCashu(): UseCashuReturn {
const manager = useCashuManager();
const balances = useCashuBalances(manager.manager);
const mints = useCashuMints(manager.manager);
const quotes = useCashuQuotes(manager.manager, manager.repositories);
const wallet = useCashuWallet(manager.manager, manager.repositories);
const history = useCashuHistory(manager.manager);
const subscriptions = useCashuSubscriptions(manager.manager);
const managerOperations = useCashuManagerOperations(manager.manager);
// Combine all errors into a single error state
const combinedError = useMemo(() => {
const errors = [
manager.error,
balances.error,
mints.error,
quotes.error,
wallet.error,
history.error,
subscriptions.error,
managerOperations.error,
].filter(Boolean) as CashuWalletError[];
return errors.length > 0 ? errors[0] : null;
}, [manager.error, balances.error, mints.error, quotes.error, wallet.error, history.error, subscriptions.error, managerOperations.error]);
// Combine all loading states
const combinedIsLoading = useMemo(() => {
return manager.isLoading || balances.isLoading || mints.isLoading || quotes.isLoading || wallet.isLoading || history.isLoading || subscriptions.isLoading || managerOperations.isLoading;
}, [manager.isLoading, balances.isLoading, mints.isLoading, quotes.isLoading, wallet.isLoading, history.isLoading, subscriptions.isLoading, managerOperations.isLoading]);
return {
// State
isInitialized: manager.isInitialized,
isLoading: combinedIsLoading,
error: combinedError,
balances: balances.balances,
mints: mints.mints,
mnemonic: manager.mnemonic,
// Actions
// Wallet operations
receive: wallet.receive,
send: wallet.send,
getBalances: balances.getBalances,
getProofs: wallet.getProofs,
// Mint operations
addMint: mints.addMint,
removeMint: mints.removeMint,
getMints: mints.getMints,
// Quote operations
createMintQuote: quotes.createMintQuote,
redeemMintQuote: quotes.redeemMintQuote,
createMeltQuote: quotes.createMeltQuote,
payMeltQuote: quotes.payMeltQuote,
addMintQuote: quotes.addMintQuote,
// Subscription operations
awaitMintQuotePaid: subscriptions.awaitMintQuotePaid,
awaitMeltQuotePaid: subscriptions.awaitMeltQuotePaid,
// Manager operations
enableMintQuoteWatcher: managerOperations.enableMintQuoteWatcher,
disableMintQuoteWatcher: managerOperations.disableMintQuoteWatcher,
enableMintQuoteProcessor: managerOperations.enableMintQuoteProcessor,
disableMintQuoteProcessor: managerOperations.disableMintQuoteProcessor,
waitForMintQuoteProcessor: managerOperations.waitForMintQuoteProcessor,
enableProofStateWatcher: managerOperations.enableProofStateWatcher,
disableProofStateWatcher: managerOperations.disableProofStateWatcher,
// Event operations
on: managerOperations.on,
once: managerOperations.once,
off: managerOperations.off,
// Mnemonic operations
setMnemonic: manager.setMnemonic,
generateMnemonic: manager.generateMnemonic,
getMnemonic: manager.getMnemonic,
// History operations
getHistory: history.getHistory,
// Utility operations
refreshBalances: balances.refreshBalances,
refreshMints: mints.refreshMints,
clearError: manager.clearError,
};
}
+142
View File
@@ -0,0 +1,142 @@
// Error types that align with coco-cashu patterns
export class CashuWalletError extends Error {
constructor(message: string, public code: string, public details?: unknown) {
super(message);
this.name = 'CashuWalletError';
}
}
export class CashuInitializationError extends CashuWalletError {
constructor(message: string, details?: unknown) {
super(message, 'INITIALIZATION_ERROR', details);
}
}
export class CashuMintError extends CashuWalletError {
constructor(message: string, mintUrl: string, details?: unknown) {
super(message, 'MINT_ERROR', details);
this.mintUrl = mintUrl;
}
public mintUrl: string;
}
export class CashuQuoteError extends CashuWalletError {
constructor(message: string, quoteId: string, details?: unknown) {
super(message, 'QUOTE_ERROR', details);
this.quoteId = quoteId;
}
public quoteId: string;
}
export class CashuTokenError extends CashuWalletError {
constructor(message: string, token?: string, details?: unknown) {
super(message, 'TOKEN_ERROR', details);
this.token = token;
}
public token?: string;
}
// Core types
export interface CashuBalance {
[mintUrl: string]: number;
}
export interface CashuMint {
url: string;
name?: string;
info?: Record<string, unknown>;
}
export interface CashuMintQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuMeltQuote {
quote: string;
request: string;
expiry: number;
}
export interface CashuToken {
mint: string;
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
}
export interface HistoryEntry {
id: string;
type: 'mint' | 'melt' | 'send' | 'receive';
mintUrl: string;
amount: number;
unit: string;
createdAt: number;
metadata?: Record<string, unknown>;
quoteId?: string;
state?: string;
paymentRequest?: string;
token?: CashuToken;
}
// Hook state types
export interface CashuState {
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
balances: CashuBalance;
mints: CashuMint[];
mnemonic: string | null;
}
export interface CashuActions {
// Wallet operations
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getBalances: () => Promise<CashuBalance>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
// Mint operations
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getMints: () => Promise<CashuMint[]>;
// Quote operations
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>;
// Subscription operations (NEW)
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
// Manager operations (NEW)
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>;
// Event operations (NEW)
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;
// Mnemonic operations
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
// History operations
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
// Utility operations
refreshBalances: () => Promise<void>;
refreshMints: () => Promise<void>;
clearError: () => void;
}
export type UseCashuReturn = CashuState & CashuActions;
+126
View File
@@ -0,0 +1,126 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { CashuBalance, CashuWalletError } from './types';
export interface UseCashuBalancesReturn {
balances: CashuBalance;
isLoading: boolean;
error: CashuWalletError | null;
refreshBalances: () => Promise<void>;
getBalances: () => Promise<CashuBalance>;
}
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
const [balances, setBalances] = useState<CashuBalance>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 500;
const refreshBalances = useCallback(async () => {
if (!manager) return;
// Prevent concurrent calls
if (isRefreshingRef.current) {
console.log('⏭️ refreshBalances: Skipping (already in progress)');
return;
}
// Throttle rapid successive calls
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
console.log('⏭️ refreshBalances: Skipping (throttled)');
return;
}
isRefreshingRef.current = true;
lastRefreshTimeRef.current = now;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<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 unsubscribeMintQuoteRedeemed = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mintQuote:redeemed', () => {
console.log('💰 Mint quote redeemed, refreshing balances...');
refreshBalances();
});
return () => {
unsubscribeProofsSaved();
unsubscribeProofsStateChanged();
unsubscribeMintQuoteRedeemed();
};
}, [manager, refreshBalances]);
// Initial balance load
useEffect(() => {
if (manager && Object.keys(balances).length === 0) {
refreshBalances();
}
}, [manager, balances, refreshBalances]);
return {
balances,
isLoading,
error,
refreshBalances,
getBalances,
};
}
+42
View File
@@ -0,0 +1,42 @@
import { useState, useCallback } from 'react';
import { HistoryEntry, CashuWalletError } from './types';
export interface UseCashuHistoryReturn {
isLoading: boolean;
error: CashuWalletError | null;
getHistory: (limit?: number, offset?: number) => Promise<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,
};
}
+167
View File
@@ -0,0 +1,167 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useLocalStorage } from '../useLocalStorage';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
import { CashuInitializationError, CashuWalletError } from './types';
// Dynamic imports for coco-cashu packages
let Manager: unknown = null;
let IndexedDbRepositories: unknown = null;
let ConsoleLogger: unknown = null;
let getEncodedToken: unknown = null;
let _getDecodedToken: unknown = null;
// Lazy load coco-cashu packages
const loadCocoCashu = async () => {
if (Manager) return; // Already loaded
try {
const coreModule = await import('coco-cashu-core');
const indexedDbModule = await import('coco-cashu-indexeddb');
Manager = coreModule.Manager;
ConsoleLogger = coreModule.ConsoleLogger;
getEncodedToken = coreModule.getEncodedToken;
_getDecodedToken = coreModule.getDecodedToken;
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
} catch (error) {
console.error('Failed to load coco-cashu packages:', error);
throw new CashuInitializationError(
'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb',
{ error }
);
}
};
export interface UseCashuManagerReturn {
manager: unknown | null;
repositories: unknown | null;
isInitialized: boolean;
isLoading: boolean;
error: CashuWalletError | null;
mnemonic: string | null;
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
clearError: () => void;
}
export function useCashuManager(): UseCashuManagerReturn {
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance refs
const managerRef = useRef<unknown>(null);
const repositoriesRef = useRef<unknown>(null);
const clearError = useCallback(() => {
setError(null);
}, []);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
}, []);
const getMnemonic = useCallback(() => {
return mnemonic;
}, [mnemonic]);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC');
}
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
}, [setMnemonicState]);
// Initialize the manager
const initializeManager = useCallback(async () => {
if (isInitialized || isLoading) return;
setIsLoading(true);
setError(null);
try {
await loadCocoCashu();
// Generate or retrieve mnemonic
let currentMnemonic = mnemonic;
if (!currentMnemonic) {
currentMnemonic = bip39.generateMnemonic(wordlist);
setMnemonicState(currentMnemonic);
}
// Create seed from mnemonic
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
await repositories.init();
repositoriesRef.current = repositories;
// Initialize manager
const manager = new (Manager as new (
repositories: unknown,
seedGetter: () => Promise<Uint8Array>,
logger?: unknown
) => {
wallet: { getBalances: () => Promise<Record<string, number>>; receive: (token: string | unknown) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<unknown> };
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<unknown>; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>; createMeltQuote: (mintUrl: string, invoice: string) => Promise<unknown>; payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> };
history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> };
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
enableProofStateWatcher: () => Promise<void>;
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
})(
repositories,
async () => seed,
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
);
managerRef.current = manager;
// Enable built-in services for automatic quote processing and state watching
try {
await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true });
await manager.enableMintQuoteProcessor();
await manager.enableProofStateWatcher();
console.log('✅ Enabled coco-cashu watcher services');
} catch (err) {
console.warn('⚠️ Failed to enable some watcher services:', err);
// Don't fail initialization if watchers can't be enabled
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err });
setError(cashuError);
console.error('Cashu initialization error:', err);
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeManager();
}, [initializeManager]);
return {
manager: managerRef.current,
repositories: repositoriesRef.current,
isInitialized,
isLoading,
error,
mnemonic,
setMnemonic,
generateMnemonic,
getMnemonic,
clearError,
};
}
@@ -0,0 +1,147 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuManagerOperationsReturn {
isLoading: boolean;
error: CashuWalletError | null;
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<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,
};
}
+125
View File
@@ -0,0 +1,125 @@
import { useState, useEffect, useCallback } from 'react';
import { CashuMint, CashuWalletError } from './types';
export interface UseCashuMintsReturn {
mints: CashuMint[];
isLoading: boolean;
error: CashuWalletError | null;
refreshMints: () => Promise<void>;
getMints: () => Promise<CashuMint[]>;
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
}
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
}));
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) => {
// Note: coco-cashu doesn't have a direct remove mint method
// This would need to be implemented at the repository level
const error = new CashuWalletError('Remove mint functionality not yet implemented', 'REMOVE_MINT_NOT_IMPLEMENTED');
setError(error);
throw error;
}, []);
// Set up event listeners for automatic mint updates using coco events
useEffect(() => {
if (!manager) return;
const unsubscribeMintAdded = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => 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]);
return {
mints,
isLoading,
error,
refreshMints,
getMints,
addMint,
removeMint,
};
}
+156
View File
@@ -0,0 +1,156 @@
import { useState, useCallback } from 'react';
import { CashuMintQuote, CashuMeltQuote, CashuWalletError, CashuQuoteError } from './types';
export interface UseCashuQuotesReturn {
isLoading: boolean;
error: CashuWalletError | null;
createMintQuote: (mintUrl: string, amount: number) => Promise<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
@@ -0,0 +1,43 @@
import { useCallback } from 'react';
import { CashuWalletError } from './types';
export interface UseCashuSubscriptionsReturn {
isLoading: boolean;
error: CashuWalletError | null;
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<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
@@ -0,0 +1,108 @@
import { useState, useCallback } from 'react';
import { CashuToken, CashuWalletError, CashuTokenError } from './types';
// Dynamic import for getEncodedToken
let getEncodedToken: unknown = null;
const loadGetEncodedToken = async () => {
if (getEncodedToken) return;
try {
const coreModule = await import('coco-cashu-core');
getEncodedToken = coreModule.getEncodedToken;
} catch (error) {
console.error('Failed to load getEncodedToken:', error);
}
};
export interface UseCashuWalletReturn {
isLoading: boolean;
error: CashuWalletError | null;
receive: (token: string | CashuToken) => Promise<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,
};
}
+16 -735
View File
@@ -1,736 +1,17 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useLocalStorage } from './useLocalStorage';
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
// Re-export the new modular useCashu hook and types
export { useCashu } from './cashu/index';
export type {
UseCashuReturn,
CashuBalance,
CashuMint,
CashuMintQuote,
CashuMeltQuote,
CashuToken,
HistoryEntry,
CashuWalletError,
CashuInitializationError,
CashuMintError,
CashuQuoteError,
CashuTokenError
} from './cashu/types';
// Types for the hook interface
export interface CashuBalance {
[mintUrl: string]: number;
}
export interface CashuMint {
url: string;
name?: string;
info?: Record<string, unknown>;
}
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<string, unknown>;
quoteId?: string;
state?: string;
paymentRequest?: string;
token?: CashuToken;
}
export interface CashuActions {
// Wallet operations
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getBalances: () => Promise<CashuBalance>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
// Mint operations
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getMints: () => Promise<CashuMint[]>;
// Quote operations
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>;
// Mnemonic operations
setMnemonic: (mnemonic: string) => void;
generateMnemonic: () => string;
getMnemonic: () => string | null;
// History operations
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
// Utility operations
refreshBalances: () => Promise<void>;
refreshMints: () => Promise<void>;
checkAndRedeemPendingQuotes: () => Promise<void>;
clearError: () => void;
// Add mint quote (for external quotes like from npubx.cash)
addMintQuote: (mintUrl: string, quoteId: string) => Promise<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<string | null>(null);
const [balances, setBalances] = useState<CashuBalance>({});
const [mints, setMints] = useState<CashuMint[]>([]);
// Mnemonic management with localStorage
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance ref
const managerRef = useRef<unknown>(null);
const repositoriesRef = useRef<unknown>(null);
// Utility operations - defined first so they can be used in other callbacks
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 500; // Prevent refreshing more than once every 500ms
const refreshBalances = useCallback(async () => {
if (!managerRef.current) return;
// Prevent concurrent calls
if (isRefreshingRef.current) {
console.log('⏭️ refreshBalances: Skipping (already in progress)');
return;
}
// Throttle rapid successive calls
const now = Date.now();
if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) {
console.log('⏭️ refreshBalances: Skipping (throttled)');
return;
}
isRefreshingRef.current = true;
lastRefreshTimeRef.current = now;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise<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);
} finally {
isRefreshingRef.current = false;
}
}, []);
const refreshMints = useCallback(async () => {
if (!managerRef.current) return;
try {
const mintList = await (managerRef.current 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
}));
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<Array<Record<string, unknown>>> } })?.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<void> } }).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<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);
}
}
} 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<string, unknown>) => { init: () => Promise<void> })({});
await repositories.init();
repositoriesRef.current = repositories;
// Initialize manager
const manager = new (Manager as new (
repositories: unknown,
seedGetter: () => Promise<Uint8Array>,
logger?: unknown
) => {
wallet: { getBalances: () => Promise<CashuBalance>; receive: (token: string | CashuToken) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<CashuToken> };
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
quotes: { 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> };
})(
repositories,
async () => seed,
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
);
managerRef.current = manager;
// Load initial data - call functions directly to avoid circular dependencies
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await manager.wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
// Only update state if balances actually changed (deep comparison)
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ refreshBalances: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
try {
const mintList = await manager.mint.getAllMints();
const formattedMints = mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
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<Array<Record<string, unknown>>> } })?.mintQuoteRepository;
if (mintQuotesRepo) {
// Get all pending mint quotes (non-ISSUED quotes)
const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes();
console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`);
// Filter for UNPAID quotes (these might have been paid but not redeemed)
const unpaidQuotes = pendingQuotes.filter((q: { state?: string }) => q.state === 'UNPAID');
console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`);
let claimedCount = 0;
for (const quote of unpaidQuotes) {
try {
const q = quote as { quote: string; mintUrl: string; amount: number };
console.log(`🔄 Attempting to redeem quote ${q.quote} from ${q.mintUrl}...`);
await manager.quotes.redeemMintQuote(q.mintUrl, q.quote);
claimedCount++;
console.log(`✅ Successfully claimed ${q.amount} sats from quote ${q.quote}`);
} catch {
const q = quote as { quote: string };
// Quote not paid yet or already claimed - this is expected, just skip
console.log(`⏭️ Quote ${q.quote} not ready yet (invoice not paid or already claimed)`);
}
}
if (claimedCount > 0) {
console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`);
// Refresh balances after claiming quotes
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await manager.wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
// Only update state if balances actually changed (deep comparison)
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ refreshBalances: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ refreshBalances: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
}
} else {
console.log('⚠️ Mint quotes repository not available');
}
} catch (err) {
console.error('❌ Error checking pending quotes:', err);
}
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
setError(errorMessage);
console.error('Cashu initialization error:', err);
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]); // Remove function dependencies to break circular dependency
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeManager();
}, [initializeManager]);
// Wallet operations
const receive = useCallback(async (token: string | CashuToken) => {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
setError(null);
await (managerRef.current as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).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<string> => {
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<CashuToken> } }).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<CashuBalance> => {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
return await (managerRef.current as { wallet: { getBalances: () => Promise<CashuBalance> } }).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<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
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<Array<Record<string, unknown>>> } })?.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<unknown> } }).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<CashuMint[]> => {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
const mintList = await (managerRef.current 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';
setError(errorMessage);
throw err;
}
}, []);
// Quote operations
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
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<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';
setError(errorMessage);
throw err;
}
}, []);
const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
setError(null);
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
console.log('🔄 redeemMintQuote: Quote ID type:', typeof quoteId, 'length:', quoteId.length);
console.log('🔄 redeemMintQuote: Mint URL type:', typeof mintUrl);
await (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...');
await refreshBalances();
} catch (err) {
console.error('❌ redeemMintQuote: Error details:', {
message: err instanceof Error ? err.message : 'Unknown error',
mintUrl,
quoteId,
quoteIdType: typeof quoteId,
quoteIdLength: quoteId.length
});
const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote';
setError(errorMessage);
throw err;
}
}, [refreshBalances]);
// Add this implementation in the useCashu function
const addMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized');
try {
setError(null);
console.log('📝 Adding mint quote to repository:', { mintUrl, quoteId });
// Access the mint quote repository
const mintQuoteRepo = (repositoriesRef.current as {
mintQuoteRepository?: {
addMintQuote: (quote: { quote: string; mintUrl: string; state: string }) => Promise<void>
}
})?.mintQuoteRepository;
if (!mintQuoteRepo) {
throw new Error('Mint quote repository not available');
}
// Add the quote to the repository with UNPAID state
// The mint processor will check and redeem it
await mintQuoteRepo.addMintQuote({
quote: quoteId,
mintUrl: mintUrl,
state: 'UNPAID', // Mark as UNPAID so coco will check it
});
console.log('✅ Mint quote added to repository successfully');
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint quote';
console.error('❌ Error adding mint quote:', err);
setError(errorMessage);
throw err;
}
}, []);
const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise<CashuMeltQuote> => {
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<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';
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<void> } }).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<HistoryEntry[]> => {
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<Array<Record<string, unknown>>> } })?.historyRepository;
if (!historyRepo) {
throw new Error('History repository not available');
}
// Get paginated history entries
const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset);
console.log(`✅ Found ${entries.length} history entries`);
return entries as unknown as HistoryEntry[];
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
console.error('❌ Error getting history:', err);
setError(errorMessage);
throw err;
}
}, []);
return {
// State
isInitialized,
isLoading,
error,
balances,
mints,
mnemonic,
// Actions
receive,
send,
getBalances,
getProofs,
addMint,
removeMint,
getMints,
createMintQuote,
redeemMintQuote,
createMeltQuote,
payMeltQuote,
setMnemonic,
generateMnemonic,
getMnemonic,
getHistory,
refreshBalances,
refreshMints,
checkAndRedeemPendingQuotes,
clearError,
addMintQuote,
};
}