solid cashu foundation

This commit is contained in:
lemonknowsall committed 2025-10-11 00:34:32 -07:00
1 parent a8faa03b49
commit 967bdca369
15 files changed
+1249 -1477

No files matched your search

File diff suppressed because it is too large. Load diff
+26 -40
View File
@@ -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 (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<div
className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4"
onClick={onClose}
>
<Card
className="w-full max-w-md border-0 shadow-lg bg-background"
onClick={(e) => e.stopPropagation()}
>
<CardHeader className="relative">
<Button
onClick={onClose}
@@ -67,38 +69,22 @@ export function QRModal({
</div>
<div className="text-center">
<div className="bg-muted p-3 rounded-lg border font-mono text-sm break-all">
<div
className="bg-muted p-3 rounded-lg border font-mono text-sm break-all cursor-pointer hover:bg-muted/80 transition-colors relative group"
onClick={handleCopy}
title="Click to copy"
>
{content}
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4 text-muted-foreground" />
)}
</div>
</div>
</div>
{showCopyButton && onCopy && (
<div className="flex gap-2 justify-center">
<Button
variant="outline"
onClick={onCopy}
className="flex items-center gap-2"
>
{copiedText === content ? (
<>
<Check className="h-4 w-4" />
Copied!
</>
) : (
<>
<Copy className="h-4 w-4" />
{copyButtonText}
</>
)}
</Button>
</div>
)}
{helpText && (
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded text-center">
{helpText}
</div>
)}
</CardContent>
</Card>
</div>
+192
View File
@@ -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 (
<div className="text-center py-2">
<div className="flex items-center justify-center gap-3">
<button
onClick={() => setShowSats(!showSats)}
className="text-5xl font-bold tabular-nums hover:opacity-80 transition-opacity cursor-pointer"
title={`Click to show in ${showSats ? 'USD' : 'sats'}`}
>
{convertCurrency(totalBalance, showSats)}
</button>
</div>
{/* Main Mode Toggle */}
<div className="mt-4 flex items-center justify-center">
<div className="flex gap-1 bg-muted rounded-lg p-1">
<button
onClick={() => setMode('tokens')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'tokens' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Coins className="h-4 w-4" />
Cashu
</button>
<button
onClick={() => setMode('lightning')}
className={`px-4 py-2 rounded text-sm transition-colors flex items-center gap-2 ${
mode === 'lightning' ? 'bg-background shadow-sm' : 'hover:bg-muted/50'
}`}
>
<Zap className="h-4 w-4" />
Lightning
</button>
</div>
</div>
{/* Active Mint Dropdown and Balance */}
<div className="mt-3 flex items-center justify-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
<Wallet className="h-4 w-4" />
{activeMintUrl ? getCleanMintLabel({ url: activeMintUrl }) : 'Select Mint'}
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="w-72">
{mints.length === 0 && (
<DropdownMenuItem disabled>No mints connected</DropdownMenuItem>
)}
{mints
.filter((mint) => mint.url)
.map((mint, index) => (
<DropdownMenuItem
key={`dd-mint-${mint.url || `unknown-${index}`}`}
className="flex items-center justify-between"
onClick={() => setActiveMintUrl(mint.url)}
>
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint)}</span>
</div>
<Button
size="sm"
variant="ghost"
className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
onClick={(e) => {
e.stopPropagation();
onRemoveMint(mint);
}}
>
<X className="h-3 w-3" />
</Button>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<div className="px-2 py-1.5">
<div className="flex gap-2">
<Input
placeholder="mint.example.com"
value={mintUrl}
onChange={(e) => setMintUrl(e.target.value)}
className="h-8"
/>
<Button size="sm" onClick={onAddMint} disabled={!mintUrl.trim()}>
<Plus className="h-3.5 w-3.5 mr-1" />
Add
</Button>
</div>
</div>
</DropdownMenuContent>
</DropdownMenu>
{/* Active Mint Balance */}
{activeMintUrl && (
<div className="flex items-center gap-2">
<button
onClick={() => activeMintUrl && onShowDenominations(activeMintUrl)}
className="text-sm font-semibold tabular-nums hover:opacity-80 transition-opacity cursor-pointer text-muted-foreground hover:text-foreground"
title="Click to see proof breakdown"
>
{convertCurrency(balances[activeMintUrl] || 0, showSats)}
</button>
{/* Help button */}
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground">
<HelpCircle className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
What is a Mint?
</DialogTitle>
<DialogDescription className="space-y-3 text-left">
<p>
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
</p>
<p>
<strong>Key features:</strong>
</p>
<ul className="list-disc list-inside space-y-1 ml-4">
<li>Issues tokens when you deposit Lightning payments</li>
<li>Redeems tokens when you receive them</li>
<li>Manages your token balance</li>
<li>Enables Lightning ↔ Cashu conversions</li>
</ul>
<p>
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
</p>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
)}
</div>
</div>
);
}
+21
View File
@@ -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 (
<div className="fixed inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-[200]">
<Card className="border-0 shadow-lg bg-background">
<CardContent className="flex items-center justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin mr-3" />
<span className="text-lg font-medium">Loading</span>
</CardContent>
</Card>
</div>
);
}
@@ -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 (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<Coins className="h-5 w-5 mr-2" />
Token Breakdown
</CardTitle>
<CardDescription>
{new URL(breakdown.mintUrl).hostname}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center py-2">
<div className="text-2xl font-bold text-primary">
{convertCurrency(breakdown.totalBalance)}
</div>
<div className="text-sm text-muted-foreground">Total Balance</div>
</div>
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">Denominations:</div>
{Object.entries(breakdown.denominations)
.sort(([a], [b]) => parseInt(a) - parseInt(b))
.map(([amount, count]) => (
<div key={amount} className="flex items-center justify-between p-2 bg-muted/30 rounded">
<div className="flex items-center gap-2">
<Coins className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{parseInt(amount).toLocaleString()} sats</span>
</div>
<Badge variant="secondary" className="bg-primary/10 text-primary">
× {count}
</Badge>
</div>
))}
</div>
<div className="text-xs text-muted-foreground bg-muted/30 p-3 rounded">
💡 Tip: If you can't pay an invoice, try sending tokens to yourself to get different denominations.
</div>
</CardContent>
</Card>
</div>
);
}
+88
View File
@@ -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 (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Download className="h-5 w-5 mr-2" />
Receive
</CardTitle>
<CardDescription>
{mode === 'tokens'
? 'Enter Cashu token to redeem'
: 'Deposit funds with Lightning'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to receive tokens
</div>
)}
<div className="flex gap-2">
<Input
placeholder="cashuBo2Ft..."
value={tokenInput}
onChange={(e) => setTokenInput(e.target.value)}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button onClick={onReceive} disabled={!tokenInput.trim() || !activeMintUrl || isLoading}>
<Download className="h-4 w-4 mr-2" />
Receive
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to create Lightning invoice
</div>
)}
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={quoteAmount}
onChange={(e) => setQuoteAmount(e.target.value)}
disabled={!activeMintUrl}
/>
<Button onClick={onReceive} disabled={!quoteAmount || !activeMintUrl || isLoading}>
<Zap className="h-4 w-4 mr-2" />
Quote
</Button>
</div>
</>
)}
</CardContent>
</Card>
);
}
+83
View File
@@ -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 (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[100] p-4">
<Card className="w-full max-w-md border-0 shadow-lg bg-background">
<CardHeader className="relative">
<Button
onClick={onClose}
className="absolute top-2 right-2"
size="sm"
variant="ghost"
>
<X className="h-4 w-4" />
</Button>
<CardTitle className="flex items-center pr-8">
<AlertTriangle className="h-5 w-5 mr-2 text-destructive" />
Remove Mint
</CardTitle>
<CardDescription>
Are you sure you want to remove this mint from your wallet?
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mint.name || new URL(mint.url).hostname}</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{mint.url}
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
<div>⚠️ This will remove the mint and all associated data. Any tokens from this mint will no longer be accessible.</div>
<div>💡 You can always add this mint back later if needed.</div>
</div>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={onClose}
>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isLoading}
>
{isLoading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Removing...
</>
) : (
<>
<X className="h-4 w-4 mr-2" />
Remove Mint
</>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
+163
View File
@@ -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 (
<Card className="border-0 shadow-none bg-muted/30">
<CardHeader>
<CardTitle className="flex items-center">
<Send className="h-5 w-5 mr-2" />
Send
</CardTitle>
<CardDescription>
{mode === 'tokens'
? 'Generate Cashu token to send'
: pendingLightningAddress
? `Sending to: ${pendingLightningAddress}`
: 'Pay Lightning invoices or addresses from balance'
}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{mode === 'tokens' ? (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to send tokens
</div>
)}
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={sendAmount}
onChange={(e) => setSendAmount(e.target.value)}
disabled={!activeMintUrl}
/>
<Button onClick={onSend} disabled={!sendAmount || !activeMintUrl || isLoading}>
<Send className="h-4 w-4 mr-2" />
Send
</Button>
</div>
</>
) : (
<>
{!activeMintUrl && (
<div className="text-sm text-muted-foreground bg-muted p-3 rounded">
Select a mint to pay Lightning invoices
</div>
)}
{pendingLightningAddress ? (
// Step 2: Show amount input for Lightning address
<div className="space-y-3">
<div className="flex gap-2">
<Input
placeholder="Amount (sats)"
type="number"
value={lightningAddressAmount}
onChange={(e) => setLightningAddressAmount(e.target.value)}
autoFocus
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
>
{isResolvingAddress ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Sending...
</>
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
)}
</Button>
<Button
variant="outline"
size="icon"
onClick={() => {
setPendingLightningAddress(null);
setLightningAddressAmount('');
}}
className="h-10 w-10"
title="Cancel"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
) : (
// Step 1: Show invoice/address input
<div className="flex gap-2">
<Input
placeholder="Lightning invoice (lnbc...) or address ([email protected])"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
if (value.includes('@')) {
setLightningAddressInput(value);
setLightningInvoice('');
} else {
setLightningInvoice(value);
setLightningAddressInput('');
}
}}
className="flex-1"
disabled={!activeMintUrl}
/>
<Button
onClick={onSend}
disabled={(!lightningInvoice.trim() && !lightningAddressInput.trim()) || !activeMintUrl || isLoading}
>
<>
<Zap className="h-4 w-4 mr-2" />
Pay
</>
</Button>
</div>
)}
</>
)}
</CardContent>
</Card>
);
}
@@ -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 <ArrowDownLeft className="h-4 w-4 text-green-500" />;
case 'melt':
return <Zap className="h-4 w-4 text-yellow-500" />;
case 'send':
return <ArrowUpRight className="h-4 w-4 text-red-500" />;
case 'receive':
return <ArrowDownLeft className="h-4 w-4 text-green-500" />;
default:
return <History className="h-4 w-4" />;
}
};
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 (
<Card className="mt-6 border-0 shadow-none">
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center">
<History className="h-5 w-5 mr-2" />
Transaction History
</div>
{entries.length > 3 && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsExpanded(!isExpanded)}
className="gap-1"
>
{isExpanded ? (
<>
<ChevronUp className="h-4 w-4" />
Hide
</>
) : (
<>
<ChevronDown className="h-4 w-4" />
Show
</>
)}
</Button>
)}
</CardTitle>
<CardDescription>
View your recent transactions
</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading history...</span>
</div>
) : entries.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transaction history yet
</div>
) : (
<div className="space-y-2">
{(isExpanded ? entries : entries.slice(0, 3)).map((entry) => (
<div
key={entry.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
{getHistoryIcon(entry.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{getHistoryLabel(entry.type)}
</span>
{entry.state && (
<Badge
variant="secondary"
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
>
{entry.state}
</Badge>
)}
</div>
<div className="text-sm text-muted-foreground mt-1">
{new URL(entry.mintUrl).hostname}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(entry.createdAt).toLocaleString()}
</div>
</div>
</div>
<div className="text-right ml-4">
<div className="font-semibold">
{entry.type === 'send' || entry.type === 'melt' ? '-' : '+'}
{entry.amount.toLocaleString()} {entry.unit}
</div>
</div>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
+48
View File
@@ -1,5 +1,7 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { CashuBalance, CashuWalletError } from './types';
import { exchangeRateService } from '@/lib/exchangeRateService';
import { toast } from '../useToast';
export interface UseCashuBalancesReturn {
balances: CashuBalance;
@@ -7,12 +9,15 @@ export interface UseCashuBalancesReturn {
error: CashuWalletError | null;
refreshBalances: () => Promise<void>;
getBalances: () => Promise<CashuBalance>;
convertCurrency: (sats: number, showSats?: boolean) => string;
convertCurrencyAsync: (sats: number, showSats?: boolean) => Promise<string>;
}
export function useCashuBalances(manager: unknown | null): UseCashuBalancesReturn {
const [balances, setBalances] = useState<CashuBalance>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<CashuWalletError | null>(null);
const [fallbackRate, setFallbackRate] = useState<number | null>(null);
// Throttling refs
const lastRefreshTimeRef = useRef<number>(0);
@@ -152,11 +157,54 @@ export function useCashuBalances(manager: unknown | null): UseCashuBalancesRetur
}
}, [manager, balances, refreshBalances]);
// Fetch exchange rate on mount for fallback
useEffect(() => {
exchangeRateService.getBtcUsdRate()
.then(rate => setFallbackRate(rate))
.catch(error => {
console.warn('Failed to fetch initial exchange rate:', error);
// Keep fallbackRate as null to show sats instead of USD
});
}, []);
const convertCurrency = useCallback((sats: number, showSats: boolean = true): string => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
// Only show USD if we have a valid exchange rate
if (fallbackRate) {
const btcAmount = sats / 100000000;
const usd = btcAmount * fallbackRate;
return `$${usd.toFixed(2)}`;
} else {
// If no exchange rate available, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, [fallbackRate]);
const convertCurrencyAsync = useCallback(async (sats: number, showSats: boolean = true): Promise<string> => {
if (showSats) {
return `${sats.toLocaleString()} sats`;
} else {
try {
const usd = await exchangeRateService.satsToUsd(sats);
return `$${usd.toFixed(2)}`;
} catch (error) {
console.warn('Failed to fetch exchange rate:', error);
// If exchange rate fails, show sats instead of incorrect USD
return `${sats.toLocaleString()} sats`;
}
}
}, []);
return {
balances,
isLoading,
error,
refreshBalances,
getBalances,
convertCurrency,
convertCurrencyAsync,
};
}
+29
View File
@@ -9,6 +9,7 @@ export interface UseCashuMintsReturn {
getMints: () => Promise<CashuMint[]>;
addMint: (mintUrl: string) => Promise<void>;
removeMint: (mintUrl: string) => Promise<void>;
getCleanMintLabel: (mint: { name?: string; url: string }) => string;
}
export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
@@ -28,6 +29,20 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
name: mint.name,
info: mint.mintInfo
}));
// If no mints exist, add the default mint
if (formattedMints.length === 0) {
console.log('🔧 No mints found, adding default mint: mint.chorus.community');
try {
await (manager as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint('https://mint.chorus.community');
// The mint:added event will trigger refreshMints again, so we don't need to set mints here
return;
} catch (err) {
console.warn('⚠️ Failed to add default mint:', err);
// Continue with empty mints if default mint fails
}
}
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
@@ -133,6 +148,19 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
}
}, [manager, mints.length, refreshMints]);
const getCleanMintLabel = useCallback((mint: { name?: string; url: string }): string => {
if (mint.name && mint.name.trim().length > 0) {
// If name looks like a URL, strip protocol as well
return mint.name.replace(/^https?:\/\//, '');
}
try {
return new URL(mint.url).host; // host excludes protocol and preserves port if any
} catch {
// Fallback: manual strip
return mint.url.replace(/^https?:\/\//, '');
}
}, []);
return {
mints,
isLoading,
@@ -141,5 +169,6 @@ export function useCashuMints(manager: unknown | null): UseCashuMintsReturn {
getMints,
addMint,
removeMint,
getCleanMintLabel,
};
}
+52
View File
@@ -0,0 +1,52 @@
import { useState, useCallback } from 'react';
import { useToast } from './useToast';
interface UseCopyToClipboardReturn {
copy: (text: string) => Promise<void>;
copied: boolean;
copyError: string | null;
}
/**
* Hook for copying text to clipboard with feedback
*
* @example
* ```tsx
* const { copy, copied, copyError } = useCopyToClipboard();
*
* await copy('cashuBo2Ft...');
* // copied will be true for 2 seconds
* ```
*/
export function useCopyToClipboard(): UseCopyToClipboardReturn {
const [copied, setCopied] = useState(false);
const [copyError, setCopyError] = useState<string | null>(null);
const { toast } = useToast();
const copy = useCallback(async (text: string): Promise<void> => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setCopyError(null);
// Auto-reset copied state after 2 seconds
setTimeout(() => setCopied(false), 2000);
} catch (err) {
const errorMessage = 'Failed to copy to clipboard';
console.error(errorMessage, err);
setCopyError(errorMessage);
toast({
variant: "destructive",
title: "Copy Failed",
description: errorMessage,
});
}
}, [toast]);
return {
copy,
copied,
copyError,
};
}
-455
View File
@@ -1,455 +0,0 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useLocalStorage } from './useLocalStorage';
import { useCurrentUser } from './useCurrentUser';
import { nip19, finalizeEvent, generateSecretKey } from 'nostr-tools';
import type { EventTemplate } from 'nostr-tools';
// API Base URL - can be configured
const NPUBCASH_API_BASE = 'https://npubx.cash/api/v2';
const NPUBCASH_DOMAIN = 'npubx.cash';
// Types for npub.cash API responses
export interface NpubCashQuote {
createdAt: number;
paidAt: number;
expiresAt: number;
mintUrl: string;
quoteId: string;
request: string; // BOLT11 invoice
amount: number; // Amount in sats
state: 'PENDING' | 'PAID' | 'EXPIRED';
locked: boolean;
}
export interface NpubCashUserInfo {
pubkey: string;
name: string | null;
mintUrl: string;
lockQuote: boolean;
}
export interface NpubCashState {
isInitialized: boolean;
isLoading: boolean;
error: string | null;
lightningAddress: string | null;
userInfo: NpubCashUserInfo | null;
quotes: NpubCashQuote[];
unclaimedAmount: number; // Total amount in unclaimed quotes
}
export interface NpubCashActions {
// Fetch user's paid quotes
fetchQuotes: (since?: number, limit?: number) => Promise<NpubCashQuote[]>;
// Get user info/settings
fetchUserInfo: () => Promise<NpubCashUserInfo>;
// Set username (costs sats via X-Cashu header)
setUsername: (username: string) => Promise<void>;
// Set preferred mint
setMint: (mintUrl: string) => Promise<void>;
// Toggle quote locking (NUT-20)
setLockQuotes: (locked: boolean) => Promise<void>;
// Refresh all data
refresh: () => Promise<void>;
// Clear JWT token (force re-auth)
clearAuth: () => void;
// Retry authentication after error
retryAuth: () => void;
}
/**
* Hook for integrating npub.cash Lightning addresses
*
* Provides a Lightning address ([email protected]) for the current user
* and methods to fetch/manage received payments stored as Cashu quotes.
*
* @example
* ```tsx
* const { lightningAddress, quotes, unclaimedAmount, fetchQuotes } = useNpubCash();
*
* // Display Lightning address
* <p>Send sats to: {lightningAddress}</p>
*
* // Show unclaimed balance
* <p>Unclaimed: {unclaimedAmount} sats</p>
*
* // Fetch new quotes
* await fetchQuotes();
* ```
*/
export function useNpubCash(): NpubCashState & NpubCashActions {
const { user } = useCurrentUser();
const pubkey = user?.pubkey;
// Store JWT token for convenience (30min expiry)
const [jwtToken, setJwtToken] = useLocalStorage<string | null>('npubcash-jwt', null);
// Store last claimed quote timestamp to track new payments
const [lastClaimedAt, setLastClaimedAt] = useLocalStorage<number>('npubcash-last-claimed', 0);
// Component state
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [userInfo, setUserInfo] = useState<NpubCashUserInfo | null>(null);
const [quotes, setQuotes] = useState<NpubCashQuote[]>([]);
const [hasTriedInitialization, setHasTriedInitialization] = useState(false);
// Generate Lightning address from pubkey
const lightningAddress = useMemo(() => {
if (!pubkey) return null;
const npub = nip19.npubEncode(pubkey);
return `${npub}@${NPUBCASH_DOMAIN}`;
}, [pubkey]);
/**
* Create NIP-98 auth token for a request
*/
const createNIP98Token = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
if (!user) {
throw new Error('No user logged in');
}
// Parse URL and reconstruct it to match server expectations
// Remove query parameters from the URL used in NIP-98 token
// The server will reconstruct the full URL from the actual request
const urlObj = new URL(url);
const baseUrl = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
console.log(`🔍 NIP-98 Token Creation - Original URL: ${url}, Base URL: ${baseUrl}, Method: ${method}`);
// Create NIP-98 event (kind 27235)
const eventTemplate: EventTemplate = {
kind: 27235,
created_at: Math.floor(Date.now() / 1000),
tags: [
['u', baseUrl],
['method', method],
],
content: '',
};
// Add payload hash for POST/PUT/PATCH requests
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
eventTemplate.tags.push(['payload', payloadHash]);
}
// Sign the event using the user's signer
const signedEvent = await user.signer.signEvent(eventTemplate);
// Encode as base64
const eventJson = JSON.stringify(signedEvent);
const base64Token = btoa(eventJson);
return base64Token;
}, [user]);
/**
* Get auth header (JWT if available, otherwise create NIP-98)
*/
const getAuthHeader = useCallback(async (url: string, method: string, body?: unknown): Promise<string> => {
// Try JWT first if available
if (jwtToken) {
return `Bearer ${jwtToken}`;
}
// Otherwise create NIP-98 token
const nip98Token = await createNIP98Token(url, method, body);
return `Nostr ${nip98Token}`;
}, [jwtToken, createNIP98Token]);
/**
* Obtain JWT token via NIP-98 auth
*/
const obtainJWT = useCallback(async (): Promise<string> => {
if (!pubkey) {
throw new Error('No user logged in');
}
const authUrl = `${NPUBCASH_API_BASE}/auth/nip98`;
const nip98Token = await createNIP98Token(authUrl, 'GET');
const response = await fetch(authUrl, {
method: 'GET',
headers: {
'Authorization': `Nostr ${nip98Token}`,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Authentication failed' }));
throw new Error(errorData.message || 'Failed to obtain JWT token');
}
const data = await response.json();
const token = data.data?.token;
if (!token) {
throw new Error('No JWT token in response');
}
setJwtToken(token);
return token;
}, [pubkey, createNIP98Token, setJwtToken]);
/**
* Make authenticated API request
*/
const apiRequest = useCallback(async <T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> => {
if (!pubkey) {
throw new Error('No user logged in');
}
const url = `${NPUBCASH_API_BASE}${endpoint}`;
let authHeader: string;
try {
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
} catch (error) {
// If JWT fails, try to obtain a new one
if (jwtToken) {
setJwtToken(null);
await obtainJWT();
authHeader = await getAuthHeader(url, options.method || 'GET', options.body ? JSON.parse(options.body as string) : undefined);
} else {
throw error;
}
}
console.log(`🔍 API Request - URL: ${url}, Method: ${options.method || 'GET'}, Auth Header: ${authHeader.substring(0, 50)}...`);
const response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': authHeader,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Request failed' }));
throw new Error(errorData.message || `API request failed: ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.message || 'API returned error');
}
return data.data;
}, [pubkey, jwtToken, getAuthHeader, obtainJWT, setJwtToken]);
/**
* Fetch paid quotes from npub.cash
*/
const fetchQuotes = useCallback(async (since?: number, limit: number = 50): Promise<NpubCashQuote[]> => {
try {
const queryParams = new URLSearchParams();
if (since) queryParams.set('since', since.toString());
queryParams.set('limit', limit.toString());
const endpoint = `/wallet/quotes?${queryParams.toString()}`;
const data = await apiRequest<{ quotes: NpubCashQuote[] }>(endpoint);
setQuotes(data.quotes);
return data.quotes;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch quotes';
setError(errorMessage);
throw err;
}
}, [apiRequest]);
/**
* Fetch user info/settings
*/
const fetchUserInfo = useCallback(async (): Promise<NpubCashUserInfo> => {
try {
const data = await apiRequest<{ user: NpubCashUserInfo }>('/user/info');
setUserInfo(data.user);
return data.user;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch user info';
setError(errorMessage);
throw err;
}
}, [apiRequest]);
/**
* Set Lightning address username (paid feature)
*/
const setUsername = useCallback(async (username: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/username', {
method: 'POST',
body: JSON.stringify({ username }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set username';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Set preferred mint URL
*/
const setMint = useCallback(async (mintUrl: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/mint', {
method: 'PATCH',
body: JSON.stringify({ mint_url: mintUrl }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set mint';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Toggle quote locking (NUT-20)
*/
const setLockQuotes = useCallback(async (locked: boolean): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await apiRequest('/user/lock', {
method: 'PATCH',
body: JSON.stringify({ lock_quotes: locked }),
});
// Refresh user info
await fetchUserInfo();
setIsLoading(false);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to set lock quotes';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, [apiRequest, fetchUserInfo]);
/**
* Refresh all data
*/
const refresh = useCallback(async (): Promise<void> => {
if (!pubkey) return;
setIsLoading(true);
setError(null);
try {
// Fetch in parallel
await Promise.all([
fetchQuotes(lastClaimedAt),
fetchUserInfo(),
]);
setIsInitialized(true);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh data';
setError(errorMessage);
// If it's an auth error, don't retry automatically
if (errorMessage.includes('Authorization') || errorMessage.includes('Invalid')) {
console.warn('npub.cash auth error - not retrying automatically:', errorMessage);
}
} finally {
setIsLoading(false);
}
}, [pubkey, fetchQuotes, fetchUserInfo, lastClaimedAt]);
/**
* Clear JWT token (force NIP-98 re-auth)
*/
const clearAuth = useCallback(() => {
setJwtToken(null);
setHasTriedInitialization(false);
setIsInitialized(false);
setError(null);
}, [setJwtToken]);
/**
* Retry initialization after auth error
*/
const retryAuth = useCallback(() => {
setHasTriedInitialization(false);
setError(null);
}, []);
// Calculate unclaimed amount
const unclaimedAmount = useMemo(() => {
return quotes
.filter(q => q.state === 'PAID' && q.paidAt > lastClaimedAt)
.reduce((sum, q) => sum + q.amount, 0);
}, [quotes, lastClaimedAt]);
// Initialize on mount - only once
useEffect(() => {
if (pubkey && !isInitialized && !hasTriedInitialization) {
setHasTriedInitialization(true);
refresh();
}
}, [pubkey, isInitialized, hasTriedInitialization, refresh]);
return {
isInitialized,
isLoading,
error,
lightningAddress,
userInfo,
quotes,
unclaimedAmount,
fetchQuotes,
fetchUserInfo,
setUsername,
setMint,
setLockQuotes,
refresh,
clearAuth,
retryAuth,
};
}
export type { EventTemplate };
// Force TypeScript recompilation
+62
View File
@@ -0,0 +1,62 @@
import { useState, useCallback } from 'react';
import QRCode from 'qrcode';
import { useToast } from './useToast';
interface UseQRCodeReturn {
generateQRCode: (text: string) => Promise<string>;
isGenerating: boolean;
error: string | null;
}
/**
* Hook for generating QR codes
*
* @example
* ```tsx
* const { generateQRCode, isGenerating, error } = useQRCode();
*
* const qrCodeUrl = await generateQRCode('cashuBo2Ft...');
* ```
*/
export function useQRCode(): UseQRCodeReturn {
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const { toast } = useToast();
const generateQRCode = useCallback(async (text: string): Promise<string> => {
setIsGenerating(true);
setError(null);
try {
const qrCodeUrl = await QRCode.toDataURL(text, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
setIsGenerating(false);
return qrCodeUrl;
} catch (err) {
const errorMessage = 'Failed to generate QR code';
console.error(errorMessage, err);
setError(errorMessage);
setIsGenerating(false);
toast({
variant: "destructive",
title: "QR Code Failed",
description: errorMessage,
});
return '';
}
}, [toast]);
return {
generateQRCode,
isGenerating,
error,
};
}
+131
View File
@@ -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<number> {
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<number> {
const rate = await this.getBtcUsdRate();
return btcAmount * rate;
}
/**
* Convert USD amount to BTC using current exchange rate
*/
async usdToBtc(usdAmount: number): Promise<number> {
const rate = await this.getBtcUsdRate();
return usdAmount / rate;
}
/**
* Convert sats to USD using current exchange rate
*/
async satsToUsd(sats: number): Promise<number> {
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();