ln decoder, default mint, drawer formatting

This commit is contained in:
lemonknowsall committed 2025-10-19 11:05:35 -07:00
1 parent 7390dd6c19
commit 617edd1784
8 files changed
+422 -130

No files matched your search

+2 -2
View File
@@ -15,10 +15,10 @@ const Slider = React.forwardRef<
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Track className="relative h-12 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
<SliderPrimitive.Thumb className="block h-10 w-10 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
+48 -7
View File
@@ -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 */}
<Drawer open={showSendModal} onOpenChange={setShowSendModal}>
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
</DrawerHeader>
@@ -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() {
</DrawerContent>
</Drawer>
<Drawer open={showReceiveModal} onOpenChange={setShowReceiveModal}>
<DrawerContent className="h-[50vh] max-w-4xl mx-auto">
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
<DrawerContent className="h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
</DrawerHeader>
@@ -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() {
</Drawer>
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
<DrawerContent className="max-h-[90vh] max-w-4xl mx-auto">
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
</DrawerHeader>
<ScrollArea className="h-[90vh] px-4 pb-4">
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
+43 -41
View File
@@ -93,49 +93,51 @@ export function MintSelector({
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
<DropdownMenuContent className="w-[var(--radix-dropdown-menu-trigger-width)] bg-muted border shadow-none max-h-[200px] overflow-hidden">
<div className="max-h-[120px] overflow-y-auto">
{mints
.filter((mint) => mint.url)
.map((mint, index) => {
const isActive = activeMintUrl === mint.url;
const balance = balances[mint.url] || 0;
return (
<DropdownMenuItem
key={`mint-${mint.url || `unknown-${index}`}`}
onClick={() => setActiveMintUrl(mint.url)}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isActive && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate">
{getCleanMintLabel(mint)}
</div>
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(balance)}
</span>
<button
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
className="p-1 rounded hover:bg-destructive hover:text-destructive-foreground transition-colors"
title="Remove mint"
>
<X className="h-4 w-4" />
</button>
</div>
</DropdownMenuItem>
);
})}
</div>
{mints.length > 0 && <DropdownMenuSeparator />}
<DropdownMenuItem asChild>
<div className="flex gap-2 p-2">
+134 -43
View File
@@ -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 (
<div className="space-y-8">
{/* Title */}
@@ -60,11 +110,40 @@ export function TransactionCard({
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
: pendingLightningAddress ? (
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending to:</span>{' '}
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
</span>
: pendingInvoice && decodedInvoiceAmount ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending:</span>{' '}
<span className="font-semibold text-foreground">{decodedInvoiceAmount} sats</span>
</span>
<button
onClick={() => {
setPendingInvoice(null);
setDecodedInvoiceAmount(null);
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : pendingLightningAddress ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-primary/10 border border-primary/20 rounded-md">
<span className="font-bold text-primary">Sending:</span>{' '}
<span className="font-semibold text-foreground">{pendingLightningAddress}</span>
</span>
<button
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : 'Pay invoices or addresses'
) : (
mode === 'tokens'
@@ -75,7 +154,7 @@ export function TransactionCard({
</div>
{/* Content */}
<div className="space-y-4">
<div className="space-y-8">
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
{operation === 'send'
@@ -89,7 +168,7 @@ export function TransactionCard({
// Send Mode
mode === 'tokens' ? (
// Cashu Token Send
<div className="space-y-3">
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
@@ -103,7 +182,7 @@ export function TransactionCard({
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={onSend}
disabled={!sendAmount || !activeMintUrl || isLoading}
@@ -114,9 +193,30 @@ export function TransactionCard({
</Button>
</div>
</div>
) : pendingInvoice && decodedInvoiceAmount ? (
// Lightning Invoice Confirmation (with slider)
<div className="space-y-8">
<div className="mt-6">
<div className="relative">
<Slider
value={invoiceSliderValue}
onValueChange={handleInvoiceSliderChange}
max={100}
step={1}
className="w-full h-12"
disabled={!activeMintUrl || isLoading}
/>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-sm font-medium text-muted-foreground">
{invoiceSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
</span>
</div>
</div>
</div>
</div>
) : pendingLightningAddress ? (
// Lightning Address Amount Input
<div className="space-y-3">
// Lightning Address Amount Input with Slider
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
@@ -130,36 +230,27 @@ export function TransactionCard({
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center gap-2 mt-4">
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
{isResolvingAddress ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Zap className="h-5 w-5" />
)}
</Button>
<Button
variant="outline"
size="icon"
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="h-12 w-12 rounded-full"
title="Cancel"
>
<X className="h-5 w-5" />
</Button>
<div className="mt-6">
<div className="relative w-full">
<Slider
value={addressSliderValue}
onValueChange={handleAddressSliderChange}
max={100}
step={1}
className="w-full h-12"
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
/>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-sm font-medium text-muted-foreground">
{addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
</span>
</div>
</div>
</div>
</div>
) : (
// Lightning Invoice/Address Input
<div className="space-y-3">
<div className="space-y-8">
<Input
placeholder="lnbc... or [email protected]"
value={lightningInvoice || lightningAddressInput}
@@ -181,14 +272,14 @@ export function TransactionCard({
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
className="h-12 px-12 rounded-full"
size="lg"
>
<Zap className="h-5 w-5" />
<ArrowRight className="h-5 w-5" />
</Button>
</div>
</div>
@@ -197,7 +288,7 @@ export function TransactionCard({
// Receive Mode
mode === 'tokens' ? (
// Cashu Token Receive
<div className="space-y-3">
<div className="space-y-8">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
@@ -210,7 +301,7 @@ export function TransactionCard({
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
/>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={onReceive}
disabled={!tokenInput.trim() || !activeMintUrl || isLoading}
@@ -223,7 +314,7 @@ export function TransactionCard({
</div>
) : (
// Lightning Invoice Receive
<div className="space-y-3">
<div className="space-y-8">
<Input
placeholder="Amount (sats)"
type="number"
@@ -237,7 +328,7 @@ export function TransactionCard({
disabled={!activeMintUrl}
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
/>
<div className="flex justify-center mt-4">
<div className="flex justify-center mt-6">
<Button
onClick={onReceive}
disabled={!quoteAmount || !activeMintUrl || isLoading}
+19 -17
View File
@@ -92,7 +92,7 @@ export function WalletHeader({
<div className="absolute top-3 left-3 sm:left-4 z-10">
<button
onClick={toggleMode}
className="px-3 py-2 rounded-lg bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
className="p-3 rounded-full bg-background hover:bg-background/80 transition-colors flex items-center justify-center"
title={mode === 'tokens' ? 'Switch to Lightning' : 'Switch to Cashu Tokens'}
>
{mode === 'tokens' ? (
@@ -129,7 +129,7 @@ export function WalletHeader({
<div className="grid grid-cols-1 gap-3">
{/* Lightning Address Row */}
{userPubkey && (
<div className="flex gap-2 items-center min-w-0">
<div className="flex gap-2 items-center min-w-[300px]">
<button
onClick={async () => {
const lightningAddress = `${npubCashUsername}@npubx.cash`;
@@ -169,21 +169,23 @@ export function WalletHeader({
)}
{/* Mint Selector Row */}
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
<div className="min-w-[300px]">
<MintSelector
balances={balances}
showSats={showSats}
activeMintUrl={activeMintUrl}
setActiveMintUrl={setActiveMintUrl}
mints={mints}
mintUrl={mintUrl}
setMintUrl={setMintUrl}
onAddMint={onAddMint}
onRemoveMint={onRemoveMint}
onShowDenominations={onShowDenominations}
getCleanMintLabel={getCleanMintLabel}
dropdownOpen={dropdownOpen}
setDropdownOpen={setDropdownOpen}
/>
</div>
</div>
</div>
</div>
+28 -3
View File
@@ -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,
+63 -17
View File
@@ -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<number | null>(null);
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(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,
};
+85
View File
@@ -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<string, number> = {
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
);
}