implement npubcash-sdk to simplify code

This commit is contained in:
lemonknowsall committed 2025-10-15 01:22:12 -07:00
1 parent 2ac097d8de
commit bd956cef3f
5 files changed
+265 -265

No files matched your search

+36 -34
View File
@@ -34,7 +34,15 @@ export function CashuWallet() {
clearError,
} = useCashu();
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
// Npub.cash integration with cleaner SDK-based implementation
const {
setMint: setNpubCashMint,
getUserInfo: getNpubCashUserInfo,
isLoggedIn: isNpubCashLoggedIn,
isLoading: isNpubCashLoading,
error: npubCashError,
clearError: clearNpubCashError
} = useNpubCash();
const { user } = useCurrentUser();
@@ -156,21 +164,13 @@ export function CashuWallet() {
* @param syncToNpubCash - Whether to sync this change to npub.cash (default: true for manual changes)
*/
const handleSetActiveMint = useCallback(async (mintUrl: string | null, syncToNpubCash = true) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
// If user is logged in to npub.cash, a mint is selected, and we should sync
// Sync to npub.cash if user is logged in and we should sync
if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) {
const success = await setNpubCashMint(mintUrl);
if (success) {
toast({
title: "Mint Synced",
description: "Your preferred mint has been updated on npub.cash",
});
}
await setNpubCashMint(mintUrl);
}
}, [isNpubCashLoggedIn, setNpubCashMint, toast]);
}, [isNpubCashLoggedIn, setNpubCashMint]);
// ============================================================================
// HELPER FUNCTIONS - History
@@ -515,53 +515,55 @@ export function CashuWallet() {
}
}, [error, toast]);
// Show npub.cash error toasts
useEffect(() => {
if (npubCashError) {
toast({
variant: "destructive",
title: "Npub.cash Error",
description: npubCashError,
});
clearNpubCashError();
}
}, [npubCashError, clearNpubCashError, toast]);
// Fetch npub.cash user info on mount/login and sync mint
useEffect(() => {
// Reset the check flag if user logs out
if (!isNpubCashLoggedIn) {
hasCheckedNpubCashRef.current = false;
setNpubCashUserInfo(null);
return;
}
// Only fetch if user is logged in, wallet is initialized, and we haven't fetched yet
if (!isInitialized || hasCheckedNpubCashRef.current) return;
if (!isInitialized || hasCheckedNpubCashRef.current || isNpubCashLoading) return;
const fetchUserInfo = async () => {
// Mark that we've checked to prevent multiple fetches
hasCheckedNpubCashRef.current = true;
const userInfo = await getNpubCashUserInfo();
if (!userInfo) return;
setNpubCashUserInfo(userInfo);
// Check if the mint from npub.cash is different from our active mint
// Sync mint from npub.cash if different from active mint
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
// Check if we have this mint in our list
const mintExists = mints.some(m => m.url === userInfo.mint_url);
if (!mintExists) {
if (!mintExists && coco) {
try {
if (coco) {
await coco.mint.addMint(userInfo.mint_url);
// Wait a bit for the mint to be added
setTimeout(() => {
handleSetActiveMint(userInfo.mint_url, false);
}, 500);
}
} catch (err) {
await coco.mint.addMint(userInfo.mint_url);
setTimeout(() => handleSetActiveMint(userInfo.mint_url, false), 500);
} catch {
// Silent failure - user can manually add mint if needed
}
} else {
// Mint exists, just set it as active (without syncing back to npub.cash)
} else if (mintExists) {
handleSetActiveMint(userInfo.mint_url, false);
}
}
};
fetchUserInfo();
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, coco, handleSetActiveMint]);
}, [isNpubCashLoggedIn, isInitialized, isNpubCashLoading, getNpubCashUserInfo, activeMintUrl, mints, coco, handleSetActiveMint]);
// Auto-select active mint when mints change (balances will update automatically via events)
useEffect(() => {
@@ -678,7 +680,7 @@ export function CashuWallet() {
setQuoteAmount={setQuoteAmount}
activeMintUrl={activeMintUrl}
onReceive={handleReceive}
isLoading={isLoading}
isLoading={isLoading || isNpubCashLoading}
/>
<SendCard
@@ -696,7 +698,7 @@ export function CashuWallet() {
activeMintUrl={activeMintUrl}
onSend={handleSend}
isResolvingAddress={isResolvingAddress}
isLoading={isLoading}
isLoading={isLoading || isNpubCashLoading}
/>
</div>
@@ -793,7 +795,7 @@ export function CashuWallet() {
onClose={() => setShowRemoveMintModal(false)}
mint={mintToRemove}
onConfirm={handleConfirmRemoveMint}
isLoading={isLoading}
isLoading={isLoading || isNpubCashLoading}
/>
</>
</div>
+4 -29
View File
@@ -1,6 +1,5 @@
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
@@ -43,32 +42,16 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
const getHistoryLabel = (type: string) => {
switch (type) {
case 'mint':
return 'Mint Tokens';
case 'melt':
return 'Melt Tokens';
case 'send':
return 'Send Tokens';
case 'receive':
return 'Receive Tokens';
return 'Received';
case 'melt':
case 'send':
return 'Sent';
default:
return type;
}
};
const getHistoryStateColor = (state?: string) => {
if (!state) return 'bg-gray-500';
switch (state) {
case 'PAID':
return 'bg-green-500';
case 'UNPAID':
return 'bg-yellow-500';
case 'PENDING':
return 'bg-blue-500';
default:
return 'bg-gray-500';
}
};
return (
<Card className="mt-6 border-0 shadow-none">
<CardHeader>
@@ -129,14 +112,6 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
{'state' in entry && entry.state && (
<Badge
variant="secondary"
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
>
{entry.state}
</Badge>
)}
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
+94 -88
View File
@@ -1,7 +1,15 @@
import { useCallback, useState } from 'react';
import { useCallback, useState, useMemo } from 'react';
import { useNIP98 } from './useNIP98';
import { NPCClient } from 'npubcash-sdk';
import type { User, Quote } from 'npubcash-types';
const NPUBCASH_API_BASE = 'https://npubx.cash/api/v2';
// 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 {
pubkey: string;
@@ -10,131 +18,129 @@ export interface NpubCashUserInfo {
lock_quote: boolean;
}
export interface NpubCashApiError {
error: true;
message: string;
}
/**
* Custom auth provider that uses NIP-98 authentication
*/
class NIP98AuthProvider implements AuthProvider {
constructor(private createAuthHeader: (options: { url: string; method: string; body?: unknown }) => Promise<string>) {}
export interface NpubCashUserInfoResponse {
error: false;
data: {
user: NpubCashUserInfo;
};
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
* Currently supports setting the user's preferred mint and getting user info
* Hook for interacting with npub.cash API using the official SDK
*/
export function useNpubCash() {
const { createAuthHeader, isLoggedIn, pubkey } = useNIP98();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/**
* Set the user's preferred mint on npub.cash
*/
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!isLoggedIn) {
console.error('❌ User must be logged in to set mint');
return false;
}
// Create NPCClient instance using the SDK with custom NIP-98 auth provider
const npcClient = useMemo(() => {
if (!isLoggedIn) return null;
const authProvider = new NIP98AuthProvider(createAuthHeader);
return new NPCClient(NPUBCASH_BASE_URL, authProvider);
}, [isLoggedIn, createAuthHeader]);
// Generic wrapper for SDK calls with loading state
const withLoading = useCallback(async <T>(operation: () => Promise<T>): Promise<T | null> => {
try {
setIsLoading(true);
setError(null);
const url = `${NPUBCASH_API_BASE}/user/mint`;
const body = { mint_url: mintUrl };
const authHeader = await createAuthHeader({ url, method: 'PATCH', body });
console.log(`🔄 Setting preferred mint on npub.cash to: ${mintUrl}`);
const response = await fetch(url, {
method: 'PATCH',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if (!response.ok) {
// Try to parse JSON error, but handle HTML responses (404, etc.)
try {
const errorData = await response.json() as NpubCashApiError;
throw new Error(errorData.message || `Failed to set mint (${response.status})`);
} catch (parseError) {
throw new Error(`Failed to set mint: ${response.status} ${response.statusText}`);
}
}
console.log(`✅ Successfully set preferred mint on npub.cash to: ${mintUrl}`);
return true;
return await operation();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
console.error('❌ Failed to set npub.cash mint:', errorMessage);
setError(errorMessage);
return false;
return null;
} finally {
setIsLoading(false);
}
}, [isLoggedIn, createAuthHeader]);
}, []);
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setMintUrl(mintUrl));
return result !== null;
}, [npcClient, withLoading]);
/**
* Get user info from npub.cash
*/
const getUserInfo = useCallback(async (): Promise<NpubCashUserInfo | null> => {
if (!isLoggedIn) {
console.error('❌ User must be logged in to get npub.cash user info');
return null;
}
try {
setIsLoading(true);
setError(null);
const url = `${NPUBCASH_API_BASE}/user/info`;
if (!npcClient) return null;
// Since SDK doesn't have getUserInfo, we'll use manual implementation
// This could be enhanced if SDK adds this method
return withLoading(async () => {
const url = `${NPUBCASH_BASE_URL}/api/v2/user/info`;
const authHeader = await createAuthHeader({ url, method: 'GET' });
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json',
},
headers: { 'Authorization': authHeader, 'Content-Type': 'application/json' },
});
if (!response.ok) {
// Try to parse JSON error, but handle HTML responses (404, etc.)
try {
const errorData = await response.json() as NpubCashApiError;
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
} catch (parseError) {
throw new Error(`Failed to get user info: ${response.status} ${response.statusText}`);
}
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `Failed to get user info (${response.status})`);
}
const data = await response.json() as NpubCashUserInfoResponse;
console.log('✅ Successfully retrieved npub.cash user info:', data.data.user);
const data = await response.json();
return data.data.user;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
console.error('❌ Failed to get npub.cash user info:', errorMessage);
setError(errorMessage);
return null;
} finally {
setIsLoading(false);
}
}, [isLoggedIn, createAuthHeader]);
});
}, [npcClient, createAuthHeader, withLoading]);
const getAllQuotes = useCallback(async (): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getAllQuotes());
return result || [];
}, [npcClient, withLoading]);
const getQuotesSince = useCallback(async (since: number): Promise<Quote[]> => {
if (!npcClient) return [];
const result = await withLoading(() => npcClient.getQuotesSince(since));
return result || [];
}, [npcClient, withLoading]);
const setLockQuotes = useCallback(async (lockQuotes: boolean): Promise<boolean> => {
if (!npcClient) return false;
const result = await withLoading(() => npcClient.settings.setLock(lockQuotes));
return result !== null;
}, [npcClient, withLoading]);
const subscribeToQuotes = useCallback((
onUpdate: (quoteId: string) => void,
onError?: (msg: string) => void
) => {
if (!npcClient) return () => {};
return npcClient.subscribe(onUpdate, onError);
}, [npcClient]);
const clearError = useCallback(() => setError(null), []);
return {
// Core methods
setMint,
getUserInfo,
// Quote management methods
getAllQuotes,
getQuotesSince,
setLockQuotes,
subscribeToQuotes,
// Status
isLoading,
error,
isLoggedIn,
pubkey,
clearError,
// SDK instance for advanced usage
npcClient,
};
}