infinite loop initialization, wallet endpoint structure, zapdialog debug

This commit is contained in:
lemonknowsall committed 2025-10-06 17:27:30 -07:00
1 parent 4672413b04
commit e14d4e887f
6 files changed
+284 -23

No files matched your search

+65 -2
View File
@@ -9,6 +9,7 @@ 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 } from 'lucide-react';
import QRCode from 'qrcode';
export function CashuWallet() {
// ============================================================================
@@ -71,6 +72,7 @@ export function CashuWallet() {
amount: number;
invoice: string;
timestamp: number;
qrCodeUrl?: string;
}>>('cashu-pending-quotes', []);
// ============================================================================
@@ -80,6 +82,7 @@ export function CashuWallet() {
const [copiedToken, setCopiedToken] = useState(false);
const [copiedInvoice, setCopiedInvoice] = useState<string | null>(null);
// ============================================================================
// STATE - History
// ============================================================================
@@ -127,6 +130,27 @@ export function CashuWallet() {
}
};
// ============================================================================
// 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 - History
// ============================================================================
@@ -218,13 +242,17 @@ export function CashuWallet() {
}
const quote = await createMintQuote(activeMintUrl, amount);
// Save the pending quote
// 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()
timestamp: Date.now(),
qrCodeUrl
}]);
const message = `Mint quote created! Request: ${quote.request}`;
@@ -479,6 +507,28 @@ export function CashuWallet() {
}
}, [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
// ============================================================================
@@ -944,6 +994,19 @@ export function CashuWallet() {
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}
+11
View File
@@ -389,6 +389,17 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
// Validate the amount
if (isNaN(finalAmount) || finalAmount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
return;
}
if (canPayWithCashu && finalAmount > cashuBalance) {
toast({
title: 'Insufficient Cashu balance',
+89 -10
View File
@@ -203,12 +203,21 @@ export function useCashu(): UseCashuReturn {
if (claimedCount > 0) {
console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`);
await refreshBalances();
// Call refreshBalances directly without dependency to avoid circular dependency
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
setBalances(newBalances);
console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints');
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
}
} catch (err) {
console.error('❌ Error checking pending quotes:', err);
}
}, [refreshBalances]);
}, []); // Remove refreshBalances dependency to break the circular dependency
// Initialize the manager
const initializeManager = useCallback(async () => {
@@ -251,12 +260,81 @@ export function useCashu(): UseCashuReturn {
);
managerRef.current = manager;
// Load initial data
await refreshBalances();
await refreshMints();
// Load initial data - call functions directly to avoid circular dependencies
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await manager.wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
setBalances(newBalances);
console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints');
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
try {
const mintList = await manager.mint.getAllMints();
const formattedMints = mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
}
// Check for any pending quotes that might have been paid
await checkAndRedeemPendingQuotes();
try {
console.log('🔍 Checking for pending mint quotes in IndexedDB...');
// Access the mint quotes repository directly
const mintQuotesRepo = (repositories as { mintQuoteRepository?: { getPendingMintQuotes: () => Promise<Array<Record<string, unknown>>> } })?.mintQuoteRepository;
if (mintQuotesRepo) {
// Get all pending mint quotes (non-ISSUED quotes)
const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes();
console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`);
// Filter for UNPAID quotes (these might have been paid but not redeemed)
const unpaidQuotes = pendingQuotes.filter((q: { state?: string }) => q.state === 'UNPAID');
console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`);
let claimedCount = 0;
for (const quote of unpaidQuotes) {
try {
const q = quote as { quote: string; mintUrl: string; amount: number };
console.log(`🔄 Attempting to redeem quote ${q.quote} from ${q.mintUrl}...`);
await manager.quotes.redeemMintQuote(q.mintUrl, q.quote);
claimedCount++;
console.log(`✅ Successfully claimed ${q.amount} sats from quote ${q.quote}`);
} catch {
const q = quote as { quote: string };
// Quote not paid yet or already claimed - this is expected, just skip
console.log(`⏭️ Quote ${q.quote} not ready yet (invoice not paid or already claimed)`);
}
}
if (claimedCount > 0) {
console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`);
// Refresh balances after claiming quotes
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await manager.wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
setBalances(newBalances);
console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints');
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
}
} else {
console.log('⚠️ Mint quotes repository not available');
}
} catch (err) {
console.error('❌ Error checking pending quotes:', err);
}
setIsInitialized(true);
} catch (err) {
@@ -266,9 +344,9 @@ export function useCashu(): UseCashuReturn {
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState, refreshBalances, refreshMints, checkAndRedeemPendingQuotes]);
}, [isInitialized, isLoading, mnemonic, setMnemonicState]); // Remove function dependencies to break circular dependency
// Initialize on mount
// Initialize on mount and when mnemonic changes
useEffect(() => {
initializeManager();
}, [initializeManager]);
@@ -459,8 +537,9 @@ export function useCashu(): UseCashuReturn {
setMnemonicState(newMnemonic);
// Reinitialize manager with new mnemonic
setIsInitialized(false);
initializeManager();
}, [setMnemonicState, initializeManager]);
// Don't call initializeManager directly to avoid circular dependency
// The useEffect will handle reinitialization when isInitialized changes
}, [setMnemonicState]);
const generateMnemonic = useCallback(() => {
return bip39.generateMnemonic(wordlist);
+26 -4
View File
@@ -133,7 +133,13 @@ export function useZaps(
}, [zapEvents, actualTarget]);
const zap = async (amount: number, comment: string) => {
if (amount <= 0) {
if (amount <= 0 || isNaN(amount)) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount greater than 0.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
@@ -160,6 +166,17 @@ export function useZaps(
return;
}
// Additional validation to ensure actualTarget has required properties
if (!actualTarget.pubkey || !actualTarget.id) {
toast({
title: 'Invalid event',
description: 'The event is missing required properties.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
try {
if (!author.data || !author.data?.metadata || !author.data?.event ) {
toast({
@@ -197,12 +214,17 @@ export function useZaps(
// Create zap request - use appropriate event format based on kind
// For addressable events (30000-39999), pass the object to get 'a' tag
// For all other events, pass the ID string to get 'e' tag
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
? actualTarget
: actualTarget.id;
const event = (actualTarget!.kind >= 30000 && actualTarget!.kind < 40000)
? actualTarget!
: actualTarget!.id;
const zapAmount = amount * 1000; // convert to millisats
// Validate zapAmount is a valid number
if (isNaN(zapAmount) || zapAmount <= 0) {
throw new Error('Invalid zap amount');
}
const zapRequest = nip57.makeZapRequest({
profile: actualTarget.pubkey,
event: event as Event,