From ea57135d1e6f8e0cff9b72093a5b7804ed37b844 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Thu, 16 Oct 2025 17:05:39 -0700 Subject: [PATCH] npubxcash lnaddress subscriptions working --- src/components/wallet/BalanceDisplay.tsx | 17 --- src/components/wallet/CashuWallet.tsx | 22 +++- src/hooks/useNIP98.ts | 1 + src/hooks/useNpubCash.ts | 158 ++++++++++++++++++----- 4 files changed, 150 insertions(+), 48 deletions(-) diff --git a/src/components/wallet/BalanceDisplay.tsx b/src/components/wallet/BalanceDisplay.tsx index 1e623c5..3e0fbf1 100644 --- a/src/components/wallet/BalanceDisplay.tsx +++ b/src/components/wallet/BalanceDisplay.tsx @@ -33,9 +33,6 @@ interface BalanceDisplayProps { onCopyToClipboard: (text: string) => Promise; onShowLightningAddressQR: (qrCode: string) => void; generateQRCode: (text: string) => Promise; - // Refresh functionality - onRefreshQuotes: () => Promise; - isRefreshingQuotes: boolean; // Dropdown state mintDropdownOpen: boolean; setMintDropdownOpen: (open: boolean) => void; @@ -62,8 +59,6 @@ export function BalanceDisplay({ onCopyToClipboard, onShowLightningAddressQR, generateQRCode, - onRefreshQuotes, - isRefreshingQuotes, mintDropdownOpen, setMintDropdownOpen, }: BalanceDisplayProps) { @@ -98,18 +93,6 @@ export function BalanceDisplay({ > {convertCurrency(totalBalance, showSats)} - - {/* Refresh Quotes Button */} - {userPubkey && ( - - )} {/* Main Mode Toggle */} diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index c370676..08e6414 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -48,6 +48,7 @@ export function CashuWallet() { getUserInfo: getNpubCashUserInfo, getAllQuotes, refreshQuotes, + syncQuotesWithWallet, isLoggedIn: isNpubCashLoggedIn, isLoading: isNpubCashLoading, error: npubCashError, @@ -233,6 +234,25 @@ export function CashuWallet() { fetchUserInfo(); }, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]); + // Set up automatic quote sync subscription when logged into npub.cash + useEffect(() => { + if (!isNpubCashLoggedIn || !coco || !isInitialized) return; + + let unsubscribe: (() => void) | null = null; + + const setupSync = async () => { + unsubscribe = await syncQuotesWithWallet(coco, toast); + }; + + setupSync(); + + return () => { + if (unsubscribe) { + unsubscribe(); + } + }; + }, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]); + // ============================================================================ // EFFECTS - Cleanup // ============================================================================ @@ -284,8 +304,6 @@ export function CashuWallet() { setShowLightningAddressQR(true); }} generateQRCode={generateQRCode} - onRefreshQuotes={() => refreshQuotes(coco, toast)} - isRefreshingQuotes={isNpubCashLoading} mintDropdownOpen={mintDropdownOpen} setMintDropdownOpen={setMintDropdownOpen} /> diff --git a/src/hooks/useNIP98.ts b/src/hooks/useNIP98.ts index 0eb2c6a..15773df 100644 --- a/src/hooks/useNIP98.ts +++ b/src/hooks/useNIP98.ts @@ -68,6 +68,7 @@ export function useNIP98() { createAuthHeader, isLoggedIn: !!user, pubkey: user?.pubkey, + signer: user?.signer, }; } diff --git a/src/hooks/useNpubCash.ts b/src/hooks/useNpubCash.ts index 7665bb6..7b00993 100644 --- a/src/hooks/useNpubCash.ts +++ b/src/hooks/useNpubCash.ts @@ -1,14 +1,8 @@ -import { useCallback, useState, useMemo } from 'react'; +import { useCallback, useState, useMemo, useEffect, useRef } from 'react'; import { useNIP98 } from './useNIP98'; -import { NPCClient } from 'npubcash-sdk'; +import { NPCClient, JWTAuthProvider } from 'npubcash-sdk'; import type { User, Quote } from 'npubcash-types'; -// AuthProvider interface for custom NIP-98 authentication -interface AuthProvider { - getAuthToken(url: string, method: string): Promise; - getNostrToken(url: string, method: string): Promise; -} - const NPUBCASH_BASE_URL = 'https://npubx.cash'; export interface NpubCashUserInfo { @@ -18,35 +12,27 @@ export interface NpubCashUserInfo { lock_quote: boolean; } -/** - * Custom auth provider that uses NIP-98 authentication - */ -class NIP98AuthProvider implements AuthProvider { - constructor(private createAuthHeader: (options: { url: string; method: string; body?: unknown }) => Promise) {} - - async getAuthToken(url: string, method: string): Promise { - return this.createAuthHeader({ url, method }); - } - - async getNostrToken(url: string, method: string): Promise { - return this.createAuthHeader({ url, method }); - } -} - /** * Hook for interacting with npub.cash API using the official SDK */ export function useNpubCash() { - const { createAuthHeader, isLoggedIn, pubkey } = useNIP98(); + const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98(); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); + + // Ref to track last sync timestamp for incremental updates + const lastSyncRef = useRef(0); - // Create NPCClient instance using the SDK with custom NIP-98 auth provider + // Create NPCClient instance using the SDK with JWTAuthProvider for proper WebSocket auth const npcClient = useMemo(() => { - if (!isLoggedIn) return null; - const authProvider = new NIP98AuthProvider(createAuthHeader); - return new NPCClient(NPUBCASH_BASE_URL, authProvider); - }, [isLoggedIn, createAuthHeader]); + if (!isLoggedIn || !signer) return null; + // Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature + const signingFunc = async (eventTemplate: any) => { + return await signer.signEvent(eventTemplate); + }; + const auth = new JWTAuthProvider(NPUBCASH_BASE_URL, signingFunc); + return new NPCClient(NPUBCASH_BASE_URL, auth); + }, [isLoggedIn, signer]); // Generic wrapper for SDK calls with loading state const withLoading = useCallback(async (operation: () => Promise): Promise => { @@ -194,6 +180,119 @@ export function useNpubCash() { const clearError = useCallback(() => setError(null), []); + // Subscribe to quote updates and sync to wallet automatically + const syncQuotesWithWallet = useCallback(async (coco: any, toast: any): Promise<() => void> => { + if (!npcClient || !coco) return () => {}; + + try { + // Fetch and sync all quotes initially + const quotes = await getAllQuotes(); + if (quotes.length > 0) { + const quotesByMint = quotes.reduce((acc, quote) => { + if (!acc[quote.mintUrl]) { + acc[quote.mintUrl] = []; + } + acc[quote.mintUrl].push(quote); + return acc; + }, {} as Record); + + let addedQuotes = 0; + for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) { + try { + const isKnown = await coco.mint.isKnownMint(mintUrl); + if (!isKnown) { + await coco.mint.addMint(mintUrl); + } + + coco.quotes.addMintQuote( + mintUrl, + mintQuotes.map((q) => ({ + ...q, + expiry: q.expiresAt, + quote: q.quoteId, + state: "PAID", + unit: "sat", + })), + ); + addedQuotes += mintQuotes.length; + } catch (err) { + console.warn(`Failed to sync quotes for mint ${mintUrl}:`, err); + } + } + + if (addedQuotes > 0) { + toast({ + title: "Quotes Synced", + description: `Synced ${addedQuotes} quotes from npub.cash`, + }); + lastSyncRef.current = Math.floor(Date.now() / 1000); + } + } + + // Subscribe to real-time updates + const unsubscribe = subscribeToQuotes( + async (quoteId: string) => { + try { + // When a quote is updated, fetch newer quotes and sync + const recentQuotes = await getQuotesSince(lastSyncRef.current); + if (recentQuotes.length > 0) { + const quotesByMint = recentQuotes.reduce((acc, quote) => { + if (!acc[quote.mintUrl]) { + acc[quote.mintUrl] = []; + } + acc[quote.mintUrl].push(quote); + return acc; + }, {} as Record); + + for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) { + try { + const isKnown = await coco.mint.isKnownMint(mintUrl); + if (!isKnown) { + await coco.mint.addMint(mintUrl); + } + + coco.quotes.addMintQuote( + mintUrl, + mintQuotes.map((q) => ({ + ...q, + expiry: q.expiresAt, + quote: q.quoteId, + state: "PAID", + unit: "sat", + })), + ); + } catch (err) { + console.warn(`Failed to sync quote ${quoteId} for mint ${mintUrl}:`, err); + } + } + lastSyncRef.current = Math.floor(Date.now() / 1000); + } + } catch (err) { + console.error('Failed to sync quote update:', err); + } + }, + (err: string) => { + console.error('Quote subscription error:', err); + toast({ + variant: "destructive", + title: "Sync Error", + description: "Failed to sync quotes from npub.cash", + }); + } + ); + + return unsubscribe; + } catch (err) { + console.error('Failed to set up quote sync:', err); + toast({ + variant: "destructive", + title: "Sync Failed", + description: err instanceof Error ? err.message : 'Failed to set up quote sync', + }); + return () => {}; + } + }, [npcClient, getAllQuotes, getQuotesSince, subscribeToQuotes]); + return { // Core methods setMint, @@ -205,6 +304,7 @@ export function useNpubCash() { setLockQuotes, subscribeToQuotes, refreshQuotes, + syncQuotesWithWallet, // Status isLoading,