mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
1426 lines
55 KiB
TypeScript
1426 lines
55 KiB
TypeScript
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 { Button } from '@/components/ui/button';
|
||
import { Input } from '@/components/ui/input';
|
||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||
import { Badge } from '@/components/ui/badge';
|
||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu';
|
||
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, CreditCard } from 'lucide-react';
|
||
import QRCode from 'qrcode';
|
||
|
||
export function CashuWallet() {
|
||
// ============================================================================
|
||
// HOOKS
|
||
// ============================================================================
|
||
|
||
const {
|
||
isInitialized,
|
||
isLoading,
|
||
error,
|
||
balances,
|
||
mints,
|
||
receive,
|
||
send,
|
||
getProofs,
|
||
addMint,
|
||
createMintQuote,
|
||
createMeltQuote,
|
||
payMeltQuote,
|
||
redeemMintQuote,
|
||
addMintQuote,
|
||
refreshBalances,
|
||
refreshMints,
|
||
checkAndRedeemPendingQuotes,
|
||
clearError,
|
||
getHistory,
|
||
} = useCashu();
|
||
|
||
const {
|
||
lightningAddress,
|
||
unclaimedAmount,
|
||
quotes,
|
||
isLoading: isNpubCashLoading,
|
||
error: npubCashError,
|
||
fetchQuotes,
|
||
refresh: refreshNpubCash,
|
||
retryAuth,
|
||
setMint,
|
||
} = useNpubCash();
|
||
|
||
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
||
|
||
// ============================================================================
|
||
// 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 [receiveMode, setReceiveMode] = useState<'tokens' | 'lightning'>('tokens');
|
||
const [sendMode, setSendMode] = useState<'tokens' | 'lightning'>('tokens');
|
||
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
|
||
|
||
// ============================================================================
|
||
// STATE - Transaction State
|
||
// ============================================================================
|
||
|
||
const [sentToken, setSentToken] = useState<string | null>(null);
|
||
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
|
||
const [pendingQuotes, setPendingQuotes] = useLocalStorage<Array<{
|
||
quoteId: string;
|
||
mintUrl: string;
|
||
amount: number;
|
||
invoice: string;
|
||
timestamp: number;
|
||
qrCodeUrl?: string;
|
||
}>>('cashu-pending-quotes', []);
|
||
|
||
// ============================================================================
|
||
// STATE - Copy Feedback
|
||
// ============================================================================
|
||
|
||
const [copiedToken, setCopiedToken] = useState(false);
|
||
const [copiedInvoice, setCopiedInvoice] = useState<string | null>(null);
|
||
const [copiedLightningAddress, setCopiedLightningAddress] = useState(false);
|
||
|
||
|
||
// ============================================================================
|
||
// 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);
|
||
|
||
// ============================================================================
|
||
// COMPUTED VALUES
|
||
// ============================================================================
|
||
|
||
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||
|
||
// ============================================================================
|
||
// HELPER FUNCTIONS - Display
|
||
// ============================================================================
|
||
|
||
const getCleanMintLabel = (mint: { name?: string; url: string }) => {
|
||
if (mint.name && mint.name.trim().length > 0) {
|
||
// If name looks like a URL, strip protocol as well
|
||
return mint.name.replace(/^https?:\/\//, '');
|
||
}
|
||
try {
|
||
return new URL(mint.url).host; // host excludes protocol and preserves port if any
|
||
} catch {
|
||
// Fallback: manual strip
|
||
return mint.url.replace(/^https?:\/\//, '');
|
||
}
|
||
};
|
||
|
||
const formatAmount = (sats: number): string => {
|
||
if (showSats) {
|
||
return `${sats.toLocaleString()} sats`;
|
||
} else {
|
||
// Simple USD conversion (you can enhance this with real BTC price)
|
||
const usd = sats * 0.0001; // Rough approximation
|
||
return `$${usd.toFixed(2)}`;
|
||
}
|
||
};
|
||
|
||
// Copy Lightning address to clipboard
|
||
const copyLightningAddress = async () => {
|
||
if (!lightningAddress) return;
|
||
|
||
try {
|
||
await navigator.clipboard.writeText(lightningAddress);
|
||
setCopiedLightningAddress(true);
|
||
setTimeout(() => setCopiedLightningAddress(false), 2000);
|
||
} catch (err) {
|
||
console.error('Failed to copy Lightning address:', err);
|
||
}
|
||
};
|
||
|
||
|
||
// ============================================================================
|
||
// HELPER FUNCTIONS - QR Code
|
||
// ============================================================================
|
||
|
||
const generateQRCodeForQuote = async (invoice: string): Promise<string> => {
|
||
try {
|
||
return await QRCode.toDataURL(invoice, {
|
||
width: 256,
|
||
margin: 2,
|
||
color: {
|
||
dark: '#000000',
|
||
light: '#FFFFFF',
|
||
},
|
||
});
|
||
} catch (err) {
|
||
console.error('Failed to generate QR code:', err);
|
||
return '';
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// HELPER FUNCTIONS - Mint Management
|
||
// ============================================================================
|
||
|
||
/**
|
||
* Set active mint and sync with npubx.cash
|
||
*/
|
||
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
|
||
// Set the active mint locally
|
||
setActiveMintUrl(mintUrl);
|
||
|
||
// If we have a mint URL, also update npubx.cash preference
|
||
if (mintUrl) {
|
||
try {
|
||
await setMint(mintUrl);
|
||
console.log(`✅ Updated npubx.cash mint preference to: ${mintUrl}`);
|
||
} catch (error) {
|
||
console.error('❌ Failed to update npubx.cash mint preference:', error);
|
||
// Don't throw - we still want to set the local mint even if npubx.cash fails
|
||
}
|
||
}
|
||
}, [setMint]);
|
||
|
||
// ============================================================================
|
||
// HELPER FUNCTIONS - History
|
||
// ============================================================================
|
||
|
||
const loadHistory = useCallback(async () => {
|
||
try {
|
||
setIsLoadingHistory(true);
|
||
const entries = await getHistory(50, 0);
|
||
setHistoryEntries(entries);
|
||
} catch (err) {
|
||
console.error('Failed to load history:', err);
|
||
} finally {
|
||
setIsLoadingHistory(false);
|
||
}
|
||
}, [getHistory]);
|
||
|
||
const getHistoryIcon = (type: string) => {
|
||
switch (type) {
|
||
case 'mint':
|
||
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
|
||
case 'melt':
|
||
return <Zap className="h-4 w-4 text-yellow-500" />;
|
||
case 'send':
|
||
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
|
||
case 'receive':
|
||
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
|
||
default:
|
||
return <History className="h-4 w-4" />;
|
||
}
|
||
};
|
||
|
||
const getHistoryLabel = (type: string) => {
|
||
switch (type) {
|
||
case 'mint':
|
||
return 'Mint (Lightning → Tokens)';
|
||
case 'melt':
|
||
return 'Melt (Tokens → Lightning)';
|
||
case 'send':
|
||
return 'Send Tokens';
|
||
case 'receive':
|
||
return 'Receive Tokens';
|
||
default:
|
||
return type;
|
||
}
|
||
};
|
||
|
||
const getHistoryStateColor = (state?: string) => {
|
||
if (!state) return 'bg-gray-500';
|
||
switch (state) {
|
||
case 'PAID':
|
||
return 'bg-green-500';
|
||
case 'UNPAID':
|
||
return 'bg-yellow-500';
|
||
case 'PENDING':
|
||
return 'bg-blue-500';
|
||
default:
|
||
return 'bg-gray-500';
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// EVENT HANDLERS - Receive
|
||
// ============================================================================
|
||
|
||
const handleReceive = async () => {
|
||
if (receiveMode === 'tokens') {
|
||
if (!tokenInput.trim()) return;
|
||
try {
|
||
await receive(tokenInput);
|
||
setTokenInput('');
|
||
const message = 'Token received successfully!';
|
||
console.log('✅', message);
|
||
alert(message);
|
||
} catch (err) {
|
||
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
} else {
|
||
// Lightning mode - create mint quote
|
||
if (!quoteAmount || !activeMintUrl) return;
|
||
try {
|
||
const amount = parseInt(quoteAmount);
|
||
if (isNaN(amount) || amount <= 0) {
|
||
const message = 'Please enter a valid amount';
|
||
console.warn('⚠️', message);
|
||
alert(message);
|
||
return;
|
||
}
|
||
const quote = await createMintQuote(activeMintUrl, amount);
|
||
|
||
// Generate QR code for the Lightning invoice
|
||
const qrCodeUrl = await generateQRCodeForQuote(quote.request);
|
||
|
||
// Save the pending quote with QR code
|
||
setPendingQuotes(prev => [...prev, {
|
||
quoteId: quote.quote,
|
||
mintUrl: activeMintUrl,
|
||
amount,
|
||
invoice: quote.request,
|
||
timestamp: Date.now(),
|
||
qrCodeUrl
|
||
}]);
|
||
|
||
const message = `Mint quote created! Request: ${quote.request}`;
|
||
console.log('✅', message);
|
||
console.log('💰 Quote object:', quote);
|
||
console.log('🔗 Lightning Invoice:', quote.request);
|
||
alert('Lightning invoice created! After paying, click the refresh button (🔄) to claim your tokens.');
|
||
setQuoteAmount('');
|
||
} catch (err) {
|
||
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// EVENT HANDLERS - Send
|
||
// ============================================================================
|
||
|
||
const handleSend = async () => {
|
||
if (sendMode === 'tokens') {
|
||
if (!sendAmount || !activeMintUrl) return;
|
||
try {
|
||
const amount = parseInt(sendAmount);
|
||
if (isNaN(amount) || amount <= 0) {
|
||
const message = 'Please enter a valid amount';
|
||
console.warn('⚠️', message);
|
||
alert(message);
|
||
return;
|
||
}
|
||
const encodedToken = await send(activeMintUrl, amount);
|
||
setSentToken(encodedToken);
|
||
console.log('✅ Token sent successfully!');
|
||
console.log('📤 Encoded token:', encodedToken);
|
||
setSendAmount('');
|
||
} catch (err) {
|
||
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
} 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) {
|
||
alert('Please enter a valid amount');
|
||
return;
|
||
}
|
||
|
||
console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount);
|
||
const invoice = await getLightningInvoice({
|
||
lightningAddress: pendingLightningAddress,
|
||
amountSats: amount,
|
||
});
|
||
|
||
console.log('🔄 Creating melt quote for invoice:', invoice);
|
||
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
|
||
|
||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||
|
||
console.log('✅ Lightning payment sent successfully!');
|
||
alert(`Successfully sent ${amount} sats to ${pendingLightningAddress}!`);
|
||
|
||
// Reset state
|
||
setPendingLightningAddress(null);
|
||
setLightningAddressInput('');
|
||
setLightningAddressAmount('');
|
||
|
||
// Refresh balances
|
||
await refreshBalances();
|
||
} catch (err) {
|
||
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
} 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('@')) {
|
||
console.log('📧 Detected Lightning address:', input);
|
||
setPendingLightningAddress(input);
|
||
setLightningAddressInput('');
|
||
} else {
|
||
// It's a regular Lightning invoice
|
||
try {
|
||
console.log('🔄 Creating melt quote for invoice:', input);
|
||
const meltQuote = await createMeltQuote(activeMintUrl, input);
|
||
|
||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||
|
||
console.log('✅ Lightning invoice paid successfully!');
|
||
alert('Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.');
|
||
setLightningInvoice('');
|
||
|
||
// Refresh balances to show updated amounts
|
||
await refreshBalances();
|
||
} catch (err) {
|
||
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// EVENT HANDLERS - Utility
|
||
// ============================================================================
|
||
|
||
const handleCopy = async (text: string, type: 'token' | 'invoice') => {
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
if (type === 'token') {
|
||
setCopiedToken(true);
|
||
setTimeout(() => setCopiedToken(false), 2000);
|
||
} else {
|
||
setCopiedInvoice(text);
|
||
setTimeout(() => setCopiedInvoice(null), 2000);
|
||
}
|
||
} catch (err) {
|
||
console.error('Failed to copy to clipboard:', err);
|
||
alert('Failed to copy to clipboard');
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// 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('');
|
||
|
||
// Explicitly refresh mints and balances
|
||
await refreshMints();
|
||
await refreshBalances();
|
||
|
||
const message = `Mint added successfully: ${normalizedUrl}`;
|
||
console.log('✅', message);
|
||
alert('Mint added successfully!');
|
||
} catch (err) {
|
||
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// EVENT HANDLERS - Quote Management
|
||
// ============================================================================
|
||
|
||
const handleClaimQuote = async (quoteId: string, mintUrl: string) => {
|
||
try {
|
||
console.log('🎯 Attempting to claim quote:', quoteId, 'from mint:', mintUrl);
|
||
await redeemMintQuote(mintUrl, quoteId);
|
||
|
||
// Remove from pending quotes
|
||
setPendingQuotes(prev => prev.filter(q => q.quoteId !== quoteId));
|
||
|
||
// Refresh balances
|
||
await refreshBalances();
|
||
|
||
console.log('✅ Quote claimed successfully!');
|
||
alert('Tokens claimed successfully! Your balance has been updated.');
|
||
} catch (err) {
|
||
const errorMessage = `Failed to claim tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||
console.error('❌', errorMessage, err);
|
||
alert(errorMessage);
|
||
}
|
||
};
|
||
|
||
// Claim npub.cash quotes
|
||
const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => {
|
||
try {
|
||
console.log('🎯 Claiming npubx.cash quote:', quote);
|
||
console.log('📋 Quote details:', {
|
||
quote_id: quote.quoteId,
|
||
mint_url: quote.mintUrl,
|
||
amount: quote.amount,
|
||
state: quote.state,
|
||
});
|
||
|
||
// Add mint if not already added
|
||
const hasMint = mints.some(m => m.url === quote.mintUrl);
|
||
if (!hasMint) {
|
||
console.log('➕ Adding mint:', quote.mintUrl);
|
||
await addMint(quote.mintUrl);
|
||
}
|
||
|
||
// Use coco-cashu's addMintQuote API instead of calling mint directly
|
||
console.log('🔄 Adding mint quote to coco-cashu:', quote.quoteId);
|
||
await addMintQuote(quote.mintUrl, quote.quoteId);
|
||
|
||
console.log('✅ Quote added to coco-cashu successfully');
|
||
console.log('💡 Coco will automatically redeem when mint processor runs');
|
||
|
||
// Trigger the mint processor to check and redeem the quote
|
||
await checkAndRedeemPendingQuotes();
|
||
|
||
// Refresh quotes and balances
|
||
await fetchQuotes();
|
||
await refreshBalances();
|
||
|
||
alert(`Successfully claimed ${quote.amount} sats!`);
|
||
} catch (err) {
|
||
console.error('Failed to claim npub.cash quote:', err);
|
||
alert(`Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`);
|
||
}
|
||
};
|
||
const handleShowDenominations = async (mintUrl: string) => {
|
||
try {
|
||
console.log('🔍 Getting token denominations for mint:', mintUrl);
|
||
|
||
// Get proofs from the wallet for this specific mint
|
||
const proofs = await getProofs(mintUrl);
|
||
console.log('💰 Raw proofs for mint:', proofs);
|
||
|
||
if (!proofs || proofs.length === 0) {
|
||
alert('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) {
|
||
console.error('Failed to get denominations:', err);
|
||
alert('Failed to get token denominations. Check console for details.');
|
||
}
|
||
};
|
||
|
||
// ============================================================================
|
||
// EFFECTS
|
||
// ============================================================================
|
||
|
||
// Auto-select active mint when mints or balances change
|
||
useEffect(() => {
|
||
if (mints.length > 0 && !activeMintUrl) {
|
||
// Find mint with highest balance, or first mint if balances are equal
|
||
const mintWithHighestBalance = mints.reduce((highest, current) => {
|
||
const currentBalance = balances[current.url] || 0;
|
||
const highestBalance = balances[highest.url] || 0;
|
||
return currentBalance > highestBalance ? current : highest;
|
||
});
|
||
handleSetActiveMint(mintWithHighestBalance.url);
|
||
}
|
||
}, [mints, activeMintUrl, balances, handleSetActiveMint]);
|
||
|
||
// Load transaction history when wallet is initialized
|
||
useEffect(() => {
|
||
if (isInitialized && historyEntries.length === 0) {
|
||
loadHistory();
|
||
}
|
||
}, [isInitialized, historyEntries.length, loadHistory]);
|
||
|
||
// Generate QR codes for existing pending quotes that don't have them
|
||
useEffect(() => {
|
||
const generateMissingQRCodes = async () => {
|
||
const quotesNeedingQR = pendingQuotes.filter(quote => !quote.qrCodeUrl);
|
||
if (quotesNeedingQR.length === 0) return;
|
||
|
||
const updatedQuotes = await Promise.all(
|
||
pendingQuotes.map(async (quote) => {
|
||
if (!quote.qrCodeUrl) {
|
||
const qrCodeUrl = await generateQRCodeForQuote(quote.invoice);
|
||
return { ...quote, qrCodeUrl };
|
||
}
|
||
return quote;
|
||
})
|
||
);
|
||
|
||
setPendingQuotes(updatedQuotes);
|
||
};
|
||
|
||
generateMissingQRCodes();
|
||
}, []); // Only run once on mount
|
||
|
||
// ============================================================================
|
||
// RENDER - Loading State
|
||
// ============================================================================
|
||
|
||
if (isLoading) {
|
||
return (
|
||
<div className="flex items-center justify-center min-h-screen">
|
||
<Card className="border-0 shadow-none bg-muted/30">
|
||
<CardContent className="flex items-center justify-center p-8">
|
||
<Loader2 className="h-8 w-8 animate-spin mr-2" />
|
||
<span>Initializing...</span>
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ============================================================================
|
||
// RENDER - Uninitialized State
|
||
// ============================================================================
|
||
|
||
if (!isInitialized) {
|
||
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>
|
||
);
|
||
}
|
||
|
||
// ============================================================================
|
||
// RENDER - Main UI
|
||
// ============================================================================
|
||
|
||
return (
|
||
<div className="container mx-auto py-1 px-3 sm:px-4">
|
||
|
||
{/* ========================================================================
|
||
SECTION: Balance Display
|
||
======================================================================== */}
|
||
{isInitialized && (
|
||
<div className="text-center py-2">
|
||
<div className="flex items-center justify-center gap-3">
|
||
<button
|
||
onClick={() => setShowSats(!showSats)}
|
||
className="text-5xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
|
||
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
|
||
>
|
||
{formatAmount(totalBalance)}
|
||
</button>
|
||
<Button
|
||
variant="ghost"
|
||
size="icon"
|
||
onClick={async () => {
|
||
console.log('🔄 Manual refresh triggered');
|
||
await checkAndRedeemPendingQuotes();
|
||
await refreshBalances();
|
||
await loadHistory();
|
||
await refreshNpubCash();
|
||
console.log('💰 Current balances after manual refresh:', balances);
|
||
}}
|
||
className="mt-2"
|
||
title="Check for paid invoices and refresh balances and history"
|
||
>
|
||
<RefreshCw className="h-5 w-5" />
|
||
</Button>
|
||
</div>
|
||
{/* Active Mint Dropdown and Balance */}
|
||
<div className="mt-3 flex items-center justify-center gap-4">
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
|
||
<Wallet className="h-4 w-4" />
|
||
{activeMintUrl ? getCleanMintLabel({ url: activeMintUrl }) : 'Select Mint'}
|
||
<ChevronDown className="h-4 w-4" />
|
||
</Button>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent align="center" className="w-72">
|
||
<DropdownMenuLabel>Connected Mints</DropdownMenuLabel>
|
||
<DropdownMenuSeparator />
|
||
{mints.length === 0 && (
|
||
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
|
||
)}
|
||
{mints
|
||
.filter((mint) => mint.url)
|
||
.map((mint, index) => (
|
||
<DropdownMenuItem
|
||
key={`dd-mint-${mint.url || `unknown-${index}`}`}
|
||
className="flex items-center justify-between"
|
||
onClick={() => handleSetActiveMint(mint.url)}
|
||
>
|
||
<div className="flex items-center gap-2">
|
||
<span className="font-medium">{getCleanMintLabel(mint)}</span>
|
||
</div>
|
||
</DropdownMenuItem>
|
||
))}
|
||
<DropdownMenuSeparator />
|
||
<div className="px-2 py-1.5">
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="mint.example.com"
|
||
value={mintUrl}
|
||
onChange={(e) => setMintUrl(e.target.value)}
|
||
className="h-8"
|
||
/>
|
||
<Button size="sm" onClick={handleAddMint} disabled={!mintUrl.trim()}>
|
||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||
Add
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
|
||
{/* Active Mint Balance */}
|
||
{activeMintUrl && (
|
||
<div className="flex items-center gap-2">
|
||
<button
|
||
onClick={() => activeMintUrl && handleShowDenominations(activeMintUrl)}
|
||
className="text-sm font-semibold tabular-nums hover:opacity-80 transition-opacity cursor-pointer text-muted-foreground hover:text-foreground"
|
||
title="Click to see proof breakdown"
|
||
>
|
||
{formatAmount(balances[activeMintUrl] || 0)}
|
||
</button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{/* npub.cash Lightning Address */}
|
||
{lightningAddress && (
|
||
<div className="mt-4 p-4 bg-muted/30 rounded-lg">
|
||
<div className="flex items-center justify-center gap-2 mb-2">
|
||
<CreditCard className="h-4 w-4 text-muted-foreground" />
|
||
<span className="text-sm font-medium text-muted-foreground">Your Lightning Address</span>
|
||
</div>
|
||
<div className="flex items-center justify-center gap-2">
|
||
<code className="bg-background px-3 py-2 rounded text-sm font-mono border">
|
||
{lightningAddress}
|
||
</code>
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={copyLightningAddress}
|
||
className="h-8"
|
||
>
|
||
{copiedLightningAddress ? (
|
||
<Check className="h-3 w-3" />
|
||
) : (
|
||
<Copy className="h-3 w-3" />
|
||
)}
|
||
</Button>
|
||
</div>
|
||
{unclaimedAmount > 0 && (
|
||
<div className="mt-2 flex items-center justify-center gap-2">
|
||
<Badge variant="secondary" className="text-sm">
|
||
{unclaimedAmount} sats unclaimed
|
||
</Badge>
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={refreshNpubCash}
|
||
disabled={isNpubCashLoading}
|
||
className="h-6 text-xs"
|
||
>
|
||
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
|
||
Refresh
|
||
</Button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{/* ========================================================================
|
||
SECTION: Error Display
|
||
======================================================================== */}
|
||
{(error || npubCashError) && (
|
||
<Alert variant="destructive" className="mb-6">
|
||
<AlertDescription className="flex items-center justify-between">
|
||
<div className="flex-1">
|
||
{error || npubCashError}
|
||
{npubCashError && npubCashError.includes('Authorization') && (
|
||
<div className="text-xs mt-1 opacity-75">
|
||
Try refreshing the page or check your Nostr extension
|
||
</div>
|
||
)}
|
||
</div>
|
||
<div className="flex gap-2">
|
||
{npubCashError && (
|
||
<Button variant="outline" size="sm" onClick={retryAuth}>
|
||
Retry Auth
|
||
</Button>
|
||
)}
|
||
<Button variant="outline" size="sm" onClick={() => {
|
||
if (error) clearError();
|
||
// npub.cash errors are handled by retryAuth
|
||
}}>
|
||
Dismiss
|
||
</Button>
|
||
</div>
|
||
</AlertDescription>
|
||
</Alert>
|
||
)}
|
||
|
||
{/* ========================================================================
|
||
SECTION: Receive & Send Cards
|
||
======================================================================== */}
|
||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||
|
||
{/* Receive Card */}
|
||
<Card className="border-0 shadow-none bg-muted/30">
|
||
<CardHeader>
|
||
<CardTitle className="flex items-center justify-between">
|
||
<div className="flex items-center">
|
||
<Download className="h-5 w-5 mr-2" />
|
||
Receive
|
||
</div>
|
||
<div className="flex gap-1 bg-muted rounded-lg p-1">
|
||
<button
|
||
onClick={() => setReceiveMode('tokens')}
|
||
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
|
||
receiveMode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||
}`}
|
||
>
|
||
<Coins className="h-3.5 w-3.5" />
|
||
</button>
|
||
<button
|
||
onClick={() => setReceiveMode('lightning')}
|
||
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
|
||
receiveMode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||
}`}
|
||
>
|
||
<Zap className="h-3.5 w-3.5" />
|
||
</button>
|
||
</div>
|
||
</CardTitle>
|
||
<CardDescription>
|
||
{receiveMode === 'tokens'
|
||
? 'Enter Cashu token to redeem'
|
||
: 'Deposit funds with Lightning'
|
||
}
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-4">
|
||
{receiveMode === 'tokens' ? (
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="cashuBo2Ft..."
|
||
value={tokenInput}
|
||
onChange={(e) => setTokenInput(e.target.value)}
|
||
className="flex-1"
|
||
/>
|
||
<Button onClick={handleReceive} disabled={!tokenInput.trim()}>
|
||
<Download className="h-4 w-4 mr-2" />
|
||
Receive
|
||
</Button>
|
||
</div>
|
||
) : (
|
||
<>
|
||
{!activeMintUrl && (
|
||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||
Select a mint from "Connected Mints" to create Lightning invoice
|
||
</div>
|
||
)}
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="Amount (sats)"
|
||
type="number"
|
||
value={quoteAmount}
|
||
onChange={(e) => setQuoteAmount(e.target.value)}
|
||
/>
|
||
<Button onClick={handleReceive} disabled={!quoteAmount || !activeMintUrl}>
|
||
<Zap className="h-4 w-4 mr-2" />
|
||
Quote
|
||
</Button>
|
||
</div>
|
||
</>
|
||
)}
|
||
</CardContent>
|
||
</Card>
|
||
|
||
{/* Send Card */}
|
||
<Card className="border-0 shadow-none bg-muted/30">
|
||
<CardHeader>
|
||
<CardTitle className="flex items-center justify-between">
|
||
<div className="flex items-center">
|
||
<Send className="h-5 w-5 mr-2" />
|
||
Send
|
||
</div>
|
||
<div className="flex gap-1 bg-muted rounded-lg p-1">
|
||
<button
|
||
onClick={() => setSendMode('tokens')}
|
||
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
|
||
sendMode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||
}`}
|
||
>
|
||
<Coins className="h-3.5 w-3.5" />
|
||
</button>
|
||
<button
|
||
onClick={() => setSendMode('lightning')}
|
||
className={`px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 ${
|
||
sendMode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
|
||
}`}
|
||
>
|
||
<Zap className="h-3.5 w-3.5" />
|
||
</button>
|
||
</div>
|
||
</CardTitle>
|
||
<CardDescription>
|
||
{sendMode === 'tokens'
|
||
? 'Generate Cashu token to send'
|
||
: pendingLightningAddress
|
||
? 'Enter the amount to send'
|
||
: 'Pay Lightning invoices or addresses from balance'
|
||
}
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-4">
|
||
{sendMode === 'tokens' ? (
|
||
<>
|
||
{!activeMintUrl && (
|
||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||
Select a mint from "Connected Mints" to send tokens
|
||
</div>
|
||
)}
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="Amount (sats)"
|
||
type="number"
|
||
value={sendAmount}
|
||
onChange={(e) => setSendAmount(e.target.value)}
|
||
/>
|
||
<Button onClick={handleSend} disabled={!sendAmount || !activeMintUrl}>
|
||
<Send className="h-4 w-4 mr-2" />
|
||
Send
|
||
</Button>
|
||
</div>
|
||
</>
|
||
) : (
|
||
<>
|
||
{!activeMintUrl && (
|
||
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
|
||
Select a mint from "Connected Mints" to pay Lightning invoices
|
||
</div>
|
||
)}
|
||
{pendingLightningAddress ? (
|
||
// Step 2: Show amount input for Lightning address
|
||
<div className="space-y-3">
|
||
<div className="text-sm bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 p-3 rounded">
|
||
<div className="font-medium text-blue-900 dark:text-blue-100">
|
||
Sending to: {pendingLightningAddress}
|
||
</div>
|
||
<div className="text-xs text-blue-700 dark:text-blue-300 mt-1">
|
||
Enter amount to send
|
||
</div>
|
||
</div>
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="Amount (sats)"
|
||
type="number"
|
||
value={lightningAddressAmount}
|
||
onChange={(e) => setLightningAddressAmount(e.target.value)}
|
||
autoFocus
|
||
/>
|
||
<Button
|
||
onClick={handleSend}
|
||
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress}
|
||
>
|
||
{isResolvingAddress ? (
|
||
<>
|
||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||
Sending...
|
||
</>
|
||
) : (
|
||
<>
|
||
<Zap className="h-4 w-4 mr-2" />
|
||
Pay
|
||
</>
|
||
)}
|
||
</Button>
|
||
<Button
|
||
variant="outline"
|
||
onClick={() => {
|
||
setPendingLightningAddress(null);
|
||
setLightningAddressAmount('');
|
||
}}
|
||
>
|
||
Cancel
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
) : (
|
||
// Step 1: Show invoice/address input
|
||
<div className="flex gap-2">
|
||
<Input
|
||
placeholder="Lightning invoice (lnbc...) or address ([email protected])"
|
||
value={lightningInvoice || lightningAddressInput}
|
||
onChange={(e) => {
|
||
const value = e.target.value;
|
||
if (value.includes('@')) {
|
||
setLightningAddressInput(value);
|
||
setLightningInvoice('');
|
||
} else {
|
||
setLightningInvoice(value);
|
||
setLightningAddressInput('');
|
||
}
|
||
}}
|
||
className="flex-1"
|
||
/>
|
||
<Button
|
||
onClick={handleSend}
|
||
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl}
|
||
>
|
||
<>
|
||
<Zap className="h-4 w-4 mr-2" />
|
||
Pay
|
||
</>
|
||
</Button>
|
||
</div>
|
||
)}
|
||
</>
|
||
)}
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
|
||
{/* ========================================================================
|
||
SECTION: Sent Token Display
|
||
======================================================================== */}
|
||
{sentToken && (
|
||
<Card className="mt-6 border-green-500/50 bg-green-500/5">
|
||
<CardHeader className="relative">
|
||
<Button
|
||
onClick={() => setSentToken(null)}
|
||
className="absolute top-2 right-2"
|
||
size="sm"
|
||
variant="ghost"
|
||
>
|
||
<X className="h-4 w-4" />
|
||
</Button>
|
||
<CardTitle className="flex items-center text-green-600 dark:text-green-400 pr-8">
|
||
<Check className="h-5 w-5 mr-2" />
|
||
Token Created Successfully
|
||
</CardTitle>
|
||
<CardDescription>
|
||
Share this token with the recipient to send them your sats
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent>
|
||
<div className="relative">
|
||
<div className="bg-muted p-4 rounded-lg border font-mono text-sm">
|
||
{sentToken.length > 20 ? `${sentToken.substring(0, 20)}...` : sentToken}
|
||
</div>
|
||
<Button
|
||
onClick={() => sentToken && handleCopy(sentToken, 'token')}
|
||
className="absolute top-2 right-2"
|
||
size="sm"
|
||
variant="secondary"
|
||
>
|
||
{copiedToken ? (
|
||
<>
|
||
<Check className="h-4 w-4 mr-2" />
|
||
Copied!
|
||
</>
|
||
) : (
|
||
<>
|
||
<Copy className="h-4 w-4 mr-2" />
|
||
Copy Token
|
||
</>
|
||
)}
|
||
</Button>
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
)}
|
||
|
||
{/* ========================================================================
|
||
SECTION: Pending Lightning Payments
|
||
======================================================================== */}
|
||
{pendingQuotes.length > 0 && (
|
||
<Card className="mt-6">
|
||
<CardHeader className="relative">
|
||
<Button
|
||
onClick={() => setPendingQuotes([])}
|
||
className="absolute top-2 right-2"
|
||
size="sm"
|
||
variant="ghost"
|
||
>
|
||
<X className="h-4 w-4" />
|
||
</Button>
|
||
<CardTitle className="flex items-center pr-8">
|
||
<Bitcoin className="h-5 w-5 mr-2" />
|
||
Pending Lightning Payments
|
||
</CardTitle>
|
||
<CardDescription>
|
||
Click "Check Payment" after paying the Lightning invoice
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent>
|
||
<div className="space-y-3">
|
||
{pendingQuotes.map((quote) => (
|
||
<div key={quote.quoteId} className="border rounded-lg p-4 space-y-3">
|
||
<div className="flex items-center justify-between">
|
||
<div>
|
||
<div className="font-medium">{quote.amount} sats</div>
|
||
<div className="text-sm text-muted-foreground">
|
||
{new URL(quote.mintUrl).hostname}
|
||
</div>
|
||
<div className="text-xs text-muted-foreground mt-1">
|
||
Created: {new Date(quote.timestamp).toLocaleTimeString()}
|
||
</div>
|
||
</div>
|
||
<Button
|
||
onClick={() => handleClaimQuote(quote.quoteId, quote.mintUrl)}
|
||
size="sm"
|
||
>
|
||
Check Payment
|
||
</Button>
|
||
</div>
|
||
{/* QR Code */}
|
||
{quote.qrCodeUrl && (
|
||
<div className="flex justify-center mb-3">
|
||
<div className="bg-white dark:bg-gray-100 p-3 rounded-lg border shadow-sm">
|
||
<img
|
||
src={quote.qrCodeUrl}
|
||
alt="Lightning Invoice QR Code"
|
||
className="w-28 h-28 sm:w-32 sm:h-32 object-contain"
|
||
/>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
<div className="relative">
|
||
<div className="bg-muted p-4 rounded-lg border font-mono text-sm">
|
||
{quote.invoice.length > 20 ? `${quote.invoice.substring(0, 20)}...` : quote.invoice}
|
||
</div>
|
||
<Button
|
||
onClick={() => handleCopy(quote.invoice, 'invoice')}
|
||
className="absolute top-2 right-2"
|
||
size="sm"
|
||
variant="secondary"
|
||
>
|
||
{copiedInvoice === quote.invoice ? (
|
||
<>
|
||
<Check className="h-4 w-4 mr-2" />
|
||
Copied!
|
||
</>
|
||
) : (
|
||
<>
|
||
<Copy className="h-4 w-4 mr-2" />
|
||
Copy Invoice
|
||
</>
|
||
)}
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
)}
|
||
|
||
{/* ========================================================================
|
||
SECTION: npub.cash Received Payments
|
||
======================================================================== */}
|
||
{quotes.length > 0 && (
|
||
<Card className="mt-6">
|
||
<CardHeader>
|
||
<CardTitle className="flex items-center justify-between">
|
||
<div className="flex items-center">
|
||
<CreditCard className="h-5 w-5 mr-2" />
|
||
Received Payments (npub.cash)
|
||
</div>
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
onClick={refreshNpubCash}
|
||
disabled={isNpubCashLoading}
|
||
className="gap-1"
|
||
>
|
||
<RefreshCw className={`h-4 w-4 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
|
||
Refresh
|
||
</Button>
|
||
</CardTitle>
|
||
<CardDescription>
|
||
Lightning payments received to your npub.cash address
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent>
|
||
<div className="space-y-2">
|
||
{quotes && quotes.length > 0 ? quotes.map(quote => {
|
||
const isExpired = quote.expiresAt < Date.now() / 1000;
|
||
const isPaid = quote.state === 'PAID';
|
||
|
||
return (
|
||
<div key={quote.quoteId} className="border rounded-lg p-3">
|
||
<div className="flex justify-between items-start mb-2">
|
||
<div>
|
||
<p className="font-semibold">{quote.amount} sats</p>
|
||
<p className="text-xs text-muted-foreground">
|
||
{quote.paidAt ? new Date(quote.paidAt * 1000).toLocaleString() : 'Unknown date'}
|
||
</p>
|
||
</div>
|
||
<div className="flex gap-2 items-center">
|
||
<Badge
|
||
variant={
|
||
isPaid ? 'default' :
|
||
isExpired ? 'secondary' :
|
||
'outline'
|
||
}
|
||
>
|
||
{quote.state}
|
||
</Badge>
|
||
{isPaid && !isExpired && (
|
||
<Button
|
||
size="sm"
|
||
onClick={() => handleClaimNpubCashQuote(quote)}
|
||
disabled={isLoading}
|
||
>
|
||
Claim
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
<div className="space-y-1 text-xs text-muted-foreground">
|
||
<p className="truncate">Mint: {quote.mintUrl}</p>
|
||
{isExpired && (
|
||
<p className="text-destructive">
|
||
Expired: {new Date(quote.expiresAt * 1000).toLocaleString()}
|
||
</p>
|
||
)}
|
||
{quote.locked && (
|
||
<Badge variant="outline" className="text-xs">
|
||
🔒 Locked to your pubkey
|
||
</Badge>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}) : null}
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
)}
|
||
|
||
{/* ========================================================================
|
||
SECTION: Transaction History
|
||
======================================================================== */}
|
||
<Card className="mt-6 border-0 shadow-none">
|
||
<CardHeader>
|
||
<CardTitle className="flex items-center justify-between">
|
||
<div className="flex items-center">
|
||
<History className="h-5 w-5 mr-2" />
|
||
Transaction History
|
||
</div>
|
||
{historyEntries.length > 3 && (
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
onClick={() => setIsHistoryExpanded(!isHistoryExpanded)}
|
||
className="gap-1"
|
||
>
|
||
{isHistoryExpanded ? (
|
||
<>
|
||
<ChevronUp className="h-4 w-4" />
|
||
Show Less
|
||
</>
|
||
) : (
|
||
<>
|
||
<ChevronDown className="h-4 w-4" />
|
||
Show All ({historyEntries.length})
|
||
</>
|
||
)}
|
||
</Button>
|
||
)}
|
||
</CardTitle>
|
||
<CardDescription>
|
||
View your recent transactions
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent>
|
||
{isLoadingHistory ? (
|
||
<div className="flex items-center justify-center py-8">
|
||
<Loader2 className="h-6 w-6 animate-spin mr-2" />
|
||
<span>Loading history...</span>
|
||
</div>
|
||
) : historyEntries.length === 0 ? (
|
||
<div className="text-center py-8 text-muted-foreground">
|
||
No transaction history yet
|
||
</div>
|
||
) : (
|
||
<div className="space-y-2">
|
||
{(isHistoryExpanded ? historyEntries : historyEntries.slice(0, 3)).map((entry) => (
|
||
<div
|
||
key={entry.id}
|
||
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
|
||
>
|
||
<div className="flex items-start justify-between">
|
||
<div className="flex items-start gap-3 flex-1">
|
||
<div className="mt-1">
|
||
{getHistoryIcon(entry.type)}
|
||
</div>
|
||
<div className="flex-1 min-w-0">
|
||
<div className="flex items-center gap-2 flex-wrap">
|
||
<span className="font-medium">
|
||
{getHistoryLabel(entry.type)}
|
||
</span>
|
||
{entry.state && (
|
||
<Badge
|
||
variant="secondary"
|
||
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
|
||
>
|
||
{entry.state}
|
||
</Badge>
|
||
)}
|
||
</div>
|
||
<div className="text-sm text-muted-foreground mt-1">
|
||
{new URL(entry.mintUrl).hostname}
|
||
</div>
|
||
<div className="text-xs text-muted-foreground mt-1">
|
||
{new Date(entry.createdAt).toLocaleString()}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div className="text-right ml-4">
|
||
<div className="font-semibold">
|
||
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
|
||
{entry.amount.toLocaleString()} {entry.unit}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</CardContent>
|
||
</Card>
|
||
|
||
{/* ========================================================================
|
||
SECTION: Proof Breakdown Modal
|
||
======================================================================== */}
|
||
{showProofBreakdown && proofBreakdown && (
|
||
<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={() => setShowProofBreakdown(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">
|
||
<Coins className="h-5 w-5 mr-2" />
|
||
Token Breakdown
|
||
</CardTitle>
|
||
<CardDescription>
|
||
{new URL(proofBreakdown.mintUrl).hostname}
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="space-y-4">
|
||
<div className="text-center py-2">
|
||
<div className="text-2xl font-bold text-primary">
|
||
{formatAmount(proofBreakdown.totalBalance)}
|
||
</div>
|
||
<div className="text-sm text-muted-foreground">Total Balance</div>
|
||
</div>
|
||
|
||
<div className="space-y-2">
|
||
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
|
||
{Object.entries(proofBreakdown.denominations)
|
||
.sort(([a], [b]) => parseInt(a) - parseInt(b))
|
||
.map(([amount, count]) => (
|
||
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
|
||
<div className="flex items-center gap-2">
|
||
<Coins className="h-4 w-4 text-muted-foreground" />
|
||
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
|
||
</div>
|
||
<Badge variant="secondary" className="bg-primary/10 text-primary">
|
||
× {count}
|
||
</Badge>
|
||
</div>
|
||
))}
|
||
</div>
|
||
|
||
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
|
||
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|