implement mint removal

This commit is contained in:
lemonknowsall committed 2025-10-15 23:12:01 -07:00
1 parent 73c68f2655
commit 77803dda38
4 files changed
+118 -30

No files matched your search

+6 -1
View File
@@ -36,6 +36,9 @@ interface BalanceDisplayProps {
// Refresh functionality
onRefreshQuotes: () => Promise<void>;
isRefreshingQuotes: boolean;
// Dropdown state
mintDropdownOpen: boolean;
setMintDropdownOpen: (open: boolean) => void;
}
export function BalanceDisplay({
@@ -61,6 +64,8 @@ export function BalanceDisplay({
generateQRCode,
onRefreshQuotes,
isRefreshingQuotes,
mintDropdownOpen,
setMintDropdownOpen,
}: BalanceDisplayProps) {
const [lightningAddressCopied, setLightningAddressCopied] = useState(false);
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
@@ -133,7 +138,7 @@ export function BalanceDisplay({
{/* Active Mint Dropdown and Balance */}
<div className="mt-3 flex items-center justify-center gap-4">
<DropdownMenu>
<DropdownMenu open={mintDropdownOpen} onOpenChange={setMintDropdownOpen}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2 text-muted-foreground hover:text-foreground">
<Wallet className="h-4 w-4" />
+93 -12
View File
@@ -32,6 +32,7 @@ export function CashuWallet() {
mints,
getEncodedToken,
clearError,
refreshMints,
} = useCashu();
// Npub.cash integration with cleaner SDK-based implementation
@@ -72,6 +73,7 @@ export function CashuWallet() {
const [showSats, setShowSats] = useState(true);
const [mode, setMode] = useState<'tokens' | 'lightning'>('tokens');
const [activeMintUrl, setActiveMintUrl] = useState<string | null>(null);
const [mintDropdownOpen, setMintDropdownOpen] = useState(false);
// ============================================================================
// STATE - Transaction State
@@ -272,6 +274,50 @@ export function CashuWallet() {
}
}, [coco]);
// ============================================================================
// HELPER FUNCTIONS - Unknown Mint Error Handling
// ============================================================================
const isUnknownMintError = (err: unknown): boolean => {
const errorMessage = (err as any)?.message || err?.toString() || '';
return (err as any)?.constructor?.name === 'UnknownMintError' ||
errorMessage.includes('UnknownMintError') ||
(errorMessage.includes('Mint') && errorMessage.includes('is not known'));
};
const extractMintUrlFromError = (err: unknown): string | null => {
const errorMessage = (err as any)?.message || err?.toString() || '';
const mintUrlMatch = errorMessage.match(/Mint (https?:\/\/[^\s]+)/);
return mintUrlMatch?.[1] || null;
};
const handleUnknownMintError = async (mintUrl: string) => {
if (!coco) return;
try {
console.log('Adding unknown mint:', mintUrl);
// Add the mint
await coco.mint.addMint(mintUrl);
// Retry receiving the token
await coco.wallet.receive(tokenInput);
setTokenInput('');
toast({
title: "Token Received",
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
});
} catch (retryErr) {
console.error('Failed to add mint and retry receive:', retryErr);
toast({
variant: "destructive",
title: "Receive Failed",
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
});
}
};
// ============================================================================
// EVENT HANDLERS - Receive
// ============================================================================
@@ -291,6 +337,16 @@ export function CashuWallet() {
});
} catch (err) {
console.error('Token receive error:', err);
// Handle UnknownMintError by automatically adding the mint
if (isUnknownMintError(err)) {
const mintUrl = extractMintUrlFromError(err);
if (mintUrl) {
await handleUnknownMintError(mintUrl);
return;
}
}
toast({
variant: "destructive",
title: "Receive Failed",
@@ -485,24 +541,47 @@ export function CashuWallet() {
const handleRemoveMintClick = useCallback((mint: { url: string; name?: string }) => {
setMintDropdownOpen(false); // Close dropdown before showing modal
setMintToRemove(mint);
setShowRemoveMintModal(true);
}, []);
const handleConfirmRemoveMint = useCallback(async () => {
if (!mintToRemove) return;
if (!mintToRemove || !repositories) return;
// Note: Mint deletion is not available in the current coco-cashu-core API
// This would require direct repository access which is not exposed
toast({
variant: "destructive",
title: "Mint Removal Not Supported",
description: "Mint removal is not currently supported in this version of coco-cashu-core",
});
setShowRemoveMintModal(false);
setMintToRemove(null);
}, [mintToRemove, toast]);
try {
// Delete the mint from the backend using the mint repository directly
await repositories.mintRepository.deleteMint(mintToRemove.url);
// If the removed mint was active, switch to the first available mint
if (activeMintUrl === mintToRemove.url) {
const remainingMints = mints.filter(mint => mint.url !== mintToRemove.url);
if (remainingMints.length > 0) {
handleSetActiveMint(remainingMints[0].url, false);
} else {
setActiveMintUrl(null);
}
}
toast({
title: "Mint Removed",
description: `${mintToRemove.name || mintToRemove.url} has been permanently removed`,
});
// Refresh the mints list to update the dropdown immediately
await refreshMints();
setShowRemoveMintModal(false);
setMintToRemove(null);
} catch (err) {
console.error('Failed to remove mint:', err);
toast({
variant: "destructive",
title: "Remove Mint Failed",
description: err instanceof Error ? err.message : 'Unknown error',
});
}
}, [mintToRemove, mints, activeMintUrl, handleSetActiveMint, repositories, toast, refreshMints]);
// ============================================================================
// EVENT HANDLERS - Mint Management
@@ -750,6 +829,8 @@ export function CashuWallet() {
generateQRCode={generateQRCode}
onRefreshQuotes={handleRefreshQuotes}
isRefreshingQuotes={isNpubCashLoading}
mintDropdownOpen={mintDropdownOpen}
setMintDropdownOpen={setMintDropdownOpen}
/>
{/* ========================================================================
@@ -41,9 +41,6 @@ export function RemoveMintModal({ isOpen, onClose, mint, onConfirm, isLoading }:
<CardContent className="space-y-4">
<div className="bg-muted p-4 rounded-lg border">
<div className="font-medium">{mint.name || new URL(mint.url).hostname}</div>
<div className="text-sm text-muted-foreground font-mono break-all">
{mint.url}
</div>
</div>
<div className="text-sm text-muted-foreground bg-muted/30 p-3 rounded space-y-2">
+19 -14
View File
@@ -38,6 +38,7 @@ export interface UseCashuReturn {
// Utility functions
clearError: () => void;
getEncodedToken: typeof getEncodedToken;
refreshMints: () => Promise<void>;
}
export function useCashu(): UseCashuReturn {
@@ -64,6 +65,22 @@ export function useCashu(): UseCashuReturn {
return bip39.generateMnemonic(wordlist);
}, []);
const refreshMints = useCallback(async () => {
const coco = cocoRef.current;
if (!coco) return;
try {
const mintList = await coco.mint.getAllMints();
setMints(mintList.map((m: any) => ({
url: m.mintUrl,
name: m.name,
info: m.mintInfo
})));
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
const setMnemonic = useCallback((newMnemonic: string) => {
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
throw new Error('Invalid mnemonic');
@@ -184,19 +201,6 @@ export function useCashu(): UseCashuReturn {
}
};
const refreshMints = async () => {
try {
const mintList = await coco.mint.getAllMints();
setMints(mintList.map((m: any) => ({
url: m.mintUrl,
name: m.name,
info: m.mintInfo
})));
} catch (err) {
// Silent failure - errors are handled by the manager
}
};
// Initial load
refreshBalances();
refreshMints();
@@ -212,7 +216,7 @@ export function useCashu(): UseCashuReturn {
];
return () => unsubs.forEach(unsub => unsub());
}, [isInitialized]);
}, [isInitialized, refreshMints]);
// Calculate total balance
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
@@ -242,5 +246,6 @@ export function useCashu(): UseCashuReturn {
// Utility functions
clearError,
getEncodedToken,
refreshMints,
};
}