diff --git a/src/components/ui/slider.tsx b/src/components/ui/slider.tsx index e161dae..17bd099 100644 --- a/src/components/ui/slider.tsx +++ b/src/components/ui/slider.tsx @@ -15,10 +15,10 @@ const Slider = React.forwardRef< )} {...props} > - + - + )) Slider.displayName = SliderPrimitive.Root.displayName diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index 2d76b4e..62dec02 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -111,6 +111,10 @@ export function CashuWallet() { setLightningAddressAmount, pendingLightningAddress, setPendingLightningAddress, + decodedInvoiceAmount, + setDecodedInvoiceAmount, + pendingInvoice, + setPendingInvoice, sentToken, setSentToken, sentTokenQRCode, @@ -120,6 +124,7 @@ export function CashuWallet() { setCurrentInvoice, handleReceive, handleSend, + handleConfirmInvoicePayment, mintQuoteUnsubscribeRef, } = useWalletTransactions({ coco, @@ -147,7 +152,7 @@ export function CashuWallet() { // ============================================================================ const [showSats, setShowSats] = useState(true); - const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens'); + const [mode, setMode] = useState<'tokens' | 'lightning'>('lightning'); const [showProofBreakdown, setShowProofBreakdown] = useState(false); const [proofBreakdown, setProofBreakdown] = useState<{ mintUrl: string; @@ -163,6 +168,30 @@ export function CashuWallet() { const [showReceiveModal, setShowReceiveModal] = useState(false); const [showHistoryModal, setShowHistoryModal] = useState(false); + // Handle drawer close with state reset + const handleSendDrawerClose = (open: boolean) => { + setShowSendModal(open); + if (!open) { + // Reset all send-related state when drawer closes + setSendAmount(''); + setLightningInvoice(''); + setLightningAddressInput(''); + setLightningAddressAmount(''); + setPendingLightningAddress(null); + setDecodedInvoiceAmount(null); + setPendingInvoice(null); + } + }; + + const handleReceiveDrawerClose = (open: boolean) => { + setShowReceiveModal(open); + if (!open) { + // Reset all receive-related state when drawer closes + setTokenInput(''); + setQuoteAmount(''); + } + }; + // Ref to track if we've fetched npub.cash user info const hasCheckedNpubCashRef = useRef(false); @@ -374,8 +403,8 @@ export function CashuWallet() { /> {/* Bottom Drawer Modals */} - - + + Send @@ -393,6 +422,10 @@ export function CashuWallet() { setLightningAddressAmount={setLightningAddressAmount} pendingLightningAddress={pendingLightningAddress} setPendingLightningAddress={setPendingLightningAddress} + decodedInvoiceAmount={decodedInvoiceAmount} + setDecodedInvoiceAmount={setDecodedInvoiceAmount} + pendingInvoice={pendingInvoice} + setPendingInvoice={setPendingInvoice} tokenInput="" setTokenInput={() => {}} quoteAmount="" @@ -406,6 +439,10 @@ export function CashuWallet() { } }} onReceive={() => {}} + onConfirmInvoice={() => { + handleConfirmInvoicePayment(); + setShowSendModal(false); + }} isResolvingAddress={isResolvingAddress} isLoading={isLoading || isNpubCashLoading} /> @@ -413,8 +450,8 @@ export function CashuWallet() { - - + + Receive @@ -432,6 +469,10 @@ export function CashuWallet() { setLightningAddressAmount={() => {}} pendingLightningAddress={null} setPendingLightningAddress={() => {}} + decodedInvoiceAmount={null} + setDecodedInvoiceAmount={() => {}} + pendingInvoice={null} + setPendingInvoice={() => {}} tokenInput={tokenInput} setTokenInput={setTokenInput} quoteAmount={quoteAmount} @@ -450,11 +491,11 @@ export function CashuWallet() { - + Transactions - + - - {mints - .filter((mint) => mint.url) - .map((mint, index) => { - const isActive = activeMintUrl === mint.url; - const balance = balances[mint.url] || 0; - - return ( - setActiveMintUrl(mint.url)} - className="flex items-center justify-between p-3 text-base" - > -
- {isActive && ( -
- -
- )} -
-
- {getCleanMintLabel(mint)} + +
+ {mints + .filter((mint) => mint.url) + .map((mint, index) => { + const isActive = activeMintUrl === mint.url; + const balance = balances[mint.url] || 0; + + return ( + setActiveMintUrl(mint.url)} + className="flex items-center justify-between p-3 text-base" + > +
+ {isActive && ( +
+ +
+ )} +
+
+ {getCleanMintLabel(mint)} +
-
-
- - {formatBalance(balance)} - - -
- - ); - })} +
+ + {formatBalance(balance)} + + +
+ + ); + })} +
{mints.length > 0 && }
diff --git a/src/components/wallet/PaymentCard.tsx b/src/components/wallet/PaymentCard.tsx index a4fc7a5..1ac08f6 100644 --- a/src/components/wallet/PaymentCard.tsx +++ b/src/components/wallet/PaymentCard.tsx @@ -1,6 +1,8 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; -import { Send, Download, Zap, Loader2, X } from 'lucide-react'; +import { Slider } from '@/components/ui/slider'; +import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react'; +import { useState, useEffect } from 'react'; interface TransactionCardProps { mode: 'tokens' | 'lightning'; @@ -16,6 +18,10 @@ interface TransactionCardProps { setLightningAddressAmount: (value: string) => void; pendingLightningAddress: string | null; setPendingLightningAddress: (value: string | null) => void; + decodedInvoiceAmount: number | null; + setDecodedInvoiceAmount: (value: number | null) => void; + pendingInvoice: string | null; + setPendingInvoice: (value: string | null) => void; // Receive props tokenInput: string; setTokenInput: (value: string) => void; @@ -25,6 +31,7 @@ interface TransactionCardProps { activeMintUrl: string | null; onSend: () => void; onReceive: () => void; + onConfirmInvoice?: () => void; isResolvingAddress: boolean; isLoading: boolean; } @@ -42,6 +49,10 @@ export function TransactionCard({ setLightningAddressAmount, pendingLightningAddress, setPendingLightningAddress, + decodedInvoiceAmount, + setDecodedInvoiceAmount, + pendingInvoice, + setPendingInvoice, tokenInput, setTokenInput, quoteAmount, @@ -49,9 +60,48 @@ export function TransactionCard({ activeMintUrl, onSend, onReceive, + onConfirmInvoice, isResolvingAddress, isLoading, }: TransactionCardProps) { + // Slider state for confirmation + const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]); + const [addressSliderValue, setAddressSliderValue] = useState([0]); + + // Handle slider value changes and auto-submit at 100% + const handleInvoiceSliderChange = (value: number[]) => { + setInvoiceSliderValue(value); + if (value[0] === 100 && onConfirmInvoice) { + onConfirmInvoice(); + } + }; + + const handleAddressSliderChange = (value: number[]) => { + setAddressSliderValue(value); + if (value[0] === 100) { + onSend(); + } + }; + + // Reset sliders when states change + const resetSliders = () => { + setInvoiceSliderValue([0]); + setAddressSliderValue([0]); + }; + + // Reset sliders when pending states change + useEffect(() => { + if (!pendingInvoice) { + setInvoiceSliderValue([0]); + } + }, [pendingInvoice]); + + useEffect(() => { + if (!pendingLightningAddress) { + setAddressSliderValue([0]); + } + }, [pendingLightningAddress]); + return (
{/* Title */} @@ -60,11 +110,40 @@ export function TransactionCard({ {operation === 'send' ? ( mode === 'tokens' ? 'Generate Cashu token to send' - : pendingLightningAddress ? ( - - Sending to:{' '} - {pendingLightningAddress} - + : pendingInvoice && decodedInvoiceAmount ? ( +
+ + Sending:{' '} + {decodedInvoiceAmount} sats + + +
+ ) : pendingLightningAddress ? ( +
+ + Sending:{' '} + {pendingLightningAddress} + + +
) : 'Pay invoices or addresses' ) : ( mode === 'tokens' @@ -75,7 +154,7 @@ export function TransactionCard({
{/* Content */} -
+
{!activeMintUrl && (
{operation === 'send' @@ -89,7 +168,7 @@ export function TransactionCard({ // Send Mode mode === 'tokens' ? ( // Cashu Token Send -
+
-
+
+ ) : pendingInvoice && decodedInvoiceAmount ? ( + // Lightning Invoice Confirmation (with slider) +
+
+
+ +
+ + {invoiceSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'} + +
+
+
+
) : pendingLightningAddress ? ( - // Lightning Address Amount Input -
+ // Lightning Address Amount Input with Slider +
-
- - +
+
+ +
+ + {addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'} + +
+
) : ( // Lightning Invoice/Address Input -
+
-
+
@@ -197,7 +288,7 @@ export function TransactionCard({ // Receive Mode mode === 'tokens' ? ( // Cashu Token Receive -
+
-
+
diff --git a/src/hooks/cashu/useMintManager.ts b/src/hooks/cashu/useMintManager.ts index 8453184..188e385 100644 --- a/src/hooks/cashu/useMintManager.ts +++ b/src/hooks/cashu/useMintManager.ts @@ -61,6 +61,20 @@ export function useMintManager({ normalizedUrl = `https://${normalizedUrl}`; } + // Check if mint with same name already exists (case insensitive) + const existingMint = mints.find(mint => + mint.url.toLowerCase() === normalizedUrl.toLowerCase() + ); + + if (existingMint) { + toast({ + variant: 'destructive', + title: 'Mint Already Exists', + description: 'A mint with this URL already exists', + }); + return; + } + await coco.mint.addMint(normalizedUrl); setMintUrl(''); @@ -75,7 +89,7 @@ export function useMintManager({ description: err instanceof Error ? err.message : 'Unknown error', }); } - }, [mintUrl, coco, toast]); + }, [mintUrl, coco, mints, toast]); // Show remove confirmation modal const handleRemoveMintClick = useCallback((mint: CashuMint) => { @@ -190,14 +204,25 @@ export function useMintManager({ [repositories, toast] ); - // Auto-select first mint when mints change + // Auto-select first mint when mints change, or add default mint if none exist useEffect(() => { if (mints.length > 0 && !activeMintUrl) { // Select first mint initially - user can change via dropdown // Don't sync to npub.cash on auto-select, only on manual changes handleSetActiveMint(mints[0].url, false); + } else if (mints.length === 0 && !activeMintUrl && coco) { + // Add default mint if no mints exist + const addDefaultMint = async () => { + try { + await coco.mint.addMint('https://mint.chorus.community'); + // The mint will be added and refreshMints will be called via event listeners + } catch (err) { + console.error('Failed to add default mint:', err); + } + }; + addDefaultMint(); } - }, [mints, activeMintUrl, handleSetActiveMint]); + }, [mints, activeMintUrl, handleSetActiveMint, coco]); return { activeMintUrl, diff --git a/src/hooks/cashu/useWalletTransactions.ts b/src/hooks/cashu/useWalletTransactions.ts index eae6e1f..ee375ec 100644 --- a/src/hooks/cashu/useWalletTransactions.ts +++ b/src/hooks/cashu/useWalletTransactions.ts @@ -1,5 +1,6 @@ import { useState, useCallback, useRef, useEffect } from 'react'; import { isUnknownMintError, extractMintUrlFromError } from './walletUtils'; +import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder'; interface UseWalletTransactionsProps { coco: any; // Coco instance @@ -37,6 +38,8 @@ export function useWalletTransactions({ const [pendingLightningAddress, setPendingLightningAddress] = useState< string | null >(null); + const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState(null); + const [pendingInvoice, setPendingInvoice] = useState(null); // Transaction output state const [sentToken, setSentToken] = useState(null); @@ -303,26 +306,34 @@ export function useWalletTransactions({ setPendingLightningAddress(input); setLightningAddressInput(''); } else { - // It's a regular Lightning invoice - try { - const meltQuote = await coco.quotes.createMeltQuote( - activeMintUrl, - input - ); - await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote); - - toast({ - title: 'Invoice Paid', - description: - 'Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.', - }); - setLightningInvoice(''); - } catch (err) { + // It's a regular Lightning invoice - decode to show amount first + if (isValidBolt11Invoice(input)) { + const amount = decodeBolt11Amount(input); + if (amount) { + // Show amount confirmation screen + setPendingInvoice(input); + setDecodedInvoiceAmount(amount); + setLightningInvoice(''); + return; + } else { + // Failed to decode amount - show error and don't attempt payment + toast({ + variant: 'destructive', + title: 'Invalid Invoice', + description: 'Unable to decode the lightning invoice amount. Please check the invoice format.', + }); + setLightningInvoice(''); + return; + } + } else { + // Not a valid BOLT11 invoice - show error and don't attempt payment toast({ variant: 'destructive', - title: 'Invoice Payment Failed', - description: err instanceof Error ? err.message : 'Unknown error', + title: 'Invalid Invoice', + description: 'This does not appear to be a valid lightning invoice. Please check the format.', }); + setLightningInvoice(''); + return; } } } @@ -334,6 +345,8 @@ export function useWalletTransactions({ lightningAddressInput, lightningAddressAmount, pendingLightningAddress, + pendingInvoice, + decodedInvoiceAmount, activeMintUrl, toast, getEncodedToken, @@ -341,6 +354,34 @@ export function useWalletTransactions({ getLightningInvoice, ]); + // Handle confirmed invoice payment + const handleConfirmInvoicePayment = useCallback(async () => { + if (!coco || !pendingInvoice || !activeMintUrl) return; + + try { + const meltQuote = await coco.quotes.createMeltQuote( + activeMintUrl, + pendingInvoice + ); + await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote); + + toast({ + title: 'Invoice Paid', + description: `Lightning invoice paid successfully for ${decodedInvoiceAmount} sats!`, + }); + + // Reset state + setPendingInvoice(null); + setDecodedInvoiceAmount(null); + } catch (err) { + toast({ + variant: 'destructive', + title: 'Invoice Payment Failed', + description: err instanceof Error ? err.message : 'Unknown error', + }); + } + }, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]); + // Cleanup mint quote listener on component unmount useEffect(() => { return () => { @@ -368,6 +409,10 @@ export function useWalletTransactions({ setLightningAddressAmount, pendingLightningAddress, setPendingLightningAddress, + decodedInvoiceAmount, + setDecodedInvoiceAmount, + pendingInvoice, + setPendingInvoice, // Transaction output state sentToken, setSentToken, @@ -380,6 +425,7 @@ export function useWalletTransactions({ // Handlers handleReceive, handleSend, + handleConfirmInvoicePayment, // Refs mintQuoteUnsubscribeRef, }; diff --git a/src/lib/bolt11Decoder.ts b/src/lib/bolt11Decoder.ts new file mode 100644 index 0000000..399fa0e --- /dev/null +++ b/src/lib/bolt11Decoder.ts @@ -0,0 +1,85 @@ +/** + * Decodes a BOLT11 lightning invoice and extracts the amount in satoshis. + * Based on the lightning-decoder project implementation. + */ + +/** + * Decode a BOLT11 invoice and extract the amount in satoshis + * @param invoice - The BOLT11 invoice string + * @returns The amount in satoshis, or null if amount cannot be determined + */ +export function decodeBolt11Amount(invoice: string): number | null { + try { + // Validate and prepare invoice + if (!invoice || typeof invoice !== 'string') { + return null; + } + + const normalizedInvoice = invoice.toLowerCase().trim(); + + // Check if it's a valid BOLT11 invoice + if (!isValidBolt11Invoice(normalizedInvoice)) { + return null; + } + + // Parse the prefix to extract amount + // Format: lnbc[amount][suffix] where suffix can be m, u, n, p + const prefixMatch = normalizedInvoice.match(/^lnbc(\d*)([munp]?)/); + if (!prefixMatch) { + return null; + } + + const [, amountStr, suffix] = prefixMatch; + + // If no amount specified, return null (amountless invoice) + if (!amountStr) { + return null; + } + + const amount = parseInt(amountStr, 10); + if (isNaN(amount)) { + return null; + } + + // Define multipliers for different denominations + const multipliers: Record = { + m: 0.001, // milli-bitcoin + u: 0.000001, // micro-bitcoin + n: 0.000000001, // nano-bitcoin + p: 0.000000000001 // pico-bitcoin + }; + + // Apply multiplier if suffix exists + const multiplier = multipliers[suffix] || 1; + const amountInBitcoin = amount * multiplier; + + // Convert Bitcoin to satoshis (1 Bitcoin = 100,000,000 satoshis) + const amountInSatoshis = Math.round(amountInBitcoin * 100_000_000); + + return amountInSatoshis; + } catch (error) { + console.error('Error decoding BOLT11 invoice:', error); + return null; + } +} + +/** + * Validate if a string is a valid BOLT11 invoice + * @param invoice - The string to validate + * @returns true if the string appears to be a valid BOLT11 invoice + */ +export function isValidBolt11Invoice(invoice: string): boolean { + if (!invoice || typeof invoice !== 'string') { + return false; + } + + const normalized = invoice.toLowerCase().trim(); + + // BOLT11 invoices start with 'lnbc' and contain '1' followed by characters (the bech32 separator) + // They also need to be long enough to contain the required components + return ( + normalized.startsWith('lnbc') && + /1[a-z0-9]/.test(normalized) && + normalized.length > 20 // Minimum reasonable length for a BOLT11 invoice + ); +}