diff --git a/docs/CASHU_ZAP_INTEGRATION.md b/docs/CASHU_ZAP_INTEGRATION.md index 9ab0623..4ecea0d 100644 --- a/docs/CASHU_ZAP_INTEGRATION.md +++ b/docs/CASHU_ZAP_INTEGRATION.md @@ -87,17 +87,74 @@ When Cashu wallet is available and has sufficient balance: ## Required Dependencies -Ensure these hooks are available in your app: +**CRITICAL**: The `useCashu` hook MUST be wrapped in a Context Provider to avoid infinite loops! + +### Setup CashuContext (Required!) + +Create `src/contexts/CashuContext.tsx`: ```tsx -// Required for Cashu integration -import { useCashu } from '@/hooks/useCashu'; +import { createContext, useContext, ReactNode } from 'react'; +import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu'; -// Required for traditional Lightning zaps -import { useWallet } from '@/hooks/useWallet'; -import { useZaps } from '@/hooks/useZaps'; +const CashuContext = createContext(null); + +export function CashuProvider({ children }: { children: ReactNode }) { + const cashu = useCashuHook(); + + return ( + + {children} + + ); +} + +export function useCashu(): UseCashuReturn { + const context = useContext(CashuContext); + + if (!context) { + throw new Error('useCashu must be used within a CashuProvider'); + } + + return context; +} ``` +### Wrap Your App + +Add `CashuProvider` to your App.tsx: + +```tsx +import { CashuProvider } from '@/contexts/CashuContext'; + +export function App() { + return ( + + + {/* Your app */} + + + ); +} +``` + +### Import from Context + +**Always** import from the context, not the hook: + +```tsx +// ✅ CORRECT +import { useCashu } from '@/contexts/CashuContext'; + +// ❌ WRONG - Will cause infinite loops! +import { useCashu } from '@/hooks/useCashu'; +``` + +This ensures all components share the same Cashu wallet instance, preventing: +- Multiple wallet initializations +- Infinite refresh loops +- Performance issues + ## Architecture Overview **IMPORTANT**: The Cashu integration uses a **two-component architecture**: @@ -276,7 +333,14 @@ data-testid="zap-modal" ### Infinite Loop: `refreshBalances` Repeatedly Called If you see continuous console logs like `🔄 refreshBalances: Getting balances from wallet...`, the issue is likely: -**Root Cause**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency. +**Root Cause #1 (MOST COMMON)**: Multiple components are calling `useCashu()` directly from the hook instead of from the Context Provider. This creates multiple wallet instances that all try to initialize and refresh balances. + +**Solution**: Ensure you: +1. Created `CashuContext.tsx` as shown in the Required Dependencies section +2. Wrapped your app with `` +3. Import `useCashu` from `@/contexts/CashuContext` in ALL components (not from `@/hooks/useCashu`) + +**Root Cause #2**: A `useEffect` that depends on `balances` is triggering `refreshBalances()`, creating a circular dependency. **Built-in Protections**: The `useCashu` hook includes: - **Throttling**: Prevents calls more than once every 500ms @@ -315,9 +379,11 @@ useEffect(() => { ## Integration Checklist +- [ ] **CRITICAL**: Create `CashuContext.tsx` with `CashuProvider` (see Required Dependencies) +- [ ] **CRITICAL**: Wrap app with `` in App.tsx +- [ ] **CRITICAL**: Import `useCashu` from `@/contexts/CashuContext` in ALL components - [ ] Import unified `ZapButton` component - [ ] 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 diff --git a/src/contexts/CashuContext.tsx b/src/contexts/CashuContext.tsx new file mode 100644 index 0000000..22db07c --- /dev/null +++ b/src/contexts/CashuContext.tsx @@ -0,0 +1,25 @@ +import { createContext, useContext, ReactNode } from 'react'; +import { useCashu as useCashuHook, type UseCashuReturn } from '@/hooks/useCashu'; + +const CashuContext = createContext(null); + +export function CashuProvider({ children }: { children: ReactNode }) { + const cashu = useCashuHook(); + + return ( + + {children} + + ); +} + +export function useCashu(): UseCashuReturn { + const context = useContext(CashuContext); + + if (!context) { + throw new Error('useCashu must be used within a CashuProvider'); + } + + return context; +} + diff --git a/src/hooks/useCashu.ts b/src/hooks/useCashu.ts index a8e75c0..bb12822 100644 --- a/src/hooks/useCashu.ts +++ b/src/hooks/useCashu.ts @@ -132,17 +132,26 @@ export function useCashu(): UseCashuReturn { // Utility operations - defined first so they can be used in other callbacks const lastRefreshTimeRef = useRef(0); + const isRefreshingRef = useRef(false); const REFRESH_THROTTLE_MS = 500; // Prevent refreshing more than once every 500ms const refreshBalances = useCallback(async () => { if (!managerRef.current) return; + // Prevent concurrent calls + if (isRefreshingRef.current) { + console.log('⏭️ refreshBalances: Skipping (already in progress)'); + return; + } + // Throttle rapid successive calls const now = Date.now(); if (now - lastRefreshTimeRef.current < REFRESH_THROTTLE_MS) { console.log('⏭️ refreshBalances: Skipping (throttled)'); return; } + + isRefreshingRef.current = true; lastRefreshTimeRef.current = now; try { @@ -166,6 +175,8 @@ export function useCashu(): UseCashuReturn { }); } catch (err) { console.error('❌ refreshBalances: Failed to refresh balances:', err); + } finally { + isRefreshingRef.current = false; } }, []);