mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
npubxcash lnaddress subscriptions working
This commit is contained in:
1 parent
b5bc571aa7
commit
ea57135d1e
4 files changed
+150
-48
No files matched your search
@@ -33,9 +33,6 @@ interface BalanceDisplayProps {
|
||||
onCopyToClipboard: (text: string) => Promise<void>;
|
||||
onShowLightningAddressQR: (qrCode: string) => void;
|
||||
generateQRCode: (text: string) => Promise<string>;
|
||||
// Refresh functionality
|
||||
onRefreshQuotes: () => Promise<void>;
|
||||
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)}
|
||||
</button>
|
||||
|
||||
{/* Refresh Quotes Button */}
|
||||
{userPubkey && (
|
||||
<button
|
||||
onClick={onRefreshQuotes}
|
||||
disabled={isRefreshingQuotes}
|
||||
className="flex items-center justify-center p-2 hover:bg-muted rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
title="Refresh quotes from npub.cash"
|
||||
>
|
||||
<RefreshCw className={`h-5 w-5 text-muted-foreground ${isRefreshingQuotes ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Main Mode Toggle */}
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -68,6 +68,7 @@ export function useNIP98() {
|
||||
createAuthHeader,
|
||||
isLoggedIn: !!user,
|
||||
pubkey: user?.pubkey,
|
||||
signer: user?.signer,
|
||||
};
|
||||
}
|
||||
|
||||
+129
-29
@@ -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<string>;
|
||||
getNostrToken(url: string, method: string): Promise<string>;
|
||||
}
|
||||
|
||||
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<string>) {}
|
||||
|
||||
async getAuthToken(url: string, method: string): Promise<string> {
|
||||
return this.createAuthHeader({ url, method });
|
||||
}
|
||||
|
||||
async getNostrToken(url: string, method: string): Promise<string> {
|
||||
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<string | null>(null);
|
||||
|
||||
// Ref to track last sync timestamp for incremental updates
|
||||
const lastSyncRef = useRef<number>(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 <T>(operation: () => Promise<T>): Promise<T | null> => {
|
||||
@@ -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<string, typeof quotes>);
|
||||
|
||||
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<string, typeof recentQuotes>);
|
||||
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user