detect lightning payment and toast

This commit is contained in:
lemonknowsall committed 2025-10-12 13:01:18 -07:00
1 parent 967bdca369
commit 45918e86e2
3 files changed
+60 -9

No files matched your search

+59 -2
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback, useRef } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useCashuMints } from '@/hooks/cashu/useCashuMints'; import { useCashuMints } from '@/hooks/cashu/useCashuMints';
import { useLightningAddress } from '@/hooks/useLightningAddress'; import { useLightningAddress } from '@/hooks/useLightningAddress';
@@ -35,6 +35,7 @@ export function CashuWallet() {
payMeltQuote, payMeltQuote,
redeemMintQuote, redeemMintQuote,
addMintQuote, addMintQuote,
on,
refreshBalances, refreshBalances,
refreshMints, refreshMints,
clearError, clearError,
@@ -110,6 +111,9 @@ export function CashuWallet() {
url: string; url: string;
name?: string; name?: string;
} | null>(null); } | null>(null);
// Ref to store the mint quote redeemed event unsubscribe function
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
// ============================================================================ // ============================================================================
// COMPUTED VALUES // COMPUTED VALUES
@@ -220,6 +224,40 @@ export function CashuWallet() {
description: "Wallet will automatically claim tokens when payment is detected.", description: "Wallet will automatically claim tokens when payment is detected.",
}); });
setQuoteAmount(''); setQuoteAmount('');
// Clean up any previous listener
if (mintQuoteUnsubscribeRef.current) {
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
// Listen for payment notification via mint-quote:redeemed event (note: hyphenated!)
console.log('🔔 Setting up payment listener for quote:', quote.quote);
const quoteId = quote.quote;
const invoiceAmount = amount;
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
const redeemedQuote = payload as { quoteId?: string };
console.log('🔔 Mint quote redeemed event received:', redeemedQuote);
// Check if this is the quote we're waiting for
if (redeemedQuote.quoteId === quoteId) {
console.log('✅ Our quote was redeemed! Payment detected:', redeemedQuote);
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) { } catch (err) {
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`; const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
console.error('❌', errorMessage, err); console.error('❌', errorMessage, err);
@@ -520,6 +558,17 @@ export function CashuWallet() {
} }
}, [isInitialized, historyEntries.length, loadHistory]); }, [isInitialized, historyEntries.length, loadHistory]);
// Cleanup mint quote listener on component unmount
useEffect(() => {
return () => {
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (component unmount)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
};
}, []);
// ============================================================================ // ============================================================================
// RENDER - Main UI // RENDER - Main UI
@@ -636,7 +685,15 @@ export function CashuWallet() {
{currentInvoice && ( {currentInvoice && (
<QRModal <QRModal
isOpen={showInvoiceModal} isOpen={showInvoiceModal}
onClose={() => setShowInvoiceModal(false)} onClose={() => {
// Clean up event listener when modal is closed manually
if (mintQuoteUnsubscribeRef.current) {
console.log('🧹 Cleaning up mint quote listener (modal closed)');
mintQuoteUnsubscribeRef.current();
mintQuoteUnsubscribeRef.current = null;
}
setShowInvoiceModal(false);
}}
title="Lightning Invoice" title="Lightning Invoice"
description={`Pay this invoice to receive ${currentInvoice.amount} sats`} description={`Pay this invoice to receive ${currentInvoice.amount} sats`}
qrCodeUrl={currentInvoice.qrCodeUrl} qrCodeUrl={currentInvoice.qrCodeUrl}
+1 -1
View File
@@ -33,7 +33,7 @@ export function QRModal({
return ( return (
<div <div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4" className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
onClick={onClose} onClick={onClose}
> >
<Card <Card
-6
View File
@@ -102,11 +102,6 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
refreshBalances(); refreshBalances();
}); });
const unsubscribeMintQuoteRedeemed = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('mintQuote:redeemed', () => {
console.log('💰 Mint quote redeemed, refreshing balances...');
refreshBalances();
});
const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => { const unsubscribeSendCreated = (manager as { on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void }).on('send:created', () => {
console.log('📤 Send created, refreshing balances...'); console.log('📤 Send created, refreshing balances...');
// Bypass throttling for send operations to ensure immediate balance update // Bypass throttling for send operations to ensure immediate balance update
@@ -144,7 +139,6 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
return () => { return () => {
unsubscribeProofsSaved(); unsubscribeProofsSaved();
unsubscribeProofsStateChanged(); unsubscribeProofsStateChanged();
unsubscribeMintQuoteRedeemed();
unsubscribeSendCreated(); unsubscribeSendCreated();
unsubscribeReceiveCreated(); unsubscribeReceiveCreated();
}; };