mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
code cleanup
This commit is contained in:
1 parent
dd3f4465c5
commit
5ce402105c
13 files changed
+277
-1042
No files matched your search
@@ -1,8 +1,8 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
||||
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
|
||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||
import { getCleanMintLabel } from '@/lib/cashuUtils';
|
||||
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
@@ -46,8 +46,6 @@ export function CashuWallet() {
|
||||
getHistory,
|
||||
} = useCashu();
|
||||
|
||||
const { getCleanMintLabel } = useCashuMints(null);
|
||||
|
||||
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
@@ -163,7 +161,6 @@ export function CashuWallet() {
|
||||
|
||||
// If user is logged in to npub.cash, a mint is selected, and we should sync
|
||||
if (isNpubCashLoggedIn && mintUrl && syncToNpubCash) {
|
||||
console.log('🔄 Syncing active mint with npub.cash:', mintUrl);
|
||||
const success = await setNpubCashMint(mintUrl);
|
||||
|
||||
if (success) {
|
||||
@@ -171,10 +168,6 @@ export function CashuWallet() {
|
||||
title: "Mint Synced",
|
||||
description: "Your preferred mint has been updated on npub.cash",
|
||||
});
|
||||
} else {
|
||||
// Don't show error toast - the hook already logs errors
|
||||
// Just log that sync failed but local mint is still set
|
||||
console.warn('⚠️ Failed to sync mint with npub.cash, but local mint is still set');
|
||||
}
|
||||
}
|
||||
}, [isNpubCashLoggedIn, setNpubCashMint, toast]);
|
||||
@@ -205,18 +198,15 @@ export function CashuWallet() {
|
||||
try {
|
||||
await receive(tokenInput);
|
||||
setTokenInput('');
|
||||
console.log('✅ Token received successfully!');
|
||||
toast({
|
||||
title: "Token Received",
|
||||
description: "Cashu token redeemed successfully!",
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to receive token: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Receive Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -225,7 +215,6 @@ export function CashuWallet() {
|
||||
try {
|
||||
const amount = parseInt(quoteAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
console.warn('⚠️ Invalid amount');
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid Amount",
|
||||
@@ -249,9 +238,6 @@ export function CashuWallet() {
|
||||
});
|
||||
setShowInvoiceModal(true);
|
||||
|
||||
console.log('✅ Mint quote created:', quote);
|
||||
console.log('🔗 Lightning Invoice:', quote.request);
|
||||
console.log('💡 Wallet will automatically redeem when payment is detected');
|
||||
toast({
|
||||
title: "Lightning Invoice Created",
|
||||
description: "Wallet will automatically claim tokens when payment is detected.",
|
||||
@@ -264,18 +250,15 @@ export function CashuWallet() {
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
|
||||
// Listen for payment notification via mint-quote:redeemed event (note: hyphenated!)
|
||||
console.log('🔔 Setting up payment listener for quote:', quote.quote);
|
||||
// Listen for payment notification via mint-quote:redeemed event
|
||||
const quoteId = quote.quote;
|
||||
const invoiceAmount = amount;
|
||||
|
||||
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
|
||||
const redeemedQuote = payload as { quoteId?: string };
|
||||
console.log('🔔 Mint quote redeemed event received:', redeemedQuote);
|
||||
|
||||
// Check if this is the quote we're waiting for
|
||||
if (redeemedQuote.quoteId === quoteId) {
|
||||
console.log('✅ Our quote was redeemed! Payment detected:', redeemedQuote);
|
||||
toast({
|
||||
title: "Payment Received",
|
||||
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
|
||||
@@ -292,12 +275,10 @@ export function CashuWallet() {
|
||||
// Store unsubscribe function for cleanup
|
||||
mintQuoteUnsubscribeRef.current = unsubscribe;
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to create mint quote: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Quote Creation Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -313,7 +294,6 @@ export function CashuWallet() {
|
||||
try {
|
||||
const amount = parseInt(sendAmount);
|
||||
if (isNaN(amount) || amount <= 0) {
|
||||
console.warn('⚠️ Invalid amount');
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invalid Amount",
|
||||
@@ -324,16 +304,12 @@ export function CashuWallet() {
|
||||
const encodedToken = await send(activeMintUrl, amount);
|
||||
setSentToken(encodedToken);
|
||||
await generateSentTokenQRCode(encodedToken);
|
||||
console.log('✅ Token created successfully!');
|
||||
console.log('📤 Encoded token:', encodedToken);
|
||||
setSendAmount('');
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to send tokens: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Send Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -356,19 +332,14 @@ export function CashuWallet() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🔄 Resolving Lightning address:', pendingLightningAddress, 'for amount:', amount);
|
||||
const invoice = await getLightningInvoice({
|
||||
lightningAddress: pendingLightningAddress,
|
||||
amountSats: amount,
|
||||
});
|
||||
|
||||
console.log('🔄 Creating melt quote for invoice:', invoice);
|
||||
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
|
||||
|
||||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
|
||||
console.log('✅ Lightning payment sent successfully!');
|
||||
toast({
|
||||
title: "Payment Sent",
|
||||
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
|
||||
@@ -378,15 +349,11 @@ export function CashuWallet() {
|
||||
setPendingLightningAddress(null);
|
||||
setLightningAddressInput('');
|
||||
setLightningAddressAmount('');
|
||||
|
||||
// No need to manually refresh balances - events will handle it automatically
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to pay Lightning address: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Payment Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -396,33 +363,24 @@ export function CashuWallet() {
|
||||
|
||||
// Check if it's a Lightning address (contains @)
|
||||
if (input.includes('@')) {
|
||||
console.log('📧 Detected Lightning address:', input);
|
||||
setPendingLightningAddress(input);
|
||||
setLightningAddressInput('');
|
||||
} else {
|
||||
// It's a regular Lightning invoice
|
||||
try {
|
||||
console.log('🔄 Creating melt quote for invoice:', input);
|
||||
const meltQuote = await createMeltQuote(activeMintUrl, input);
|
||||
|
||||
console.log('🔄 Paying melt quote:', meltQuote.quote);
|
||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||
|
||||
console.log('✅ Lightning invoice paid successfully!');
|
||||
toast({
|
||||
title: "Invoice Paid",
|
||||
description: "Lightning invoice paid successfully! Your tokens have been converted to Lightning payment.",
|
||||
});
|
||||
setLightningInvoice('');
|
||||
|
||||
// No need to manually refresh balances - events will handle it automatically
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to pay Lightning invoice: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invoice Payment Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -467,11 +425,10 @@ export function CashuWallet() {
|
||||
setShowRemoveMintModal(false);
|
||||
setMintToRemove(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to remove mint:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Remove Failed",
|
||||
description: `Failed to remove mint: ${err instanceof Error ? err.message : 'Unknown error'}`,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
|
||||
@@ -492,19 +449,15 @@ export function CashuWallet() {
|
||||
await addMint(normalizedUrl);
|
||||
setMintUrl('');
|
||||
|
||||
// No need to manually refresh - events will handle it automatically
|
||||
console.log('✅ Mint added successfully:', normalizedUrl);
|
||||
toast({
|
||||
title: "Mint Added",
|
||||
description: "Mint added successfully!",
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = `Failed to add mint: ${err instanceof Error ? err.message : 'Unknown error'}`;
|
||||
console.error('❌', errorMessage, err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Add Mint Failed",
|
||||
description: errorMessage,
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -517,11 +470,7 @@ export function CashuWallet() {
|
||||
|
||||
const handleShowDenominations = async (mintUrl: string) => {
|
||||
try {
|
||||
console.log('🔍 Getting token denominations for mint:', mintUrl);
|
||||
|
||||
// Get proofs from the wallet for this specific mint
|
||||
const proofs = await getProofs(mintUrl);
|
||||
console.log('💰 Raw proofs for mint:', proofs);
|
||||
|
||||
if (!proofs || proofs.length === 0) {
|
||||
toast({
|
||||
@@ -551,11 +500,10 @@ export function CashuWallet() {
|
||||
setShowProofBreakdown(true);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Failed to get denominations:', err);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Failed to Get Denominations",
|
||||
description: "Failed to get token denominations. Check console for details.",
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -590,23 +538,18 @@ export function CashuWallet() {
|
||||
// Mark that we've checked to prevent multiple fetches
|
||||
hasCheckedNpubCashRef.current = true;
|
||||
|
||||
console.log('🔄 Fetching npub.cash user info...');
|
||||
const userInfo = await getNpubCashUserInfo();
|
||||
|
||||
if (!userInfo) return;
|
||||
|
||||
setNpubCashUserInfo(userInfo);
|
||||
console.log('📋 npub.cash user info:', userInfo);
|
||||
|
||||
// Check if the mint from npub.cash is different from our active mint
|
||||
if (userInfo.mint_url && userInfo.mint_url !== activeMintUrl) {
|
||||
console.log('🔄 npub.cash has a different preferred mint:', userInfo.mint_url);
|
||||
|
||||
// Check if we have this mint in our list
|
||||
const mintExists = mints.some(m => m.url === userInfo.mint_url);
|
||||
|
||||
if (!mintExists) {
|
||||
console.log('➕ Mint not in our list, adding it:', userInfo.mint_url);
|
||||
try {
|
||||
await addMint(userInfo.mint_url);
|
||||
// Wait a bit for the mint to be added
|
||||
@@ -614,14 +557,12 @@ export function CashuWallet() {
|
||||
handleSetActiveMint(userInfo.mint_url, false);
|
||||
}, 500);
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to add mint from npub.cash:', err);
|
||||
// Silent failure - user can manually add mint if needed
|
||||
}
|
||||
} else {
|
||||
// Mint exists, just set it as active (without syncing back to npub.cash)
|
||||
handleSetActiveMint(userInfo.mint_url, false);
|
||||
}
|
||||
} else if (userInfo.mint_url === activeMintUrl) {
|
||||
console.log('✅ Active mint already matches npub.cash preferred mint');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -647,30 +588,24 @@ export function CashuWallet() {
|
||||
// Auto-refresh transaction history on new transactions
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
console.log('📜 Setting up history auto-refresh listeners...');
|
||||
|
||||
// Listen for history updates (fires on send, receive transactions)
|
||||
const unsubscribeHistoryUpdated = on('history:updated', () => {
|
||||
console.log('📜 History updated event, refreshing...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
|
||||
const unsubscribeMeltCreated = on('melt-quote:created', () => {
|
||||
console.log('📜 Melt quote created, refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for melt quote paid (backup, in case creation event missed)
|
||||
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
|
||||
console.log('📜 Melt quote paid, refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
|
||||
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
|
||||
console.log('📜 Mint quote redeemed (invoice paid), refreshing history...');
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
@@ -686,7 +621,6 @@ export function CashuWallet() {
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (component unmount)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
@@ -835,7 +769,6 @@ export function CashuWallet() {
|
||||
onClose={() => {
|
||||
// Clean up event listener when modal is closed manually
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (modal closed)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
@@ -844,11 +777,9 @@ export function CashuWallet() {
|
||||
onExpiry={() => {
|
||||
// Clean up event listener when invoice expires
|
||||
if (mintQuoteUnsubscribeRef.current) {
|
||||
console.log('🧹 Cleaning up mint quote listener (invoice expired)');
|
||||
mintQuoteUnsubscribeRef.current();
|
||||
mintQuoteUnsubscribeRef.current = null;
|
||||
}
|
||||
// Show destructive toast
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Invoice Expired",
|
||||
|
||||
@@ -3,8 +3,8 @@ 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, QrCode, Copy, Check } from 'lucide-react';
|
||||
import { useCashuBalances } from '@/hooks/cashu/useCashuBalances';
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||
|
||||
interface CashuMint {
|
||||
url: string;
|
||||
@@ -57,8 +57,26 @@ export function BalanceDisplay({
|
||||
onShowLightningAddressQR,
|
||||
generateQRCode,
|
||||
}: BalanceDisplayProps) {
|
||||
const { convertCurrency } = useCashuBalances(null);
|
||||
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
|
||||
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
exchangeRateService.getBtcUsdRate()
|
||||
.then(rate => setBtcUsdRate(rate))
|
||||
.catch(() => setBtcUsdRate(null));
|
||||
}, []);
|
||||
|
||||
const convertCurrency = (sats: number, showSats: boolean): string => {
|
||||
if (showSats) {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
} else if (btcUsdRate) {
|
||||
const btcAmount = sats / 100000000;
|
||||
const usd = btcAmount * btcUsdRate;
|
||||
return `$${usd.toFixed(2)}`;
|
||||
} else {
|
||||
return `${sats.toLocaleString()} sats`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="text-center py-2">
|
||||
|
||||
@@ -2,7 +2,6 @@ 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;
|
||||
@@ -17,8 +16,6 @@ interface ProofBreakdownModalProps {
|
||||
}
|
||||
|
||||
export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdownModalProps) {
|
||||
const { convertCurrency } = useCashuBalances(null);
|
||||
|
||||
if (!isOpen || !breakdown) return null;
|
||||
|
||||
return (
|
||||
@@ -50,7 +47,7 @@ export function ProofBreakdownModal({ isOpen, onClose, breakdown }: ProofBreakdo
|
||||
<CardContent className="space-y-4">
|
||||
<div className="text-center py-2">
|
||||
<div className="text-2xl font-bold text-primary">
|
||||
{convertCurrency(breakdown.totalBalance)}
|
||||
{breakdown.totalBalance.toLocaleString()} sats
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">Total Balance</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user