mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 08:47:23 +00:00
separate cashu and bitcoin wallets
This commit is contained in:
1 parent
0b8d104808
commit
28e50a9d7a
10 files changed
+1003
-393
No files matched your search
+2
-2
@@ -4,7 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
|
|||||||
import Index from "./pages/Index";
|
import Index from "./pages/Index";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
import { CashuWallet } from "./components/wallet/CashuWallet";
|
import { WalletContainer } from "./components/wallet/WalletContainer";
|
||||||
|
|
||||||
export function AppRouter() {
|
export function AppRouter() {
|
||||||
return (
|
return (
|
||||||
@@ -12,7 +12,7 @@ export function AppRouter() {
|
|||||||
<ScrollToTop />
|
<ScrollToTop />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Index />} />
|
<Route path="/" element={<Index />} />
|
||||||
<Route path="/wallet" element={<CashuWallet />} />
|
<Route path="/wallet" element={<WalletContainer />} />
|
||||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||||
<Route path="/:nip19" element={<NIP19Page />} />
|
<Route path="/:nip19" element={<NIP19Page />} />
|
||||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
import { useState, useEffect, useRef } from 'react';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
||||||
|
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||||
|
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
||||||
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
|
import { TransactionCard } from './PaymentCard';
|
||||||
|
import { ConsolidationModal } from './ConsolidationModal';
|
||||||
|
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
|
||||||
|
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
|
||||||
|
import { TransactionHistory } from './TransactionHistory';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import type { QRScanResult } from '@/hooks/useQRCode';
|
||||||
|
|
||||||
|
interface BitcoinWalletProps {
|
||||||
|
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
|
||||||
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
|
copyToClipboard: (text: string) => Promise<void>;
|
||||||
|
user?: { pubkey: string };
|
||||||
|
onRequestQRScanner: () => void;
|
||||||
|
onQRResult?: (result: QRScanResult) => void;
|
||||||
|
onWalletHeaderPropsChange?: (props: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BitcoinWallet({
|
||||||
|
toast,
|
||||||
|
generateQRCode,
|
||||||
|
copyToClipboard,
|
||||||
|
user,
|
||||||
|
onRequestQRScanner,
|
||||||
|
onQRResult,
|
||||||
|
onWalletHeaderPropsChange,
|
||||||
|
}: BitcoinWalletProps) {
|
||||||
|
const { hasNsecAccess } = useNsecAccess();
|
||||||
|
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||||
|
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
|
||||||
|
|
||||||
|
const {
|
||||||
|
utxos,
|
||||||
|
isConsolidating,
|
||||||
|
bitcoinMaxAmount,
|
||||||
|
fetchBitcoinUtxos,
|
||||||
|
handleSendMax,
|
||||||
|
handleBitcoinSend,
|
||||||
|
handleBitcoinReceive,
|
||||||
|
handleConsolidateUtxos,
|
||||||
|
} = useBitcoinOperations(bitcoinAddress);
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: bitcoinTransactions = [],
|
||||||
|
isLoading: isBitcoinTransactionsLoading
|
||||||
|
} = useBitcoinTransactionHistory(bitcoinAddress);
|
||||||
|
|
||||||
|
// Bitcoin state
|
||||||
|
const [bitcoinAmount, setBitcoinAmount] = useState('');
|
||||||
|
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
|
||||||
|
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
|
||||||
|
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
|
||||||
|
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
|
||||||
|
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
|
||||||
|
const [showSendModal, setShowSendModal] = useState(false);
|
||||||
|
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
||||||
|
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
||||||
|
|
||||||
|
// UTXO state
|
||||||
|
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
|
||||||
|
|
||||||
|
// Fetch UTXOs when component mounts
|
||||||
|
useEffect(() => {
|
||||||
|
if (bitcoinAddress) {
|
||||||
|
fetchBitcoinUtxos();
|
||||||
|
}
|
||||||
|
}, [bitcoinAddress, fetchBitcoinUtxos]);
|
||||||
|
|
||||||
|
// Handle drawer close with state reset
|
||||||
|
const handleSendDrawerClose = (open: boolean) => {
|
||||||
|
setShowSendModal(open);
|
||||||
|
if (!open) {
|
||||||
|
setBitcoinAmount('');
|
||||||
|
setBitcoinRecipient('');
|
||||||
|
setPendingBitcoinRecipient(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReceiveDrawerClose = (open: boolean) => {
|
||||||
|
setShowReceiveModal(open);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle focus management when drawers open
|
||||||
|
useEffect(() => {
|
||||||
|
if (showSendModal || showReceiveModal || showHistoryModal) {
|
||||||
|
const activeElement = document.activeElement as HTMLElement;
|
||||||
|
if (activeElement && activeElement.blur) {
|
||||||
|
activeElement.blur();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [showSendModal, showReceiveModal, showHistoryModal]);
|
||||||
|
|
||||||
|
// Handle QR scan results (called from parent WalletContainer)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onQRResult) return;
|
||||||
|
|
||||||
|
const handleQRResult = (result: QRScanResult) => {
|
||||||
|
if (result.type === 'bitcoin_address') {
|
||||||
|
setBitcoinRecipient(result.value);
|
||||||
|
setPendingBitcoinRecipient(result.value);
|
||||||
|
setShowSendModal(true);
|
||||||
|
toast({
|
||||||
|
title: "Bitcoin Address Scanned",
|
||||||
|
description: "Enter amount to send",
|
||||||
|
});
|
||||||
|
} else if (result.type === 'npub') {
|
||||||
|
try {
|
||||||
|
const decoded = nip19.decode(result.value);
|
||||||
|
if (decoded.type === 'npub') {
|
||||||
|
const address = nostrPubkeyToBitcoinAddress(decoded.data);
|
||||||
|
setBitcoinRecipient(address);
|
||||||
|
setPendingBitcoinRecipient(address);
|
||||||
|
setShowSendModal(true);
|
||||||
|
toast({
|
||||||
|
title: "Nostr npub Scanned",
|
||||||
|
description: "Enter amount to send",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Invalid npub",
|
||||||
|
description: "Could not decode npub",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Store handler for parent to call
|
||||||
|
(window as any).__bitcoinWalletQRHandler = handleQRResult;
|
||||||
|
return () => {
|
||||||
|
delete (window as any).__bitcoinWalletQRHandler;
|
||||||
|
};
|
||||||
|
}, [onQRResult, toast]);
|
||||||
|
|
||||||
|
const totalBalance = bitcoinBalanceData?.balance || 0;
|
||||||
|
|
||||||
|
// Expose WalletHeader props to parent WalletContainer
|
||||||
|
// Use ref to track previous values and prevent infinite loops
|
||||||
|
const prevPropsRef = useRef<{
|
||||||
|
utxosLength?: number;
|
||||||
|
utxoDropdownOpen?: boolean;
|
||||||
|
isConsolidating?: boolean;
|
||||||
|
}>({});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onWalletHeaderPropsChange) return;
|
||||||
|
|
||||||
|
// Check if values actually changed
|
||||||
|
const currentProps = {
|
||||||
|
utxosLength: utxos?.length,
|
||||||
|
utxoDropdownOpen,
|
||||||
|
isConsolidating,
|
||||||
|
};
|
||||||
|
|
||||||
|
const prevProps = prevPropsRef.current;
|
||||||
|
const hasChanged =
|
||||||
|
prevProps.utxosLength !== currentProps.utxosLength ||
|
||||||
|
prevProps.utxoDropdownOpen !== currentProps.utxoDropdownOpen ||
|
||||||
|
prevProps.isConsolidating !== currentProps.isConsolidating;
|
||||||
|
|
||||||
|
if (!hasChanged && Object.keys(prevProps).length > 0) {
|
||||||
|
// Values haven't changed, skip update
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update ref
|
||||||
|
prevPropsRef.current = currentProps;
|
||||||
|
|
||||||
|
// Send updated props
|
||||||
|
onWalletHeaderPropsChange({
|
||||||
|
utxos,
|
||||||
|
utxoDropdownOpen,
|
||||||
|
setUtxoDropdownOpen,
|
||||||
|
onShowConsolidationModal: () => setShowConsolidationModal(true),
|
||||||
|
isConsolidating,
|
||||||
|
onShowBitcoinAddressQR: async (qr: string) => {
|
||||||
|
setBitcoinAddressQRCode(qr);
|
||||||
|
setShowBitcoinAddressQR(true);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
onWalletHeaderPropsChange,
|
||||||
|
utxos?.length,
|
||||||
|
utxoDropdownOpen,
|
||||||
|
isConsolidating,
|
||||||
|
// Note: Functions (setUtxoDropdownOpen, etc.) are not in deps
|
||||||
|
// because they're stable setters or we accept they may change
|
||||||
|
// The ref-based change detection ensures we only update when primitives change
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Action Buttons and Transaction History Container */}
|
||||||
|
<div className="fixed bottom-0 left-0 right-0 pb-8 pb-safe">
|
||||||
|
{/* Action Buttons */}
|
||||||
|
<div className="flex gap-8 justify-center py-8">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setShowReceiveModal(true)}
|
||||||
|
disabled={isBitcoinBalanceLoading}
|
||||||
|
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||||
|
>
|
||||||
|
<Download className="h-12 w-12" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={onRequestQRScanner}
|
||||||
|
disabled={isBitcoinBalanceLoading}
|
||||||
|
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||||
|
>
|
||||||
|
<ScanLine className="h-12 w-12" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => setShowSendModal(true)}
|
||||||
|
disabled={isBitcoinBalanceLoading}
|
||||||
|
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||||
|
>
|
||||||
|
<Send className="h-12 w-12" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Transaction History Button */}
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<button
|
||||||
|
onClick={() => setShowHistoryModal(true)}
|
||||||
|
className="w-full py-2 px-4 flex flex-col items-center gap-1 border-t border-muted hover:bg-muted/30 transition-colors"
|
||||||
|
>
|
||||||
|
<ChevronUp className="h-5 w-5 text-muted-foreground" />
|
||||||
|
<span className="text-xs text-muted-foreground font-medium">History</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Modals */}
|
||||||
|
<>
|
||||||
|
{/* Consolidation Modal */}
|
||||||
|
<ConsolidationModal
|
||||||
|
isOpen={showConsolidationModal}
|
||||||
|
onClose={() => setShowConsolidationModal(false)}
|
||||||
|
utxos={utxos}
|
||||||
|
onConfirm={handleConsolidateUtxos}
|
||||||
|
isConsolidating={isConsolidating}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Bitcoin Address QR Modal */}
|
||||||
|
<QRModal
|
||||||
|
isOpen={showBitcoinAddressQR}
|
||||||
|
onClose={() => setShowBitcoinAddressQR(false)}
|
||||||
|
title="Bitcoin Address"
|
||||||
|
description="Scan this QR code to send Bitcoin to your address"
|
||||||
|
qrCodeUrl={bitcoinAddressQRCode}
|
||||||
|
content={bitcoinAddress || ''}
|
||||||
|
icon="qr"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Bottom Drawer Modals */}
|
||||||
|
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
|
||||||
|
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
||||||
|
<VisuallyHidden.Root asChild>
|
||||||
|
<DrawerDescription>
|
||||||
|
Send Bitcoin on-chain
|
||||||
|
</DrawerDescription>
|
||||||
|
</VisuallyHidden.Root>
|
||||||
|
</DrawerHeader>
|
||||||
|
<div className="px-4 pb-6 pb-safe-bottom">
|
||||||
|
<TransactionCard
|
||||||
|
mode="bitcoin"
|
||||||
|
operation="send"
|
||||||
|
sendAmount=""
|
||||||
|
setSendAmount={() => {}}
|
||||||
|
lightningInvoice=""
|
||||||
|
setLightningInvoice={() => {}}
|
||||||
|
lightningAddressInput=""
|
||||||
|
setLightningAddressInput={() => {}}
|
||||||
|
lightningAddressAmount=""
|
||||||
|
setLightningAddressAmount={() => {}}
|
||||||
|
pendingLightningAddress={null}
|
||||||
|
setPendingLightningAddress={() => {}}
|
||||||
|
decodedInvoiceAmount={null}
|
||||||
|
setDecodedInvoiceAmount={() => {}}
|
||||||
|
pendingInvoice={null}
|
||||||
|
setPendingInvoice={() => {}}
|
||||||
|
tokenInput=""
|
||||||
|
setTokenInput={() => {}}
|
||||||
|
quoteAmount=""
|
||||||
|
setQuoteAmount={() => {}}
|
||||||
|
activeMintUrl={null}
|
||||||
|
onSend={() => {
|
||||||
|
handleBitcoinSend(
|
||||||
|
bitcoinAmount,
|
||||||
|
pendingBitcoinRecipient,
|
||||||
|
setBitcoinAmount,
|
||||||
|
setBitcoinRecipient,
|
||||||
|
setPendingBitcoinRecipient,
|
||||||
|
setShowSendModal
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
onReceive={() => {}}
|
||||||
|
isResolvingAddress={false}
|
||||||
|
isLoading={isBitcoinBalanceLoading}
|
||||||
|
bitcoinAddress={bitcoinAddress || ''}
|
||||||
|
bitcoinAmount={bitcoinAmount}
|
||||||
|
setBitcoinAmount={setBitcoinAmount}
|
||||||
|
bitcoinRecipient={bitcoinRecipient}
|
||||||
|
setBitcoinRecipient={setBitcoinRecipient}
|
||||||
|
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
||||||
|
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
||||||
|
hasNsecAccess={hasNsecAccess}
|
||||||
|
bitcoinMaxAmount={bitcoinMaxAmount}
|
||||||
|
onSendMax={() => handleSendMax(setBitcoinAmount)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
|
||||||
|
<Drawer open={showReceiveModal} onOpenChange={handleReceiveDrawerClose}>
|
||||||
|
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
||||||
|
<VisuallyHidden.Root asChild>
|
||||||
|
<DrawerDescription>
|
||||||
|
Receive Bitcoin on-chain
|
||||||
|
</DrawerDescription>
|
||||||
|
</VisuallyHidden.Root>
|
||||||
|
</DrawerHeader>
|
||||||
|
<div className="px-4 pb-6 pb-safe-bottom">
|
||||||
|
<TransactionCard
|
||||||
|
mode="bitcoin"
|
||||||
|
operation="receive"
|
||||||
|
sendAmount=""
|
||||||
|
setSendAmount={() => {}}
|
||||||
|
lightningInvoice=""
|
||||||
|
setLightningInvoice={() => {}}
|
||||||
|
lightningAddressInput=""
|
||||||
|
setLightningAddressInput={() => {}}
|
||||||
|
lightningAddressAmount=""
|
||||||
|
setLightningAddressAmount={() => {}}
|
||||||
|
pendingLightningAddress={null}
|
||||||
|
setPendingLightningAddress={() => {}}
|
||||||
|
decodedInvoiceAmount={null}
|
||||||
|
setDecodedInvoiceAmount={() => {}}
|
||||||
|
pendingInvoice={null}
|
||||||
|
setPendingInvoice={() => {}}
|
||||||
|
tokenInput=""
|
||||||
|
setTokenInput={() => {}}
|
||||||
|
quoteAmount=""
|
||||||
|
setQuoteAmount={() => {}}
|
||||||
|
activeMintUrl={null}
|
||||||
|
onSend={() => {}}
|
||||||
|
onReceive={() => {
|
||||||
|
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
|
||||||
|
setShowReceiveModal(false);
|
||||||
|
}}
|
||||||
|
isResolvingAddress={false}
|
||||||
|
isLoading={isBitcoinBalanceLoading}
|
||||||
|
bitcoinAddress={bitcoinAddress || ''}
|
||||||
|
bitcoinAmount=""
|
||||||
|
setBitcoinAmount={() => {}}
|
||||||
|
bitcoinRecipient=""
|
||||||
|
setBitcoinRecipient={() => {}}
|
||||||
|
pendingBitcoinRecipient={null}
|
||||||
|
setPendingBitcoinRecipient={() => {}}
|
||||||
|
hasNsecAccess={hasNsecAccess}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
|
||||||
|
<Drawer open={showHistoryModal} onOpenChange={setShowHistoryModal}>
|
||||||
|
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
|
||||||
|
<VisuallyHidden.Root asChild>
|
||||||
|
<DrawerDescription>
|
||||||
|
View your Bitcoin transaction history
|
||||||
|
</DrawerDescription>
|
||||||
|
</VisuallyHidden.Root>
|
||||||
|
</DrawerHeader>
|
||||||
|
<ScrollArea className="h-[80vh] px-4 pb-4">
|
||||||
|
<TransactionHistory
|
||||||
|
entries={[]}
|
||||||
|
isLoading={isBitcoinTransactionsLoading}
|
||||||
|
bitcoinTransactions={bitcoinTransactions}
|
||||||
|
isBitcoinLoading={isBitcoinTransactionsLoading}
|
||||||
|
showSats={true}
|
||||||
|
/>
|
||||||
|
</ScrollArea>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
</>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -3,27 +3,18 @@ import { nip19 } from 'nostr-tools';
|
|||||||
import { useCashu } from '@/hooks/cashu/useCashu';
|
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
||||||
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
import { useNpubCash, type NpubCashUserInfo } from '@/hooks/useNpubCash';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import type { QRScanResult } from '@/hooks/useQRCode';
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { useQRCode, type QRScanResult } from '@/hooks/useQRCode';
|
|
||||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
|
||||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||||
import { useTokenOperations } from '@/hooks/cashu/useTokenOperations';
|
import { useTokenOperations } from '@/hooks/cashu/useTokenOperations';
|
||||||
import { useLightningOperations } from '@/hooks/cashu/useLightningOperations';
|
import { useLightningOperations } from '@/hooks/cashu/useLightningOperations';
|
||||||
import { useReverseSwapOperations } from '@/hooks/cashu/useReverseSwapOperations';
|
import { useReverseSwapOperations } from '@/hooks/cashu/useReverseSwapOperations';
|
||||||
import { useSeedPhraseRestore } from '@/hooks/cashu/useSeedPhraseRestore';
|
import { useSeedPhraseRestore } from '@/hooks/cashu/useSeedPhraseRestore';
|
||||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||||
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
|
||||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
|
||||||
import { decodeBolt11Amount } from '@/lib/bolt11Decoder';
|
import { decodeBolt11Amount } from '@/lib/bolt11Decoder';
|
||||||
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
|
||||||
import { QRModal } from '@/components/ui/qr-modal';
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { WalletHeader } from './WalletHeader';
|
|
||||||
import { TransactionCard } from './PaymentCard';
|
import { TransactionCard } from './PaymentCard';
|
||||||
import { ProofBreakdownModal } from './ProofBreakdownModal';
|
import { ProofBreakdownModal } from './ProofBreakdownModal';
|
||||||
import { RemoveMintModal } from './RemoveMintModal';
|
import { RemoveMintModal } from './RemoveMintModal';
|
||||||
import { ConsolidationModal } from './ConsolidationModal';
|
|
||||||
import { QRScannerModal } from './QRScannerModal';
|
|
||||||
import { SeedPhraseModal } from './SeedPhraseModal';
|
import { SeedPhraseModal } from './SeedPhraseModal';
|
||||||
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
|
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
|
||||||
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
|
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
|
||||||
@@ -32,7 +23,25 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
|||||||
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
|
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
export function CashuWallet() {
|
interface CashuWalletProps {
|
||||||
|
mode: 'tokens' | 'lightning';
|
||||||
|
toast: ReturnType<typeof import('@/hooks/useToast').useToast>['toast'];
|
||||||
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
|
copyToClipboard: (text: string) => Promise<void>;
|
||||||
|
user?: { pubkey: string };
|
||||||
|
onRequestQRScanner: () => void;
|
||||||
|
onWalletHeaderPropsChange?: (props: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CashuWallet({
|
||||||
|
mode,
|
||||||
|
toast,
|
||||||
|
generateQRCode,
|
||||||
|
copyToClipboard,
|
||||||
|
user,
|
||||||
|
onRequestQRScanner,
|
||||||
|
onWalletHeaderPropsChange,
|
||||||
|
}: CashuWalletProps) {
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// CORE HOOKS
|
// CORE HOOKS
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -50,28 +59,7 @@ export function CashuWallet() {
|
|||||||
refreshMints,
|
refreshMints,
|
||||||
} = useCashu();
|
} = useCashu();
|
||||||
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
|
||||||
const { toast } = useToast();
|
|
||||||
const { generateQRCode, isScanning, startScanning, stopScanning, error: qrError, classifyQRCode, setModalOpen } = useQRCode();
|
|
||||||
const { copy: copyToClipboard } = useCopyToClipboard();
|
|
||||||
const { hasNsecAccess } = useNsecAccess();
|
|
||||||
|
|
||||||
// Bitcoin hooks - including balance and transaction history
|
|
||||||
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
|
||||||
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading } = useBitcoinBalance(bitcoinAddress);
|
|
||||||
|
|
||||||
// Bitcoin operations hook
|
|
||||||
const {
|
|
||||||
utxos,
|
|
||||||
isConsolidating,
|
|
||||||
bitcoinMaxAmount,
|
|
||||||
fetchBitcoinUtxos,
|
|
||||||
handleSendMax,
|
|
||||||
handleBitcoinSend,
|
|
||||||
handleBitcoinReceive,
|
|
||||||
handleConsolidateUtxos,
|
|
||||||
} = useBitcoinOperations(bitcoinAddress);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
setMint: setNpubCashMint,
|
setMint: setNpubCashMint,
|
||||||
@@ -238,18 +226,11 @@ export function CashuWallet() {
|
|||||||
isInitialized,
|
isInitialized,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Bitcoin transaction history
|
|
||||||
const {
|
|
||||||
data: bitcoinTransactions = [],
|
|
||||||
isLoading: isBitcoinTransactionsLoading
|
|
||||||
} = useBitcoinTransactionHistory(bitcoinAddress);
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// UI STATE
|
// UI STATE
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const [showSats, setShowSats] = useState(true);
|
const [showSats, setShowSats] = useState(true);
|
||||||
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
|
|
||||||
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
const [showProofBreakdown, setShowProofBreakdown] = useState(false);
|
||||||
const [proofBreakdown, setProofBreakdown] = useState<{
|
const [proofBreakdown, setProofBreakdown] = useState<{
|
||||||
mintUrl: string;
|
mintUrl: string;
|
||||||
@@ -262,19 +243,7 @@ export function CashuWallet() {
|
|||||||
const [showSendModal, setShowSendModal] = useState(false);
|
const [showSendModal, setShowSendModal] = useState(false);
|
||||||
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
const [showReceiveModal, setShowReceiveModal] = useState(false);
|
||||||
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
const [showHistoryModal, setShowHistoryModal] = useState(false);
|
||||||
const [showQRScanner, setShowQRScanner] = useState(false);
|
|
||||||
|
|
||||||
// Bitcoin state
|
|
||||||
const [bitcoinAmount, setBitcoinAmount] = useState('');
|
|
||||||
const [bitcoinRecipient, setBitcoinRecipient] = useState('');
|
|
||||||
const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState<string | null>(null);
|
|
||||||
const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
|
|
||||||
const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
|
|
||||||
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
|
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
|
||||||
const [showConsolidationModal, setShowConsolidationModal] = useState(false);
|
|
||||||
|
|
||||||
// UTXO state
|
|
||||||
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
|
|
||||||
|
|
||||||
|
|
||||||
// Handle drawer close with state reset
|
// Handle drawer close with state reset
|
||||||
@@ -292,10 +261,6 @@ export function CashuWallet() {
|
|||||||
// Reset reverse swap state
|
// Reset reverse swap state
|
||||||
setPendingBitcoinSwapAddress(null);
|
setPendingBitcoinSwapAddress(null);
|
||||||
setBitcoinSwapAmount('');
|
setBitcoinSwapAmount('');
|
||||||
// Reset Bitcoin state
|
|
||||||
setBitcoinAmount('');
|
|
||||||
setBitcoinRecipient('');
|
|
||||||
setPendingBitcoinRecipient(null);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -315,9 +280,7 @@ export function CashuWallet() {
|
|||||||
// COMPUTED VALUES
|
// COMPUTED VALUES
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const totalBalance: number = mode === 'bitcoin'
|
const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
||||||
? (bitcoinBalanceData?.balance || 0)
|
|
||||||
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// EFFECTS - Error Handling
|
// EFFECTS - Error Handling
|
||||||
@@ -371,7 +334,20 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
if (!mintExists && coco) {
|
if (!mintExists && coco) {
|
||||||
try {
|
try {
|
||||||
await coco.mint.addMint(userInfo.mint_url);
|
// Check if mint exists (known) by checking all mints
|
||||||
|
const allMints = await coco.mint.getAllMints();
|
||||||
|
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === userInfo.mint_url.toLowerCase());
|
||||||
|
|
||||||
|
if (isKnown) {
|
||||||
|
// Mint exists but may not be trusted, ensure it's trusted
|
||||||
|
const isTrusted = await coco.mint.isTrustedMint(userInfo.mint_url);
|
||||||
|
if (!isTrusted) {
|
||||||
|
await coco.mint.trustMint(userInfo.mint_url);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Add mint from npub.cash and automatically trust it
|
||||||
|
await coco.mint.addMint(userInfo.mint_url, { trusted: true });
|
||||||
|
}
|
||||||
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
|
setTimeout(() => setActiveMintUrl(userInfo.mint_url, false), 500);
|
||||||
} catch {
|
} catch {
|
||||||
// Silent failure - user can manually add mint if needed
|
// Silent failure - user can manually add mint if needed
|
||||||
@@ -404,27 +380,6 @@ export function CashuWallet() {
|
|||||||
};
|
};
|
||||||
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
|
}, [isNpubCashLoggedIn, coco, isInitialized, syncQuotesWithWallet, toast]);
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// EFFECTS - UTXO Fetching
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (mode === 'bitcoin' && bitcoinAddress) {
|
|
||||||
fetchBitcoinUtxos();
|
|
||||||
}
|
|
||||||
}, [mode, bitcoinAddress, fetchBitcoinUtxos]);
|
|
||||||
|
|
||||||
// Start/stop QR scanner when modal opens/closes
|
|
||||||
useEffect(() => {
|
|
||||||
if (showQRScanner) {
|
|
||||||
setModalOpen?.(true);
|
|
||||||
startScanning(handleQRScanResult);
|
|
||||||
} else {
|
|
||||||
setModalOpen?.(false);
|
|
||||||
stopScanning();
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [showQRScanner, startScanning, stopScanning, setModalOpen]);
|
|
||||||
|
|
||||||
// Handle focus management when drawers open to prevent aria-hidden warnings
|
// Handle focus management when drawers open to prevent aria-hidden warnings
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -450,170 +405,139 @@ export function CashuWallet() {
|
|||||||
};
|
};
|
||||||
}, [mintQuoteUnsubscribeRef]);
|
}, [mintQuoteUnsubscribeRef]);
|
||||||
|
|
||||||
// Handle QR scanner results
|
// Handle QR scan results (called from parent WalletContainer)
|
||||||
const handleQRScanResult = async (result: QRScanResult) => {
|
const handleQRResult = (result: QRScanResult) => {
|
||||||
try {
|
switch (result.type) {
|
||||||
await stopScanning();
|
case 'lightning_invoice': {
|
||||||
setShowQRScanner(false);
|
setLightningInvoice(result.value);
|
||||||
|
setPendingInvoice(result.value);
|
||||||
switch (result.type) {
|
// Decode invoice amount
|
||||||
case 'lightning_invoice': {
|
const amount = decodeBolt11Amount(result.value);
|
||||||
setMode('lightning');
|
setDecodedInvoiceAmount(amount);
|
||||||
setLightningInvoice(result.value);
|
setShowSendModal(true);
|
||||||
setPendingInvoice(result.value);
|
|
||||||
// Decode invoice amount
|
|
||||||
const amount = decodeBolt11Amount(result.value);
|
|
||||||
setDecodedInvoiceAmount(amount);
|
|
||||||
setShowSendModal(true);
|
|
||||||
toast({
|
|
||||||
title: "Lightning Invoice Scanned",
|
|
||||||
description: amount ? `${amount} sats` : "Invoice ready to pay",
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'lightning_address': {
|
|
||||||
setMode('lightning');
|
|
||||||
setLightningAddressInput(result.value);
|
|
||||||
setPendingLightningAddress(result.value);
|
|
||||||
setShowSendModal(true);
|
|
||||||
toast({
|
|
||||||
title: "Lightning Address Scanned",
|
|
||||||
description: "Enter amount to send",
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'cashu_token': {
|
|
||||||
setMode('tokens');
|
|
||||||
setTokenInput(result.value);
|
|
||||||
setShowReceiveModal(true);
|
|
||||||
toast({
|
|
||||||
title: "Cashu Token Scanned",
|
|
||||||
description: "Token ready to redeem",
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'bitcoin_address': {
|
|
||||||
setMode('bitcoin');
|
|
||||||
setBitcoinRecipient(result.value);
|
|
||||||
setPendingBitcoinRecipient(result.value);
|
|
||||||
setShowSendModal(true);
|
|
||||||
toast({
|
|
||||||
title: "Bitcoin Address Scanned",
|
|
||||||
description: "Enter amount to send",
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'npub': {
|
|
||||||
// Convert npub to bitcoin address
|
|
||||||
try {
|
|
||||||
const decoded = nip19.decode(result.value);
|
|
||||||
if (decoded.type === 'npub') {
|
|
||||||
const address = nostrPubkeyToBitcoinAddress(decoded.data);
|
|
||||||
setMode('bitcoin');
|
|
||||||
setBitcoinRecipient(address);
|
|
||||||
setPendingBitcoinRecipient(address);
|
|
||||||
setShowSendModal(true);
|
|
||||||
toast({
|
|
||||||
title: "Nostr npub Scanned",
|
|
||||||
description: "Enter amount to send",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: "Invalid npub",
|
|
||||||
description: "Could not decode npub",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default: {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: "Unknown QR Code",
|
|
||||||
description: result.value,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error handling QR scan:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle paste from clipboard
|
|
||||||
const handlePasteQRCode = async () => {
|
|
||||||
try {
|
|
||||||
const text = await navigator.clipboard.readText();
|
|
||||||
if (!text || !text.trim()) {
|
|
||||||
toast({
|
toast({
|
||||||
variant: "destructive",
|
title: "Lightning Invoice Scanned",
|
||||||
title: "Clipboard Empty",
|
description: amount ? `${amount} sats` : "Invoice ready to pay",
|
||||||
description: "No text found in clipboard",
|
|
||||||
});
|
});
|
||||||
return;
|
break;
|
||||||
|
}
|
||||||
|
case 'lightning_address': {
|
||||||
|
setLightningAddressInput(result.value);
|
||||||
|
setPendingLightningAddress(result.value);
|
||||||
|
setShowSendModal(true);
|
||||||
|
toast({
|
||||||
|
title: "Lightning Address Scanned",
|
||||||
|
description: "Enter amount to send",
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'cashu_token': {
|
||||||
|
setTokenInput(result.value);
|
||||||
|
setShowReceiveModal(true);
|
||||||
|
toast({
|
||||||
|
title: "Cashu Token Scanned",
|
||||||
|
description: "Token ready to redeem",
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
// Bitcoin addresses and npubs are handled by BitcoinWallet
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = classifyQRCode(text.trim());
|
|
||||||
await handleQRScanResult(result);
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: "Paste Failed",
|
|
||||||
description: "Could not read from clipboard",
|
|
||||||
});
|
|
||||||
console.error('Error pasting from clipboard:', err);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Expose handler to parent via window (temporary, will be improved)
|
||||||
|
useEffect(() => {
|
||||||
|
(window as any).__cashuWalletQRHandler = handleQRResult;
|
||||||
|
return () => {
|
||||||
|
delete (window as any).__cashuWalletQRHandler;
|
||||||
|
};
|
||||||
|
}, [mode, setLightningInvoice, setPendingInvoice, setDecodedInvoiceAmount, setShowSendModal, setLightningAddressInput, setPendingLightningAddress, setTokenInput, setShowReceiveModal, toast]); // Re-setup when mode changes
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// RENDER
|
// RENDER
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
|
// Expose WalletHeader props to parent WalletContainer
|
||||||
|
// Use ref to track previous values and prevent infinite loops
|
||||||
|
const prevPropsRef = useRef<{
|
||||||
|
activeMintUrl?: string | null;
|
||||||
|
mintsLength?: number;
|
||||||
|
firstMintUrl?: string;
|
||||||
|
mintUrl?: string;
|
||||||
|
mintDropdownOpen?: boolean;
|
||||||
|
npubCashUsername?: string;
|
||||||
|
}>({});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onWalletHeaderPropsChange) return;
|
||||||
|
|
||||||
|
const npubCashUsername = user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined;
|
||||||
|
|
||||||
|
// Check if values actually changed
|
||||||
|
const currentProps = {
|
||||||
|
activeMintUrl,
|
||||||
|
mintsLength: mints?.length,
|
||||||
|
firstMintUrl: mints?.[0]?.url,
|
||||||
|
mintUrl,
|
||||||
|
mintDropdownOpen,
|
||||||
|
npubCashUsername,
|
||||||
|
};
|
||||||
|
|
||||||
|
const prevProps = prevPropsRef.current;
|
||||||
|
const hasChanged =
|
||||||
|
prevProps.activeMintUrl !== currentProps.activeMintUrl ||
|
||||||
|
prevProps.mintsLength !== currentProps.mintsLength ||
|
||||||
|
prevProps.firstMintUrl !== currentProps.firstMintUrl ||
|
||||||
|
prevProps.mintUrl !== currentProps.mintUrl ||
|
||||||
|
prevProps.mintDropdownOpen !== currentProps.mintDropdownOpen ||
|
||||||
|
prevProps.npubCashUsername !== currentProps.npubCashUsername;
|
||||||
|
|
||||||
|
if (!hasChanged && Object.keys(prevProps).length > 0) {
|
||||||
|
// Values haven't changed, skip update
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update ref
|
||||||
|
prevPropsRef.current = currentProps;
|
||||||
|
|
||||||
|
// Send updated props
|
||||||
|
onWalletHeaderPropsChange({
|
||||||
|
activeMintUrl,
|
||||||
|
setActiveMintUrl: handleSetActiveMintSync,
|
||||||
|
mints,
|
||||||
|
mintUrl,
|
||||||
|
setMintUrl,
|
||||||
|
onAddMint: handleAddMint,
|
||||||
|
onRemoveMint: handleRemoveMintClick,
|
||||||
|
onShowDenominations: (mintUrl: string) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown),
|
||||||
|
getCleanMintLabel,
|
||||||
|
mintDropdownOpen,
|
||||||
|
setMintDropdownOpen,
|
||||||
|
npubCashUsername,
|
||||||
|
onShowLightningAddressQR: async (qr: string) => {
|
||||||
|
setLightningAddressQRCode(qr);
|
||||||
|
setShowLightningAddressQR(true);
|
||||||
|
},
|
||||||
|
onShowSeedPhraseInfo: () => setShowSeedPhraseInfo(true),
|
||||||
|
});
|
||||||
|
}, [
|
||||||
|
onWalletHeaderPropsChange,
|
||||||
|
activeMintUrl,
|
||||||
|
mints?.length,
|
||||||
|
mints?.[0]?.url,
|
||||||
|
mintUrl,
|
||||||
|
mintDropdownOpen,
|
||||||
|
npubCashUserInfo?.name,
|
||||||
|
user?.pubkey,
|
||||||
|
// Note: Functions (handleSetActiveMintSync, handleAddMint, etc.) are not in deps
|
||||||
|
// because they're stable from hooks or we accept they may change
|
||||||
|
// The ref-based change detection ensures we only update when primitives change
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
|
|
||||||
|
|
||||||
{/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */}
|
|
||||||
<WalletHeader
|
|
||||||
totalBalance={totalBalance}
|
|
||||||
balances={balances}
|
|
||||||
showSats={showSats}
|
|
||||||
setShowSats={setShowSats}
|
|
||||||
mode={mode}
|
|
||||||
setMode={setMode}
|
|
||||||
userPubkey={user?.pubkey}
|
|
||||||
npubCashUsername={user?.pubkey ? (npubCashUserInfo?.name || nip19.npubEncode(user.pubkey)) : undefined}
|
|
||||||
mnemonic={mnemonic}
|
|
||||||
onCopyToClipboard={copyToClipboard}
|
|
||||||
onShowLightningAddressQR={(qr) => {
|
|
||||||
setLightningAddressQRCode(qr);
|
|
||||||
setShowLightningAddressQR(true);
|
|
||||||
}}
|
|
||||||
onShowBitcoinAddressQR={(qr) => {
|
|
||||||
setBitcoinAddressQRCode(qr);
|
|
||||||
setShowBitcoinAddressQR(true);
|
|
||||||
}}
|
|
||||||
onShowSeedPhraseInfo={() => setShowSeedPhraseInfo(true)}
|
|
||||||
generateQRCode={generateQRCode}
|
|
||||||
// MintSelector props
|
|
||||||
activeMintUrl={activeMintUrl}
|
|
||||||
setActiveMintUrl={handleSetActiveMintSync}
|
|
||||||
mints={mints}
|
|
||||||
mintUrl={mintUrl}
|
|
||||||
setMintUrl={setMintUrl}
|
|
||||||
onAddMint={handleAddMint}
|
|
||||||
onRemoveMint={handleRemoveMintClick}
|
|
||||||
onShowDenominations={(mintUrl) => handleShowDenominations(mintUrl, setShowProofBreakdown, setProofBreakdown)}
|
|
||||||
getCleanMintLabel={getCleanMintLabel}
|
|
||||||
dropdownOpen={mintDropdownOpen}
|
|
||||||
setDropdownOpen={setMintDropdownOpen}
|
|
||||||
// UTXOSelector props
|
|
||||||
utxos={utxos}
|
|
||||||
utxoDropdownOpen={utxoDropdownOpen}
|
|
||||||
setUtxoDropdownOpen={setUtxoDropdownOpen}
|
|
||||||
onShowConsolidationModal={() => setShowConsolidationModal(true)}
|
|
||||||
isConsolidating={isConsolidating}
|
|
||||||
/>
|
|
||||||
|
|
||||||
|
|
||||||
{/* Action Buttons and Transaction History Container */}
|
{/* Action Buttons and Transaction History Container */}
|
||||||
@@ -633,7 +557,7 @@ export function CashuWallet() {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => setShowQRScanner(true)}
|
onClick={onRequestQRScanner}
|
||||||
disabled={isLoading || isNpubCashLoading}
|
disabled={isLoading || isNpubCashLoading}
|
||||||
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
className="h-20 w-20 rounded-full bg-muted transition-all duration-200 hover:scale-105 [&_svg]:size-6"
|
||||||
>
|
>
|
||||||
@@ -681,14 +605,6 @@ export function CashuWallet() {
|
|||||||
isLoading={isLoading || isNpubCashLoading}
|
isLoading={isLoading || isNpubCashLoading}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Consolidation Modal */}
|
|
||||||
<ConsolidationModal
|
|
||||||
isOpen={showConsolidationModal}
|
|
||||||
onClose={() => setShowConsolidationModal(false)}
|
|
||||||
utxos={utxos}
|
|
||||||
onConfirm={handleConsolidateUtxos}
|
|
||||||
isConsolidating={isConsolidating}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* QR Modals */}
|
{/* QR Modals */}
|
||||||
<QRModal
|
<QRModal
|
||||||
@@ -754,16 +670,6 @@ export function CashuWallet() {
|
|||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* QR Scanner Modal */}
|
|
||||||
<QRScannerModal
|
|
||||||
isOpen={showQRScanner}
|
|
||||||
onClose={async () => {
|
|
||||||
setShowQRScanner(false);
|
|
||||||
await stopScanning();
|
|
||||||
}}
|
|
||||||
qrError={qrError}
|
|
||||||
onPasteQRCode={handlePasteQRCode}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Bottom Drawer Modals */}
|
{/* Bottom Drawer Modals */}
|
||||||
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
|
<Drawer open={showSendModal} onOpenChange={handleSendDrawerClose}>
|
||||||
@@ -772,7 +678,7 @@ export function CashuWallet() {
|
|||||||
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
|
||||||
<VisuallyHidden.Root asChild>
|
<VisuallyHidden.Root asChild>
|
||||||
<DrawerDescription>
|
<DrawerDescription>
|
||||||
Send tokens, Lightning payments, or Bitcoin
|
Send tokens or Lightning payments
|
||||||
</DrawerDescription>
|
</DrawerDescription>
|
||||||
</VisuallyHidden.Root>
|
</VisuallyHidden.Root>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
@@ -800,21 +706,10 @@ export function CashuWallet() {
|
|||||||
setQuoteAmount={() => {}}
|
setQuoteAmount={() => {}}
|
||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
onSend={() => {
|
onSend={() => {
|
||||||
if (mode === 'bitcoin') {
|
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
|
||||||
handleBitcoinSend(
|
handleSend();
|
||||||
bitcoinAmount,
|
if (mode === 'tokens' || wasPendingBefore) {
|
||||||
pendingBitcoinRecipient,
|
setShowSendModal(false);
|
||||||
setBitcoinAmount,
|
|
||||||
setBitcoinRecipient,
|
|
||||||
setPendingBitcoinRecipient,
|
|
||||||
setShowSendModal
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== '';
|
|
||||||
handleSend();
|
|
||||||
if (mode === 'tokens' || wasPendingBefore) {
|
|
||||||
setShowSendModal(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onReceive={() => {}}
|
onReceive={() => {}}
|
||||||
@@ -823,18 +718,7 @@ export function CashuWallet() {
|
|||||||
setShowSendModal(false);
|
setShowSendModal(false);
|
||||||
}}
|
}}
|
||||||
isResolvingAddress={isResolvingAddress}
|
isResolvingAddress={isResolvingAddress}
|
||||||
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
isLoading={isLoading || isNpubCashLoading}
|
||||||
// Bitcoin props
|
|
||||||
bitcoinAddress={bitcoinAddress || ''}
|
|
||||||
bitcoinAmount={bitcoinAmount}
|
|
||||||
setBitcoinAmount={setBitcoinAmount}
|
|
||||||
bitcoinRecipient={bitcoinRecipient}
|
|
||||||
setBitcoinRecipient={setBitcoinRecipient}
|
|
||||||
pendingBitcoinRecipient={pendingBitcoinRecipient}
|
|
||||||
setPendingBitcoinRecipient={setPendingBitcoinRecipient}
|
|
||||||
hasNsecAccess={hasNsecAccess}
|
|
||||||
bitcoinMaxAmount={bitcoinMaxAmount}
|
|
||||||
onSendMax={() => handleSendMax(setBitcoinAmount)}
|
|
||||||
// Reverse swap props
|
// Reverse swap props
|
||||||
pendingBitcoinSwapAddress={pendingBitcoinSwapAddress}
|
pendingBitcoinSwapAddress={pendingBitcoinSwapAddress}
|
||||||
setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress}
|
setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress}
|
||||||
@@ -852,7 +736,7 @@ export function CashuWallet() {
|
|||||||
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
|
||||||
<VisuallyHidden.Root asChild>
|
<VisuallyHidden.Root asChild>
|
||||||
<DrawerDescription>
|
<DrawerDescription>
|
||||||
Receive tokens, Lightning invoices, or Bitcoin
|
Receive tokens or Lightning invoices
|
||||||
</DrawerDescription>
|
</DrawerDescription>
|
||||||
</VisuallyHidden.Root>
|
</VisuallyHidden.Root>
|
||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
@@ -881,25 +765,11 @@ export function CashuWallet() {
|
|||||||
activeMintUrl={activeMintUrl}
|
activeMintUrl={activeMintUrl}
|
||||||
onSend={() => {}}
|
onSend={() => {}}
|
||||||
onReceive={() => {
|
onReceive={() => {
|
||||||
if (mode === 'bitcoin') {
|
handleReceive();
|
||||||
handleBitcoinReceive(setBitcoinAddressQRCode, setShowBitcoinAddressQR);
|
setShowReceiveModal(false);
|
||||||
setShowReceiveModal(false);
|
|
||||||
} else {
|
|
||||||
handleReceive();
|
|
||||||
setShowReceiveModal(false);
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
isResolvingAddress={false}
|
isResolvingAddress={false}
|
||||||
isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading}
|
isLoading={isLoading || isNpubCashLoading}
|
||||||
// Bitcoin props
|
|
||||||
bitcoinAddress={bitcoinAddress || ''}
|
|
||||||
bitcoinAmount=""
|
|
||||||
setBitcoinAmount={() => {}}
|
|
||||||
bitcoinRecipient=""
|
|
||||||
setBitcoinRecipient={() => {}}
|
|
||||||
pendingBitcoinRecipient={null}
|
|
||||||
setPendingBitcoinRecipient={() => {}}
|
|
||||||
hasNsecAccess={hasNsecAccess}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
@@ -917,28 +787,17 @@ export function CashuWallet() {
|
|||||||
</DrawerHeader>
|
</DrawerHeader>
|
||||||
<ScrollArea className="h-[80vh] px-4 pb-4">
|
<ScrollArea className="h-[80vh] px-4 pb-4">
|
||||||
<TransactionHistory
|
<TransactionHistory
|
||||||
entries={mode === 'bitcoin' ? [] : historyEntries}
|
entries={historyEntries}
|
||||||
isLoading={mode === 'bitcoin' ? isBitcoinTransactionsLoading : isLoadingHistory}
|
isLoading={isLoadingHistory}
|
||||||
bitcoinTransactions={mode === 'bitcoin' ? bitcoinTransactions : []}
|
bitcoinTransactions={[]}
|
||||||
isBitcoinLoading={isBitcoinTransactionsLoading}
|
isBitcoinLoading={false}
|
||||||
showSats={showSats}
|
showSats={showSats}
|
||||||
/>
|
/>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
{/* Bitcoin Address QR Modal */}
|
|
||||||
<QRModal
|
|
||||||
isOpen={showBitcoinAddressQR}
|
|
||||||
onClose={() => setShowBitcoinAddressQR(false)}
|
|
||||||
title="Bitcoin Address"
|
|
||||||
description="Scan this QR code to send Bitcoin to your address"
|
|
||||||
qrCodeUrl={bitcoinAddressQRCode}
|
|
||||||
content={bitcoinAddress || ''}
|
|
||||||
icon="qr"
|
|
||||||
/>
|
|
||||||
</>
|
</>
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
import type { QRScanResult } from '@/hooks/useQRCode';
|
||||||
|
|
||||||
|
interface QRScannerProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => Promise<void>;
|
||||||
|
onResult: (result: QRScanResult) => void;
|
||||||
|
classifyQRCode: (text: string) => QRScanResult;
|
||||||
|
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
|
||||||
|
stopScanning: () => Promise<void>;
|
||||||
|
setModalOpen?: (isOpen: boolean) => void;
|
||||||
|
qrError: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QRScanner({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onResult,
|
||||||
|
classifyQRCode,
|
||||||
|
startScanning,
|
||||||
|
stopScanning,
|
||||||
|
setModalOpen,
|
||||||
|
qrError,
|
||||||
|
}: QRScannerProps) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Handle paste from clipboard
|
||||||
|
const handlePasteQRCode = async () => {
|
||||||
|
try {
|
||||||
|
const text = await navigator.clipboard.readText();
|
||||||
|
if (!text || !text.trim()) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Clipboard Empty",
|
||||||
|
description: "No text found in clipboard",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = classifyQRCode(text.trim());
|
||||||
|
onResult(result);
|
||||||
|
await stopScanning();
|
||||||
|
await onClose();
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Paste Failed",
|
||||||
|
description: "Could not read from clipboard",
|
||||||
|
});
|
||||||
|
console.error('Error pasting from clipboard:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Start/stop scanning based on isOpen
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
setModalOpen?.(true);
|
||||||
|
startScanning(onResult);
|
||||||
|
} else {
|
||||||
|
setModalOpen?.(false);
|
||||||
|
stopScanning();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [isOpen, startScanning, stopScanning, setModalOpen]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={isOpen} onOpenChange={async (open) => {
|
||||||
|
if (!open) {
|
||||||
|
await onClose();
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Scan QR Code</DialogTitle>
|
||||||
|
<VisuallyHidden.Root asChild>
|
||||||
|
<DialogDescription>
|
||||||
|
Position the QR code within the camera view to scan
|
||||||
|
</DialogDescription>
|
||||||
|
</VisuallyHidden.Root>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
|
||||||
|
<div
|
||||||
|
id="qr-reader"
|
||||||
|
className="w-full h-full rounded-xl overflow-hidden bg-muted"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{qrError && (
|
||||||
|
<div className="absolute inset-x-4 top-4 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50 shadow-lg">
|
||||||
|
{qrError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 flex justify-center">
|
||||||
|
<Button
|
||||||
|
onClick={handlePasteQRCode}
|
||||||
|
className="h-12 px-12 rounded-full"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
Paste
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
|
||||||
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
|
|
||||||
|
|
||||||
interface QRScannerModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => Promise<void>;
|
|
||||||
qrError: string | null;
|
|
||||||
onPasteQRCode?: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function QRScannerModal({
|
|
||||||
isOpen,
|
|
||||||
onClose,
|
|
||||||
qrError,
|
|
||||||
onPasteQRCode,
|
|
||||||
}: QRScannerModalProps) {
|
|
||||||
return (
|
|
||||||
<Dialog open={isOpen} onOpenChange={async (open) => {
|
|
||||||
if (!open) {
|
|
||||||
await onClose();
|
|
||||||
}
|
|
||||||
}}>
|
|
||||||
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Scan QR Code</DialogTitle>
|
|
||||||
<VisuallyHidden.Root asChild>
|
|
||||||
<DialogDescription>
|
|
||||||
Position the QR code within the camera view to scan
|
|
||||||
</DialogDescription>
|
|
||||||
</VisuallyHidden.Root>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
|
|
||||||
<div
|
|
||||||
id="qr-reader"
|
|
||||||
className="w-full h-full rounded-xl overflow-hidden bg-muted"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{qrError && (
|
|
||||||
<div className="absolute inset-x-4 top-4 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50 shadow-lg">
|
|
||||||
{qrError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4 flex justify-center">
|
|
||||||
<Button
|
|
||||||
onClick={async () => {
|
|
||||||
if (onPasteQRCode) {
|
|
||||||
await onPasteQRCode();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="h-12 px-12 rounded-full"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
Paste
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
import { useQRCode, type QRScanResult } from '@/hooks/useQRCode';
|
||||||
|
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||||
|
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||||
|
import { useBitcoinBalance } from '@/hooks/useBitcoinBalance';
|
||||||
|
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
||||||
|
import { WalletHeader } from './WalletHeader';
|
||||||
|
import { CashuWallet } from './CashuWallet';
|
||||||
|
import { BitcoinWallet } from './BitcoinWallet';
|
||||||
|
import { QRScanner } from './QRScanner';
|
||||||
|
import { decodeBolt11Amount } from '@/lib/bolt11Decoder';
|
||||||
|
|
||||||
|
export function WalletContainer() {
|
||||||
|
const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning');
|
||||||
|
const [showSats, setShowSats] = useState(true);
|
||||||
|
const [showQRScanner, setShowQRScanner] = useState(false);
|
||||||
|
|
||||||
|
// Shared hooks
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const { generateQRCode, classifyQRCode, startScanning, stopScanning, setModalOpen, error: qrError } = useQRCode();
|
||||||
|
const { copy: copyToClipboard } = useCopyToClipboard();
|
||||||
|
|
||||||
|
// Get balance data for WalletHeader
|
||||||
|
const { balances, mnemonic } = useCashu();
|
||||||
|
const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null;
|
||||||
|
const { data: bitcoinBalanceData } = useBitcoinBalance(bitcoinAddress);
|
||||||
|
|
||||||
|
// Calculate total balance based on mode
|
||||||
|
const totalBalance: number = mode === 'bitcoin'
|
||||||
|
? (bitcoinBalanceData?.balance || 0)
|
||||||
|
: (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
|
||||||
|
|
||||||
|
// Refs to call wallet QR handlers
|
||||||
|
const cashuWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
|
||||||
|
const bitcoinWalletQRHandlerRef = useRef<((result: QRScanResult) => void) | null>(null);
|
||||||
|
|
||||||
|
// Handle QR scanner results and route to appropriate wallet
|
||||||
|
const handleQRScanResult = async (result: QRScanResult) => {
|
||||||
|
try {
|
||||||
|
await stopScanning();
|
||||||
|
setShowQRScanner(false);
|
||||||
|
|
||||||
|
switch (result.type) {
|
||||||
|
case 'cashu_token': {
|
||||||
|
setMode('tokens');
|
||||||
|
// Call CashuWallet handler if available
|
||||||
|
if (cashuWalletQRHandlerRef.current) {
|
||||||
|
cashuWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'lightning_invoice': {
|
||||||
|
setMode('lightning');
|
||||||
|
// Call CashuWallet handler if available
|
||||||
|
if (cashuWalletQRHandlerRef.current) {
|
||||||
|
cashuWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'lightning_address': {
|
||||||
|
setMode('lightning');
|
||||||
|
// Call CashuWallet handler if available
|
||||||
|
if (cashuWalletQRHandlerRef.current) {
|
||||||
|
cashuWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'bitcoin_address': {
|
||||||
|
setMode('bitcoin');
|
||||||
|
// Call BitcoinWallet handler if available
|
||||||
|
if (bitcoinWalletQRHandlerRef.current) {
|
||||||
|
bitcoinWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'npub': {
|
||||||
|
setMode('bitcoin');
|
||||||
|
// Call BitcoinWallet handler if available
|
||||||
|
if (bitcoinWalletQRHandlerRef.current) {
|
||||||
|
bitcoinWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Unknown QR Code",
|
||||||
|
description: result.value,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error handling QR scan:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Set up refs to wallet QR handlers
|
||||||
|
useEffect(() => {
|
||||||
|
const checkHandlers = () => {
|
||||||
|
if ((window as any).__cashuWalletQRHandler) {
|
||||||
|
cashuWalletQRHandlerRef.current = (window as any).__cashuWalletQRHandler;
|
||||||
|
}
|
||||||
|
if ((window as any).__bitcoinWalletQRHandler) {
|
||||||
|
bitcoinWalletQRHandlerRef.current = (window as any).__bitcoinWalletQRHandler;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check periodically for handlers (wallets set them up asynchronously)
|
||||||
|
const interval = setInterval(checkHandlers, 100);
|
||||||
|
checkHandlers(); // Initial check
|
||||||
|
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// WalletHeader props - these will be passed from wallets via callbacks
|
||||||
|
const [walletHeaderProps, setWalletHeaderProps] = useState<{
|
||||||
|
activeMintUrl?: string | null;
|
||||||
|
mints?: Array<{ url: string; name?: string }>;
|
||||||
|
mintUrl?: string;
|
||||||
|
setMintUrl?: (url: string) => void;
|
||||||
|
onAddMint?: () => void;
|
||||||
|
onRemoveMint?: (mint: { url: string; name?: string }) => void;
|
||||||
|
onShowDenominations?: (mintUrl: string) => void;
|
||||||
|
getCleanMintLabel?: (mint: { name?: string; url: string }) => string;
|
||||||
|
mintDropdownOpen?: boolean;
|
||||||
|
setMintDropdownOpen?: (open: boolean) => void;
|
||||||
|
npubCashUsername?: string;
|
||||||
|
utxos?: Array<any>;
|
||||||
|
utxoDropdownOpen?: boolean;
|
||||||
|
setUtxoDropdownOpen?: (open: boolean) => void;
|
||||||
|
onShowConsolidationModal?: () => void;
|
||||||
|
isConsolidating?: boolean;
|
||||||
|
onShowLightningAddressQR?: (qr: string) => void;
|
||||||
|
onShowBitcoinAddressQR?: (qr: string) => void;
|
||||||
|
onShowSeedPhraseInfo?: () => void;
|
||||||
|
setActiveMintUrl?: (url: string | null) => void;
|
||||||
|
}>({});
|
||||||
|
|
||||||
|
// Memoize the callback to prevent infinite loops
|
||||||
|
const handleWalletHeaderPropsChange = useCallback((props: typeof walletHeaderProps) => {
|
||||||
|
setWalletHeaderProps(props);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="max-w-4xl mx-auto pt-16 pb-32 px-3 sm:px-4 relative">
|
||||||
|
{/* Wallet Header */}
|
||||||
|
<WalletHeader
|
||||||
|
totalBalance={totalBalance}
|
||||||
|
balances={mode === 'bitcoin' ? {} : balances}
|
||||||
|
showSats={showSats}
|
||||||
|
setShowSats={setShowSats}
|
||||||
|
mode={mode}
|
||||||
|
setMode={setMode}
|
||||||
|
userPubkey={user?.pubkey}
|
||||||
|
npubCashUsername={walletHeaderProps.npubCashUsername}
|
||||||
|
mnemonic={mode !== 'bitcoin' ? mnemonic : undefined}
|
||||||
|
onCopyToClipboard={copyToClipboard}
|
||||||
|
onShowLightningAddressQR={walletHeaderProps.onShowLightningAddressQR || (() => {})}
|
||||||
|
onShowBitcoinAddressQR={walletHeaderProps.onShowBitcoinAddressQR || (() => {})}
|
||||||
|
onShowSeedPhraseInfo={walletHeaderProps.onShowSeedPhraseInfo || (() => {})}
|
||||||
|
generateQRCode={generateQRCode}
|
||||||
|
// MintSelector props (only for tokens/lightning)
|
||||||
|
activeMintUrl={mode !== 'bitcoin' ? (walletHeaderProps.activeMintUrl ?? null) : null}
|
||||||
|
setActiveMintUrl={walletHeaderProps.setActiveMintUrl || (() => {})}
|
||||||
|
mints={mode !== 'bitcoin' ? (walletHeaderProps.mints || []) : []}
|
||||||
|
mintUrl={walletHeaderProps.mintUrl || ''}
|
||||||
|
setMintUrl={walletHeaderProps.setMintUrl || (() => {})}
|
||||||
|
onAddMint={walletHeaderProps.onAddMint || (() => {})}
|
||||||
|
onRemoveMint={walletHeaderProps.onRemoveMint || (() => {})}
|
||||||
|
onShowDenominations={walletHeaderProps.onShowDenominations || (() => {})}
|
||||||
|
getCleanMintLabel={walletHeaderProps.getCleanMintLabel || (() => '')}
|
||||||
|
dropdownOpen={walletHeaderProps.mintDropdownOpen || false}
|
||||||
|
setDropdownOpen={walletHeaderProps.setMintDropdownOpen || (() => {})}
|
||||||
|
// UTXOSelector props (only for bitcoin)
|
||||||
|
utxos={mode === 'bitcoin' ? (walletHeaderProps.utxos || []) : []}
|
||||||
|
utxoDropdownOpen={walletHeaderProps.utxoDropdownOpen || false}
|
||||||
|
setUtxoDropdownOpen={walletHeaderProps.setUtxoDropdownOpen || (() => {})}
|
||||||
|
onShowConsolidationModal={walletHeaderProps.onShowConsolidationModal}
|
||||||
|
isConsolidating={walletHeaderProps.isConsolidating}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Render appropriate wallet based on mode */}
|
||||||
|
{mode === 'tokens' || mode === 'lightning' ? (
|
||||||
|
<CashuWallet
|
||||||
|
mode={mode}
|
||||||
|
toast={toast}
|
||||||
|
generateQRCode={generateQRCode}
|
||||||
|
copyToClipboard={copyToClipboard}
|
||||||
|
user={user}
|
||||||
|
onRequestQRScanner={() => setShowQRScanner(true)}
|
||||||
|
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<BitcoinWallet
|
||||||
|
toast={toast}
|
||||||
|
generateQRCode={generateQRCode}
|
||||||
|
copyToClipboard={copyToClipboard}
|
||||||
|
user={user}
|
||||||
|
onRequestQRScanner={() => setShowQRScanner(true)}
|
||||||
|
onQRResult={(result) => {
|
||||||
|
if (bitcoinWalletQRHandlerRef.current) {
|
||||||
|
bitcoinWalletQRHandlerRef.current(result);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Shared QR Scanner */}
|
||||||
|
<QRScanner
|
||||||
|
isOpen={showQRScanner}
|
||||||
|
onClose={async () => {
|
||||||
|
await stopScanning();
|
||||||
|
setShowQRScanner(false);
|
||||||
|
}}
|
||||||
|
onResult={handleQRScanResult}
|
||||||
|
classifyQRCode={classifyQRCode}
|
||||||
|
startScanning={startScanning}
|
||||||
|
stopScanning={stopScanning}
|
||||||
|
setModalOpen={setModalOpen}
|
||||||
|
qrError={qrError}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -71,7 +71,8 @@ export function useCashu(): UseCashuReturn {
|
|||||||
if (!coco) return;
|
if (!coco) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const mintList = await coco.mint.getAllMints();
|
// Only show trusted mints in the UI
|
||||||
|
const mintList = await coco.mint.getAllTrustedMints();
|
||||||
setMints(mintList.map((m: Mint) => ({
|
setMints(mintList.map((m: Mint) => ({
|
||||||
url: m.mintUrl,
|
url: m.mintUrl,
|
||||||
name: m.name,
|
name: m.name,
|
||||||
@@ -101,7 +102,6 @@ export function useCashu(): UseCashuReturn {
|
|||||||
try {
|
try {
|
||||||
// Use singleton pattern to prevent multiple initializations
|
// Use singleton pattern to prevent multiple initializations
|
||||||
if (globalCocoInstance && globalRepositories) {
|
if (globalCocoInstance && globalRepositories) {
|
||||||
console.log('Using existing coco instance (singleton)');
|
|
||||||
cocoRef.current = globalCocoInstance;
|
cocoRef.current = globalCocoInstance;
|
||||||
repositoriesRef.current = globalRepositories;
|
repositoriesRef.current = globalRepositories;
|
||||||
setIsInitialized(true);
|
setIsInitialized(true);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useCallback, useEffect } from 'react';
|
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
import { getCleanMintLabel } from './walletUtils';
|
import { getCleanMintLabel } from './walletUtils';
|
||||||
import type { Manager, Repositories } from 'coco-cashu-core';
|
import type { Manager, Repositories } from 'coco-cashu-core';
|
||||||
import { toast } from '@/hooks/useToast';
|
import { toast } from '@/hooks/useToast';
|
||||||
@@ -30,6 +30,7 @@ export function useMintManager({
|
|||||||
const [mintUrl, setMintUrl] = useState('');
|
const [mintUrl, setMintUrl] = useState('');
|
||||||
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
|
const [mintToRemove, setMintToRemove] = useState<CashuMint | null>(null);
|
||||||
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
|
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
|
||||||
|
const isAddingDefaultMintRef = useRef(false);
|
||||||
|
|
||||||
// Set active mint and optionally sync to npub.cash
|
// Set active mint and optionally sync to npub.cash
|
||||||
const handleSetActiveMint = useCallback(
|
const handleSetActiveMint = useCallback(
|
||||||
@@ -75,12 +76,13 @@ export function useMintManager({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await coco.mint.addMint(normalizedUrl);
|
// Add mint and automatically trust it
|
||||||
|
await coco.mint.addMint(normalizedUrl, { trusted: true });
|
||||||
setMintUrl('');
|
setMintUrl('');
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: 'Mint Added',
|
title: 'Mint Added',
|
||||||
description: 'Mint added successfully!',
|
description: 'Mint added and trusted successfully!',
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast({
|
toast({
|
||||||
@@ -209,14 +211,32 @@ export function useMintManager({
|
|||||||
// Select first mint initially - user can change via dropdown
|
// Select first mint initially - user can change via dropdown
|
||||||
// Don't sync to npub.cash on auto-select, only on manual changes
|
// Don't sync to npub.cash on auto-select, only on manual changes
|
||||||
handleSetActiveMint(mints[0].url, false);
|
handleSetActiveMint(mints[0].url, false);
|
||||||
} else if (mints.length === 0 && !activeMintUrl && coco) {
|
} else if (mints.length === 0 && !activeMintUrl && coco && !isAddingDefaultMintRef.current) {
|
||||||
// Add default mint if no mints exist
|
// Add default mint if no mints exist
|
||||||
|
// Use ref guard to prevent multiple simultaneous additions
|
||||||
|
isAddingDefaultMintRef.current = true;
|
||||||
const addDefaultMint = async () => {
|
const addDefaultMint = async () => {
|
||||||
try {
|
try {
|
||||||
await coco.mint.addMint('https://mint.chorus.community');
|
const defaultMintUrl = 'https://mint.chorus.community';
|
||||||
|
|
||||||
|
// Check if mint already exists (check trusted mints since that's what we display)
|
||||||
|
const trustedMints = await coco.mint.getAllTrustedMints();
|
||||||
|
const mintExists = trustedMints.some((mint: { mintUrl: string }) =>
|
||||||
|
mint.mintUrl.toLowerCase() === defaultMintUrl.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!mintExists) {
|
||||||
|
// Add default mint and automatically trust it
|
||||||
|
await coco.mint.addMint(defaultMintUrl, { trusted: true });
|
||||||
// The mint will be added and refreshMints will be called via event listeners
|
// The mint will be added and refreshMints will be called via event listeners
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to add default mint:', err);
|
console.error('Failed to add default mint:', err);
|
||||||
|
} finally {
|
||||||
|
// Reset the guard after a short delay to allow mints to update
|
||||||
|
setTimeout(() => {
|
||||||
|
isAddingDefaultMintRef.current = false;
|
||||||
|
}, 1000);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
addDefaultMint();
|
addDefaultMint();
|
||||||
|
|||||||
@@ -47,8 +47,20 @@ export function useTokenOperations({
|
|||||||
try {
|
try {
|
||||||
console.log('Adding unknown mint:', mintUrl);
|
console.log('Adding unknown mint:', mintUrl);
|
||||||
|
|
||||||
// Add the mint
|
// Check if mint exists (known) by checking all mints
|
||||||
await coco.mint.addMint(mintUrl);
|
const allMints = await coco.mint.getAllMints();
|
||||||
|
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
|
||||||
|
|
||||||
|
if (isKnown) {
|
||||||
|
// Mint exists but may not be trusted, ensure it's trusted
|
||||||
|
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
|
||||||
|
if (!isTrusted) {
|
||||||
|
await coco.mint.trustMint(mintUrl);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Add the mint and automatically trust it (user is explicitly receiving from it)
|
||||||
|
await coco.mint.addMint(mintUrl, { trusted: true });
|
||||||
|
}
|
||||||
|
|
||||||
// Retry receiving the token
|
// Retry receiving the token
|
||||||
await coco.wallet.receive(tokenInput);
|
await coco.wallet.receive(tokenInput);
|
||||||
|
|||||||
@@ -138,10 +138,18 @@ export function useNpubCash() {
|
|||||||
// Process each mint's quotes
|
// Process each mint's quotes
|
||||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||||
try {
|
try {
|
||||||
// Check if mint exists, add if not
|
// Check if mint exists (known) by checking all mints
|
||||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
const allMints = await coco.mint.getAllMints();
|
||||||
|
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
|
||||||
|
|
||||||
if (!isKnown) {
|
if (!isKnown) {
|
||||||
await coco.mint.addMint(mintUrl);
|
await coco.mint.addMint(mintUrl, { trusted: true });
|
||||||
|
} else {
|
||||||
|
// Mint exists, ensure it's trusted
|
||||||
|
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
|
||||||
|
if (!isTrusted) {
|
||||||
|
await coco.mint.trustMint(mintUrl);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add quotes to the wallet (matching main.ts format)
|
// Add quotes to the wallet (matching main.ts format)
|
||||||
@@ -203,9 +211,18 @@ export function useNpubCash() {
|
|||||||
let addedQuotes = 0;
|
let addedQuotes = 0;
|
||||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||||
try {
|
try {
|
||||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
// Check if mint exists (known) by checking all mints
|
||||||
|
const allMints = await coco.mint.getAllMints();
|
||||||
|
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
|
||||||
|
|
||||||
if (!isKnown) {
|
if (!isKnown) {
|
||||||
await coco.mint.addMint(mintUrl);
|
await coco.mint.addMint(mintUrl, { trusted: true });
|
||||||
|
} else {
|
||||||
|
// Mint exists, ensure it's trusted
|
||||||
|
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
|
||||||
|
if (!isTrusted) {
|
||||||
|
await coco.mint.trustMint(mintUrl);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
coco.quotes.addMintQuote(
|
coco.quotes.addMintQuote(
|
||||||
@@ -250,9 +267,18 @@ export function useNpubCash() {
|
|||||||
|
|
||||||
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
|
||||||
try {
|
try {
|
||||||
const isKnown = await coco.mint.isKnownMint(mintUrl);
|
// Check if mint exists (known) by checking all mints
|
||||||
|
const allMints = await coco.mint.getAllMints();
|
||||||
|
const isKnown = allMints.some(m => m.mintUrl.toLowerCase() === mintUrl.toLowerCase());
|
||||||
|
|
||||||
if (!isKnown) {
|
if (!isKnown) {
|
||||||
await coco.mint.addMint(mintUrl);
|
await coco.mint.addMint(mintUrl, { trusted: true });
|
||||||
|
} else {
|
||||||
|
// Mint exists, ensure it's trusted
|
||||||
|
const isTrusted = await coco.mint.isTrustedMint(mintUrl);
|
||||||
|
if (!isTrusted) {
|
||||||
|
await coco.mint.trustMint(mintUrl);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
coco.quotes.addMintQuote(
|
coco.quotes.addMintQuote(
|
||||||
|
|||||||
Reference in new issue
Block a user