mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +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>;
|
onCopyToClipboard: (text: string) => Promise<void>;
|
||||||
onShowLightningAddressQR: (qrCode: string) => void;
|
onShowLightningAddressQR: (qrCode: string) => void;
|
||||||
generateQRCode: (text: string) => Promise<string>;
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
// Refresh functionality
|
|
||||||
onRefreshQuotes: () => Promise<void>;
|
|
||||||
isRefreshingQuotes: boolean;
|
|
||||||
// Dropdown state
|
// Dropdown state
|
||||||
mintDropdownOpen: boolean;
|
mintDropdownOpen: boolean;
|
||||||
setMintDropdownOpen: (open: boolean) => void;
|
setMintDropdownOpen: (open: boolean) => void;
|
||||||
@@ -62,8 +59,6 @@ export function BalanceDisplay({
|
|||||||
onCopyToClipboard,
|
onCopyToClipboard,
|
||||||
onShowLightningAddressQR,
|
onShowLightningAddressQR,
|
||||||
generateQRCode,
|
generateQRCode,
|
||||||
onRefreshQuotes,
|
|
||||||
isRefreshingQuotes,
|
|
||||||
mintDropdownOpen,
|
mintDropdownOpen,
|
||||||
setMintDropdownOpen,
|
setMintDropdownOpen,
|
||||||
}: BalanceDisplayProps) {
|
}: BalanceDisplayProps) {
|
||||||
@@ -98,18 +93,6 @@ export function BalanceDisplay({
|
|||||||
>
|
>
|
||||||
{convertCurrency(totalBalance, showSats)}
|
{convertCurrency(totalBalance, showSats)}
|
||||||
</button>
|
</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>
|
</div>
|
||||||
|
|
||||||
{/* Main Mode Toggle */}
|
{/* Main Mode Toggle */}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export function CashuWallet() {
|
|||||||
getUserInfo: getNpubCashUserInfo,
|
getUserInfo: getNpubCashUserInfo,
|
||||||
getAllQuotes,
|
getAllQuotes,
|
||||||
refreshQuotes,
|
refreshQuotes,
|
||||||
|
syncQuotesWithWallet,
|
||||||
isLoggedIn: isNpubCashLoggedIn,
|
isLoggedIn: isNpubCashLoggedIn,
|
||||||
isLoading: isNpubCashLoading,
|
isLoading: isNpubCashLoading,
|
||||||
error: npubCashError,
|
error: npubCashError,
|
||||||
@@ -233,6 +234,25 @@ export function CashuWallet() {
|
|||||||
fetchUserInfo();
|
fetchUserInfo();
|
||||||
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, setActiveMintUrl]);
|
}, [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
|
// EFFECTS - Cleanup
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -284,8 +304,6 @@ export function CashuWallet() {
|
|||||||
setShowLightningAddressQR(true);
|
setShowLightningAddressQR(true);
|
||||||
}}
|
}}
|
||||||
generateQRCode={generateQRCode}
|
generateQRCode={generateQRCode}
|
||||||
onRefreshQuotes={() => refreshQuotes(coco, toast)}
|
|
||||||
isRefreshingQuotes={isNpubCashLoading}
|
|
||||||
mintDropdownOpen={mintDropdownOpen}
|
mintDropdownOpen={mintDropdownOpen}
|
||||||
setMintDropdownOpen={setMintDropdownOpen}
|
setMintDropdownOpen={setMintDropdownOpen}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ export function useNIP98() {
|
|||||||
createAuthHeader,
|
createAuthHeader,
|
||||||
isLoggedIn: !!user,
|
isLoggedIn: !!user,
|
||||||
pubkey: user?.pubkey,
|
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 { useNIP98 } from './useNIP98';
|
||||||
import { NPCClient } from 'npubcash-sdk';
|
import { NPCClient, JWTAuthProvider } from 'npubcash-sdk';
|
||||||
import type { User, Quote } from 'npubcash-types';
|
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';
|
const NPUBCASH_BASE_URL = 'https://npubx.cash';
|
||||||
|
|
||||||
export interface NpubCashUserInfo {
|
export interface NpubCashUserInfo {
|
||||||
@@ -18,35 +12,27 @@ export interface NpubCashUserInfo {
|
|||||||
lock_quote: boolean;
|
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
|
* Hook for interacting with npub.cash API using the official SDK
|
||||||
*/
|
*/
|
||||||
export function useNpubCash() {
|
export function useNpubCash() {
|
||||||
const { createAuthHeader, isLoggedIn, pubkey } = useNIP98();
|
const { createAuthHeader, signer, isLoggedIn, pubkey } = useNIP98();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
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(() => {
|
const npcClient = useMemo(() => {
|
||||||
if (!isLoggedIn) return null;
|
if (!isLoggedIn || !signer) return null;
|
||||||
const authProvider = new NIP98AuthProvider(createAuthHeader);
|
// Adapt NostrSigner to JWTAuthProvider's expected SigningFunc signature
|
||||||
return new NPCClient(NPUBCASH_BASE_URL, authProvider);
|
const signingFunc = async (eventTemplate: any) => {
|
||||||
}, [isLoggedIn, createAuthHeader]);
|
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
|
// Generic wrapper for SDK calls with loading state
|
||||||
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
|
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
|
||||||
@@ -194,6 +180,119 @@ export function useNpubCash() {
|
|||||||
|
|
||||||
const clearError = useCallback(() => setError(null), []);
|
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 {
|
return {
|
||||||
// Core methods
|
// Core methods
|
||||||
setMint,
|
setMint,
|
||||||
@@ -205,6 +304,7 @@ export function useNpubCash() {
|
|||||||
setLockQuotes,
|
setLockQuotes,
|
||||||
subscribeToQuotes,
|
subscribeToQuotes,
|
||||||
refreshQuotes,
|
refreshQuotes,
|
||||||
|
syncQuotesWithWallet,
|
||||||
|
|
||||||
// Status
|
// Status
|
||||||
isLoading,
|
isLoading,
|
||||||
|
|||||||
Reference in new issue
Block a user