mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
add npubxCash lightning address
This commit is contained in:
1 parent
565305a592
commit
579cd3584b
5 files changed
+1351
-9
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
||||
import { useNpubCash } from '@/hooks/useNpubCash';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -8,7 +9,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
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, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp } from 'lucide-react';
|
||||
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp, CreditCard } from 'lucide-react';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
export function CashuWallet() {
|
||||
@@ -37,6 +38,18 @@ export function CashuWallet() {
|
||||
getHistory,
|
||||
} = useCashu();
|
||||
|
||||
const {
|
||||
lightningAddress,
|
||||
unclaimedAmount,
|
||||
quotes,
|
||||
isLoading: isNpubCashLoading,
|
||||
error: npubCashError,
|
||||
fetchQuotes,
|
||||
refresh: refreshNpubCash,
|
||||
retryAuth,
|
||||
setMint,
|
||||
} = useNpubCash();
|
||||
|
||||
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
||||
|
||||
// ============================================================================
|
||||
@@ -81,6 +94,7 @@ export function CashuWallet() {
|
||||
|
||||
const [copiedToken, setCopiedToken] = useState(false);
|
||||
const [copiedInvoice, setCopiedInvoice] = useState<string | null>(null);
|
||||
const [copiedLightningAddress, setCopiedLightningAddress] = useState(false);
|
||||
|
||||
|
||||
// ============================================================================
|
||||
@@ -130,6 +144,19 @@ export function CashuWallet() {
|
||||
}
|
||||
};
|
||||
|
||||
// Copy Lightning address to clipboard
|
||||
const copyLightningAddress = async () => {
|
||||
if (!lightningAddress) return;
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(lightningAddress);
|
||||
setCopiedLightningAddress(true);
|
||||
setTimeout(() => setCopiedLightningAddress(false), 2000);
|
||||
} catch (err) {
|
||||
console.error('Failed to copy Lightning address:', err);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - QR Code
|
||||
@@ -151,6 +178,29 @@ export function CashuWallet() {
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - Mint Management
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Set active mint and sync with npubx.cash
|
||||
*/
|
||||
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
|
||||
// Set the active mint locally
|
||||
setActiveMintUrl(mintUrl);
|
||||
|
||||
// If we have a mint URL, also update npubx.cash preference
|
||||
if (mintUrl) {
|
||||
try {
|
||||
await setMint(mintUrl);
|
||||
console.log(`✅ Updated npubx.cash mint preference to: ${mintUrl}`);
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to update npubx.cash mint preference:', error);
|
||||
// Don't throw - we still want to set the local mint even if npubx.cash fails
|
||||
}
|
||||
}
|
||||
}, [setMint]);
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS - History
|
||||
// ============================================================================
|
||||
@@ -446,6 +496,68 @@ export function CashuWallet() {
|
||||
}
|
||||
};
|
||||
|
||||
// Claim npub.cash quotes
|
||||
const handleClaimNpubCashQuote = async (quote: typeof quotes[0]) => {
|
||||
try {
|
||||
console.log('🎯 Claiming npubx.cash quote:', quote);
|
||||
console.log('📋 Quote details:', {
|
||||
quote_id: quote.quoteId,
|
||||
mint_url: quote.mintUrl,
|
||||
amount: quote.amount,
|
||||
state: quote.state,
|
||||
request: quote.request?.substring(0, 50) + '...'
|
||||
});
|
||||
|
||||
// Add mint if not already added
|
||||
const hasMint = mints.some(m => m.url === quote.mintUrl);
|
||||
if (!hasMint) {
|
||||
console.log('➕ Adding mint:', quote.mintUrl);
|
||||
await addMint(quote.mintUrl);
|
||||
}
|
||||
|
||||
// Call the mint's API directly since this is an external quote
|
||||
console.log('🔄 Redeeming npubx.cash quote via mint API:', quote.quoteId, 'from mint:', quote.mintUrl);
|
||||
console.log('🔄 Lightning invoice:', quote.request);
|
||||
|
||||
// Try the /mint endpoint for quote redemption
|
||||
const response = await fetch(`${quote.mintUrl}/mint`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
quote: quote.quoteId, // Use the quote ID to redeem
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ message: 'Failed to redeem quote' }));
|
||||
throw new Error(errorData.message || `Mint API error: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('✅ Mint API response:', data);
|
||||
|
||||
if (data.paid && data.proofs) {
|
||||
// We received tokens, now we need to add them to our wallet
|
||||
console.log('🔄 Adding received tokens to wallet...');
|
||||
await receive(JSON.stringify(data.proofs));
|
||||
console.log('✅ Successfully claimed tokens from npubx.cash quote');
|
||||
} else {
|
||||
throw new Error('No tokens received from mint');
|
||||
}
|
||||
|
||||
// Refresh quotes and balances
|
||||
await fetchQuotes();
|
||||
await refreshBalances();
|
||||
|
||||
alert(`Successfully claimed ${quote.amount} sats!`);
|
||||
} catch (err) {
|
||||
console.error('Failed to claim npub.cash quote:', err);
|
||||
alert(`Failed to claim: ${err instanceof Error ? err.message : 'Unknown error'}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowDenominations = async (mintUrl: string) => {
|
||||
try {
|
||||
console.log('🔍 Getting token denominations for mint:', mintUrl);
|
||||
@@ -496,9 +608,9 @@ export function CashuWallet() {
|
||||
const highestBalance = balances[highest.url] || 0;
|
||||
return currentBalance > highestBalance ? current : highest;
|
||||
});
|
||||
setActiveMintUrl(mintWithHighestBalance.url);
|
||||
handleSetActiveMint(mintWithHighestBalance.url);
|
||||
}
|
||||
}, [mints, activeMintUrl, balances]);
|
||||
}, [mints, activeMintUrl, balances, handleSetActiveMint]);
|
||||
|
||||
// Load transaction history when wallet is initialized
|
||||
useEffect(() => {
|
||||
@@ -594,6 +706,7 @@ export function CashuWallet() {
|
||||
await checkAndRedeemPendingQuotes();
|
||||
await refreshBalances();
|
||||
await loadHistory();
|
||||
await refreshNpubCash();
|
||||
console.log('💰 Current balances after manual refresh:', balances);
|
||||
}}
|
||||
className="mt-2"
|
||||
@@ -624,7 +737,7 @@ export function CashuWallet() {
|
||||
<DropdownMenuItem
|
||||
key={`dd-mint-${mint.url || `unknown-${index}`}`}
|
||||
className="flex items-center justify-between"
|
||||
onClick={() => setActiveMintUrl(mint.url)}
|
||||
onClick={() => handleSetActiveMint(mint.url)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{getCleanMintLabel(mint)}</span>
|
||||
@@ -662,19 +775,80 @@ export function CashuWallet() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* npub.cash Lightning Address */}
|
||||
{lightningAddress && (
|
||||
<div className="mt-4 p-4 bg-muted/30 rounded-lg">
|
||||
<div className="flex items-center justify-center gap-2 mb-2">
|
||||
<CreditCard className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium text-muted-foreground">Your Lightning Address</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<code className="bg-background px-3 py-2 rounded text-sm font-mono border">
|
||||
{lightningAddress}
|
||||
</code>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={copyLightningAddress}
|
||||
className="h-8"
|
||||
>
|
||||
{copiedLightningAddress ? (
|
||||
<Check className="h-3 w-3" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{unclaimedAmount > 0 && (
|
||||
<div className="mt-2 flex items-center justify-center gap-2">
|
||||
<Badge variant="secondary" className="text-sm">
|
||||
{unclaimedAmount} sats unclaimed
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={refreshNpubCash}
|
||||
disabled={isNpubCashLoading}
|
||||
className="h-6 text-xs"
|
||||
>
|
||||
<RefreshCw className={`h-3 w-3 mr-1 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Error Display
|
||||
======================================================================== */}
|
||||
{error && (
|
||||
{(error || npubCashError) && (
|
||||
<Alert variant="destructive" className="mb-6">
|
||||
<AlertDescription className="flex items-center justify-between">
|
||||
{error}
|
||||
<Button variant="outline" size="sm" onClick={clearError}>
|
||||
Dismiss
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
{error || npubCashError}
|
||||
{npubCashError && npubCashError.includes('Authorization') && (
|
||||
<div className="text-xs mt-1 opacity-75">
|
||||
Try refreshing the page or check your Nostr extension
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{npubCashError && (
|
||||
<Button variant="outline" size="sm" onClick={retryAuth}>
|
||||
Retry Auth
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={() => {
|
||||
if (error) clearError();
|
||||
// npub.cash errors are handled by retryAuth
|
||||
}}>
|
||||
Dismiss
|
||||
</Button>
|
||||
</div>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
@@ -1037,6 +1211,90 @@ export function CashuWallet() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: npub.cash Received Payments
|
||||
======================================================================== */}
|
||||
{quotes.length > 0 && (
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<CreditCard className="h-5 w-5 mr-2" />
|
||||
Received Payments (npub.cash)
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={refreshNpubCash}
|
||||
disabled={isNpubCashLoading}
|
||||
className="gap-1"
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 ${isNpubCashLoading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Lightning payments received to your npub.cash address
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{quotes && quotes.length > 0 ? quotes.map(quote => {
|
||||
const isExpired = quote.expiresAt < Date.now() / 1000;
|
||||
const isPaid = quote.state === 'PAID';
|
||||
|
||||
return (
|
||||
<div key={quote.quoteId} className="border rounded-lg p-3">
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<div>
|
||||
<p className="font-semibold">{quote.amount} sats</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{quote.paidAt ? new Date(quote.paidAt * 1000).toLocaleString() : 'Unknown date'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2 items-center">
|
||||
<Badge
|
||||
variant={
|
||||
isPaid ? 'default' :
|
||||
isExpired ? 'secondary' :
|
||||
'outline'
|
||||
}
|
||||
>
|
||||
{quote.state}
|
||||
</Badge>
|
||||
{isPaid && !isExpired && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleClaimNpubCashQuote(quote)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Claim
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 text-xs text-muted-foreground">
|
||||
<p className="truncate">Mint: {quote.mintUrl}</p>
|
||||
{isExpired && (
|
||||
<p className="text-destructive">
|
||||
Expired: {new Date(quote.expiresAt * 1000).toLocaleString()}
|
||||
</p>
|
||||
)}
|
||||
{quote.locked && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
🔒 Locked to your pubkey
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* ========================================================================
|
||||
SECTION: Transaction History
|
||||
======================================================================== */}
|
||||
|
||||
Reference in new issue
Block a user