From 6dacd3d9642e7d15da757cca02d387980bbea222 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sun, 5 Oct 2025 23:02:06 -0700 Subject: [PATCH] cashu wallet integration --- package-lock.json | 87 ++- package.json | 3 + src/AppRouter.tsx | 2 + src/components/CashuWallet.tsx | 1127 ++++++++++++++++++++++++++++++ src/hooks/useCashu.ts | 523 ++++++++++++++ src/hooks/useLightningAddress.ts | 159 +++++ 6 files changed, 1896 insertions(+), 5 deletions(-) create mode 100644 src/components/CashuWallet.tsx create mode 100644 src/hooks/useCashu.ts create mode 100644 src/hooks/useLightningAddress.ts diff --git a/package-lock.json b/package-lock.json index 5aad45d..9236e66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -40,12 +40,15 @@ "@radix-ui/react-toggle": "^1.1.0", "@radix-ui/react-toggle-group": "^1.1.0", "@radix-ui/react-tooltip": "^1.1.4", + "@scure/bip39": "^2.0.0", "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.0.0", + "coco-cashu-core": "file:../coco/packages/core", + "coco-cashu-indexeddb": "file:../coco/packages/indexeddb", "date-fns": "^3.6.0", "embla-carousel-react": "^8.3.0", "input-otp": "^1.2.4", @@ -92,6 +95,38 @@ "vitest": "^3.1.4" } }, + "../coco/packages/core": { + "name": "coco-cashu-core", + "version": "1.0.0-rc9", + "dependencies": { + "@cashu/cashu-ts": "^2.7.2" + }, + "devDependencies": { + "@types/bun": "latest", + "esbuild": "latest", + "tsdown": "^0.14.1", + "typescript": "^5.9.2", + "typescript-eslint": "^8.40.0" + }, + "peerDependencies": { + "typescript": "^5" + } + }, + "../coco/packages/indexeddb": { + "name": "coco-cashu-indexeddb", + "version": "0.8.0", + "dependencies": { + "dexie": "^4.0.8" + }, + "devDependencies": { + "@types/bun": "latest", + "tsdown": "^0.14.1" + }, + "peerDependencies": { + "coco-cashu-core": "workspace:^", + "typescript": "^5" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.3.tgz", @@ -3037,18 +3072,39 @@ } }, "node_modules/@scure/bip39": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz", - "integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.0.0.tgz", + "integrity": "sha512-F2Tza4KyTSFO/13JymY6a6UHfSLzx0YGbkQGz7wjGx2BYJLyG/qXELKnFFsDfeIK+WfV2v2+5XOQftvL4d8RBA==", "license": "MIT", "dependencies": { - "@noble/hashes": "~1.3.0", - "@scure/base": "~1.1.0" + "@noble/hashes": "2.0.0", + "@scure/base": "2.0.0" }, "funding": { "url": "https://paulmillr.com/funding/" } }, + "node_modules/@scure/bip39/node_modules/@noble/hashes": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.0.tgz", + "integrity": "sha512-h8VUBlE8R42+XIDO229cgisD287im3kdY6nbNZJFjc6ZvKIXPYXe6Vc/t+kyjFdMFyt5JpapzTsEg8n63w5/lw==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39/node_modules/@scure/base": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz", + "integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@swc/core": { "version": "1.11.24", "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz", @@ -4426,6 +4482,14 @@ "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, + "node_modules/coco-cashu-core": { + "resolved": "../coco/packages/core", + "link": true + }, + "node_modules/coco-cashu-indexeddb": { + "resolved": "../coco/packages/indexeddb", + "link": true + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -6046,6 +6110,19 @@ } } }, + "node_modules/nostr-tools/node_modules/@scure/bip39": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz", + "integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.3.0", + "@scure/base": "~1.1.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/nostr-wasm": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz", diff --git a/package.json b/package.json index a2b34ac..b0ae3ca 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,9 @@ "@hookform/resolvers": "^3.9.0", "@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4", "@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8", + "@scure/bip39": "^2.0.0", + "coco-cashu-core": "file:../coco/packages/core", + "coco-cashu-indexeddb": "file:../coco/packages/indexeddb", "@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-aspect-ratio": "^1.1.0", diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 2db53ee..473f8ef 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -4,6 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop"; import Index from "./pages/Index"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; +import { CashuWallet } from "./components/CashuWallet"; export function AppRouter() { return ( @@ -11,6 +12,7 @@ export function AppRouter() { } /> + } /> {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} } /> {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} diff --git a/src/components/CashuWallet.tsx b/src/components/CashuWallet.tsx new file mode 100644 index 0000000..120397f --- /dev/null +++ b/src/components/CashuWallet.tsx @@ -0,0 +1,1127 @@ +import { useState, useEffect } from 'react'; +import { useCashu, type HistoryEntry } from '@/hooks/useCashu'; +import { useLocalStorage } from '@/hooks/useLocalStorage'; +import { useLightningAddress } from '@/hooks/useLightningAddress'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Badge } from '@/components/ui/badge'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu'; +import { Loader2, Wallet, Plus, Send, Download, Bitcoin, DollarSign, ArrowLeftRight, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp } from 'lucide-react'; + +export function CashuWallet() { + // ============================================================================ + // HOOKS + // ============================================================================ + + const { + isInitialized, + isLoading, + error, + balances, + mints, + receive, + send, + getProofs, + addMint, + createMintQuote, + createMeltQuote, + payMeltQuote, + redeemMintQuote, + refreshBalances, + refreshMints, + checkAndRedeemPendingQuotes, + clearError, + getHistory, + } = useCashu(); + + const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress(); + + // ============================================================================ + // STATE - Input Values + // ============================================================================ + + const [tokenInput, setTokenInput] = useState(''); + const [mintUrl, setMintUrl] = useState(''); + const [sendAmount, setSendAmount] = useState(''); + const [quoteAmount, setQuoteAmount] = useState(''); + const [lightningInvoice, setLightningInvoice] = useState(''); + const [lightningAddressInput, setLightningAddressInput] = useState(''); + const [lightningAddressAmount, setLightningAddressAmount] = useState(''); + + // ============================================================================ + // STATE - UI State + // ============================================================================ + + const [showSats, setShowSats] = useState(true); + const [receiveMode, setReceiveMode] = useState<'tokens' | 'lightning'>('tokens'); + const [sendMode, setSendMode] = useState<'tokens' | 'lightning'>('tokens'); + const [activeMintUrl, setActiveMintUrl] = useState(null); + + // ============================================================================ + // STATE - Transaction State + // ============================================================================ + + const [sentToken, setSentToken] = useState(null); + const [pendingLightningAddress, setPendingLightningAddress] = useState(null); + const [pendingQuotes, setPendingQuotes] = useLocalStorage>('cashu-pending-quotes', []); + + // ============================================================================ + // STATE - Copy Feedback + // ============================================================================ + + const [copiedToken, setCopiedToken] = useState(false); + const [copiedInvoice, setCopiedInvoice] = useState(null); + + // ============================================================================ + // STATE - History + // ============================================================================ + + const [historyEntries, setHistoryEntries] = useState([]); + const [isLoadingHistory, setIsLoadingHistory] = useState(false); + const [isHistoryExpanded, setIsHistoryExpanded] = useState(false); + const [showProofBreakdown, setShowProofBreakdown] = useState(false); + const [proofBreakdown, setProofBreakdown] = useState<{ + mintUrl: string; + denominations: { [key: number]: number }; + totalBalance: number; + } | null>(null); + + // ============================================================================ + // COMPUTED VALUES + // ============================================================================ + + const totalBalance = Object.values(balances).reduce((sum, balance) => 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)}`; + } + }; + + // ============================================================================ + // HELPER FUNCTIONS - History + // ============================================================================ + + const loadHistory = async () => { + try { + setIsLoadingHistory(true); + const entries = await getHistory(50, 0); + setHistoryEntries(entries); + } catch (err) { + console.error('Failed to load history:', err); + } finally { + setIsLoadingHistory(false); + } + }; + + 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 + // ============================================================================ + + const handleReceive = async () => { + if (receiveMode === 'tokens') { + if (!tokenInput.trim()) return; + try { + await receive(tokenInput); + setTokenInput(''); + const message = 'Token received successfully!'; + console.log('✅', message); + alert(message); + } catch (err) { + const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + } else { + // Lightning mode - create mint quote + if (!quoteAmount || !activeMintUrl) return; + try { + const amount = parseInt(quoteAmount); + if (isNaN(amount) || amount <= 0) { + const message = 'Please enter a valid amount'; + console.warn('⚠️', message); + alert(message); + return; + } + const quote = await createMintQuote(activeMintUrl, amount); + + // Save the pending quote + setPendingQuotes(prev => [...prev, { + quoteId: quote.quote, + mintUrl: activeMintUrl, + amount, + invoice: quote.request, + timestamp: Date.now() + }]); + + const message = `Mint quote created! Request: ${quote.request}`; + console.log('✅', message); + console.log('💰 Quote object:', quote); + console.log('🔗 Lightning Invoice:', quote.request); + alert('Lightning invoice created! After paying, click the refresh button (🔄) to claim your tokens.'); + setQuoteAmount(''); + } catch (err) { + const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + } + }; + + // ============================================================================ + // EVENT HANDLERS - Send + // ============================================================================ + + const handleSend = async () => { + if (sendMode === 'tokens') { + if (!sendAmount || !activeMintUrl) return; + try { + const amount = parseInt(sendAmount); + if (isNaN(amount) || amount <= 0) { + const message = 'Please enter a valid amount'; + console.warn('⚠️', message); + alert(message); + return; + } + const encodedToken = await send(activeMintUrl, amount); + setSentToken(encodedToken); + console.log('✅ Token sent successfully!'); + console.log('📤 Encoded token:', encodedToken); + setSendAmount(''); + } catch (err) { + const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + } else { + // Lightning mode + if (!activeMintUrl) return; + + // Step 1: Check if we have a pending Lightning address awaiting amount + if (pendingLightningAddress) { + // Step 2: User entered amount, now resolve address and pay + if (!lightningAddressAmount) return; + + try { + const amount = parseInt(lightningAddressAmount); + if (isNaN(amount) || amount <= 0) { + alert('Please enter a valid amount'); + return; + } + + console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount); + const invoice = await getLightningInvoice({ + lightningAddress: pendingLightningAddress, + amountSats: amount, + }); + + console.log('🔄 Creating melt quote for invoice:', invoice); + const meltQuote = await createMeltQuote(activeMintUrl, invoice); + + console.log('🔄 Paying melt quote:', meltQuote.quote); + await payMeltQuote(activeMintUrl, meltQuote.quote); + + console.log('✅ Lightning payment sent successfully!'); + alert(`Successfully sent ${amount} sats to ${pendingLightningAddress}!`); + + // Reset state + setPendingLightningAddress(null); + setLightningAddressInput(''); + setLightningAddressAmount(''); + + // Refresh balances + await refreshBalances(); + } catch (err) { + const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + } else { + // Step 1: Check if input is a Lightning address or invoice + const input = lightningInvoice.trim() || lightningAddressInput.trim(); + if (!input) return; + + // Check if it's a Lightning address (contains @) + if (input.includes('@')) { + console.log('📧 Detected Lightning address:', input); + setPendingLightningAddress(input); + setLightningAddressInput(''); + } else { + // It's a regular Lightning invoice + try { + console.log('🔄 Creating melt quote for invoice:', input); + const meltQuote = await createMeltQuote(activeMintUrl, input); + + console.log('🔄 Paying melt quote:', meltQuote.quote); + await payMeltQuote(activeMintUrl, meltQuote.quote); + + console.log('✅ Lightning invoice paid successfully!'); + alert('Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.'); + setLightningInvoice(''); + + // Refresh balances to show updated amounts + await refreshBalances(); + } catch (err) { + const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + } + } + } + }; + + // ============================================================================ + // 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); + alert('Failed to copy to clipboard'); + } + }; + + // ============================================================================ + // EVENT HANDLERS - Mint Management + // ============================================================================ + + const handleAddMint = async () => { + if (!mintUrl.trim()) return; + try { + // Normalize URL - add https:// if not present + let normalizedUrl = mintUrl.trim(); + if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) { + normalizedUrl = `https://${normalizedUrl}`; + } + + await addMint(normalizedUrl); + setMintUrl(''); + + // Explicitly refresh mints and balances + await refreshMints(); + await refreshBalances(); + + const message = `Mint added successfully: ${normalizedUrl}`; + console.log('✅', message); + alert('Mint added successfully!'); + } catch (err) { + const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + }; + + // ============================================================================ + // EVENT HANDLERS - Quote Management + // ============================================================================ + + const handleClaimQuote = async (quoteId: string, mintUrl: string) => { + try { + console.log('🎯 Attempting to claim quote:', quoteId, 'from mint:', mintUrl); + await redeemMintQuote(mintUrl, quoteId); + + // Remove from pending quotes + setPendingQuotes(prev => prev.filter(q => q.quoteId !== quoteId)); + + // Refresh balances + await refreshBalances(); + + console.log('✅ Quote claimed successfully!'); + alert('Tokens claimed successfully! Your balance has been updated.'); + } catch (err) { + const errorMessage = `Failed to claim tokens: ${err instanceof Error ? err.message : 'Unknown error'}`; + console.error('❌', errorMessage, err); + alert(errorMessage); + } + }; + + const handleShowDenominations = async (mintUrl: string) => { + try { + console.log('🔍 Getting token denominations for mint:', mintUrl); + + // Get proofs from the wallet for this specific mint + const proofs = await getProofs(mintUrl); + console.log('💰 Raw proofs for mint:', proofs); + + if (!proofs || proofs.length === 0) { + alert('No tokens found for this mint'); + return; + } + + // Group proofs by denomination + const denominations: { [key: number]: number } = {}; + proofs.forEach((proof: any) => { + const amount = proof.amount || 0; + denominations[amount] = (denominations[amount] || 0) + 1; + }); + + const totalBalance = Object.entries(denominations) + .reduce((sum, [amount, count]) => sum + (parseInt(amount) * count), 0); + + // Set the breakdown data and show the modal + setProofBreakdown({ + mintUrl, + denominations, + totalBalance + }); + setShowProofBreakdown(true); + + } catch (err) { + console.error('Failed to get denominations:', err); + alert('Failed to get token denominations. Check console for details.'); + } + }; + + // ============================================================================ + // EFFECTS + // ============================================================================ + + // Auto-select active mint when mints or balances change + useEffect(() => { + if (mints.length > 0 && !activeMintUrl) { + // Find mint with highest balance, or first mint if balances are equal + const mintWithHighestBalance = mints.reduce((highest, current) => { + const currentBalance = balances[current.url] || 0; + const highestBalance = balances[highest.url] || 0; + return currentBalance > highestBalance ? current : highest; + }); + setActiveMintUrl(mintWithHighestBalance.url); + } + }, [mints, activeMintUrl, balances]); + + // Load transaction history when wallet is initialized + useEffect(() => { + if (isInitialized && historyEntries.length === 0) { + loadHistory(); + } + }, [isInitialized]); + + // ============================================================================ + // RENDER - Loading State + // ============================================================================ + + if (isLoading) { + return ( +
+ + + + Initializing... + + +
+ ); + } + + // ============================================================================ + // RENDER - Uninitialized State + // ============================================================================ + + if (!isInitialized) { + return ( + + + + + Cashu Wallet + + + Failed to initialize wallet. Please check the console for errors. + + + + ); + } + + // ============================================================================ + // RENDER - Main UI + // ============================================================================ + + return ( +
+ + {/* ======================================================================== + SECTION: Balance Display + ======================================================================== */} + {isInitialized && ( +
+
+ + +
+ {/* Active Mint Dropdown and Balance */} +
+ + + + + + Connected Mints + + {mints.length === 0 && ( + No mints connected + )} + {mints + .filter((mint) => mint.url) + .map((mint, index) => ( + setActiveMintUrl(mint.url)} + > +
+ {getCleanMintLabel(mint as any)} +
+
+ ))} + +
+
+ setMintUrl(e.target.value)} + className="h-8" + /> + +
+
+
+
+ + {/* Active Mint Balance */} + {activeMintUrl && ( +
+ +
+ )} +
+
+ )} + + {/* ======================================================================== + SECTION: Error Display + ======================================================================== */} + {error && ( + + + {error} + + + + )} + + {/* ======================================================================== + SECTION: Receive & Send Cards + ======================================================================== */} +
+ + {/* Receive Card */} + + + +
+ + Receive +
+
+ + +
+
+ + {receiveMode === 'tokens' + ? 'Enter Cashu token to redeem' + : 'Deposit funds with Lightning' + } + +
+ + {receiveMode === '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 +
+
+ + +
+
+ + {sendMode === 'tokens' + ? 'Generate Cashu token to send' + : pendingLightningAddress + ? 'Enter the amount to send' + : 'Pay Lightning invoices or addresses from balance' + } + +
+ + {sendMode === '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} +
+ +
+
+
+ )} + + {/* ======================================================================== + SECTION: Pending Lightning Payments + ======================================================================== */} + {pendingQuotes.length > 0 && ( + + + + + + Pending Lightning Payments + + + Click "Check Payment" after paying the Lightning invoice + + + +
+ {pendingQuotes.map((quote) => ( +
+
+
+
{quote.amount} sats
+
+ {new URL(quote.mintUrl).hostname} +
+
+ Created: {new Date(quote.timestamp).toLocaleTimeString()} +
+
+ +
+
+
+ {quote.invoice.length > 20 ? `${quote.invoice.substring(0, 20)}...` : quote.invoice} +
+ +
+
+ ))} +
+
+
+ )} + + {/* ======================================================================== + 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. +
+
+
+
+ )} +
+ ); +} diff --git a/src/hooks/useCashu.ts b/src/hooks/useCashu.ts new file mode 100644 index 0000000..cc0bde8 --- /dev/null +++ b/src/hooks/useCashu.ts @@ -0,0 +1,523 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { useLocalStorage } from './useLocalStorage'; +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english'; + +// Types for the hook interface +export interface CashuBalance { + [mintUrl: string]: number; +} + +export interface CashuMint { + url: string; + name?: string; + info?: any; +} + +export interface CashuMintQuote { + quote: string; + request: string; + expiry: number; +} + +export interface CashuMeltQuote { + quote: string; + request: string; + expiry: number; +} + +export interface CashuToken { + mint: string; + proofs: any[]; +} + +export interface CashuState { + isInitialized: boolean; + isLoading: boolean; + error: string | null; + balances: CashuBalance; + mints: CashuMint[]; + mnemonic: string | null; +} + +export interface HistoryEntry { + id: string; + type: 'mint' | 'melt' | 'send' | 'receive'; + mintUrl: string; + amount: number; + unit: string; + createdAt: number; + metadata?: any; + quoteId?: string; + state?: string; + paymentRequest?: string; + token?: any; +} + +export interface CashuActions { + // Wallet operations + receive: (token: string | CashuToken) => Promise; + send: (mintUrl: string, amount: number) => Promise; + getBalances: () => Promise; + getProofs: (mintUrl: string) => Promise; + + // Mint operations + addMint: (mintUrl: string) => Promise; + removeMint: (mintUrl: string) => Promise; + getMints: () => Promise; + + // Quote operations + createMintQuote: (mintUrl: string, amount: number) => Promise; + redeemMintQuote: (mintUrl: string, quoteId: string) => Promise; + createMeltQuote: (mintUrl: string, invoice: string) => Promise; + payMeltQuote: (mintUrl: string, quoteId: string) => Promise; + + // Mnemonic operations + setMnemonic: (mnemonic: string) => void; + generateMnemonic: () => string; + getMnemonic: () => string | null; + + // History operations + getHistory: (limit?: number, offset?: number) => Promise; + + // Utility operations + refreshBalances: () => Promise; + refreshMints: () => Promise; + checkAndRedeemPendingQuotes: () => Promise; + clearError: () => void; +} + +export type UseCashuReturn = CashuState & CashuActions; + +// Dynamic imports for coco-cashu packages +let Manager: any; +let IndexedDbRepositories: any; +let ConsoleLogger: any; +let getEncodedToken: any; +let getDecodedToken: any; + +// Lazy load coco-cashu packages +const loadCocoCashu = async () => { + if (Manager) return; // Already loaded + + try { + const coreModule = await import('coco-cashu-core'); + const indexedDbModule = await import('coco-cashu-indexeddb'); + + Manager = coreModule.Manager; + ConsoleLogger = coreModule.ConsoleLogger; + getEncodedToken = coreModule.getEncodedToken; + getDecodedToken = coreModule.getDecodedToken; + IndexedDbRepositories = indexedDbModule.IndexedDbRepositories; + } catch (error) { + console.error('Failed to load coco-cashu packages:', error); + throw new Error('Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb'); + } +}; + +export function useCashu(): UseCashuReturn { + // State management + const [isInitialized, setIsInitialized] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + const [balances, setBalances] = useState({}); + const [mints, setMints] = useState([]); + + // Mnemonic management with localStorage + const [mnemonic, setMnemonicState] = useLocalStorage('cashu-mnemonic', null); + + // Manager instance ref + const managerRef = useRef(null); + const repositoriesRef = useRef(null); + + // Initialize the manager + const initializeManager = useCallback(async () => { + if (isInitialized || isLoading) return; + + setIsLoading(true); + setError(null); + + try { + await loadCocoCashu(); + + // Generate or retrieve mnemonic + let currentMnemonic = mnemonic; + if (!currentMnemonic) { + currentMnemonic = bip39.generateMnemonic(wordlist); + setMnemonicState(currentMnemonic); + } + + // Create seed from mnemonic + const seed = bip39.mnemonicToSeedSync(currentMnemonic); + + // Initialize repositories + const repositories = new IndexedDbRepositories({}); + await repositories.init(); + repositoriesRef.current = repositories; + + // Initialize manager + const manager = new Manager( + repositories, + async () => seed, + new ConsoleLogger(undefined, { level: 'info' }) + ); + managerRef.current = manager; + + // Load initial data + await refreshBalances(); + await refreshMints(); + + // Check for any pending quotes that might have been paid + await checkAndRedeemPendingQuotes(); + + setIsInitialized(true); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet'; + setError(errorMessage); + console.error('Cashu initialization error:', err); + } finally { + setIsLoading(false); + } + }, [isInitialized, isLoading, mnemonic, setMnemonicState]); + + // Initialize on mount + useEffect(() => { + initializeManager(); + }, [initializeManager]); + + // Utility operations - defined first so they can be used in other callbacks + const refreshBalances = useCallback(async () => { + if (!managerRef.current) return; + + try { + console.log('🔄 refreshBalances: Getting balances from wallet...'); + const newBalances = await managerRef.current.wallet.getBalances(); + console.log('💰 refreshBalances: Raw balances from wallet:', newBalances); + setBalances(newBalances); + console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints'); + } catch (err) { + console.error('❌ refreshBalances: Failed to refresh balances:', err); + } + }, []); + + const refreshMints = useCallback(async () => { + if (!managerRef.current) return; + + try { + const mintList = await managerRef.current.mint.getAllMints(); + const formattedMints = mintList + .filter((mint: any) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url + .map((mint: any) => ({ + url: mint.mintUrl, // Map mintUrl to url for consistency + name: mint.name, + info: mint.mintInfo + })); + setMints(formattedMints); + } catch (err) { + console.error('Failed to refresh mints:', err); + } + }, []); + + // Wallet operations + const receive = useCallback(async (token: string | CashuToken) => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + await managerRef.current.wallet.receive(token); + await refreshBalances(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to receive token'; + setError(errorMessage); + throw err; + } + }, [refreshBalances]); + + const send = useCallback(async (mintUrl: string, amount: number): Promise => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + const token = await managerRef.current.wallet.send(mintUrl, amount); + await refreshBalances(); + + // Encode the token into a Cashu token string + const encodedToken = getEncodedToken(token); + return encodedToken; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens'; + setError(errorMessage); + throw err; + } + }, [refreshBalances]); + + const getBalances = useCallback(async (): Promise => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + return await managerRef.current.wallet.getBalances(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get balances'; + setError(errorMessage); + throw err; + } + }, []); + + const getProofs = useCallback(async (mintUrl: string): Promise => { + if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized'); + + try { + console.log('🔍 Getting proofs from wallet for mint:', mintUrl); + + // Access the proof repository + const proofRepo = (repositoriesRef.current as any).proofRepository; + if (!proofRepo) { + throw new Error('Proof repository not available'); + } + + // Get ready proofs for this mint (proofs available to spend) + const readyProofs = await proofRepo.getReadyProofs(mintUrl); + console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`); + + return readyProofs; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs'; + console.error('❌ Error getting proofs:', err); + setError(errorMessage); + throw err; + } + }, []); + + // Mint operations + const addMint = useCallback(async (mintUrl: string) => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + await managerRef.current.mint.addMint(mintUrl); + await refreshMints(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to add mint'; + setError(errorMessage); + throw err; + } + }, [refreshMints]); + + const removeMint = useCallback(async (mintUrl: string) => { + // Note: coco-cashu doesn't have a direct remove mint method + // This would need to be implemented at the repository level + setError('Remove mint functionality not yet implemented'); + throw new Error('Remove mint functionality not yet implemented'); + }, []); + + const getMints = useCallback(async (): Promise => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + const mintList = await managerRef.current.mint.getAllMints(); + return mintList + .filter((mint: any) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url + .map((mint: any) => ({ + url: mint.mintUrl, // Map mintUrl to url for consistency + name: mint.name, + info: mint.mintInfo + })); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get mints'; + setError(errorMessage); + throw err; + } + }, []); + + // Quote operations + const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + const quote = await managerRef.current.quotes.createMintQuote(mintUrl, amount); + return { + quote: quote.quote, + request: quote.request, + expiry: quote.expiry + }; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote'; + setError(errorMessage); + throw err; + } + }, []); + + const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId); + await managerRef.current.quotes.redeemMintQuote(mintUrl, quoteId); + console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...'); + await refreshBalances(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote'; + setError(errorMessage); + throw err; + } + }, [refreshBalances]); + + const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + const quote = await managerRef.current.quotes.createMeltQuote(mintUrl, invoice); + return { + quote: quote.quote, + request: quote.request, + expiry: quote.expiry + }; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote'; + setError(errorMessage); + throw err; + } + }, []); + + const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => { + if (!managerRef.current) throw new Error('Wallet not initialized'); + + try { + setError(null); + await managerRef.current.quotes.payMeltQuote(mintUrl, quoteId); + await refreshBalances(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote'; + setError(errorMessage); + throw err; + } + }, [refreshBalances]); + + // Mnemonic operations + const setMnemonic = useCallback((newMnemonic: string) => { + if (!bip39.validateMnemonic(newMnemonic, wordlist)) { + throw new Error('Invalid mnemonic'); + } + setMnemonicState(newMnemonic); + // Reinitialize manager with new mnemonic + setIsInitialized(false); + initializeManager(); + }, [setMnemonicState, initializeManager]); + + const generateMnemonic = useCallback(() => { + return bip39.generateMnemonic(wordlist); + }, []); + + const getMnemonic = useCallback(() => { + return mnemonic; + }, [mnemonic]); + + // Check and redeem all pending mint quotes + const checkAndRedeemPendingQuotes = useCallback(async () => { + if (!managerRef.current || !repositoriesRef.current) return; + + try { + console.log('🔍 Checking for pending mint quotes in IndexedDB...'); + + // Access the mint quotes repository directly + const mintQuotesRepo = (repositoriesRef.current as any).mintQuoteRepository; + if (!mintQuotesRepo) { + console.log('⚠️ Mint quotes repository not available'); + return; + } + + // Get all pending mint quotes (non-ISSUED quotes) + const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes(); + console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`); + + // Filter for UNPAID quotes (these might have been paid but not redeemed) + const unpaidQuotes = pendingQuotes.filter((q: any) => q.state === 'UNPAID'); + console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`); + + let claimedCount = 0; + + for (const quote of unpaidQuotes) { + try { + console.log(`🔄 Attempting to redeem quote ${quote.quote} from ${quote.mintUrl}...`); + await managerRef.current.quotes.redeemMintQuote(quote.mintUrl, quote.quote); + claimedCount++; + console.log(`✅ Successfully claimed ${quote.amount} sats from quote ${quote.quote}`); + } catch (err) { + // Quote not paid yet or already claimed - this is expected, just skip + console.log(`⏭️ Quote ${quote.quote} not ready yet (invoice not paid or already claimed)`); + } + } + + if (claimedCount > 0) { + console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`); + await refreshBalances(); + } + } catch (err) { + console.error('❌ Error checking pending quotes:', err); + } + }, [refreshBalances]); + + const clearError = useCallback(() => { + setError(null); + }, []); + + // History operations + const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise => { + if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized'); + + try { + console.log('📜 Getting transaction history...'); + + // Access the history repository (correct property name is historyRepository) + const historyRepo = (repositoriesRef.current as any).historyRepository; + if (!historyRepo) { + throw new Error('History repository not available'); + } + + // Get paginated history entries + const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset); + console.log(`✅ Found ${entries.length} history entries`); + + return entries; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Failed to get history'; + console.error('❌ Error getting history:', err); + setError(errorMessage); + throw err; + } + }, []); + + return { + // State + isInitialized, + isLoading, + error, + balances, + mints, + mnemonic, + + // Actions + receive, + send, + getBalances, + getProofs, + addMint, + removeMint, + getMints, + createMintQuote, + redeemMintQuote, + createMeltQuote, + payMeltQuote, + setMnemonic, + generateMnemonic, + getMnemonic, + getHistory, + refreshBalances, + refreshMints, + checkAndRedeemPendingQuotes, + clearError, + }; +} diff --git a/src/hooks/useLightningAddress.ts b/src/hooks/useLightningAddress.ts new file mode 100644 index 0000000..7b193c4 --- /dev/null +++ b/src/hooks/useLightningAddress.ts @@ -0,0 +1,159 @@ +import { useState, useCallback } from 'react'; + +// LNURL Protocol Types +interface LNURLPayResponse { + status: 'OK' | 'ERROR'; + tag: 'payRequest'; + commentAllowed?: number; + minSendable: number; // millisats + maxSendable: number; // millisats + metadata: string; + callback: string; +} + +interface LNURLInvoiceResponse { + status: 'OK' | 'ERROR'; + reason?: string; + pr?: string; // BOLT11 invoice +} + +interface GetInvoiceParams { + lightningAddress: string; + amountSats: number; + comment?: string; +} + +interface UseLightningAddressReturn { + getInvoice: (params: GetInvoiceParams) => Promise; + isLoading: boolean; + error: string | null; +} + +/** + * Hook for resolving Lightning addresses to invoices + * + * @example + * ```tsx + * const { getInvoice, isLoading, error } = useLightningAddress(); + * + * const invoice = await getInvoice({ + * lightningAddress: 'alice@strike.me', + * amountSats: 1000, + * comment: 'Thanks for the coffee!' + * }); + * ``` + */ +export function useLightningAddress(): UseLightningAddressReturn { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + /** + * Fetches a Lightning invoice for the given address and amount + * + * @param params - Lightning address, amount in sats, and optional comment + * @returns BOLT11 invoice string + * @throws Error if resolution fails + */ + const getInvoice = useCallback(async (params: GetInvoiceParams): Promise => { + const { lightningAddress, amountSats, comment } = params; + + setIsLoading(true); + setError(null); + + try { + // Validate inputs + if (!lightningAddress || !lightningAddress.includes('@')) { + throw new Error('Invalid Lightning address format. Expected: username@domain.com'); + } + + if (amountSats <= 0) { + throw new Error('Amount must be greater than 0'); + } + + // Parse Lightning address + const [username, domain] = lightningAddress.split('@'); + if (!username || !domain) { + throw new Error('Invalid Lightning address format'); + } + + // Step 1: Fetch LNURL-pay info + const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`; + + const lnurlResponse = await fetch(lnurlEndpoint, { + headers: { 'Accept': 'application/json' }, + }); + + if (!lnurlResponse.ok) { + throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status}`); + } + + const lnurlData: LNURLPayResponse = await lnurlResponse.json(); + + if (lnurlData.status !== 'OK') { + throw new Error('LNURL endpoint returned error status'); + } + + if (lnurlData.tag !== 'payRequest') { + throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`); + } + + // Validate amount against min/max bounds + const minSats = lnurlData.minSendable / 1000; + const maxSats = lnurlData.maxSendable / 1000; + + if (amountSats < minSats) { + throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`); + } + + if (amountSats > maxSats) { + throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`); + } + + // Step 2: Request invoice from callback URL + const amountMsats = amountSats * 1000; + const callbackUrl = new URL(lnurlData.callback); + callbackUrl.searchParams.set('amount', amountMsats.toString()); + + // Add comment if provided and allowed + if (comment && lnurlData.commentAllowed && comment.length <= lnurlData.commentAllowed) { + callbackUrl.searchParams.set('comment', comment); + } + + const invoiceResponse = await fetch(callbackUrl.toString(), { + headers: { 'Accept': 'application/json' }, + }); + + if (!invoiceResponse.ok) { + throw new Error(`Failed to get invoice: ${invoiceResponse.status}`); + } + + const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json(); + + if (invoiceData.status !== 'OK') { + throw new Error(invoiceData.reason || 'Invoice generation failed'); + } + + if (!invoiceData.pr) { + throw new Error('No invoice returned from provider'); + } + + setIsLoading(false); + return invoiceData.pr; + + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred'; + setError(errorMessage); + setIsLoading(false); + throw err; + } + }, []); + + return { + getInvoice, + isLoading, + error, + }; +} + +export type { GetInvoiceParams }; +