refactor the refactor

This commit is contained in:
lemonknowsall committed 2025-10-16 13:03:59 -07:00
1 parent 77803dda38
commit b5bc571aa7
6 files changed
+901 -668

No files matched your search

+116 -668
View File
@@ -1,13 +1,15 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useRef } from 'react';
import { nip19 } from 'nostr-tools';
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';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
import { useMintManager } from '@/hooks/cashu/useMintManager';
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
import { QRModal } from '@/components/ui/qr-modal';
import { BalanceDisplay } from './BalanceDisplay';
import { ReceiveCard } from './ReceiveCard';
@@ -19,7 +21,7 @@ import { LoginArea } from '@/components/auth/LoginArea';
export function CashuWallet() {
// ============================================================================
// HOOKS
// CORE HOOKS
// ============================================================================
const {
@@ -35,93 +37,127 @@ export function CashuWallet() {
refreshMints,
} = useCashu();
// Npub.cash integration with cleaner SDK-based implementation
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
const {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
getAllQuotes,
refreshQuotes,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// Wrapper to handle return type mismatch
const handleSetNpubCashMint = (mintUrl: string): Promise<boolean> => {
return setNpubCashMint(mintUrl);
};
// ============================================================================
// STATE - Input Values
// DOMAIN HOOKS
// ============================================================================
const [tokenInput, setTokenInput] = useState('');
const [mintUrl, setMintUrl] = useState('');
const [sendAmount, setSendAmount] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
const {
activeMintUrl,
setActiveMintUrl,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
} = useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint: handleSetNpubCashMint,
refreshMints,
toast,
});
// Wrapper for setActiveMintUrl to handle the async nature
const handleSetActiveMintSync = (url: string | null) => {
setActiveMintUrl(url);
};
const {
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
sentToken,
setSentToken,
sentTokenQRCode,
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
handleReceive,
handleSend,
mintQuoteUnsubscribeRef,
} = useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
});
const {
historyEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
} = useHistoryManager({
coco,
isInitialized,
});
// ============================================================================
// STATE - UI State
// UI STATE
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
// ============================================================================
// STATE - Transaction State
// ============================================================================
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
// ============================================================================
// STATE - History
// ============================================================================
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
const [proofBreakdown, setProofBreakdown] = useState<{
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
} | null>(null);
const [showLightningQR, setShowLightningQR] = useState(false);
const [lightningQRCode, setLightningQRCode] = useState<string>('');
const [showLightningAddressQR, setShowLightningAddressQR] = useState(false);
const [lightningAddressQRCode, setLightningAddressQRCode] = useState<string>('');
const [npubCashUserInfo, setNpubCashUserInfo] = useState<NpubCashUserInfo | null>(null);
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
const [mintToRemove, setMintToRemove] = useState<{
url: string;
name?: string;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// Ref to track if we've fetched npub.cash user info
const hasCheckedNpubCashRef = useRef(false);
@@ -132,540 +168,9 @@ export function CashuWallet() {
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// HELPER FUNCTIONS - QR Code Generation & Formatting
// EFFECTS - Error Handling
// ============================================================================
// Generate QR code for sent token
const generateSentTokenQRCode = async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
};
// Get clean mint label for display
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host;
} catch {
return mint.url.replace(/^https?:\/\//, '');
}
}, []);
// ============================================================================
// HELPER FUNCTIONS - Quote Refresh
// ============================================================================
/**
* Refresh quotes from npub.cash and add them to the wallet
* This matches the functionality from main.ts example
*/
const handleRefreshQuotes = useCallback(async () => {
if (!coco || !isNpubCashLoggedIn) return;
try {
// Fetch all quotes from npub.cash
const quotes = await getAllQuotes();
if (quotes.length === 0) {
toast({
title: "No Quotes Found",
description: "No pending quotes found on npub.cash",
});
return;
}
// Group quotes by mint URL
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists, add if not
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
// Add quotes to the wallet (matching main.ts format)
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Refreshed",
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
});
} else {
toast({
title: "No New Quotes",
description: "All quotes from npub.cash are already processed",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Refresh Failed",
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
});
}
}, [coco, isNpubCashLoggedIn, getAllQuotes, toast]);
// ============================================================================
// HELPER FUNCTIONS - Mint Management
// ============================================================================
/**
* Set active mint
* @param mintUrl - The mint URL to set as active
* @param syncToNpubCash - Whether to sync this change to npub.cash (default: true for manual changes)
*/
const handleSetActiveMint = useCallback(async (mintUrl: string | null, syncToNpubCash = true) => {
setActiveMintUrl(mintUrl);
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) {
await setNpubCashMint(mintUrl);
}
}, [isNpubCashLoggedIn, setNpubCashMint]);
// ============================================================================
// HELPER FUNCTIONS - History
// ============================================================================
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
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);
}
}, [coco]);
// ============================================================================
// HELPER FUNCTIONS - Unknown Mint Error Handling
// ============================================================================
const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = (err as any)?.message || err?.toString() || '';
return (err as any)?.constructor?.name === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = (err as any)?.message || err?.toString() || '';
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
const handleUnknownMintError = async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Add the mint
await coco.mint.addMint(mintUrl);
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: "Token Received",
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: "destructive",
title: "Receive Failed",
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
};
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
const handleReceive = async () => {
if (!coco) return;
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
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);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: "destructive",
title: "Receive Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Lightning mode - create mint quote
if (!quoteAmount || !activeMintUrl) return;
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry
});
setShowInvoiceModal(true);
toast({
title: "Lightning Invoice Created",
description: "Wallet will automatically claim tokens when payment is detected.",
});
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event
const quoteId = quote.quote;
const invoiceAmount = amount;
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
if (redeemedQuote.quoteId === quoteId) {
toast({
title: "Payment Received",
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
toast({
variant: "destructive",
title: "Quote Creation Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
};
// ============================================================================
// EVENT HANDLERS - Send
// ============================================================================
const handleSend = async () => {
if (!coco) return;
if (mode === 'tokens') {
if (!sendAmount || !activeMintUrl) return;
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
} catch (err) {
toast({
variant: "destructive",
title: "Send Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Lightning mode
if (!activeMintUrl) return;
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: "destructive",
title: "Invalid Amount",
description: "Please enter a valid amount",
});
return;
}
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: "Payment Sent",
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
} catch (err) {
toast({
variant: "destructive",
title: "Payment Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice
try {
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, input);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: "Invoice Paid",
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
});
setLightningInvoice('');
} catch (err) {
toast({
variant: "destructive",
title: "Invoice Payment Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}
}
};
// ============================================================================
// EVENT HANDLERS - Utility
// ============================================================================
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove || !repositories) return;
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(mint => mint.url !== mintToRemove.url);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: "Mint Removed",
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: "destructive",
title: "Remove Mint Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintToRemove, mints, activeMintUrl, handleSetActiveMint, repositories, toast, refreshMints]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
const handleAddMint = async () => {
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
normalizedUrl = `https://${normalizedUrl}`;
}
await coco.mint.addMint(normalizedUrl);
setMintUrl('');
toast({
title: "Mint Added",
description: "Mint added successfully!",
});
} catch (err) {
toast({
variant: "destructive",
title: "Add Mint Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
};
// ============================================================================
// EVENT HANDLERS - Quote Management
// ============================================================================
const handleShowDenominations = async (mintUrl: string) => {
if (!repositories) return;
try {
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(mintUrl);
if (!proofs || proofs.length === 0) {
toast({
variant: "destructive",
title: "No Tokens",
description: "No tokens found for this mint",
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations)
.reduce((sum, [amount, count]) => sum + (parseInt(amount) * count), 0);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance
});
setShowProofBreakdown(true);
} catch (err) {
toast({
variant: "destructive",
title: "Failed to Get Denominations",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
};
// ============================================================================
// EFFECTS
// ============================================================================
// Show error toasts when errors occur
useEffect(() => {
if (error) {
toast({
@@ -676,7 +181,6 @@ export function CashuWallet() {
}
}, [error, toast]);
// Show npub.cash error toasts
useEffect(() => {
if (npubCashError) {
toast({
@@ -688,7 +192,10 @@ export function CashuWallet() {
}
}, [npubCashError, clearNpubCashError, toast]);
// Fetch npub.cash user info on mount/login and sync mint
// ============================================================================
// EFFECTS - NPub.cash Integration
// ============================================================================
useEffect(() => {
if (!isNpubCashLoggedIn) {
hasCheckedNpubCashRef.current = false;
@@ -713,68 +220,23 @@ export function CashuWallet() {
if (!mintExists && coco) {
try {
await coco.mint.addMint(userInfo.mint_url);
setTimeout(() => handleSetActiveMint(userInfo.mint_url, false), 500);
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
} catch {
// Silent failure - user can manually add mint if needed
}
} else if (mintExists) {
handleSetActiveMint(userInfo.mint_url, false);
setActiveMintUrl(userInfo.mint_url, false);
}
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, handleSetActiveMint]);
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
// Don't sync to npub.cash on auto-select, only on manual changes
handleSetActiveMint(mints[0].url, false);
}
}, [mints, activeMintUrl, handleSetActiveMint]);
// Load transaction history when wallet is initialized
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh transaction history on new transactions
useEffect(() => {
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, coco, loadHistory]);
// Cleanup mint quote listener on component unmount
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
@@ -784,25 +246,20 @@ export function CashuWallet() {
};
}, []);
// ============================================================================
// RENDER - Main UI
// RENDER
// ============================================================================
return (
<>
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
SECTION: Login Area
======================================================================== */}
{/* Login Area */}
<div className="absolute top-1 right-3 sm:right-4 z-10">
<LoginArea />
</div>
{/* ========================================================================
SECTION: Balance Display
======================================================================== */}
{/* Balance Display */}
<BalanceDisplay
totalBalance={totalBalance}
balances={balances}
@@ -811,13 +268,13 @@ export function CashuWallet() {
mode={mode}
setMode={setMode}
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMint}
setActiveMintUrl={handleSetActiveMintSync}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={handleShowDenominations}
onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)}
getCleanMintLabel={getCleanMintLabel}
userPubkey={user?.pubkey}
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
@@ -827,15 +284,13 @@ export function CashuWallet() {
setShowLightningAddressQR(true);
}}
generateQRCode={generateQRCode}
onRefreshQuotes={handleRefreshQuotes}
onRefreshQuotes={() => refreshQuotes(coco, toast)}
isRefreshingQuotes={isNpubCashLoading}
mintDropdownOpen={mintDropdownOpen}
setMintDropdownOpen={setMintDropdownOpen}
/>
{/* ========================================================================
SECTION: Receive & Send Cards
======================================================================== */}
{/* Receive & Send Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<ReceiveCard
mode={mode}
@@ -867,9 +322,7 @@ export function CashuWallet() {
/>
</div>
{/* ========================================================================
SECTION: Sent Token Display
======================================================================== */}
{/* Sent Token Display */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
@@ -882,10 +335,7 @@ export function CashuWallet() {
/>
)}
{/* ========================================================================
SECTION: Transaction History
======================================================================== */}
{/* Transaction History */}
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
@@ -893,9 +343,7 @@ export function CashuWallet() {
setIsExpanded={setIsHistoryExpanded}
/>
{/* ========================================================================
SECTION: Modals
======================================================================== */}
{/* Modals */}
<>
<ProofBreakdownModal
isOpen={showProofBreakdown}
+79
View File
@@ -0,0 +1,79 @@
import { useState, useCallback, useEffect } from 'react';
import type { HistoryEntry } from 'coco-cashu-core';
interface UseHistoryManagerProps {
coco: any; // Coco instance
isInitialized: boolean;
}
export function useHistoryManager({
coco,
isInitialized,
}: UseHistoryManagerProps) {
const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
// Load history from wallet
const loadHistory = useCallback(async () => {
if (!coco) return;
try {
setIsLoadingHistory(true);
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);
}
}, [coco]);
// Load history on wallet initialization
useEffect(() => {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized, historyEntries.length, loadHistory]);
// Auto-refresh on wallet events
useEffect(() => {
if (!isInitialized || !coco) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, coco, loadHistory]);
return {
historyEntries,
setHistoryEntries,
isLoadingHistory,
isHistoryExpanded,
setIsHistoryExpanded,
loadHistory,
};
}
+219
View File
@@ -0,0 +1,219 @@
import { useState, useCallback, useEffect } from 'react';
import { getCleanMintLabel } from './walletUtils';
export interface CashuMint {
url: string;
name?: string;
}
interface UseMintManagerProps {
coco: any; // Coco instance
mints: CashuMint[];
repositories: any; // Repositories instance
isNpubCashLoggedIn: boolean;
setNpubCashMint: (mintUrl: string) => Promise<boolean>;
refreshMints: () => Promise<void>;
toast: any; // Toast function
}
export function useMintManager({
coco,
mints,
repositories,
isNpubCashLoggedIn,
setNpubCashMint,
refreshMints,
toast,
}: UseMintManagerProps) {
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
const [mintUrl, setMintUrl] = useState('');
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
// Set active mint and optionally sync to npub.cash
const handleSetActiveMint = useCallback(
async (url: string | null, syncToNpubCash = true) => {
setActiveMintUrl(url);
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && url && syncToNpubCash) {
try {
await setNpubCashMint(url);
} catch (err) {
console.error('Failed to sync mint to npub.cash:', err);
}
}
},
[isNpubCashLoggedIn, setNpubCashMint]
);
// Add a new mint
const handleAddMint = useCallback(async () => {
if (!mintUrl.trim() || !coco) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (
!normalizedUrl.startsWith('http://') &&
!normalizedUrl.startsWith('https://')
) {
normalizedUrl = `https://${normalizedUrl}`;
}
await coco.mint.addMint(normalizedUrl);
setMintUrl('');
toast({
title: 'Mint Added',
description: 'Mint added successfully!',
});
} catch (err) {
toast({
variant: 'destructive',
title: 'Add Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintUrl, coco, toast]);
// Show remove confirmation modal
const handleRemoveMintClick = useCallback((mint: CashuMint) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
// Confirm and remove mint
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove || !repositories) return;
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(
(mint) => mint.url !== mintToRemove.url
);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: 'Mint Removed',
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: 'destructive',
title: 'Remove Mint Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [
mintToRemove,
mints,
activeMintUrl,
handleSetActiveMint,
repositories,
toast,
refreshMints,
]);
// Show denomination breakdown for a mint
const handleShowDenominations = useCallback(
async (
mintUrl: string,
setShowProofBreakdown: (show: boolean) => void,
setProofBreakdown: (breakdown: {
mintUrl: string;
denominations: { [key: number]: number };
totalBalance: number;
}) => void
) => {
if (!repositories) return;
try {
// Access proofs directly through the proof repository
const proofs = await repositories.proofRepository.getReadyProofs(
mintUrl
);
if (!proofs || proofs.length === 0) {
toast({
variant: 'destructive',
title: 'No Tokens',
description: 'No tokens found for this mint',
});
return;
}
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
const totalBalance = Object.entries(denominations).reduce(
(sum, [amount, count]) => sum + parseInt(amount) * count,
0
);
// Set the breakdown data and show the modal
setProofBreakdown({
mintUrl,
denominations,
totalBalance,
});
setShowProofBreakdown(true);
} catch (err) {
toast({
variant: 'destructive',
title: 'Failed to Get Denominations',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
},
[repositories, toast]
);
// Auto-select first mint when mints change
useEffect(() => {
if (mints.length > 0 && !activeMintUrl) {
// Select first mint initially - user can change via dropdown
// Don't sync to npub.cash on auto-select, only on manual changes
handleSetActiveMint(mints[0].url, false);
}
}, [mints, activeMintUrl, handleSetActiveMint]);
return {
activeMintUrl,
setActiveMintUrl: handleSetActiveMint,
mintUrl,
setMintUrl,
mintDropdownOpen,
setMintDropdownOpen,
handleAddMint,
handleRemoveMintClick,
handleConfirmRemoveMint,
mintToRemove,
setMintToRemove,
showRemoveMintModal,
setShowRemoveMintModal,
getCleanMintLabel,
handleShowDenominations,
};
}
+390
View File
@@ -0,0 +1,390 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
interface UseWalletTransactionsProps {
coco: any; // Coco instance
activeMintUrl: string | null;
isNpubCashLoggedIn: boolean;
repositories: any; // Repositories instance
generateQRCode: (text: string) => Promise<string>;
toast: any; // Toast function
getEncodedToken: (token: any) => string;
getLightningInvoice: (params: {
lightningAddress: string;
amountSats: number;
}) => Promise<string>;
}
export function useWalletTransactions({
coco,
activeMintUrl,
isNpubCashLoggedIn,
repositories,
generateQRCode,
toast,
getEncodedToken,
getLightningInvoice,
}: UseWalletTransactionsProps) {
// Receive state
const [tokenInput, setTokenInput] = useState('');
const [quoteAmount, setQuoteAmount] = useState('');
// Send state
const [sendAmount, setSendAmount] = useState('');
const [lightningInvoice, setLightningInvoice] = useState('');
const [lightningAddressInput, setLightningAddressInput] = useState('');
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
const [pendingLightningAddress, setPendingLightningAddress] = useState<
string | null
>(null);
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(null);
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
// Invoice modal state
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
const [currentInvoice, setCurrentInvoice] = useState<{
quoteId: string;
mintUrl: string;
amount: number;
invoice: string;
qrCodeUrl: string;
expiry: number;
} | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// Generate QR code for sent token
const generateSentTokenQRCode = useCallback(async (token: string) => {
try {
const qrCodeUrl = await generateQRCode(token);
setSentTokenQRCode(qrCodeUrl);
} catch (err) {
console.error('Failed to generate sent token QR code:', err);
}
}, [generateQRCode]);
// Handle unknown mint error by adding the mint and retrying
const handleUnknownMintError = useCallback(
async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Add the mint
await coco.mint.addMint(mintUrl);
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: 'Token Received',
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: 'destructive',
title: 'Receive Failed',
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
},
[coco, tokenInput, toast]
);
// Handle receive (token or Lightning)
const handleReceive = useCallback(async () => {
if (!coco) return;
// Receive Cashu token mode
if (!tokenInput && !quoteAmount) {
return;
}
if (tokenInput) {
// Receive token mode
try {
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);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: 'destructive',
title: 'Receive Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (quoteAmount && activeMintUrl) {
// Lightning quote mode
try {
const amount = parseInt(quoteAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
// Generate QR code for the Lightning invoice
const qrCodeUrl = await generateQRCode(quote.request);
// Set the invoice data and show modal
setCurrentInvoice({
quoteId: quote.quote,
mintUrl: activeMintUrl,
amount,
invoice: quote.request,
qrCodeUrl,
expiry: quote.expiry,
});
setShowInvoiceModal(true);
toast({
title: 'Lightning Invoice Created',
description:
'Wallet will automatically claim tokens when payment is detected.',
});
setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event
const quoteId = quote.quote;
const invoiceAmount = amount;
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
if (redeemedQuote.quoteId === quoteId) {
toast({
title: 'Payment Received',
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
});
setShowInvoiceModal(false);
setCurrentInvoice(null);
// Clean up the event listener
mintQuoteUnsubscribeRef.current = null;
unsubscribe();
}
});
// Store unsubscribe function for cleanup
mintQuoteUnsubscribeRef.current = unsubscribe;
} catch (err) {
toast({
variant: 'destructive',
title: 'Quote Creation Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}, [
coco,
tokenInput,
quoteAmount,
activeMintUrl,
toast,
generateQRCode,
handleUnknownMintError,
]);
// Handle send (token or Lightning)
const handleSend = useCallback(async () => {
if (!coco) return;
if (!sendAmount && !lightningInvoice && !lightningAddressInput) {
return;
}
// Send Cashu token mode
if (sendAmount && activeMintUrl) {
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const token = await coco.wallet.send(activeMintUrl, amount);
const encodedToken = getEncodedToken(token);
setSentToken(encodedToken);
await generateSentTokenQRCode(encodedToken);
setSendAmount('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Send Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else if (activeMintUrl) {
// Lightning mode
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
try {
const amount = parseInt(lightningAddressAmount);
if (isNaN(amount) || amount <= 0) {
toast({
variant: 'destructive',
title: 'Invalid Amount',
description: 'Please enter a valid amount',
});
return;
}
const invoice = await getLightningInvoice({
lightningAddress: pendingLightningAddress,
amountSats: amount,
});
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
invoice
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Payment Sent',
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
});
// Reset state
setPendingLightningAddress(null);
setLightningAddressInput('');
setLightningAddressAmount('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
setPendingLightningAddress(input);
setLightningAddressInput('');
} else {
// It's a regular Lightning invoice
try {
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
input
);
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
toast({
title: 'Invoice Paid',
description:
'Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.',
});
setLightningInvoice('');
} catch (err) {
toast({
variant: 'destructive',
title: 'Invoice Payment Failed',
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}
}
}
}, [
coco,
sendAmount,
lightningInvoice,
lightningAddressInput,
lightningAddressAmount,
pendingLightningAddress,
activeMintUrl,
toast,
getEncodedToken,
generateSentTokenQRCode,
getLightningInvoice,
]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
return {
// Receive state
tokenInput,
setTokenInput,
quoteAmount,
setQuoteAmount,
// Send state
sendAmount,
setSendAmount,
lightningInvoice,
setLightningInvoice,
lightningAddressInput,
setLightningAddressInput,
lightningAddressAmount,
setLightningAddressAmount,
pendingLightningAddress,
setPendingLightningAddress,
// Transaction output state
sentToken,
setSentToken,
sentTokenQRCode,
// Invoice modal state
showInvoiceModal,
setShowInvoiceModal,
currentInvoice,
setCurrentInvoice,
// Handlers
handleReceive,
handleSend,
// Refs
mintQuoteUnsubscribeRef,
};
}
+23
View File
@@ -0,0 +1,23 @@
export const getCleanMintLabel = (mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host;
} catch {
return mint.url.replace(/^https?:\/\//, '');
}
};
export const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = (err as any)?.message || err?.toString() || '';
return (err as any)?.constructor?.name === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
export const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = (err as any)?.message || err?.toString() || '';
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
+74
View File
@@ -119,6 +119,79 @@ export function useNpubCash() {
return npcClient.subscribe(onUpdate, onError);
}, [npcClient]);
const refreshQuotes = useCallback(async (coco: any, toast: any): Promise<void> => {
if (!npcClient || !coco) return;
try {
// Fetch all quotes from npub.cash
const quotes = await getAllQuotes();
if (quotes.length === 0) {
toast({
title: "No Quotes Found",
description: "No pending quotes found on npub.cash",
});
return;
}
// Group quotes by mint URL
const quotesByMint = quotes.reduce((acc, quote) => {
if (!acc[quote.mintUrl]) {
acc[quote.mintUrl] = [];
}
acc[quote.mintUrl].push(quote);
return acc;
}, {} as Record<string, typeof quotes>);
let addedQuotes = 0;
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
// Check if mint exists, add if not
const isKnown = await coco.mint.isKnownMint(mintUrl);
if (!isKnown) {
await coco.mint.addMint(mintUrl);
}
// Add quotes to the wallet (matching main.ts format)
coco.quotes.addMintQuote(
mintUrl,
mintQuotes.map((q) => ({
...q,
expiry: q.expiresAt,
quote: q.quoteId,
state: "PAID",
unit: "sat",
})),
);
addedQuotes += mintQuotes.length;
} catch (err) {
console.warn(`Failed to process quotes for mint ${mintUrl}:`, err);
}
}
if (addedQuotes > 0) {
toast({
title: "Quotes Refreshed",
description: `Successfully added ${addedQuotes} quotes from npub.cash`,
});
} else {
toast({
title: "No New Quotes",
description: "All quotes from npub.cash are already processed",
});
}
} catch (err) {
toast({
variant: "destructive",
title: "Refresh Failed",
description: err instanceof Error ? err.message : 'Failed to refresh quotes',
});
}
}, [npcClient, getAllQuotes]);
const clearError = useCallback(() => setError(null), []);
return {
@@ -131,6 +204,7 @@ export function useNpubCash() {
getQuotesSince,
setLockQuotes,
subscribeToQuotes,
refreshQuotes,
// Status
isLoading,