mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
implement npubcash-sdk to simplify code
This commit is contained in:
1 parent
2ac097d8de
commit
bd956cef3f
5 files changed
+265
-265
No files matched your search
+94
-88
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user