mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
solid cashu foundation
This commit is contained in:
1 parent
a8faa03b49
commit
967bdca369
15 files changed
+1249
-1477
No files matched your search
@@ -1,5 +1,7 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { CashuBalance, CashuWalletError } from './types';
|
||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||
import { toast } from '../useToast';
|
||||
|
||||
export interface UseCashuBalancesReturn {
|
||||
balances: CashuBalance;
|
||||
@@ -7,12 +9,15 @@ export interface UseCashuBalancesReturn {
|
||||
error: CashuWalletError | null;
|
||||
refreshBalances: () => Promise<void>;
|
||||
getBalances: () => Promise<CashuBalance>;
|
||||
convertCurrency: (sats: number, showSats?: boolean) => string;
|
||||
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
|
||||
}
|
||||
|
||||
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
|
||||
const [balances, setBalances] = useState<CashuBalance>({});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
||||
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
|
||||
|
||||
// Throttling refs
|
||||
const lastRefreshTimeRef = useRef<number>(0);
|
||||
@@ -152,11 +157,54 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
|
||||
}
|
||||
}, [manager, balances, refreshBalances]);
|
||||
|
||||
// Fetch exchange rate on mount for fallback
|
||||
useEffect(() => {
|
||||
exchangeRateService.getBtcUsdRate()
|
||||
.then(rate => setFallbackRate(rate))
|
||||
.catch(error => {
|
||||
console.warn('Failed to fetch initial exchange rate:', error);
|
||||
// Keep fallbackRate as null to show sats instead of USD
|
||||
});
|
||||
}, []);
|
||||
|
||||
const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => {
|
||||
if (showSats) {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
} else {
|
||||
// Only show USD if we have a valid exchange rate
|
||||
if (fallbackRate) {
|
||||
const btcAmount = sats / 100000000;
|
||||
const usd = btcAmount * fallbackRate;
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} else {
|
||||
// If no exchange rate available, show sats instead of incorrect USD
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
}
|
||||
}
|
||||
}, [fallbackRate]);
|
||||
|
||||
const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise<string> => {
|
||||
if (showSats) {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
} else {
|
||||
try {
|
||||
const usd = await exchangeRateService.satsToUsd(sats);
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch exchange rate:', error);
|
||||
// If exchange rate fails, show sats instead of incorrect USD
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
balances,
|
||||
isLoading,
|
||||
error,
|
||||
refreshBalances,
|
||||
getBalances,
|
||||
convertCurrency,
|
||||
convertCurrencyAsync,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface UseCashuMintsReturn {
|
||||
getMints: () => Promise<CashuMint[]>;
|
||||
addMint: (mintUrl: string) => Promise<void>;
|
||||
removeMint: (mintUrl: string) => Promise<void>;
|
||||
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
|
||||
}
|
||||
|
||||
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
|
||||
@@ -28,6 +29,20 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
|
||||
name: mint.name,
|
||||
info: mint.mintInfo
|
||||
}));
|
||||
|
||||
// If no mints exist, add the default mint
|
||||
if (formattedMints.length === 0) {
|
||||
console.log('🔧 No mints found, adding default mint: mint.chorus.community');
|
||||
try {
|
||||
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint('https://mint.chorus.community');
|
||||
// The mint:added event will trigger refreshMints again, so we don't need to set mints here
|
||||
return;
|
||||
} catch (err) {
|
||||
console.warn('⚠️ Failed to add default mint:', err);
|
||||
// Continue with empty mints if default mint fails
|
||||
}
|
||||
}
|
||||
|
||||
setMints(formattedMints);
|
||||
} catch (err) {
|
||||
console.error('Failed to refresh mints:', err);
|
||||
@@ -133,6 +148,19 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
|
||||
}
|
||||
}, [manager, mints.length, refreshMints]);
|
||||
|
||||
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
|
||||
if (mint.name && mint.name.trim().length > 0) {
|
||||
// If name looks like a URL, strip protocol as well
|
||||
return mint.name.replace(/^https?:\/\//, '');
|
||||
}
|
||||
try {
|
||||
return new URL(mint.url).host; // host excludes protocol and preserves port if any
|
||||
} catch {
|
||||
// Fallback: manual strip
|
||||
return mint.url.replace(/^https?:\/\//, '');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mints,
|
||||
isLoading,
|
||||
@@ -141,5 +169,6 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
|
||||
getMints,
|
||||
addMint,
|
||||
removeMint,
|
||||
getCleanMintLabel,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useToast } from './useToast';
|
||||
|
||||
interface UseCopyToClipboardReturn {
|
||||
copy: (text: string) => Promise<void>;
|
||||
copied: boolean;
|
||||
copyError: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for copying text to clipboard with feedback
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { copy, copied, copyError } = useCopyToClipboard();
|
||||
*
|
||||
* await copy('cashuBo2Ft...');
|
||||
* // copied will be true for 2 seconds
|
||||
* ```
|
||||
*/
|
||||
export function useCopyToClipboard(): UseCopyToClipboardReturn {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [copyError, setCopyError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const copy = useCallback(async (text: string): Promise<void> => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setCopyError(null);
|
||||
|
||||
// Auto-reset copied state after 2 seconds
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (err) {
|
||||
const errorMessage = 'Failed to copy to clipboard';
|
||||
console.error(errorMessage, err);
|
||||
setCopyError(errorMessage);
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Copy Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
return {
|
||||
copy,
|
||||
copied,
|
||||
copyError,
|
||||
};
|
||||
}
|
||||
@@ -1,455 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useLocalStorage } from './useLocalStorage';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { nip19, finalizeEvent, generateSecretKey } from 'nostr-tools';
|
||||
import type { EventTemplate } from 'nostr-tools';
|
||||
|
||||
// API Base URL - can be configured
|
||||
const NPUBCASH_API_BASE = 'https://npubx.cash/api/v2';
|
||||
const NPUBCASH_DOMAIN = 'npubx.cash';
|
||||
|
||||
// Types for npub.cash API responses
|
||||
export interface NpubCashQuote {
|
||||
createdAt: number;
|
||||
paidAt: number;
|
||||
expiresAt: number;
|
||||
mintUrl: string;
|
||||
quoteId: string;
|
||||
request: string; // BOLT11 invoice
|
||||
amount: number; // Amount in sats
|
||||
state: 'PENDING' | 'PAID' | 'EXPIRED';
|
||||
locked: boolean;
|
||||
}
|
||||
|
||||
export interface NpubCashUserInfo {
|
||||
pubkey: string;
|
||||
name: string | null;
|
||||
mintUrl: string;
|
||||
lockQuote: boolean;
|
||||
}
|
||||
|
||||
export interface NpubCashState {
|
||||
isInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
lightningAddress: string | null;
|
||||
userInfo: NpubCashUserInfo | null;
|
||||
quotes: NpubCashQuote[];
|
||||
unclaimedAmount: number; // Total amount in unclaimed quotes
|
||||
}
|
||||
|
||||
export interface NpubCashActions {
|
||||
// Fetch user's paid quotes
|
||||
fetchQuotes: (since?: number, limit?: number) => Promise<NpubCashQuote[]>;
|
||||
|
||||
// Get user info/settings
|
||||
fetchUserInfo: () => Promise<NpubCashUserInfo>;
|
||||
|
||||
// Set username (costs sats via X-Cashu header)
|
||||
setUsername: (username: string) => Promise<void>;
|
||||
|
||||
// Set preferred mint
|
||||
setMint: (mintUrl: string) => Promise<void>;
|
||||
|
||||
// Toggle quote locking (NUT-20)
|
||||
setLockQuotes: (locked: boolean) => Promise<void>;
|
||||
|
||||
// Refresh all data
|
||||
refresh: () => Promise<void>;
|
||||
|
||||
// Clear JWT token (force re-auth)
|
||||
clearAuth: () => void;
|
||||
|
||||
// Retry authentication after error
|
||||
retryAuth: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for integrating npub.cash Lightning addresses
|
||||
*
|
||||
* Provides a Lightning address ([email protected]) for the current user
|
||||
* and methods to fetch/manage received payments stored as Cashu quotes.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { lightningAddress, quotes, unclaimedAmount, fetchQuotes } = useNpubCash();
|
||||
*
|
||||
* // Display Lightning address
|
||||
* <p>Send sats to: {lightningAddress}</p>
|
||||
*
|
||||
* // Show unclaimed balance
|
||||
* <p>Unclaimed: {unclaimedAmount} sats</p>
|
||||
*
|
||||
* // Fetch new quotes
|
||||
* await fetchQuotes();
|
||||
* ```
|
||||
*/
|
||||
export function useNpubCash(): NpubCashState & NpubCashActions {
|
||||
const { user } = useCurrentUser();
|
||||
const pubkey = user?.pubkey;
|
||||
|
||||
// Store JWT token for convenience (30min expiry)
|
||||
const [jwtToken, setJwtToken] = useLocalStorage<string | null>('npubcash-jwt', null);
|
||||
|
||||
// Store last claimed quote timestamp to track new payments
|
||||
const [lastClaimedAt, setLastClaimedAt] = useLocalStorage<number>('npubcash-last-claimed', 0);
|
||||
|
||||
// Component state
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [userInfo, setUserInfo] = useState<NpubCashUserInfo | null>(null);
|
||||
const [quotes, setQuotes] = useState<NpubCashQuote[]>([]);
|
||||
const [hasTriedInitialization, setHasTriedInitialization] = useState(false);
|
||||
|
||||
// Generate Lightning address from pubkey
|
||||
const lightningAddress = useMemo(() => {
|
||||
if (!pubkey) return null;
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
return `${npub}@${NPUBCASH_DOMAIN}`;
|
||||
}, [pubkey]);
|
||||
|
||||
/**
|
||||
* Create NIP-98 auth token for a request
|
||||
*/
|
||||
const createNIP98Token = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
|
||||
if (!user) {
|
||||
throw new Error('No user logged in');
|
||||
}
|
||||
|
||||
// Parse URL and reconstruct it to match server expectations
|
||||
// Remove query parameters from the URL used in NIP-98 token
|
||||
// The server will reconstruct the full URL from the actual request
|
||||
const urlObj = new URL(url);
|
||||
const baseUrl = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
|
||||
|
||||
console.log(`🔍 NIP-98 Token Creation - Original URL: ${url}, Base URL: ${baseUrl}, Method: ${method}`);
|
||||
|
||||
// Create NIP-98 event (kind 27235)
|
||||
const eventTemplate: EventTemplate = {
|
||||
kind: 27235,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['u', baseUrl],
|
||||
['method', method],
|
||||
],
|
||||
content: '',
|
||||
};
|
||||
|
||||
// Add payload hash for POST/PUT/PATCH requests
|
||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
||||
const bodyString = JSON.stringify(body);
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(bodyString);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
eventTemplate.tags.push(['payload', payloadHash]);
|
||||
}
|
||||
|
||||
// Sign the event using the user's signer
|
||||
const signedEvent = await user.signer.signEvent(eventTemplate);
|
||||
|
||||
// Encode as base64
|
||||
const eventJson = JSON.stringify(signedEvent);
|
||||
const base64Token = btoa(eventJson);
|
||||
|
||||
return base64Token;
|
||||
}, [user]);
|
||||
|
||||
/**
|
||||
* Get auth header (JWT if available, otherwise create NIP-98)
|
||||
*/
|
||||
const getAuthHeader = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
|
||||
// Try JWT first if available
|
||||
if (jwtToken) {
|
||||
return `Bearer ${jwtToken}`;
|
||||
}
|
||||
|
||||
// Otherwise create NIP-98 token
|
||||
const nip98Token = await createNIP98Token(url, method, body);
|
||||
return `Nostr ${nip98Token}`;
|
||||
}, [jwtToken, createNIP98Token]);
|
||||
|
||||
/**
|
||||
* Obtain JWT token via NIP-98 auth
|
||||
*/
|
||||
const obtainJWT = useCallback(async (): Promise<string> => {
|
||||
if (!pubkey) {
|
||||
throw new Error('No user logged in');
|
||||
}
|
||||
|
||||
const authUrl = `${NPUBCASH_API_BASE}/auth/nip98`;
|
||||
const nip98Token = await createNIP98Token(authUrl, 'GET');
|
||||
|
||||
const response = await fetch(authUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${nip98Token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ message: 'Authentication failed' }));
|
||||
throw new Error(errorData.message || 'Failed to obtain JWT token');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const token = data.data?.token;
|
||||
|
||||
if (!token) {
|
||||
throw new Error('No JWT token in response');
|
||||
}
|
||||
|
||||
setJwtToken(token);
|
||||
return token;
|
||||
}, [pubkey, createNIP98Token, setJwtToken]);
|
||||
|
||||
/**
|
||||
* Make authenticated API request
|
||||
*/
|
||||
const apiRequest = useCallback(async <T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> => {
|
||||
if (!pubkey) {
|
||||
throw new Error('No user logged in');
|
||||
}
|
||||
|
||||
const url = `${NPUBCASH_API_BASE}${endpoint}`;
|
||||
let authHeader: string;
|
||||
|
||||
try {
|
||||
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
|
||||
} catch (error) {
|
||||
// If JWT fails, try to obtain a new one
|
||||
if (jwtToken) {
|
||||
setJwtToken(null);
|
||||
await obtainJWT();
|
||||
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`🔍 API Request - URL: ${url}, Method: ${options.method || 'GET'}, Auth Header: ${authHeader.substring(0, 50)}...`);
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...options.headers,
|
||||
'Authorization': authHeader,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ message: 'Request failed' }));
|
||||
throw new Error(errorData.message || `API request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
throw new Error(data.message || 'API returned error');
|
||||
}
|
||||
|
||||
return data.data;
|
||||
}, [pubkey, jwtToken, getAuthHeader, obtainJWT, setJwtToken]);
|
||||
|
||||
/**
|
||||
* Fetch paid quotes from npub.cash
|
||||
*/
|
||||
const fetchQuotes = useCallback(async (since?: number, limit: number = 50): Promise<NpubCashQuote[]> => {
|
||||
try {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (since) queryParams.set('since', since.toString());
|
||||
queryParams.set('limit', limit.toString());
|
||||
|
||||
const endpoint = `/wallet/quotes?${queryParams.toString()}`;
|
||||
const data = await apiRequest<{ quotes: NpubCashQuote[] }>(endpoint);
|
||||
|
||||
setQuotes(data.quotes);
|
||||
return data.quotes;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch quotes';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [apiRequest]);
|
||||
|
||||
/**
|
||||
* Fetch user info/settings
|
||||
*/
|
||||
const fetchUserInfo = useCallback(async (): Promise<NpubCashUserInfo> => {
|
||||
try {
|
||||
const data = await apiRequest<{ user: NpubCashUserInfo }>('/user/info');
|
||||
setUserInfo(data.user);
|
||||
return data.user;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch user info';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [apiRequest]);
|
||||
|
||||
/**
|
||||
* Set Lightning address username (paid feature)
|
||||
*/
|
||||
const setUsername = useCallback(async (username: string): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await apiRequest('/user/username', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username }),
|
||||
});
|
||||
|
||||
// Refresh user info
|
||||
await fetchUserInfo();
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to set username';
|
||||
setError(errorMessage);
|
||||
setIsLoading(false);
|
||||
throw err;
|
||||
}
|
||||
}, [apiRequest, fetchUserInfo]);
|
||||
|
||||
/**
|
||||
* Set preferred mint URL
|
||||
*/
|
||||
const setMint = useCallback(async (mintUrl: string): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await apiRequest('/user/mint', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ mint_url: mintUrl }),
|
||||
});
|
||||
|
||||
// Refresh user info
|
||||
await fetchUserInfo();
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to set mint';
|
||||
setError(errorMessage);
|
||||
setIsLoading(false);
|
||||
throw err;
|
||||
}
|
||||
}, [apiRequest, fetchUserInfo]);
|
||||
|
||||
/**
|
||||
* Toggle quote locking (NUT-20)
|
||||
*/
|
||||
const setLockQuotes = useCallback(async (locked: boolean): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await apiRequest('/user/lock', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ lock_quotes: locked }),
|
||||
});
|
||||
|
||||
// Refresh user info
|
||||
await fetchUserInfo();
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to set lock quotes';
|
||||
setError(errorMessage);
|
||||
setIsLoading(false);
|
||||
throw err;
|
||||
}
|
||||
}, [apiRequest, fetchUserInfo]);
|
||||
|
||||
/**
|
||||
* Refresh all data
|
||||
*/
|
||||
const refresh = useCallback(async (): Promise<void> => {
|
||||
if (!pubkey) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Fetch in parallel
|
||||
await Promise.all([
|
||||
fetchQuotes(lastClaimedAt),
|
||||
fetchUserInfo(),
|
||||
]);
|
||||
|
||||
setIsInitialized(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh data';
|
||||
setError(errorMessage);
|
||||
|
||||
// If it's an auth error, don't retry automatically
|
||||
if (errorMessage.includes('Authorization') || errorMessage.includes('Invalid')) {
|
||||
console.warn('npub.cash auth error - not retrying automatically:', errorMessage);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [pubkey, fetchQuotes, fetchUserInfo, lastClaimedAt]);
|
||||
|
||||
/**
|
||||
* Clear JWT token (force NIP-98 re-auth)
|
||||
*/
|
||||
const clearAuth = useCallback(() => {
|
||||
setJwtToken(null);
|
||||
setHasTriedInitialization(false);
|
||||
setIsInitialized(false);
|
||||
setError(null);
|
||||
}, [setJwtToken]);
|
||||
|
||||
/**
|
||||
* Retry initialization after auth error
|
||||
*/
|
||||
const retryAuth = useCallback(() => {
|
||||
setHasTriedInitialization(false);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// Calculate unclaimed amount
|
||||
const unclaimedAmount = useMemo(() => {
|
||||
return quotes
|
||||
.filter(q => q.state === 'PAID' && q.paidAt > lastClaimedAt)
|
||||
.reduce((sum, q) => sum + q.amount, 0);
|
||||
}, [quotes, lastClaimedAt]);
|
||||
|
||||
// Initialize on mount - only once
|
||||
useEffect(() => {
|
||||
if (pubkey && !isInitialized && !hasTriedInitialization) {
|
||||
setHasTriedInitialization(true);
|
||||
refresh();
|
||||
}
|
||||
}, [pubkey, isInitialized, hasTriedInitialization, refresh]);
|
||||
|
||||
return {
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
lightningAddress,
|
||||
userInfo,
|
||||
quotes,
|
||||
unclaimedAmount,
|
||||
fetchQuotes,
|
||||
fetchUserInfo,
|
||||
setUsername,
|
||||
setMint,
|
||||
setLockQuotes,
|
||||
refresh,
|
||||
clearAuth,
|
||||
retryAuth,
|
||||
};
|
||||
}
|
||||
|
||||
export type { EventTemplate };
|
||||
|
||||
// Force TypeScript recompilation
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import { useToast } from './useToast';
|
||||
|
||||
interface UseQRCodeReturn {
|
||||
generateQRCode: (text: string) => Promise<string>;
|
||||
isGenerating: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for generating QR codes
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { generateQRCode, isGenerating, error } = useQRCode();
|
||||
*
|
||||
* const qrCodeUrl = await generateQRCode('cashuBo2Ft...');
|
||||
* ```
|
||||
*/
|
||||
export function useQRCode(): UseQRCodeReturn {
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const generateQRCode = useCallback(async (text: string): Promise<string> => {
|
||||
setIsGenerating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const qrCodeUrl = await QRCode.toDataURL(text, {
|
||||
width: 256,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF',
|
||||
},
|
||||
});
|
||||
setIsGenerating(false);
|
||||
return qrCodeUrl;
|
||||
} catch (err) {
|
||||
const errorMessage = 'Failed to generate QR code';
|
||||
console.error(errorMessage, err);
|
||||
setError(errorMessage);
|
||||
setIsGenerating(false);
|
||||
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "QR Code Failed",
|
||||
description: errorMessage,
|
||||
});
|
||||
|
||||
return '';
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
return {
|
||||
generateQRCode,
|
||||
isGenerating,
|
||||
error,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user