From 967bdca36960b2c78674494a7a7d605b9433c9d8 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sat, 11 Oct 2025 00:34:32 -0700 Subject: [PATCH] solid cashu foundation --- src/components/CashuWallet.tsx | 1110 ++--------------- src/components/ui/qr-modal.tsx | 66 +- src/components/wallet/BalanceDisplay.tsx | 192 +++ src/components/wallet/LoadingModal.tsx | 21 + src/components/wallet/ProofBreakdownModal.tsx | 76 ++ src/components/wallet/ReceiveCard.tsx | 88 ++ src/components/wallet/RemoveMintModal.tsx | 83 ++ src/components/wallet/SendCard.tsx | 163 +++ src/components/wallet/TransactionHistory.tsx | 150 +++ src/hooks/cashu/useCashuBalances.ts | 48 + src/hooks/cashu/useCashuMints.ts | 29 + src/hooks/useCopyToClipboard.ts | 52 + src/hooks/useNpubCash.ts | 455 ------- src/hooks/useQRCode.ts | 62 + src/lib/exchangeRateService.ts | 131 ++ 15 files changed, 1249 insertions(+), 1477 deletions(-) create mode 100644 src/components/wallet/BalanceDisplay.tsx create mode 100644 src/components/wallet/LoadingModal.tsx create mode 100644 src/components/wallet/ProofBreakdownModal.tsx create mode 100644 src/components/wallet/ReceiveCard.tsx create mode 100644 src/components/wallet/RemoveMintModal.tsx create mode 100644 src/components/wallet/SendCard.tsx create mode 100644 src/components/wallet/TransactionHistory.tsx create mode 100644 src/hooks/useCopyToClipboard.ts delete mode 100644 src/hooks/useNpubCash.ts create mode 100644 src/hooks/useQRCode.ts create mode 100644 src/lib/exchangeRateService.ts diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx index faaf557..94ee9d3 100644 --- a/src/components/CashuWallet.tsx +++ b/src/components/CashuWallet.tsx @@ -1,16 +1,18 @@ import { useState, useEffect, useCallback } from 'react'; import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; -import { useNpubCash } from '@/hooks/useNpubCash'; +import { useCashuMints } from '@/hooks/cashu/useCashuMints'; import { useLightningAddress } from '@/hooks/useLightningAddress'; import { useToast } from '@/hooks/useToast'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Badge } from '@/components/ui/badge'; -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu'; +import { useQRCode } from '@/hooks/useQRCode'; +import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; import { QRModal } from '@/components/ui/qr-modal'; -import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, QrCode, AlertTriangle } from 'lucide-react'; -import QRCode from 'qrcode'; +import { LoadingModal } from '@/components/wallet/LoadingModal'; +import { BalanceDisplay } from '@/components/wallet/BalanceDisplay'; +import { ReceiveCard } from '@/components/wallet/ReceiveCard'; +import { SendCard } from '@/components/wallet/SendCard'; +import { TransactionHistory } from '@/components/wallet/TransactionHistory'; +import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal'; +import { RemoveMintModal } from '@/components/wallet/RemoveMintModal'; export function CashuWallet() { // ============================================================================ @@ -39,21 +41,15 @@ export function CashuWallet() { getHistory, } = useCashu(); - const { - lightningAddress, - unclaimedAmount, - quotes, - isLoading: isNpubCashLoading, - error: npubCashError, - fetchQuotes, - refresh: refreshNpubCash, - retryAuth, - setMint, - } = useNpubCash(); + const { getCleanMintLabel } = useCashuMints(null); + + const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); const { toast } = useToast(); + const { generateQRCode } = useQRCode(); + const { copy: copyToClipboard } = useCopyToClipboard(); // ============================================================================ // STATE - Input Values @@ -80,17 +76,9 @@ export function CashuWallet() { // ============================================================================ const [sentToken, setSentToken] = useState(null); + const [sentTokenQRCode, setSentTokenQRCode] = useState(''); const [pendingLightningAddress, setPendingLightningAddress] = useState(null); - // ============================================================================ - // STATE - Copy Feedback - // ============================================================================ - - const [copiedToken, setCopiedToken] = useState(false); - const [copiedInvoice, setCopiedInvoice] = useState(null); - const [copiedLightningAddress, setCopiedLightningAddress] = useState(false); - - // ============================================================================ // STATE - History // ============================================================================ @@ -129,81 +117,17 @@ export function CashuWallet() { const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); - // ============================================================================ - // HELPER FUNCTIONS - Display - // ============================================================================ - - const getCleanMintLabel = (mint: { name?: string; url: 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?:\/\//, ''); - } - }; - - const formatAmount = (sats: number): string => { - if (showSats) { - return `${sats.toLocaleString()} sats`; - } else { - // Simple USD conversion (you can enhance this with real BTC price) - const usd = sats * 0.0001; // Rough approximation - return `$${usd.toFixed(2)}`; - } - }; - - // Copy Lightning address to clipboard - const copyLightningAddress = async () => { - if (!lightningAddress) return; - - try { - await navigator.clipboard.writeText(lightningAddress); - setCopiedLightningAddress(true); - setTimeout(() => setCopiedLightningAddress(false), 2000); - } catch (err) { - console.error('Failed to copy Lightning address:', err); - } - }; - // ============================================================================ // HELPER FUNCTIONS - QR Code Generation // ============================================================================ - const generateQRCode = async (text: string): Promise => { + // Generate QR code for sent token + const generateSentTokenQRCode = async (token: string) => { try { - return await QRCode.toDataURL(text, { - width: 256, - margin: 2, - color: { - dark: '#000000', - light: '#FFFFFF', - }, - }); + const qrCodeUrl = await generateQRCode(token); + setSentTokenQRCode(qrCodeUrl); } catch (err) { - console.error('Failed to generate QR code:', err); - toast({ - variant: "destructive", - title: "QR Code Failed", - description: "Failed to generate QR code", - }); - return ''; - } - }; - - // Generate QR code for Lightning address - const generateLightningQRCode = async () => { - if (!lightningAddress) return; - - try { - const qrCodeUrl = await generateQRCode(lightningAddress); - setLightningQRCode(qrCodeUrl); - setShowLightningQR(true); - } catch (err) { - console.error('Failed to generate Lightning address QR code:', err); + console.error('Failed to generate sent token QR code:', err); } }; @@ -212,23 +136,12 @@ export function CashuWallet() { // ============================================================================ /** - * Set active mint and sync with npubx.cash + * Set active mint */ const handleSetActiveMint = useCallback(async (mintUrl: string | null) => { // Set the active mint locally setActiveMintUrl(mintUrl); - - // If we have a mint URL, also update npubx.cash preference - if (mintUrl) { - try { - await setMint(mintUrl); - console.log(`✅ Updated npubx.cash mint preference to: ${mintUrl}`); - } catch (error) { - console.error('❌ Failed to update npubx.cash mint preference:', error); - // Don't throw - we still want to set the local mint even if npubx.cash fails - } - } - }, [setMint]); + }, []); // ============================================================================ // HELPER FUNCTIONS - History @@ -237,7 +150,7 @@ export function CashuWallet() { const loadHistory = useCallback(async () => { try { setIsLoadingHistory(true); - const entries = await getHistory(50, 0); + const entries = await getHistory(50, 0); //TODO: show entire history setHistoryEntries(entries); } catch (err) { console.error('Failed to load history:', err); @@ -246,50 +159,6 @@ export function CashuWallet() { } }, [getHistory]); - const getHistoryIcon = (type: string) => { - switch (type) { - case 'mint': - return ; - case 'melt': - return ; - case 'send': - return ; - case 'receive': - return ; - default: - return ; - } - }; - - const getHistoryLabel = (type: string) => { - switch (type) { - case 'mint': - return 'Mint (Lightning → Tokens)'; - case 'melt': - return 'Melt (Tokens → Lightning)'; - case 'send': - return 'Send Tokens'; - case 'receive': - return 'Receive Tokens'; - 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'; - } - }; - // ============================================================================ // EVENT HANDLERS - Receive // ============================================================================ @@ -345,10 +214,10 @@ export function CashuWallet() { console.log('✅ Mint quote created:', quote); console.log('🔗 Lightning Invoice:', quote.request); - console.log('💡 Coco will automatically redeem when payment is detected'); + console.log('💡 Wallet will automatically redeem when payment is detected'); toast({ title: "Lightning Invoice Created", - description: "Coco will automatically claim your tokens when payment is detected.", + description: "Wallet will automatically claim tokens when payment is detected.", }); setQuoteAmount(''); } catch (err) { @@ -383,7 +252,8 @@ export function CashuWallet() { } const encodedToken = await send(activeMintUrl, amount); setSentToken(encodedToken); - console.log('✅ Token sent successfully!'); + await generateSentTokenQRCode(encodedToken); + console.log('✅ Token created successfully!'); console.log('📤 Encoded token:', encodedToken); setSendAmount(''); } catch (err) { @@ -493,25 +363,6 @@ export function CashuWallet() { // EVENT HANDLERS - Utility // ============================================================================ - const handleCopy = async (text: string, type: 'token' | 'invoice') => { - try { - await navigator.clipboard.writeText(text); - if (type === 'token') { - setCopiedToken(true); - setTimeout(() => setCopiedToken(false), 2000); - } else { - setCopiedInvoice(text); - setTimeout(() => setCopiedInvoice(null), 2000); - } - } catch (err) { - console.error('Failed to copy to clipboard:', err); - toast({ - variant: "destructive", - title: "Copy Failed", - description: "Failed to copy to clipboard", - }); - } - }; const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => { setMintToRemove(mint); @@ -592,47 +443,7 @@ export function CashuWallet() { // ============================================================================ - // Claim npub.cash quotes - const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => { - try { - console.log('🎯 Claiming npubx.cash quote:', quote); - console.log('📋 Quote details:', { - quote_id: quote.quoteId, - mint_url: quote.mintUrl, - amount: quote.amount, - state: quote.state, - }); - - // Add mint if not already added - const hasMint = mints.some(m => m.url === quote.mintUrl); - if (!hasMint) { - console.log('➕ Adding mint:', quote.mintUrl); - await addMint(quote.mintUrl); - } - - // Use coco-cashu's addMintQuote API instead of calling mint directly - console.log('🔄 Adding mint quote to coco-cashu:', quote.quoteId); - await addMintQuote(quote.mintUrl, quote.quoteId); - - console.log('✅ Quote added to coco-cashu successfully'); - console.log('💡 Coco will automatically redeem when mint processor runs'); - - // Refresh quotes (balances will be updated automatically via events) - await fetchQuotes(); - - toast({ - title: "Quote Claimed", - description: `Successfully claimed ${quote.amount} sats!`, - }); - } catch (err) { - console.error('Failed to claim npub.cash quote:', err); - toast({ - variant: "destructive", - title: "Claim Failed", - description: `Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`, - }); - } - }; + const handleShowDenominations = async (mintUrl: string) => { try { console.log('🔍 Getting token denominations for mint:', mintUrl); @@ -693,20 +504,6 @@ export function CashuWallet() { } }, [error, toast]); - useEffect(() => { - if (npubCashError) { - toast({ - variant: "destructive", - title: "npub.cash Error", - description: npubCashError, - action: npubCashError.includes('Authorization') ? ( - - ) : undefined, - }); - } - }, [npubCashError, toast, retryAuth]); // Auto-select active mint when mints change (balances will update automatically via events) useEffect(() => { @@ -724,789 +521,138 @@ export function CashuWallet() { }, [isInitialized, historyEntries.length, loadHistory]); - // ============================================================================ - // RENDER - Loading Modal - // ============================================================================ - - const LoadingModal = () => { - if (!isLoading) return null; - - return ( -
- - - - Loading - - -
- ); - }; - - // ============================================================================ - // RENDER - Uninitialized State Modal - // ============================================================================ - - const UninitializedModal = () => { - if (isInitialized) return null; - - return ( -
- - - - - Cashu Wallet - - - Failed to initialize wallet. Please check the console for errors. - - - -
- ); - }; - // ============================================================================ // RENDER - Main UI // ============================================================================ return ( <> - - -
+ +
+ {/* ======================================================================== SECTION: Balance Display ======================================================================== */} - {isInitialized && ( -
-
- - -
- - {/* Main Mode Toggle */} -
-
- - -
-
- - {/* Active Mint Dropdown and Balance */} -
- - - - - - {mints.length === 0 && ( - No mints connected - )} - {mints - .filter((mint) => mint.url) - .map((mint, index) => ( - handleSetActiveMint(mint.url)} - > -
- {getCleanMintLabel(mint)} -
- -
- ))} - -
-
- setMintUrl(e.target.value)} - className="h-8" - /> - -
-
-
-
- - {/* Active Mint Balance */} - {activeMintUrl && ( -
- -
- )} -
- - {/* Lightning Address */} - {lightningAddress && ( -
- - {lightningAddress} - - - - {unclaimedAmount > 0 && ( - - )} -
- )} -
- )} + {/* ======================================================================== SECTION: Receive & Send Cards ======================================================================== */}
+ - {/* Receive Card */} - - - - - Receive - - - {mode === 'tokens' - ? 'Enter Cashu token to redeem' - : 'Deposit funds with Lightning' - } - - - - {mode === 'tokens' ? ( -
- setTokenInput(e.target.value)} - className="flex-1" - /> - -
- ) : ( - <> - {!activeMintUrl && ( -
- Select a mint from "Connected Mints" to create Lightning invoice -
- )} -
- setQuoteAmount(e.target.value)} - /> - -
- - )} -
-
- - {/* Send Card */} - - - - - Send - - - {mode === 'tokens' - ? 'Generate Cashu token to send' - : pendingLightningAddress - ? 'Enter the amount to send' - : 'Pay Lightning invoices or addresses from balance' - } - - - - {mode === 'tokens' ? ( - <> - {!activeMintUrl && ( -
- Select a mint from "Connected Mints" to send tokens -
- )} -
- setSendAmount(e.target.value)} - /> - -
- - ) : ( - <> - {!activeMintUrl && ( -
- Select a mint from "Connected Mints" to pay Lightning invoices -
- )} - {pendingLightningAddress ? ( - // Step 2: Show amount input for Lightning address -
-
-
- Sending to: {pendingLightningAddress} -
-
- Enter amount to send -
-
-
- setLightningAddressAmount(e.target.value)} - autoFocus - /> - - -
-
- ) : ( - // Step 1: Show invoice/address input -
- { - const value = e.target.value; - if (value.includes('@')) { - setLightningAddressInput(value); - setLightningInvoice(''); - } else { - setLightningInvoice(value); - setLightningAddressInput(''); - } - }} - className="flex-1" - /> - -
- )} - - )} -
-
-
+ +
{/* ======================================================================== SECTION: Sent Token Display ======================================================================== */} {sentToken && ( - - - - - - Token Created Successfully - - - Share this token with the recipient to send them your sats - - - -
-
- {sentToken.length > 20 ? `${sentToken.substring(0, 20)}...` : sentToken} -
- -
-
-
+ setSentToken(null)} + title="Cashu Token" + description="Share this token with the recipient to send them your sats" + qrCodeUrl={sentTokenQRCode} + content={sentToken} + icon="qr" + /> )} - {/* ======================================================================== - SECTION: npub.cash Received Payments - ======================================================================== */} - {quotes.length > 0 && ( - - - -
- - Received Payments (npub.cash) -
- -
- - Lightning payments received to your npub.cash address - -
- -
- {quotes && quotes.length > 0 ? quotes.map(quote => { - const isExpired = quote.expiresAt < Date.now() / 1000; - const isPaid = quote.state === 'PAID'; - - return ( -
-
-
-

{quote.amount} sats

-

- {quote.paidAt ? new Date(quote.paidAt * 1000).toLocaleString() : 'Unknown date'} -

-
-
- - {quote.state} - - {isPaid && !isExpired && ( - - )} -
-
- -
-

Mint: {quote.mintUrl}

- {isExpired && ( -

- Expired: {new Date(quote.expiresAt * 1000).toLocaleString()} -

- )} - {quote.locked && ( - - 🔒 Locked to your pubkey - - )} -
-
- ); - }) : null} -
-
-
- )} - {/* ======================================================================== SECTION: Transaction History ======================================================================== */} - - - -
- - Transaction History -
- {historyEntries.length > 3 && ( - - )} -
- - View your recent transactions - -
- - {isLoadingHistory ? ( -
- - Loading history... -
- ) : historyEntries.length === 0 ? ( -
- No transaction history yet -
- ) : ( -
- {(isHistoryExpanded ? historyEntries : historyEntries.slice(0, 3)).map((entry) => ( -
-
-
-
- {getHistoryIcon(entry.type)} -
-
-
- - {getHistoryLabel(entry.type)} - - {entry.state && ( - - {entry.state} - - )} -
-
- {new URL(entry.mintUrl).hostname} -
-
- {new Date(entry.createdAt).toLocaleString()} -
-
-
-
-
- {entry.type === 'send' || entry.type === 'melt' ? '-' : '+'} - {entry.amount.toLocaleString()} {entry.unit} -
-
-
-
- ))} -
- )} -
-
- - {/* ======================================================================== - SECTION: Proof Breakdown Modal - ======================================================================== */} - {showProofBreakdown && proofBreakdown && ( -
- - - - - - Token Breakdown - - - {new URL(proofBreakdown.mintUrl).hostname} - - - -
-
- {formatAmount(proofBreakdown.totalBalance)} -
-
Total Balance
-
- -
-
Denominations:
- {Object.entries(proofBreakdown.denominations) - .sort(([a], [b]) => parseInt(a) - parseInt(b)) - .map(([amount, count]) => ( -
-
- - {parseInt(amount).toLocaleString()} sats -
- - × {count} - -
- ))} -
- -
- 💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations. -
-
-
-
- )} - - {/* ======================================================================== - SECTION: Lightning Address QR Code Modal - ======================================================================== */} - setShowLightningQR(false)} - title="Lightning Address QR Code" - description="Scan to send Lightning payments" - qrCodeUrl={lightningQRCode} - content={lightningAddress || ''} - icon="qr" - helpText="💡 Share this QR code or address to receive Lightning payments" + {/* ======================================================================== - SECTION: Lightning Invoice Modal + SECTION: Modals ======================================================================== */} - setShowInvoiceModal(false)} - title="Lightning Invoice" - description={currentInvoice ? `Pay this invoice to receive ${currentInvoice.amount} sats` : ''} - qrCodeUrl={currentInvoice?.qrCodeUrl || ''} - content={currentInvoice?.invoice || ''} - icon="zap" - showCopyButton={true} - copiedText={copiedInvoice} - onCopy={() => currentInvoice && handleCopy(currentInvoice.invoice, 'invoice')} - copyButtonText="Copy Invoice" - helpText="💡 Coco will automatically claim your tokens when payment is detected" - /> + <> + setShowProofBreakdown(false)} + breakdown={proofBreakdown} + /> - {/* ======================================================================== - SECTION: Remove Mint Confirmation Modal - ======================================================================== */} - {showRemoveMintModal && mintToRemove && ( -
- - - - - - Remove Mint - - - Are you sure you want to remove this mint from your wallet? - - - -
-
{mintToRemove.name || new URL(mintToRemove.url).hostname}
-
- {mintToRemove.url} -
-
- -
-
⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.
-
💡 You can always add this mint back later if needed.
-
- -
- - -
-
-
-
- )} + setShowLightningQR(false)} + title="Lightning Address QR Code" + description="Scan to send Lightning payments" + qrCodeUrl={lightningQRCode} + content={''} + icon="qr" + /> + + {currentInvoice && ( + setShowInvoiceModal(false)} + title="Lightning Invoice" + description={`Pay this invoice to receive ${currentInvoice.amount} sats`} + qrCodeUrl={currentInvoice.qrCodeUrl} + content={currentInvoice.invoice} + icon="zap" + /> + )} + + setShowRemoveMintModal(false)} + mint={mintToRemove} + onConfirm={handleConfirmRemoveMint} + isLoading={isLoading} + /> +
); diff --git a/src/components/ui/qr-modal.tsx b/src/components/ui/qr-modal.tsx index 88c4966..1406069 100644 --- a/src/components/ui/qr-modal.tsx +++ b/src/components/ui/qr-modal.tsx @@ -1,6 +1,7 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { X, Copy, Check, QrCode, Zap } from 'lucide-react'; +import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; interface QRModalProps { isOpen: boolean; @@ -10,11 +11,6 @@ interface QRModalProps { qrCodeUrl: string; content: string; icon?: 'qr' | 'zap'; - showCopyButton?: boolean; - copiedText?: string | null; - onCopy?: () => void; - copyButtonText?: string; - helpText?: string; } export function QRModal({ @@ -25,19 +21,25 @@ export function QRModal({ qrCodeUrl, content, icon = 'qr', - showCopyButton = false, - copiedText, - onCopy, - copyButtonText = 'Copy', - helpText, }: QRModalProps) { + const { copy, copied } = useCopyToClipboard(); + + const handleCopy = () => { + copy(content); + }; if (!isOpen) return null; const IconComponent = icon === 'zap' ? Zap : QrCode; return ( -
- +
+ e.stopPropagation()} + > -
- )} - - {helpText && ( -
- {helpText} -
- )}
diff --git a/src/components/wallet/BalanceDisplay.tsx b/src/components/wallet/BalanceDisplay.tsx new file mode 100644 index 0000000..10799e2 --- /dev/null +++ b/src/components/wallet/BalanceDisplay.tsx @@ -0,0 +1,192 @@ +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Wallet, ChevronDown, Plus, X, Zap, Coins, HelpCircle } from 'lucide-react'; +import { useCashuBalances } from '@/hooks/cashu/useCashuBalances'; + +interface CashuMint { + url: string; + name?: string; +} + +interface BalanceDisplayProps { + totalBalance: number; + balances: { [key: string]: number }; + showSats: boolean; + setShowSats: (showSats: boolean) => void; + mode: 'tokens' | 'lightning'; + setMode: (mode: 'tokens' | 'lightning') => void; + activeMintUrl: string | null; + setActiveMintUrl: (url: string | null) => void; + mints: CashuMint[]; + mintUrl: string; + setMintUrl: (url: string) => void; + onAddMint: () => void; + onRemoveMint: (mint: CashuMint) => void; + onShowDenominations: (mintUrl: string) => void; + getCleanMintLabel: (mint: { name?: string; url: string }) => string; +} + +export function BalanceDisplay({ + totalBalance, + balances, + showSats, + setShowSats, + mode, + setMode, + activeMintUrl, + setActiveMintUrl, + mints, + mintUrl, + setMintUrl, + onAddMint, + onRemoveMint, + onShowDenominations, + getCleanMintLabel, +}: BalanceDisplayProps) { + const { convertCurrency } = useCashuBalances(null); + + return ( +
+
+ +
+ + {/* Main Mode Toggle */} +
+
+ + +
+
+ + {/* Active Mint Dropdown and Balance */} +
+ + + + + + {mints.length === 0 && ( + No mints connected + )} + {mints + .filter((mint) => mint.url) + .map((mint, index) => ( + setActiveMintUrl(mint.url)} + > +
+ {getCleanMintLabel(mint)} +
+ +
+ ))} + +
+
+ setMintUrl(e.target.value)} + className="h-8" + /> + +
+
+
+
+ + {/* Active Mint Balance */} + {activeMintUrl && ( +
+ + + {/* Help button */} + + + + + + + + + What is a Mint? + + +

+ A mint is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash. +

+

+ Key features: +

+
    +
  • Issues tokens when you deposit Lightning payments
  • +
  • Redeems tokens when you receive them
  • +
  • Manages your token balance
  • +
  • Enables Lightning ↔ Cashu conversions
  • +
+

+ Note: Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them. +

+
+
+
+
+
+ )} +
+ +
+ ); +} diff --git a/src/components/wallet/LoadingModal.tsx b/src/components/wallet/LoadingModal.tsx new file mode 100644 index 0000000..a4e8f97 --- /dev/null +++ b/src/components/wallet/LoadingModal.tsx @@ -0,0 +1,21 @@ +import { Card, CardContent } from '@/components/ui/card'; +import { Loader2 } from 'lucide-react'; + +interface LoadingModalProps { + isLoading: boolean; +} + +export function LoadingModal({ isLoading }: LoadingModalProps) { + if (!isLoading) return null; + + return ( +
+ + + + Loading + + +
+ ); +} diff --git a/src/components/wallet/ProofBreakdownModal.tsx b/src/components/wallet/ProofBreakdownModal.tsx new file mode 100644 index 0000000..a915ef4 --- /dev/null +++ b/src/components/wallet/ProofBreakdownModal.tsx @@ -0,0 +1,76 @@ +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { X, Coins } from 'lucide-react'; +import { useCashuBalances } from '@/hooks/cashu/useCashuBalances'; + +interface ProofBreakdown { + mintUrl: string; + denominations: { [key: number]: number }; + totalBalance: number; +} + +interface ProofBreakdownModalProps { + isOpen: boolean; + onClose: () => void; + breakdown: ProofBreakdown | null; +} + +export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) { + const { convertCurrency } = useCashuBalances(null); + + if (!isOpen || !breakdown) return null; + + return ( +
+ + + + + + Token Breakdown + + + {new URL(breakdown.mintUrl).hostname} + + + +
+
+ {convertCurrency(breakdown.totalBalance)} +
+
Total Balance
+
+ +
+
Denominations:
+ {Object.entries(breakdown.denominations) + .sort(([a], [b]) => parseInt(a) - parseInt(b)) + .map(([amount, count]) => ( +
+
+ + {parseInt(amount).toLocaleString()} sats +
+ + × {count} + +
+ ))} +
+ +
+ 💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations. +
+
+
+
+ ); +} diff --git a/src/components/wallet/ReceiveCard.tsx b/src/components/wallet/ReceiveCard.tsx new file mode 100644 index 0000000..3792fbb --- /dev/null +++ b/src/components/wallet/ReceiveCard.tsx @@ -0,0 +1,88 @@ +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Download, Zap } from 'lucide-react'; + +interface ReceiveCardProps { + mode: 'tokens' | 'lightning'; + tokenInput: string; + setTokenInput: (value: string) => void; + quoteAmount: string; + setQuoteAmount: (value: string) => void; + activeMintUrl: string | null; + onReceive: () => void; + isLoading: boolean; +} + +export function ReceiveCard({ + mode, + tokenInput, + setTokenInput, + quoteAmount, + setQuoteAmount, + activeMintUrl, + onReceive, + isLoading, +}: ReceiveCardProps) { + return ( + + + + + Receive + + + {mode === 'tokens' + ? 'Enter Cashu token to redeem' + : 'Deposit funds with Lightning' + } + + + + {mode === 'tokens' ? ( + <> + {!activeMintUrl && ( +
+ Select a mint to receive tokens +
+ )} +
+ setTokenInput(e.target.value)} + className="flex-1" + disabled={!activeMintUrl} + /> + +
+ + ) : ( + <> + {!activeMintUrl && ( +
+ Select a mint to create Lightning invoice +
+ )} +
+ setQuoteAmount(e.target.value)} + disabled={!activeMintUrl} + /> + +
+ + )} +
+
+ ); +} diff --git a/src/components/wallet/RemoveMintModal.tsx b/src/components/wallet/RemoveMintModal.tsx new file mode 100644 index 0000000..4dc4f09 --- /dev/null +++ b/src/components/wallet/RemoveMintModal.tsx @@ -0,0 +1,83 @@ +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { AlertTriangle, X, RefreshCw } from 'lucide-react'; + +interface MintToRemove { + url: string; + name?: string; +} + +interface RemoveMintModalProps { + isOpen: boolean; + onClose: () => void; + mint: MintToRemove | null; + onConfirm: () => void; + isLoading: boolean; +} + +export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }: RemoveMintModalProps) { + if (!isOpen || !mint) return null; + + return ( +
+ + + + + + Remove Mint + + + Are you sure you want to remove this mint from your wallet? + + + +
+
{mint.name || new URL(mint.url).hostname}
+
+ {mint.url} +
+
+ +
+
⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.
+
💡 You can always add this mint back later if needed.
+
+ +
+ + +
+
+
+
+ ); +} diff --git a/src/components/wallet/SendCard.tsx b/src/components/wallet/SendCard.tsx new file mode 100644 index 0000000..5ab10f1 --- /dev/null +++ b/src/components/wallet/SendCard.tsx @@ -0,0 +1,163 @@ +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Send, Zap, Loader2, X } from 'lucide-react'; + +interface SendCardProps { + mode: 'tokens' | 'lightning'; + sendAmount: string; + setSendAmount: (value: string) => void; + lightningInvoice: string; + setLightningInvoice: (value: string) => void; + lightningAddressInput: string; + setLightningAddressInput: (value: string) => void; + lightningAddressAmount: string; + setLightningAddressAmount: (value: string) => void; + pendingLightningAddress: string | null; + setPendingLightningAddress: (value: string | null) => void; + activeMintUrl: string | null; + onSend: () => void; + isResolvingAddress: boolean; + isLoading: boolean; +} + +export function SendCard({ + mode, + sendAmount, + setSendAmount, + lightningInvoice, + setLightningInvoice, + lightningAddressInput, + setLightningAddressInput, + lightningAddressAmount, + setLightningAddressAmount, + pendingLightningAddress, + setPendingLightningAddress, + activeMintUrl, + onSend, + isResolvingAddress, + isLoading, +}: SendCardProps) { + return ( + + + + + Send + + + {mode === 'tokens' + ? 'Generate Cashu token to send' + : pendingLightningAddress + ? `Sending to: ${pendingLightningAddress}` + : 'Pay Lightning invoices or addresses from balance' + } + + + + {mode === 'tokens' ? ( + <> + {!activeMintUrl && ( +
+ Select a mint to send tokens +
+ )} +
+ setSendAmount(e.target.value)} + disabled={!activeMintUrl} + /> + +
+ + ) : ( + <> + {!activeMintUrl && ( +
+ Select a mint to pay Lightning invoices +
+ )} + {pendingLightningAddress ? ( + // Step 2: Show amount input for Lightning address +
+
+ setLightningAddressAmount(e.target.value)} + autoFocus + disabled={!activeMintUrl} + /> + + +
+
+ ) : ( + // Step 1: Show invoice/address input +
+ { + const value = e.target.value; + if (value.includes('@')) { + setLightningAddressInput(value); + setLightningInvoice(''); + } else { + setLightningInvoice(value); + setLightningAddressInput(''); + } + }} + className="flex-1" + disabled={!activeMintUrl} + /> + +
+ )} + + )} +
+
+ ); +} diff --git a/src/components/wallet/TransactionHistory.tsx b/src/components/wallet/TransactionHistory.tsx new file mode 100644 index 0000000..02086d0 --- /dev/null +++ b/src/components/wallet/TransactionHistory.tsx @@ -0,0 +1,150 @@ +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 } from 'lucide-react'; +import type { HistoryEntry } from '@/hooks/useCashu'; + +interface TransactionHistoryProps { + entries: HistoryEntry[]; + isLoading: boolean; + isExpanded: boolean; + setIsExpanded: (expanded: boolean) => void; +} + +export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpanded }: TransactionHistoryProps) { + const getHistoryIcon = (type: string) => { + switch (type) { + case 'mint': + return ; + case 'melt': + return ; + case 'send': + return ; + case 'receive': + return ; + default: + return ; + } + }; + + const getHistoryLabel = (type: string) => { + switch (type) { + case 'mint': + return 'Mint (Lightning → Tokens)'; + case 'melt': + return 'Melt (Tokens → Lightning)'; + case 'send': + return 'Send Tokens'; + case 'receive': + return 'Receive Tokens'; + 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 ( + + + +
+ + Transaction History +
+ {entries.length > 3 && ( + + )} +
+ + View your recent transactions + +
+ + {isLoading ? ( +
+ + Loading history... +
+ ) : entries.length === 0 ? ( +
+ No transaction history yet +
+ ) : ( +
+ {(isExpanded ? entries : entries.slice(0, 3)).map((entry) => ( +
+
+
+
+ {getHistoryIcon(entry.type)} +
+
+
+ + {getHistoryLabel(entry.type)} + + {entry.state && ( + + {entry.state} + + )} +
+
+ {new URL(entry.mintUrl).hostname} +
+
+ {new Date(entry.createdAt).toLocaleString()} +
+
+
+
+
+ {entry.type === 'send' || entry.type === 'melt' ? '-' : '+'} + {entry.amount.toLocaleString()} {entry.unit} +
+
+
+
+ ))} +
+ )} +
+
+ ); +} diff --git a/src/hooks/cashu/useCashuBalances.ts b/src/hooks/cashu/useCashuBalances.ts index 8d8d456..7cd6645 100644 --- a/src/hooks/cashu/useCashuBalances.ts +++ b/src/hooks/cashu/useCashuBalances.ts @@ -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; getBalances: () => Promise; + convertCurrency: (sats: number, showSats?: boolean) => string; + convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise; } export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn { const [balances, setBalances] = useState({}); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); + const [fallbackRate, setFallbackRate] = useState(null); // Throttling refs const lastRefreshTimeRef = useRef(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 => { + 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, }; } diff --git a/src/hooks/cashu/useCashuMints.ts b/src/hooks/cashu/useCashuMints.ts index 5a55d3a..3ede786 100644 --- a/src/hooks/cashu/useCashuMints.ts +++ b/src/hooks/cashu/useCashuMints.ts @@ -9,6 +9,7 @@ export interface UseCashuMintsReturn { getMints: () => Promise; addMint: (mintUrl: string) => Promise; removeMint: (mintUrl: string) => Promise; + 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 } }).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, }; } diff --git a/src/hooks/useCopyToClipboard.ts b/src/hooks/useCopyToClipboard.ts new file mode 100644 index 0000000..4ffa3f8 --- /dev/null +++ b/src/hooks/useCopyToClipboard.ts @@ -0,0 +1,52 @@ +import { useState, useCallback } from 'react'; +import { useToast } from './useToast'; + +interface UseCopyToClipboardReturn { + copy: (text: string) => Promise; + 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(null); + const { toast } = useToast(); + + const copy = useCallback(async (text: string): Promise => { + 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, + }; +} diff --git a/src/hooks/useNpubCash.ts b/src/hooks/useNpubCash.ts deleted file mode 100644 index 3f7ba88..0000000 --- a/src/hooks/useNpubCash.ts +++ /dev/null @@ -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; - - // Get user info/settings - fetchUserInfo: () => Promise; - - // Set username (costs sats via X-Cashu header) - setUsername: (username: string) => Promise; - - // Set preferred mint - setMint: (mintUrl: string) => Promise; - - // Toggle quote locking (NUT-20) - setLockQuotes: (locked: boolean) => Promise; - - // Refresh all data - refresh: () => Promise; - - // 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 (npub@npubx.cash) 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 - *

Send sats to: {lightningAddress}

- * - * // Show unclaimed balance - *

Unclaimed: {unclaimedAmount} sats

- * - * // 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('npubcash-jwt', null); - - // Store last claimed quote timestamp to track new payments - const [lastClaimedAt, setLastClaimedAt] = useLocalStorage('npubcash-last-claimed', 0); - - // Component state - const [isInitialized, setIsInitialized] = useState(false); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - const [userInfo, setUserInfo] = useState(null); - const [quotes, setQuotes] = useState([]); - 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 => { - 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 => { - // 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 => { - 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 ( - endpoint: string, - options: RequestInit = {} - ): Promise => { - 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 => { - 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 => { - 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 => { - 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 => { - 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 => { - 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 => { - 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 - diff --git a/src/hooks/useQRCode.ts b/src/hooks/useQRCode.ts new file mode 100644 index 0000000..2043b06 --- /dev/null +++ b/src/hooks/useQRCode.ts @@ -0,0 +1,62 @@ +import { useState, useCallback } from 'react'; +import QRCode from 'qrcode'; +import { useToast } from './useToast'; + +interface UseQRCodeReturn { + generateQRCode: (text: string) => Promise; + 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(null); + const { toast } = useToast(); + + const generateQRCode = useCallback(async (text: string): Promise => { + 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, + }; +} diff --git a/src/lib/exchangeRateService.ts b/src/lib/exchangeRateService.ts new file mode 100644 index 0000000..ff065b3 --- /dev/null +++ b/src/lib/exchangeRateService.ts @@ -0,0 +1,131 @@ +/** + * Exchange rate service for fetching BTC/USD rates from Coinbase API + */ +export class ExchangeRateService { + private static readonly COINBASE_API_URL = "https://api.coinbase.com/v2/exchange-rates"; + private static readonly CACHE_DURATION_MS = 60000; // 1 minute cache + + private cachedRate: number | null = null; + private cacheTimestamp: number = 0; + + /** + * Get the current BTC/USD exchange rate from Coinbase API + * Uses caching to avoid excessive API calls + */ + async getBtcUsdRate(): Promise { + const now = Date.now(); + + // Return cached rate if still valid + if (this.cachedRate && (now - this.cacheTimestamp) < ExchangeRateService.CACHE_DURATION_MS) { + console.debug(`Using cached BTC/USD rate: ${this.cachedRate}`, { + cache_age_ms: now - this.cacheTimestamp, + }); + return this.cachedRate; + } + + try { + console.debug("Fetching BTC/USD rate from Coinbase API"); + + const response = await fetch(`${ExchangeRateService.COINBASE_API_URL}?currency=BTC`, { + method: "GET", + headers: { + "Accept": "application/json", + "User-Agent": "MKStack/1.0", + }, + // Add timeout to prevent hanging + signal: AbortSignal.timeout(10000), // 10 second timeout + }); + + if (!response.ok) { + throw new Error(`Coinbase API error: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + + // Validate response structure + if (!data?.data?.rates?.USD) { + throw new Error("Invalid response format from Coinbase API"); + } + + const rate = parseFloat(data.data.rates.USD); + + if (isNaN(rate) || rate <= 0) { + throw new Error(`Invalid exchange rate received: ${data.data.rates.USD}`); + } + + // Update cache + this.cachedRate = rate; + this.cacheTimestamp = now; + + console.info(`Fetched BTC/USD rate from Coinbase: ${rate}`, { rate }); + + return rate; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + + console.error(`Failed to fetch BTC/USD rate: ${errorMessage}`); + + // If we have a cached rate, use it as fallback + if (this.cachedRate) { + const cacheAge = now - this.cacheTimestamp; + console.warn(`Using stale cached rate as fallback: ${this.cachedRate}`, { + cache_age_ms: cacheAge, + }); + return this.cachedRate; + } + + // If no cached rate available, throw error + throw new Error(`Unable to fetch BTC/USD exchange rate: ${errorMessage}`); + } + } + + /** + * Convert BTC amount to USD using current exchange rate + */ + async btcToUsd(btcAmount: number): Promise { + const rate = await this.getBtcUsdRate(); + return btcAmount * rate; + } + + /** + * Convert USD amount to BTC using current exchange rate + */ + async usdToBtc(usdAmount: number): Promise { + const rate = await this.getBtcUsdRate(); + return usdAmount / rate; + } + + /** + * Convert sats to USD using current exchange rate + */ + async satsToUsd(sats: number): Promise { + const btcAmount = sats / 100000000; // Convert sats to BTC + return this.btcToUsd(btcAmount); + } + + /** + * Clear the cached exchange rate (useful for testing) + */ + clearCache(): void { + this.cachedRate = null; + this.cacheTimestamp = 0; + } + + /** + * Get cache status for debugging + */ + getCacheStatus(): { rate: number | null; age_ms: number; is_valid: boolean } { + const now = Date.now(); + const age = now - this.cacheTimestamp; + const isValid = this.cachedRate !== null && age < ExchangeRateService.CACHE_DURATION_MS; + + return { + rate: this.cachedRate, + age_ms: age, + is_valid: isValid, + }; + } +} + +// Export a singleton instance +export const exchangeRateService = new ExchangeRateService();