diff --git a/AGENTS.md b/AGENTS.md
index 317838f..519480e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -111,7 +111,29 @@ The project includes a **`docs/`** directory containing specialized documentatio
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
-- **`docs/CASHU_ZAP_INTEGRATION.md`**: Read when implementing zap functionality, integrating Cashu wallet payments, or building Lightning payment features. Essential for understanding the unified ZapButton architecture and Cashu-powered Lightning zaps.
+- **`docs/CASHU_ZAP_INTEGRATION.md`**: Read when implementing zap functionality, integrating Cashu wallet payments, or building Lightning payment features. Essential for understanding the unified ZapButton architecture and Cashu-powered Lightning zaps. **CRITICAL**: Follow the two-component architecture - `CashuWallet` for standalone wallet management, `ZapButton` for content integration.
+
+## Cashu Integration Architecture
+
+**IMPORTANT**: The Cashu wallet integration follows a **two-component architecture** that must be preserved:
+
+### Component Separation
+- **`CashuWallet`**: Standalone wallet management interface (dedicated page/route)
+- **`ZapButton`**: Integrated zap functionality within content feeds
+
+### Why This Architecture?
+- **Clean UX**: Users manage wallet separately from consuming content
+- **Performance**: Wallet operations don't interfere with feed rendering
+- **Security**: Sensitive wallet operations are isolated
+- **Mobile Optimization**: Wallet can use full-screen layouts
+
+### Integration Rules
+- ✅ **CORRECT**: `CashuWallet` as separate route/page
+- ✅ **CORRECT**: `ZapButton` embedded in content feeds
+- ❌ **INCORRECT**: Embedding `CashuWallet` in content feeds
+- ❌ **INCORRECT**: Mixing wallet management with content consumption
+
+**Always read `docs/CASHU_ZAP_INTEGRATION.md` before implementing any Cashu-related features.**
## System Prompt Management
diff --git a/docs/CASHU_ZAP_INTEGRATION.md b/docs/CASHU_ZAP_INTEGRATION.md
index a2e060e..4bb1d1f 100644
--- a/docs/CASHU_ZAP_INTEGRATION.md
+++ b/docs/CASHU_ZAP_INTEGRATION.md
@@ -98,6 +98,67 @@ import { useWallet } from '@/hooks/useWallet';
import { useZaps } from '@/hooks/useZaps';
```
+## Architecture Overview
+
+**IMPORTANT**: The Cashu integration uses a **two-component architecture**:
+
+1. **`CashuWallet`** - Standalone wallet management interface (separate page/route)
+2. **`ZapButton`** - Integrated zap functionality within content feeds
+
+### Component Separation
+
+The `CashuWallet` component is designed as a **standalone wallet management interface** and should remain separate from content feeds. This separation provides:
+
+- **Clean UX**: Users manage their wallet separately from consuming content
+- **Performance**: Wallet operations don't interfere with feed rendering
+- **Security**: Sensitive wallet operations are isolated
+- **Mobile Optimization**: Wallet can use full-screen layouts on mobile
+
+### Integration Pattern
+
+```tsx
+// ✅ CORRECT: Separate wallet management
+function App() {
+ return (
+
+
+ } />
+ } />
+
+
+ );
+}
+
+// ✅ CORRECT: ZapButton integrated in content
+function FeedPage() {
+ return (
+
+ {events.map(event => (
+
+ ))}
+
+ );
+}
+
+// ❌ INCORRECT: Don't embed CashuWallet in content feeds
+function FeedPage() {
+ return (
+
+
{/* Don't do this */}
+ {events.map(event => (
+
+ ))}
+
+ );
+}
+```
+
## Complete Example
```tsx
@@ -182,11 +243,13 @@ data-testid="zap-modal"
## Best Practices for AI Agents
-1. **Always include CashuWallet**: Let users manage their balance
-2. **Use consistent styling**: Apply your app's design system
-3. **Handle loading states**: The component manages its own loading states
-4. **Trust the intelligence**: The component handles payment method selection automatically
-5. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work
+1. **Maintain Component Separation**: Keep `CashuWallet` as a standalone page/route, not embedded in content feeds
+2. **Always include CashuWallet**: Provide a dedicated route/page for wallet management
+3. **Use consistent styling**: Apply your app's design system
+4. **Handle loading states**: The component manages its own loading states
+5. **Trust the intelligence**: The component handles payment method selection automatically
+6. **Test all scenarios**: Ensure Cashu, WebLN, NWC, and manual zaps all work
+7. **Follow the architecture**: Use `ZapButton` for content integration, `CashuWallet` for wallet management
## Troubleshooting
@@ -209,10 +272,11 @@ data-testid="zap-modal"
## Integration Checklist
- [ ] Import unified `ZapButton` component
-- [ ] Include `CashuWallet` for balance management
+- [ ] Create dedicated route/page for `CashuWallet` (don't embed in content feeds)
- [ ] Ensure `useCashu` hook is available
- [ ] Test all payment methods: Cashu → WebLN → NWC → Manual QR
- [ ] Verify mobile responsiveness
- [ ] Test error handling scenarios
+- [ ] Verify component separation (wallet management vs content integration)
This unified integration provides a seamless, intelligent zap experience that automatically selects the best available payment method while leveraging the benefits of both Cashu tokens and Lightning payments.
diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx
index 440abe3..268dccc 100644
--- a/src/components/CashuWallet.tsx
+++ b/src/components/CashuWallet.tsx
@@ -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(null);
+
// ============================================================================
// STATE - History
// ============================================================================
@@ -127,6 +130,27 @@ export function CashuWallet() {
}
};
+
+ // ============================================================================
+ // HELPER FUNCTIONS - QR Code
+ // ============================================================================
+
+ const generateQRCodeForQuote = async (invoice: string): Promise => {
+ 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
+ {/* QR Code */}
+ {quote.qrCodeUrl && (
+
+
+

+
+
+ )}
+
{quote.invoice.length > 20 ? `${quote.invoice.substring(0, 20)}...` : quote.invoice}
diff --git a/src/components/ZapDialog.tsx b/src/components/ZapDialog.tsx
index 52684d2..08c99ba 100644
--- a/src/components/ZapDialog.tsx
+++ b/src/components/ZapDialog.tsx
@@ -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',
diff --git a/src/hooks/useCashu.ts b/src/hooks/useCashu.ts
index 5f7960c..06962a3 100644
--- a/src/hooks/useCashu.ts
+++ b/src/hooks/useCashu.ts
@@ -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
} }).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 }) => ({
+ 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>> } })?.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);
diff --git a/src/hooks/useZaps.ts b/src/hooks/useZaps.ts
index e99f070..56216a9 100644
--- a/src/hooks/useZaps.ts
+++ b/src/hooks/useZaps.ts
@@ -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,