(null);
- const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false);
- const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState('');
const [showSeedPhraseInfo, setShowSeedPhraseInfo] = useState(false);
- const [showConsolidationModal, setShowConsolidationModal] = useState(false);
-
- // UTXO state
- const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
// Handle drawer close with state reset
@@ -292,10 +261,6 @@ export function CashuWallet() {
// Reset reverse swap state
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
- // Reset Bitcoin state
- setBitcoinAmount('');
- setBitcoinRecipient('');
- setPendingBitcoinRecipient(null);
}
};
@@ -315,9 +280,7 @@ export function CashuWallet() {
// COMPUTED VALUES
// ============================================================================
- const totalBalance: number = mode === 'bitcoin'
- ? (bitcoinBalanceData?.balance || 0)
- : (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
+ const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0);
// ============================================================================
// EFFECTS - Error Handling
@@ -371,7 +334,20 @@ export function CashuWallet() {
if (!mintExists && coco) {
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);
} catch {
// Silent failure - user can manually add mint if needed
@@ -404,27 +380,6 @@ export function CashuWallet() {
};
}, [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
useEffect(() => {
@@ -450,170 +405,139 @@ export function CashuWallet() {
};
}, [mintQuoteUnsubscribeRef]);
- // Handle QR scanner results
- const handleQRScanResult = async (result: QRScanResult) => {
- try {
- await stopScanning();
- setShowQRScanner(false);
-
- switch (result.type) {
- case 'lightning_invoice': {
- setMode('lightning');
- setLightningInvoice(result.value);
- 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()) {
+ // Handle QR scan results (called from parent WalletContainer)
+ const handleQRResult = (result: QRScanResult) => {
+ switch (result.type) {
+ case 'lightning_invoice': {
+ setLightningInvoice(result.value);
+ setPendingInvoice(result.value);
+ // Decode invoice amount
+ const amount = decodeBolt11Amount(result.value);
+ setDecodedInvoiceAmount(amount);
+ setShowSendModal(true);
toast({
- variant: "destructive",
- title: "Clipboard Empty",
- description: "No text found in clipboard",
+ title: "Lightning Invoice Scanned",
+ description: amount ? `${amount} sats` : "Invoice ready to pay",
});
- 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
// ============================================================================
+ // 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 (
<>
-
-
- {/* Wallet Header (includes mode toggle, login icon, balance, lightning address, and mint selector) */}
- {
- 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 */}
@@ -633,7 +557,7 @@ export function CashuWallet() {
@@ -917,28 +787,17 @@ export function CashuWallet() {
- {/* Bitcoin Address QR Modal */}
- setShowBitcoinAddressQR(false)}
- title="Bitcoin Address"
- description="Scan this QR code to send Bitcoin to your address"
- qrCodeUrl={bitcoinAddressQRCode}
- content={bitcoinAddress || ''}
- icon="qr"
- />
>
-
>
);
}
diff --git a/src/components/wallet/QRScanner.tsx b/src/components/wallet/QRScanner.tsx
new file mode 100644
index 0000000..5d0a4a9
--- /dev/null
+++ b/src/components/wallet/QRScanner.tsx
@@ -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;
+ onResult: (result: QRScanResult) => void;
+ classifyQRCode: (text: string) => QRScanResult;
+ startScanning: (onResult: (result: QRScanResult) => void) => Promise;
+ stopScanning: () => Promise;
+ 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 (
+
+ );
+}
+
diff --git a/src/components/wallet/QRScannerModal.tsx b/src/components/wallet/QRScannerModal.tsx
deleted file mode 100644
index 0a99d62..0000000
--- a/src/components/wallet/QRScannerModal.tsx
+++ /dev/null
@@ -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;
- qrError: string | null;
- onPasteQRCode?: () => Promise;
-}
-
-export function QRScannerModal({
- isOpen,
- onClose,
- qrError,
- onPasteQRCode,
-}: QRScannerModalProps) {
- return (
-
- );
-}
diff --git a/src/components/wallet/WalletContainer.tsx b/src/components/wallet/WalletContainer.tsx
new file mode 100644
index 0000000..cf69d59
--- /dev/null
+++ b/src/components/wallet/WalletContainer.tsx
@@ -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;
+ 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 (
+ <>
+
+ {/* Wallet Header */}
+ {})}
+ 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' ? (
+ setShowQRScanner(true)}
+ onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
+ />
+ ) : (
+ setShowQRScanner(true)}
+ onQRResult={(result) => {
+ if (bitcoinWalletQRHandlerRef.current) {
+ bitcoinWalletQRHandlerRef.current(result);
+ }
+ }}
+ onWalletHeaderPropsChange={handleWalletHeaderPropsChange}
+ />
+ )}
+
+
+ {/* Shared QR Scanner */}
+ {
+ await stopScanning();
+ setShowQRScanner(false);
+ }}
+ onResult={handleQRScanResult}
+ classifyQRCode={classifyQRCode}
+ startScanning={startScanning}
+ stopScanning={stopScanning}
+ setModalOpen={setModalOpen}
+ qrError={qrError}
+ />
+ >
+ );
+}
+
diff --git a/src/hooks/cashu/useCashu.ts b/src/hooks/cashu/useCashu.ts
index e9a147f..a1c1fcb 100644
--- a/src/hooks/cashu/useCashu.ts
+++ b/src/hooks/cashu/useCashu.ts
@@ -71,7 +71,8 @@ export function useCashu(): UseCashuReturn {
if (!coco) return;
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) => ({
url: m.mintUrl,
name: m.name,
@@ -101,7 +102,6 @@ export function useCashu(): UseCashuReturn {
try {
// Use singleton pattern to prevent multiple initializations
if (globalCocoInstance && globalRepositories) {
- console.log('Using existing coco instance (singleton)');
cocoRef.current = globalCocoInstance;
repositoriesRef.current = globalRepositories;
setIsInitialized(true);
diff --git a/src/hooks/cashu/useMintManager.ts b/src/hooks/cashu/useMintManager.ts
index 0895c95..f0015a7 100644
--- a/src/hooks/cashu/useMintManager.ts
+++ b/src/hooks/cashu/useMintManager.ts
@@ -1,4 +1,4 @@
-import { useState, useCallback, useEffect } from 'react';
+import { useState, useCallback, useEffect, useRef } from 'react';
import { getCleanMintLabel } from './walletUtils';
import type { Manager, Repositories } from 'coco-cashu-core';
import { toast } from '@/hooks/useToast';
@@ -30,6 +30,7 @@ export function useMintManager({
const [mintUrl, setMintUrl] = useState('');
const [mintToRemove, setMintToRemove] = useState(null);
const [showRemoveMintModal, setShowRemoveMintModal] = useState(false);
+ const isAddingDefaultMintRef = useRef(false);
// Set active mint and optionally sync to npub.cash
const handleSetActiveMint = useCallback(
@@ -75,12 +76,13 @@ export function useMintManager({
return;
}
- await coco.mint.addMint(normalizedUrl);
+ // Add mint and automatically trust it
+ await coco.mint.addMint(normalizedUrl, { trusted: true });
setMintUrl('');
toast({
title: 'Mint Added',
- description: 'Mint added successfully!',
+ description: 'Mint added and trusted successfully!',
});
} catch (err) {
toast({
@@ -209,14 +211,32 @@ export function useMintManager({
// Select first mint initially - user can change via dropdown
// Don't sync to npub.cash on auto-select, only on manual changes
handleSetActiveMint(mints[0].url, false);
- } else if (mints.length === 0 && !activeMintUrl && coco) {
+ } else if (mints.length === 0 && !activeMintUrl && coco && !isAddingDefaultMintRef.current) {
// Add default mint if no mints exist
+ // Use ref guard to prevent multiple simultaneous additions
+ isAddingDefaultMintRef.current = true;
const addDefaultMint = async () => {
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
+ }
} catch (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();
diff --git a/src/hooks/cashu/useTokenOperations.ts b/src/hooks/cashu/useTokenOperations.ts
index bdf4bd2..d93fe55 100644
--- a/src/hooks/cashu/useTokenOperations.ts
+++ b/src/hooks/cashu/useTokenOperations.ts
@@ -47,8 +47,20 @@ export function useTokenOperations({
try {
console.log('Adding unknown mint:', mintUrl);
- // Add the mint
- await coco.mint.addMint(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) {
+ // 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
await coco.wallet.receive(tokenInput);
diff --git a/src/hooks/useNpubCash.ts b/src/hooks/useNpubCash.ts
index ad96a01..97879aa 100644
--- a/src/hooks/useNpubCash.ts
+++ b/src/hooks/useNpubCash.ts
@@ -138,10 +138,18 @@ export function useNpubCash() {
// Process each mint's quotes
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
try {
- // Check if mint exists, add if not
- 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) {
- 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)
@@ -203,9 +211,18 @@ export function useNpubCash() {
let addedQuotes = 0;
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
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) {
- 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(
@@ -250,9 +267,18 @@ export function useNpubCash() {
for (const [mintUrl, mintQuotes] of Object.entries(quotesByMint)) {
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) {
- 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(