code cleanup round 2

This commit is contained in:
lemonknowsall committed 2025-10-15 00:10:24 -07:00
1 parent aaf12120e6
commit 2ac097d8de
9 files changed
+326 -669

No files matched your search

@@ -1,11 +1,11 @@
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
interface LoadingModalProps {
interface LoadingScreenProps {
isLoading: boolean;
}
export function LoadingModal({ isLoading }: LoadingModalProps) {
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
if (!isLoading) return null;
return (
@@ -13,7 +13,6 @@ export function LoadingModal({ isLoading }: LoadingModalProps) {
<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-3" />
<span className="text-lg font-medium">Loading</span>
</CardContent>
</Card>
</div>
+18 -18
View File
@@ -188,30 +188,30 @@ export function BalanceDisplay({
<HelpCircle className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogContent className="max-w-md" aria-describedby="mint-description">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
What is a Mint?
</DialogTitle>
<DialogDescription className="space-y-3 text-left">
<p>
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
</p>
<p>
<strong>Key features:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-4">
<li>Issues tokens when you deposit Lightning payments</li>
<li>Redeems tokens when you receive them</li>
<li>Manages your token balance</li>
<li>Enables Lightning ↔ Cashu conversions</li>
</ul>
<p>
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
</p>
</DialogDescription>
</DialogHeader>
<div id="mint-description" className="space-y-3 text-left text-sm text-muted-foreground">
<p>
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
</p>
<p>
<strong>Key features:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-4">
<li>Issues tokens when you deposit Lightning payments</li>
<li>Redeems tokens when you receive them</li>
<li>Manages your token balance</li>
<li>Enables Lightning ↔ Cashu conversions</li>
</ul>
<p>
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
</p>
</div>
</DialogContent>
</Dialog>
</div>
+55 -73
View File
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu, type HistoryEntry } from '@/hooks/cashu/useCashu';
import { useCashu } from '@/hooks/cashu/useCashu';
import type { HistoryEntry } from 'coco-cashu-core';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -8,7 +9,6 @@ import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { QRModal } from '@/components/ui/qr-modal';
import { LoadingModal } from './LoadingModal';
import { BalanceDisplay } from './BalanceDisplay';
import { ReceiveCard } from './ReceiveCard';
import { SendCard } from './SendCard';
@@ -23,26 +23,15 @@ export function CashuWallet() {
// ============================================================================
const {
coco,
repositories,
isInitialized,
isLoading,
error,
balances,
mints,
receive,
send,
getProofs,
addMint,
removeMint,
createMintQuote,
createMeltQuote,
payMeltQuote,
redeemMintQuote,
addMintQuote,
on,
refreshBalances,
refreshMints,
getEncodedToken,
clearError,
getHistory,
} = useCashu();
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
@@ -188,32 +177,38 @@ export function CashuWallet() {
// ============================================================================
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
const entries = await getHistory(50, 0); //TODO: show entire history
const entries = await coco.history.getPaginatedHistory(0, 50); //TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [getHistory]);
}, [coco]);
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
const handleReceive = async () => {
if (!coco) return;
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
await receive(tokenInput);
console.log('Attempting to receive token:', tokenInput.substring(0, 20) + '...');
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: "Token Received",
description: "Cashu token redeemed successfully!",
});
} catch (err) {
console.error('Token receive error:', err);
toast({
variant: "destructive",
title: "Receive Failed",
@@ -233,7 +228,7 @@ export function CashuWallet() {
});
return;
}
const quote = await createMintQuote(activeMintUrl, amount);
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
@@ -265,7 +260,7 @@ export function CashuWallet() {
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
// Check if this is the quote we're waiting for
@@ -300,6 +295,8 @@ export function CashuWallet() {
// ============================================================================
const handleSend = async () => {
if (!coco) return;
if (mode === 'tokens') {
if (!sendAmount || !activeMintUrl) return;
try {
@@ -312,7 +309,8 @@ export function CashuWallet() {
});
return;
}
const encodedToken = await send(activeMintUrl, amount);
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
@@ -348,8 +346,8 @@ export function CashuWallet() {
amountSats: amount,
});
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
await payMeltQuote(activeMintUrl, meltQuote.quote);
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: "Payment Sent",
@@ -379,8 +377,8 @@ export function CashuWallet() {
} else {
// It's a regular Lightning invoice
try {
const meltQuote = await createMeltQuote(activeMintUrl, input);
await payMeltQuote(activeMintUrl, meltQuote.quote);
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, input);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: "Invoice Paid",
@@ -412,44 +410,24 @@ export function CashuWallet() {
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) {
toast({
variant: "destructive",
title: "Remove Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
// Note: Mint deletion is not available in the current coco-cashu-core API
// This would require direct repository access which is not exposed
toast({
variant: "destructive",
title: "Mint Removal Not Supported",
description: "Mint removal is not currently supported in this version of coco-cashu-core",
});
setShowRemoveMintModal(false);
setMintToRemove(null);
}, [mintToRemove, toast]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
const handleAddMint = async () => {
if (!mintUrl.trim()) return;
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
@@ -457,7 +435,7 @@ export function CashuWallet() {
normalizedUrl = `https://${normalizedUrl}`;
}
await addMint(normalizedUrl);
await coco.mint.addMint(normalizedUrl);
setMintUrl('');
toast({
@@ -480,8 +458,11 @@ export function CashuWallet() {
const handleShowDenominations = async (mintUrl: string) => {
if (!repositories) return;
try {
const proofs = await getProofs(mintUrl);
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(mintUrl);
if (!proofs || proofs.length === 0) {
toast({
@@ -562,11 +543,13 @@ export function CashuWallet() {
if (!mintExists) {
try {
await addMint(userInfo.mint_url);
// Wait a bit for the mint to be added
setTimeout(() => {
handleSetActiveMint(userInfo.mint_url, false);
}, 500);
if (coco) {
await coco.mint.addMint(userInfo.mint_url);
// Wait a bit for the mint to be added
setTimeout(() => {
handleSetActiveMint(userInfo.mint_url, false);
}, 500);
}
} catch (err) {
// Silent failure - user can manually add mint if needed
}
@@ -578,7 +561,7 @@ export function CashuWallet() {
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, addMint, handleSetActiveMint]);
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, coco, handleSetActiveMint]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
@@ -598,25 +581,25 @@ export function CashuWallet() {
// Auto-refresh transaction history on new transactions
useEffect(() => {
if (!isInitialized) return;
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = on('history:updated', () => {
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = on('melt-quote:created', () => {
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
@@ -626,7 +609,7 @@ export function CashuWallet() {
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, on, loadHistory]);
}, [isInitialized, coco, loadHistory]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
@@ -645,7 +628,6 @@ export function CashuWallet() {
return (
<>
<LoadingModal isLoading={isLoading || !isInitialized} />
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
+2 -2
View File
@@ -2,7 +2,7 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
import type { HistoryEntry } from '@/hooks/cashu/useCashu';
import type { HistoryEntry } from 'coco-cashu-core';
interface TransactionHistoryProps {
entries: HistoryEntry[];
@@ -129,7 +129,7 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
{entry.state && entry.type !== 'mint' && entry.type !== 'melt' && (
{'state' in entry && entry.state && (
<Badge
variant="secondary"
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}