modals and mint removal

This commit is contained in:
lemonknowsall committed 2025-10-09 21:19:02 -07:00
1 parent 22d3675f2b
commit a8faa03b49
4 files changed
+368 -165

No files matched your search

+198 -157
View File
@@ -1,7 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
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';
@@ -9,7 +8,8 @@ import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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, QrCode } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode, AlertTriangle } from 'lucide-react';
import QRCode from 'qrcode';
export function CashuWallet() {
@@ -27,6 +27,7 @@ export function CashuWallet() {
send,
getProofs,
addMint,
removeMint,
createMintQuote,
createMeltQuote,
payMeltQuote,
@@ -115,6 +116,12 @@ export function CashuWallet() {
invoice: string;
qrCodeUrl: string;
} | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
const [mintToRemove, setMintToRemove] = useState<{
url: string;
name?: string;
} | null>(null);
// ============================================================================
// COMPUTED VALUES
@@ -162,39 +169,13 @@ 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
// HELPER FUNCTIONS - QR Code Generation
// ============================================================================
const generateQRCodeForQuote = async (invoice: string): Promise<string> => {
const generateQRCode = async (text: string): Promise<string> => {
try {
return await QRCode.toDataURL(invoice, {
return await QRCode.toDataURL(text, {
width: 256,
margin: 2,
color: {
@@ -204,10 +185,28 @@ export function CashuWallet() {
});
} catch (err) {
console.error('Failed to generate QR code:', err);
toast({
variant: "destructive",
title: "QR Code Failed",
description: "Failed to generate QR code",
});
return '';
}
};
// Generate QR code for Lightning address
const generateLightningQRCode = async () => {
if (!lightningAddress) return;
try {
const qrCodeUrl = await generateQRCode(lightningAddress);
setLightningQRCode(qrCodeUrl);
setShowLightningQR(true);
} catch (err) {
console.error('Failed to generate Lightning address QR code:', err);
}
};
// ============================================================================
// HELPER FUNCTIONS - Mint Management
// ============================================================================
@@ -332,7 +331,7 @@ export function CashuWallet() {
const quote = await createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCodeForQuote(quote.request);
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
@@ -514,6 +513,47 @@ export function CashuWallet() {
}
};
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove) return;
try {
await removeMint(mintToRemove.url);
// Manually refresh mints since there's no mint:removed event
await refreshMints();
// If the removed mint was the active mint, select the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(m => m.url !== mintToRemove.url);
if (remainingMints.length > 0) {
setActiveMintUrl(remainingMints[0].url);
} else {
setActiveMintUrl(null);
}
}
toast({
title: "Mint Removed",
description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`,
});
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: "destructive",
title: "Remove Failed",
description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`,
});
}
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
@@ -685,48 +725,57 @@ export function CashuWallet() {
// ============================================================================
// RENDER - Loading State
// RENDER - Loading Modal
// ============================================================================
if (isLoading) {
const LoadingModal = () => {
if (!isLoading) return null;
return (
<div className="flex items-center justify-center min-h-screen">
<Card className="border-0 shadow-none bg-muted/30">
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
<Card className="border-0 shadow-lg bg-background">
<CardContent className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin mr-2" />
<span>Initializing...</span>
<Loader2 className="h-8 w-8 animate-spin mr-3" />
<span className="text-lg font-medium">Loading</span>
</CardContent>
</Card>
</div>
);
}
};
// ============================================================================
// RENDER - Uninitialized State
// RENDER - Uninitialized State Modal
// ============================================================================
if (!isInitialized) {
const UninitializedModal = () => {
if (isInitialized) return null;
return (
<Card className="w-full max-w-2xl mx-auto">
<CardHeader>
<CardTitle className="flex items-center">
<Wallet className="h-5 w-5 mr-2" />
Cashu Wallet
</CardTitle>
<CardDescription>
Failed to initialize wallet. Please check the console for errors.
</CardDescription>
</CardHeader>
</Card>
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader>
<CardTitle className="flex items-center">
<Wallet className="h-5 w-5 mr-2" />
Cashu Wallet
</CardTitle>
<CardDescription>
Failed to initialize wallet. Please check the console for errors.
</CardDescription>
</CardHeader>
</Card>
</div>
);
}
};
// ============================================================================
// RENDER - Main UI
// ============================================================================
return (
<div className="container mx-auto py-1 px-3 sm:px-4">
<>
<LoadingModal />
<UninitializedModal />
<div className="container mx-auto py-1 px-3 sm:px-4">
{/* ========================================================================
SECTION: Balance Display
@@ -792,8 +841,6 @@ export function CashuWallet() {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="w-72">
<DropdownMenuLabel>Connected Mints</DropdownMenuLabel>
<DropdownMenuSeparator />
{mints.length === 0 && (
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
)}
@@ -808,6 +855,17 @@ export function CashuWallet() {
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint)}</span>
</div>
<Button
size="sm"
variant="ghost"
className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
onClick={(e) => {
e.stopPropagation();
handleRemoveMintClick(mint);
}}
>
<X className="h-3 w-3" />
</Button>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
@@ -845,21 +903,21 @@ export function CashuWallet() {
{/* Lightning Address */}
{lightningAddress && (
<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>
<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"
@@ -869,16 +927,16 @@ export function CashuWallet() {
<QrCode className="h-3 w-3" />
</Button>
{unclaimedAmount > 0 && (
<Button
size="sm"
variant="outline"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
<Button
size="sm"
variant="outline"
onClick={refreshNpubCash}
disabled={isNpubCashLoading}
className="h-8 text-xs"
>
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
>
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
{unclaimedAmount} sats
</Button>
</Button>
)}
</div>
)}
@@ -895,8 +953,8 @@ export function CashuWallet() {
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
<Download className="h-5 w-5 mr-2" />
Receive
</CardTitle>
<CardDescription>
{mode === 'tokens'
@@ -947,8 +1005,8 @@ export function CashuWallet() {
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
<Send className="h-5 w-5 mr-2" />
Send
</CardTitle>
<CardDescription>
{mode === 'tokens'
@@ -1355,60 +1413,44 @@ export function CashuWallet() {
{/* ========================================================================
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>
)}
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={lightningAddress || ''}
icon="qr"
helpText="💡 Share this QR code or address to receive Lightning payments"
/>
{/* ========================================================================
SECTION: Lightning Invoice Modal
======================================================================== */}
{showInvoiceModal && currentInvoice && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<QRModal
isOpen={showInvoiceModal}
onClose={() => setShowInvoiceModal(false)}
title="Lightning Invoice"
description={currentInvoice ? `Pay this invoice to receive ${currentInvoice.amount} sats` : ''}
qrCodeUrl={currentInvoice?.qrCodeUrl || ''}
content={currentInvoice?.invoice || ''}
icon="zap"
showCopyButton={true}
copiedText={copiedInvoice}
onCopy={() => currentInvoice && handleCopy(currentInvoice.invoice, 'invoice')}
copyButtonText="Copy Invoice"
helpText="💡 Coco will automatically claim your tokens when payment is detected"
/>
{/* ========================================================================
SECTION: Remove Mint Confirmation Modal
======================================================================== */}
{showRemoveMintModal && mintToRemove && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={() => setShowInvoiceModal(false)}
onClick={() => setShowRemoveMintModal(false)}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
@@ -1416,57 +1458,56 @@ export function CashuWallet() {
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Zap className="h-5 w-5 mr-2" />
Lightning Invoice
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Pay this invoice to receive {currentInvoice.amount} sats
Are you sure you want to remove this mint from your wallet?
</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 className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mintToRemove.name || new URL(mintToRemove.url).hostname}</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{mintToRemove.url}
</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 className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-center">
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => handleCopy(currentInvoice.invoice, 'invoice')}
className="flex items-center gap-2"
onClick={() => setShowRemoveMintModal(false)}
>
{copiedInvoice === currentInvoice.invoice ? (
Cancel
</Button>
<Button
variant="destructive"
onClick={handleConfirmRemoveMint}
disabled={isLoading}
>
{isLoading ? (
<>
<Check className="h-4 w-4" />
Copied!
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<Copy className="h-4 w-4" />
Copy Invoice
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</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>
</div>
</>
);
}
+106
View File
@@ -0,0 +1,106 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { X, Copy, Check, QrCode, Zap } from 'lucide-react';
interface QRModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
description: string;
qrCodeUrl: string;
content: string;
icon?: 'qr' | 'zap';
showCopyButton?: boolean;
copiedText?: string | null;
onCopy?: () => void;
copyButtonText?: string;
helpText?: string;
}
export function QRModal({
isOpen,
onClose,
title,
description,
qrCodeUrl,
content,
icon = 'qr',
showCopyButton = false,
copiedText,
onCopy,
copyButtonText = 'Copy',
helpText,
}: QRModalProps) {
if (!isOpen) return null;
const IconComponent = icon === 'zap' ? Zap : QrCode;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<IconComponent className="h-5 w-5 mr-2" />
{title}
</CardTitle>
<CardDescription>
{description}
</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={qrCodeUrl}
alt={`${title} 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">
{content}
</div>
</div>
{showCopyButton && onCopy && (
<div className="flex gap-2 justify-center">
<Button
variant="outline"
onClick={onCopy}
className="flex items-center gap-2"
>
{copiedText === content ? (
<>
<Check className="h-4 w-4" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4" />
{copyButtonText}
</>
)}
</Button>
</div>
)}
{helpText && (
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded text-center">
{helpText}
</div>
)}
</CardContent>
</Card>
</div>
);
}
+37 -1
View File
@@ -17,7 +17,7 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
const isRefreshingRef = useRef<boolean>(false);
const REFRESH_THROTTLE_MS = 500;
const REFRESH_THROTTLE_MS = 200;
const refreshBalances = useCallback(async () => {
if (!manager) return;
@@ -102,10 +102,46 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
refreshBalances();
});
const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => {
console.log('📤 Send created, refreshing balances...');
// Bypass throttling for send operations to ensure immediate balance update
setTimeout(async () => {
if (!manager) return;
try {
console.log('🔄 send:created: Getting balances from wallet...');
const newBalances = await (manager as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 send:created: Raw balances from wallet:', newBalances);
setBalances(prevBalances => {
const hasChanged =
Object.keys(newBalances).length !== Object.keys(prevBalances).length ||
Object.keys(newBalances).some(key => newBalances[key] !== prevBalances[key]);
if (hasChanged) {
console.log('✅ send:created: Balances changed, updating state:', Object.keys(newBalances).length, 'mints');
return newBalances;
} else {
console.log('⏭️ send:created: Balances unchanged, skipping state update');
return prevBalances;
}
});
} catch (err) {
console.error('❌ send:created: Failed to refresh balances:', err);
}
}, 100);
});
const unsubscribeReceiveCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('receive:created', () => {
console.log('📥 Receive created, refreshing balances...');
refreshBalances();
});
return () => {
unsubscribeProofsSaved();
unsubscribeProofsStateChanged();
unsubscribeMintQuoteRedeemed();
unsubscribeSendCreated();
unsubscribeReceiveCreated();
};
}, [manager, refreshBalances]);
+27 -7
View File
@@ -78,13 +78,33 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
}
}, [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;
}, []);
const removeMint = useCallback(async (mintUrl: string) => {
if (!manager) throw new CashuWalletError('Wallet not initialized', 'WALLET_NOT_INITIALIZED');
try {
setIsLoading(true);
setError(null);
// Access the mintService directly through the manager to use deleteMint
// The manager has a private mintService property that we can access
const mintService = (manager as any).mintService;
if (!mintService || typeof mintService.deleteMint !== 'function') {
throw new CashuWalletError('Mint service not available', 'MINT_SERVICE_ERROR');
}
await mintService.deleteMint(mintUrl);
// No need to manually refresh - events will handle it automatically
console.log('✅ Mint removed successfully:', mintUrl);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to remove mint';
const cashuError = new CashuWalletError(errorMessage, 'REMOVE_MINT_ERROR', { mintUrl, originalError: err });
setError(cashuError);
throw cashuError;
} finally {
setIsLoading(false);
}
}, [manager]);
// Set up event listeners for automatic mint updates using coco events
useEffect(() => {