move files together

This commit is contained in:
lemonknowsall committed 2025-10-13 19:57:15 -07:00
1 parent 5ce402105c
commit aaf12120e6
11 files changed
+32 -41

No files matched your search

+821
View File
@@ -0,0 +1,821 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { nip19 } from 'nostr-tools';
import { useCashu, type HistoryEntry } from '@/hooks/cashu/useCashu';
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 { QRModal } from '@/components/ui/qr-modal';
import { LoadingModal } from './LoadingModal';
import { BalanceDisplay } from './BalanceDisplay';
import { ReceiveCard } from './ReceiveCard';
import { SendCard } from './SendCard';
import { TransactionHistory } from './TransactionHistory';
import { ProofBreakdownModal } from './ProofBreakdownModal';
import { RemoveMintModal } from './RemoveMintModal';
import { LoginArea } from '@/components/auth/LoginArea';
export function CashuWallet() {
// ============================================================================
// HOOKS
// ============================================================================
const {
isInitialized,
isLoading,
error,
balances,
mints,
receive,
send,
getProofs,
addMint,
removeMint,
createMintQuote,
createMeltQuote,
payMeltQuote,
redeemMintQuote,
addMintQuote,
on,
refreshBalances,
refreshMints,
clearError,
getHistory,
} = useCashu();
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
// ============================================================================
// STATE - Input Values
// ============================================================================
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('');
// ============================================================================
// STATE - UI State
// ============================================================================
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
// ============================================================================
// 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);
// ============================================================================
// COMPUTED VALUES
// ============================================================================
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// HELPER FUNCTIONS - QR Code Generation & Formatting
// ============================================================================
// 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 - 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) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
// If user is logged in to npub.cash, a mint is selected, and we should sync
if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) {
const success = await setNpubCashMint(mintUrl);
if (success) {
toast({
title: "Mint Synced",
description: "Your preferred mint has been updated on npub.cash",
});
}
}
}, [isNpubCashLoggedIn, setNpubCashMint, toast]);
// ============================================================================
// HELPER FUNCTIONS - History
// ============================================================================
const loadHistory = useCallback(async () => {
try {
setIsLoadingHistory(true);
const entries = await getHistory(50, 0); //TODO: show entire history
setHistoryEntries(entries);
} catch (err) {
console.error('Failed to load history:', err);
} finally {
setIsLoadingHistory(false);
}
}, [getHistory]);
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
const handleReceive = async () => {
if (mode === 'tokens') {
if (!tokenInput.trim()) return;
try {
await receive(tokenInput);
setTokenInput('');
toast({
title: "Token Received",
description: "Cashu token redeemed successfully!",
});
} catch (err) {
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 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 = 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 (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 encodedToken = await send(activeMintUrl, amount);
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 createMeltQuote(activeMintUrl, invoice);
await 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 createMeltQuote(activeMintUrl, input);
await 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 }) => {
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) {
toast({
variant: "destructive",
title: "Remove Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
// ============================================================================
// EVENT HANDLERS - Mint Management
// ============================================================================
const handleAddMint = async () => {
if (!mintUrl.trim()) return;
try {
// Normalize URL - add https:// if not present
let normalizedUrl = mintUrl.trim();
if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
normalizedUrl = `https://${normalizedUrl}`;
}
await 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) => {
try {
const proofs = await getProofs(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({
variant: "destructive",
title: "Wallet Error",
description: error.message,
});
}
}, [error, toast]);
// Fetch npub.cash user info on mount/login and sync mint
useEffect(() => {
// Reset the check flag if user logs out
if (!isNpubCashLoggedIn) {
hasCheckedNpubCashRef.current = false;
return;
}
// Only fetch if user is logged in, wallet is initialized, and we haven't fetched yet
if (!isInitialized || hasCheckedNpubCashRef.current) return;
const fetchUserInfo = async () => {
// Mark that we've checked to prevent multiple fetches
hasCheckedNpubCashRef.current = true;
const userInfo = await getNpubCashUserInfo();
if (!userInfo) return;
setNpubCashUserInfo(userInfo);
// Check if the mint from npub.cash is different from our active mint
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
// Check if we have this mint in our list
const mintExists = mints.some(m => m.url === userInfo.mint_url);
if (!mintExists) {
try {
await 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
}
} else {
// Mint exists, just set it as active (without syncing back to npub.cash)
handleSetActiveMint(userInfo.mint_url, false);
}
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, addMint, handleSetActiveMint]);
// 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) return;
// Listen for history updates (fires on send, receive transactions)
const unsubscribeHistoryUpdated = on('history:updated', () => {
loadHistory();
});
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
const unsubscribeMeltCreated = on('melt-quote:created', () => {
loadHistory();
});
// Listen for melt quote paid (backup, in case creation event missed)
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
loadHistory();
});
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
loadHistory();
});
return () => {
unsubscribeHistoryUpdated();
unsubscribeMeltCreated();
unsubscribeMeltPaid();
unsubscribeMintRedeemed();
};
}, [isInitialized, on, loadHistory]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================
// RENDER - Main UI
// ============================================================================
return (
<>
<LoadingModal isLoading={isLoading || !isInitialized} />
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
SECTION: Login Area
======================================================================== */}
<div className="absolute top-1 right-3 sm:right-4 z-10">
<LoginArea />
</div>
{/* ========================================================================
SECTION: Balance Display
======================================================================== */}
<BalanceDisplay
totalBalance={totalBalance}
balances={balances}
showSats={showSats}
setShowSats={setShowSats}
mode={mode}
setMode={setMode}
activeMintUrl={activeMintUrl}
setActiveMintUrl={handleSetActiveMint}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={handleAddMint}
onRemoveMint={handleRemoveMintClick}
onShowDenominations={handleShowDenominations}
getCleanMintLabel={getCleanMintLabel}
userPubkey={user?.pubkey}
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
onCopyToClipboard={copyToClipboard}
onShowLightningAddressQR={(qr) => {
setLightningAddressQRCode(qr);
setShowLightningAddressQR(true);
}}
generateQRCode={generateQRCode}
/>
{/* ========================================================================
SECTION: Receive & Send Cards
======================================================================== */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<ReceiveCard
mode={mode}
tokenInput={tokenInput}
setTokenInput={setTokenInput}
quoteAmount={quoteAmount}
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onReceive={handleReceive}
isLoading={isLoading}
/>
<SendCard
mode={mode}
sendAmount={sendAmount}
setSendAmount={setSendAmount}
lightningInvoice={lightningInvoice}
setLightningInvoice={setLightningInvoice}
lightningAddressInput={lightningAddressInput}
setLightningAddressInput={setLightningAddressInput}
lightningAddressAmount={lightningAddressAmount}
setLightningAddressAmount={setLightningAddressAmount}
pendingLightningAddress={pendingLightningAddress}
setPendingLightningAddress={setPendingLightningAddress}
activeMintUrl={activeMintUrl}
onSend={handleSend}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading}
/>
</div>
{/* ========================================================================
SECTION: Sent Token Display
======================================================================== */}
{sentToken && (
<QRModal
isOpen={!!sentToken}
onClose={() => setSentToken(null)}
title="Cashu Token"
description="Share this token with the recipient to send them your sats"
qrCodeUrl={sentTokenQRCode}
content={sentToken}
icon="qr"
/>
)}
{/* ========================================================================
SECTION: Transaction History
======================================================================== */}
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
isExpanded={isHistoryExpanded}
setIsExpanded={setIsHistoryExpanded}
/>
{/* ========================================================================
SECTION: Modals
======================================================================== */}
<>
<ProofBreakdownModal
isOpen={showProofBreakdown}
onClose={() => setShowProofBreakdown(false)}
breakdown={proofBreakdown}
/>
<QRModal
isOpen={showLightningQR}
onClose={() => setShowLightningQR(false)}
title="Lightning Address QR Code"
description="Scan to send Lightning payments"
qrCodeUrl={lightningQRCode}
content={''}
icon="qr"
/>
<QRModal
isOpen={showLightningAddressQR}
onClose={() => setShowLightningAddressQR(false)}
title="Lightning Address"
description="Scan this QR code to send payments to your Lightning address"
qrCodeUrl={lightningAddressQRCode}
content={user?.pubkey ? `${npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)}@npubx.cash` : ''}
icon="zap"
/>
{currentInvoice && (
<QRModal
isOpen={showInvoiceModal}
onClose={() => {
// Clean up event listener when modal is closed manually
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
onExpiry={() => {
// Clean up event listener when invoice expires
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
toast({
variant: "destructive",
title: "Invoice Expired",
description: "The Lightning invoice has expired. Please create a new one.",
});
}}
title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl}
content={currentInvoice.invoice}
icon="zap"
expiryTimestamp={currentInvoice.expiry}
/>
)}
<RemoveMintModal
isOpen={showRemoveMintModal}
onClose={() => setShowRemoveMintModal(false)}
mint={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading}
/>
</>
</div>
</>
);
}
+1 -1
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/useCashu';
import type { HistoryEntry } from '@/hooks/cashu/useCashu';
interface TransactionHistoryProps {
entries: HistoryEntry[];