mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
code cleanup round 2
This commit is contained in:
1 parent
aaf12120e6
commit
2ac097d8de
9 files changed
+325
-668
No files matched your search
@@ -1,11 +1,11 @@
|
|||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
import { Loader2 } from 'lucide-react';
|
import { Loader2 } from 'lucide-react';
|
||||||
|
|
||||||
interface LoadingModalProps {
|
interface LoadingScreenProps {
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LoadingModal({ isLoading }: LoadingModalProps) {
|
export function LoadingScreen({ isLoading }: LoadingScreenProps) {
|
||||||
if (!isLoading) return null;
|
if (!isLoading) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -13,7 +13,6 @@ export function LoadingModal({ isLoading }: LoadingModalProps) {
|
|||||||
<Card className="border-0 shadow-lg bg-background">
|
<Card className="border-0 shadow-lg bg-background">
|
||||||
<CardContent className="flex items-center justify-center p-8">
|
<CardContent className="flex items-center justify-center p-8">
|
||||||
<Loader2 className="h-8 w-8 animate-spin mr-3" />
|
<Loader2 className="h-8 w-8 animate-spin mr-3" />
|
||||||
<span className="text-lg font-medium">Loading</span>
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
@@ -188,30 +188,30 @@ export function BalanceDisplay({
|
|||||||
<HelpCircle className="h-4 w-4" />
|
<HelpCircle className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
<DialogContent className="max-w-md">
|
<DialogContent className="max-w-md" aria-describedby="mint-description">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
<Wallet className="h-5 w-5" />
|
<Wallet className="h-5 w-5" />
|
||||||
What is a Mint?
|
What is a Mint?
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="space-y-3 text-left">
|
|
||||||
<p>
|
|
||||||
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong>Key features:</strong>
|
|
||||||
</p>
|
|
||||||
<ul className="list-disc list-inside space-y-1 ml-4">
|
|
||||||
<li>Issues tokens when you deposit Lightning payments</li>
|
|
||||||
<li>Redeems tokens when you receive them</li>
|
|
||||||
<li>Manages your token balance</li>
|
|
||||||
<li>Enables Lightning ↔ Cashu conversions</li>
|
|
||||||
</ul>
|
|
||||||
<p>
|
|
||||||
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
|
|
||||||
</p>
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
<div id="mint-description" className="space-y-3 text-left text-sm text-muted-foreground">
|
||||||
|
<p>
|
||||||
|
A <strong>mint</strong> is a server that issues and manages Cashu tokens. Think of it like a bank for digital cash.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Key features:</strong>
|
||||||
|
</p>
|
||||||
|
<ul className="list-disc list-inside space-y-1 ml-4">
|
||||||
|
<li>Issues tokens when you deposit Lightning payments</li>
|
||||||
|
<li>Redeems tokens when you receive them</li>
|
||||||
|
<li>Manages your token balance</li>
|
||||||
|
<li>Enables Lightning ↔ Cashu conversions</li>
|
||||||
|
</ul>
|
||||||
|
<p>
|
||||||
|
<strong>Note:</strong> Each mint maintains its own separate balance. You can add multiple mints to diversify your holdings and swap balances between them.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { useCashu, type HistoryEntry } from '@/hooks/cashu/useCashu';
|
import { useCashu } from '@/hooks/cashu/useCashu';
|
||||||
|
import type { HistoryEntry } from 'coco-cashu-core';
|
||||||
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 { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
@@ -8,7 +9,6 @@ import { useToast } from '@/hooks/useToast';
|
|||||||
import { useQRCode } from '@/hooks/useQRCode';
|
import { useQRCode } from '@/hooks/useQRCode';
|
||||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||||
import { QRModal } from '@/components/ui/qr-modal';
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { LoadingModal } from './LoadingModal';
|
|
||||||
import { BalanceDisplay } from './BalanceDisplay';
|
import { BalanceDisplay } from './BalanceDisplay';
|
||||||
import { ReceiveCard } from './ReceiveCard';
|
import { ReceiveCard } from './ReceiveCard';
|
||||||
import { SendCard } from './SendCard';
|
import { SendCard } from './SendCard';
|
||||||
@@ -23,26 +23,15 @@ export function CashuWallet() {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
coco,
|
||||||
|
repositories,
|
||||||
isInitialized,
|
isInitialized,
|
||||||
isLoading,
|
isLoading,
|
||||||
error,
|
error,
|
||||||
balances,
|
balances,
|
||||||
mints,
|
mints,
|
||||||
receive,
|
getEncodedToken,
|
||||||
send,
|
|
||||||
getProofs,
|
|
||||||
addMint,
|
|
||||||
removeMint,
|
|
||||||
createMintQuote,
|
|
||||||
createMeltQuote,
|
|
||||||
payMeltQuote,
|
|
||||||
redeemMintQuote,
|
|
||||||
addMintQuote,
|
|
||||||
on,
|
|
||||||
refreshBalances,
|
|
||||||
refreshMints,
|
|
||||||
clearError,
|
clearError,
|
||||||
getHistory,
|
|
||||||
} = useCashu();
|
} = useCashu();
|
||||||
|
|
||||||
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
|
const { setMint: setNpubCashMint, getUserInfo: getNpubCashUserInfo, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
|
||||||
@@ -188,32 +177,38 @@ export function CashuWallet() {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const loadHistory = useCallback(async () => {
|
const loadHistory = useCallback(async () => {
|
||||||
|
if (!coco) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setIsLoadingHistory(true);
|
setIsLoadingHistory(true);
|
||||||
const entries = await getHistory(50, 0); //TODO: show entire history
|
const entries = await coco.history.getPaginatedHistory(0, 50); //TODO: show entire history
|
||||||
setHistoryEntries(entries);
|
setHistoryEntries(entries);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load history:', err);
|
console.error('Failed to load history:', err);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingHistory(false);
|
setIsLoadingHistory(false);
|
||||||
}
|
}
|
||||||
}, [getHistory]);
|
}, [coco]);
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// EVENT HANDLERS - Receive
|
// EVENT HANDLERS - Receive
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const handleReceive = async () => {
|
const handleReceive = async () => {
|
||||||
|
if (!coco) return;
|
||||||
|
|
||||||
if (mode === 'tokens') {
|
if (mode === 'tokens') {
|
||||||
if (!tokenInput.trim()) return;
|
if (!tokenInput.trim()) return;
|
||||||
try {
|
try {
|
||||||
await receive(tokenInput);
|
console.log('Attempting to receive token:', tokenInput.substring(0, 20) + '...');
|
||||||
|
await coco.wallet.receive(tokenInput);
|
||||||
setTokenInput('');
|
setTokenInput('');
|
||||||
toast({
|
toast({
|
||||||
title: "Token Received",
|
title: "Token Received",
|
||||||
description: "Cashu token redeemed successfully!",
|
description: "Cashu token redeemed successfully!",
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('Token receive error:', err);
|
||||||
toast({
|
toast({
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
title: "Receive Failed",
|
title: "Receive Failed",
|
||||||
@@ -233,7 +228,7 @@ export function CashuWallet() {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const quote = await createMintQuote(activeMintUrl, amount);
|
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
|
||||||
|
|
||||||
// Generate QR code for the Lightning invoice
|
// Generate QR code for the Lightning invoice
|
||||||
const qrCodeUrl = await generateQRCode(quote.request);
|
const qrCodeUrl = await generateQRCode(quote.request);
|
||||||
@@ -265,7 +260,7 @@ export function CashuWallet() {
|
|||||||
const quoteId = quote.quote;
|
const quoteId = quote.quote;
|
||||||
const invoiceAmount = amount;
|
const invoiceAmount = amount;
|
||||||
|
|
||||||
const unsubscribe = on('mint-quote:redeemed', (payload: unknown) => {
|
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
|
||||||
const redeemedQuote = payload as { quoteId?: string };
|
const redeemedQuote = payload as { quoteId?: string };
|
||||||
|
|
||||||
// Check if this is the quote we're waiting for
|
// Check if this is the quote we're waiting for
|
||||||
@@ -300,6 +295,8 @@ export function CashuWallet() {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const handleSend = async () => {
|
const handleSend = async () => {
|
||||||
|
if (!coco) return;
|
||||||
|
|
||||||
if (mode === 'tokens') {
|
if (mode === 'tokens') {
|
||||||
if (!sendAmount || !activeMintUrl) return;
|
if (!sendAmount || !activeMintUrl) return;
|
||||||
try {
|
try {
|
||||||
@@ -312,7 +309,8 @@ export function CashuWallet() {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const encodedToken = await send(activeMintUrl, amount);
|
const token = await coco.wallet.send(activeMintUrl, amount);
|
||||||
|
const encodedToken = getEncodedToken(token);
|
||||||
setSentToken(encodedToken);
|
setSentToken(encodedToken);
|
||||||
await generateSentTokenQRCode(encodedToken);
|
await generateSentTokenQRCode(encodedToken);
|
||||||
setSendAmount('');
|
setSendAmount('');
|
||||||
@@ -348,8 +346,8 @@ export function CashuWallet() {
|
|||||||
amountSats: amount,
|
amountSats: amount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const meltQuote = await createMeltQuote(activeMintUrl, invoice);
|
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, invoice);
|
||||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Payment Sent",
|
title: "Payment Sent",
|
||||||
@@ -379,8 +377,8 @@ export function CashuWallet() {
|
|||||||
} else {
|
} else {
|
||||||
// It's a regular Lightning invoice
|
// It's a regular Lightning invoice
|
||||||
try {
|
try {
|
||||||
const meltQuote = await createMeltQuote(activeMintUrl, input);
|
const meltQuote = await coco.quotes.createMeltQuote(activeMintUrl, input);
|
||||||
await payMeltQuote(activeMintUrl, meltQuote.quote);
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: "Invoice Paid",
|
title: "Invoice Paid",
|
||||||
@@ -412,44 +410,24 @@ export function CashuWallet() {
|
|||||||
const handleConfirmRemoveMint = useCallback(async () => {
|
const handleConfirmRemoveMint = useCallback(async () => {
|
||||||
if (!mintToRemove) return;
|
if (!mintToRemove) return;
|
||||||
|
|
||||||
try {
|
// Note: Mint deletion is not available in the current coco-cashu-core API
|
||||||
await removeMint(mintToRemove.url);
|
// 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",
|
||||||
|
});
|
||||||
|
|
||||||
// Manually refresh mints since there's no mint:removed event
|
setShowRemoveMintModal(false);
|
||||||
await refreshMints();
|
setMintToRemove(null);
|
||||||
|
}, [mintToRemove, toast]);
|
||||||
// If the removed mint was the active mint, select the first available mint
|
|
||||||
if (activeMintUrl === mintToRemove.url) {
|
|
||||||
const remainingMints = mints.filter(m => m.url !== mintToRemove.url);
|
|
||||||
if (remainingMints.length > 0) {
|
|
||||||
setActiveMintUrl(remainingMints[0].url);
|
|
||||||
} else {
|
|
||||||
setActiveMintUrl(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Mint Removed",
|
|
||||||
description: `${mintToRemove.name || new URL(mintToRemove.url).hostname} has been removed from your wallet`,
|
|
||||||
});
|
|
||||||
|
|
||||||
setShowRemoveMintModal(false);
|
|
||||||
setMintToRemove(null);
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: "Remove Failed",
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [mintToRemove, removeMint, refreshMints, activeMintUrl, mints, toast]);
|
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// EVENT HANDLERS - Mint Management
|
// EVENT HANDLERS - Mint Management
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const handleAddMint = async () => {
|
const handleAddMint = async () => {
|
||||||
if (!mintUrl.trim()) return;
|
if (!mintUrl.trim() || !coco) return;
|
||||||
try {
|
try {
|
||||||
// Normalize URL - add https:// if not present
|
// Normalize URL - add https:// if not present
|
||||||
let normalizedUrl = mintUrl.trim();
|
let normalizedUrl = mintUrl.trim();
|
||||||
@@ -457,7 +435,7 @@ export function CashuWallet() {
|
|||||||
normalizedUrl = `https://${normalizedUrl}`;
|
normalizedUrl = `https://${normalizedUrl}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
await addMint(normalizedUrl);
|
await coco.mint.addMint(normalizedUrl);
|
||||||
setMintUrl('');
|
setMintUrl('');
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
@@ -480,8 +458,11 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
|
|
||||||
const handleShowDenominations = async (mintUrl: string) => {
|
const handleShowDenominations = async (mintUrl: string) => {
|
||||||
|
if (!repositories) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const proofs = await getProofs(mintUrl);
|
// Access proofs directly through the proof repository
|
||||||
|
const proofs = await repositories.proofRepository.getReadyProofs(mintUrl);
|
||||||
|
|
||||||
if (!proofs || proofs.length === 0) {
|
if (!proofs || proofs.length === 0) {
|
||||||
toast({
|
toast({
|
||||||
@@ -562,11 +543,13 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
if (!mintExists) {
|
if (!mintExists) {
|
||||||
try {
|
try {
|
||||||
await addMint(userInfo.mint_url);
|
if (coco) {
|
||||||
// Wait a bit for the mint to be added
|
await coco.mint.addMint(userInfo.mint_url);
|
||||||
setTimeout(() => {
|
// Wait a bit for the mint to be added
|
||||||
handleSetActiveMint(userInfo.mint_url, false);
|
setTimeout(() => {
|
||||||
}, 500);
|
handleSetActiveMint(userInfo.mint_url, false);
|
||||||
|
}, 500);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Silent failure - user can manually add mint if needed
|
// Silent failure - user can manually add mint if needed
|
||||||
}
|
}
|
||||||
@@ -578,7 +561,7 @@ export function CashuWallet() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
fetchUserInfo();
|
fetchUserInfo();
|
||||||
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, addMint, handleSetActiveMint]);
|
}, [isNpubCashLoggedIn, isInitialized, getNpubCashUserInfo, activeMintUrl, mints, coco, handleSetActiveMint]);
|
||||||
|
|
||||||
// Auto-select active mint when mints change (balances will update automatically via events)
|
// Auto-select active mint when mints change (balances will update automatically via events)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -598,25 +581,25 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
// Auto-refresh transaction history on new transactions
|
// Auto-refresh transaction history on new transactions
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isInitialized) return;
|
if (!isInitialized || !coco) return;
|
||||||
|
|
||||||
// Listen for history updates (fires on send, receive transactions)
|
// Listen for history updates (fires on send, receive transactions)
|
||||||
const unsubscribeHistoryUpdated = on('history:updated', () => {
|
const unsubscribeHistoryUpdated = coco.on('history:updated', () => {
|
||||||
loadHistory();
|
loadHistory();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
|
// Listen for melt quote creation (coco-cashu bug: doesn't emit history:updated)
|
||||||
const unsubscribeMeltCreated = on('melt-quote:created', () => {
|
const unsubscribeMeltCreated = coco.on('melt-quote:created', () => {
|
||||||
loadHistory();
|
loadHistory();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for melt quote paid (backup, in case creation event missed)
|
// Listen for melt quote paid (backup, in case creation event missed)
|
||||||
const unsubscribeMeltPaid = on('melt-quote:paid', () => {
|
const unsubscribeMeltPaid = coco.on('melt-quote:paid', () => {
|
||||||
loadHistory();
|
loadHistory();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
|
// Listen for mint quote REDEEMED (only after invoice is paid, not created)
|
||||||
const unsubscribeMintRedeemed = on('mint-quote:redeemed', () => {
|
const unsubscribeMintRedeemed = coco.on('mint-quote:redeemed', () => {
|
||||||
loadHistory();
|
loadHistory();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -626,7 +609,7 @@ export function CashuWallet() {
|
|||||||
unsubscribeMeltPaid();
|
unsubscribeMeltPaid();
|
||||||
unsubscribeMintRedeemed();
|
unsubscribeMintRedeemed();
|
||||||
};
|
};
|
||||||
}, [isInitialized, on, loadHistory]);
|
}, [isInitialized, coco, loadHistory]);
|
||||||
|
|
||||||
// Cleanup mint quote listener on component unmount
|
// Cleanup mint quote listener on component unmount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -645,7 +628,6 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<LoadingModal isLoading={isLoading || !isInitialized} />
|
|
||||||
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
|
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
|
||||||
|
|
||||||
{/* ========================================================================
|
{/* ========================================================================
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
|
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, ChevronDown, ChevronUp, Coins } from 'lucide-react';
|
||||||
import type { HistoryEntry } from '@/hooks/cashu/useCashu';
|
import type { HistoryEntry } from 'coco-cashu-core';
|
||||||
|
|
||||||
interface TransactionHistoryProps {
|
interface TransactionHistoryProps {
|
||||||
entries: HistoryEntry[];
|
entries: HistoryEntry[];
|
||||||
@@ -129,7 +129,7 @@ export function TransactionHistory({ entries, isLoading, isExpanded, setIsExpand
|
|||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{getHistoryLabel(entry.type)}
|
{getHistoryLabel(entry.type)}
|
||||||
</span>
|
</span>
|
||||||
{entry.state && entry.type !== 'mint' && entry.type !== 'melt' && (
|
{'state' in entry && entry.state && (
|
||||||
<Badge
|
<Badge
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
|
className={`${getHistoryStateColor(entry.state)} text-white text-xs`}
|
||||||
|
|||||||
@@ -1,247 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useCashuManager } from './useCashuManager';
|
|
||||||
import type { UseCashuReturn, CashuBalance, CashuMint } from './types';
|
|
||||||
|
|
||||||
export function useCashu(): UseCashuReturn {
|
|
||||||
const {
|
|
||||||
manager,
|
|
||||||
repositories,
|
|
||||||
isInitialized,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
mnemonic,
|
|
||||||
setMnemonic,
|
|
||||||
generateMnemonic,
|
|
||||||
getMnemonic,
|
|
||||||
clearError
|
|
||||||
} = useCashuManager();
|
|
||||||
|
|
||||||
const [balances, setBalances] = useState<CashuBalance>({});
|
|
||||||
const [mints, setMints] = useState<CashuMint[]>([]);
|
|
||||||
|
|
||||||
// Auto-refresh balances and mints on manager events
|
|
||||||
useEffect(() => {
|
|
||||||
if (!manager) return;
|
|
||||||
|
|
||||||
const refreshBalances = async () => {
|
|
||||||
try {
|
|
||||||
const newBalances = await (manager as any).wallet.getBalances();
|
|
||||||
setBalances(newBalances);
|
|
||||||
} catch (err) {
|
|
||||||
// Silent failure - errors are handled by the manager
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const refreshMints = async () => {
|
|
||||||
try {
|
|
||||||
const mintList = await (manager as any).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();
|
|
||||||
|
|
||||||
// Listen to events
|
|
||||||
const unsubs = [
|
|
||||||
(manager as any).on('proofs:saved', refreshBalances),
|
|
||||||
(manager as any).on('proofs:state-changed', refreshBalances),
|
|
||||||
(manager as any).on('send:created', refreshBalances),
|
|
||||||
(manager as any).on('receive:created', refreshBalances),
|
|
||||||
(manager as any).on('mint:added', refreshMints),
|
|
||||||
(manager as any).on('mint:updated', refreshMints),
|
|
||||||
];
|
|
||||||
|
|
||||||
return () => unsubs.forEach(unsub => unsub());
|
|
||||||
}, [manager]);
|
|
||||||
|
|
||||||
// Helper to get getEncodedToken lazily
|
|
||||||
const getEncodedTokenFn = async () => {
|
|
||||||
const { getEncodedToken } = await import('coco-cashu-core');
|
|
||||||
return getEncodedToken;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Return direct manager access - no wrappers needed
|
|
||||||
return {
|
|
||||||
// State
|
|
||||||
isInitialized,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
balances,
|
|
||||||
mints,
|
|
||||||
mnemonic,
|
|
||||||
|
|
||||||
// Wallet operations - direct manager API access
|
|
||||||
receive: async (token) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).wallet.receive(token);
|
|
||||||
},
|
|
||||||
|
|
||||||
send: async (mintUrl, amount) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
const token = await (manager as any).wallet.send(mintUrl, amount);
|
|
||||||
const getEncodedToken = await getEncodedTokenFn();
|
|
||||||
return getEncodedToken(token);
|
|
||||||
},
|
|
||||||
|
|
||||||
getBalances: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).wallet.getBalances();
|
|
||||||
},
|
|
||||||
|
|
||||||
getProofs: async (mintUrl) => {
|
|
||||||
if (!repositories) throw new Error('Wallet not initialized');
|
|
||||||
return (repositories as any).proofRepository.getReadyProofs(mintUrl);
|
|
||||||
},
|
|
||||||
|
|
||||||
// Mint operations
|
|
||||||
addMint: async (mintUrl) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).mint.addMint(mintUrl);
|
|
||||||
},
|
|
||||||
|
|
||||||
removeMint: async (mintUrl) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).mintService.deleteMint(mintUrl);
|
|
||||||
},
|
|
||||||
|
|
||||||
getMints: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
const mintList = await (manager as any).mint.getAllMints();
|
|
||||||
return mintList.map((m: any) => ({
|
|
||||||
url: m.mintUrl,
|
|
||||||
name: m.name,
|
|
||||||
info: m.mintInfo
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
|
|
||||||
// Quote operations
|
|
||||||
createMintQuote: async (mintUrl, amount) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).quotes.createMintQuote(mintUrl, amount);
|
|
||||||
},
|
|
||||||
|
|
||||||
redeemMintQuote: async (mintUrl, quoteId) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).quotes.redeemMintQuote(mintUrl, quoteId);
|
|
||||||
},
|
|
||||||
|
|
||||||
createMeltQuote: async (mintUrl, invoice) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).quotes.createMeltQuote(mintUrl, invoice);
|
|
||||||
},
|
|
||||||
|
|
||||||
payMeltQuote: async (mintUrl, quoteId) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).quotes.payMeltQuote(mintUrl, quoteId);
|
|
||||||
},
|
|
||||||
|
|
||||||
addMintQuote: async (mintUrl, quoteId) => {
|
|
||||||
if (!repositories) throw new Error('Wallet not initialized');
|
|
||||||
return (repositories as any).mintQuoteRepository.addMintQuote({
|
|
||||||
quote: quoteId,
|
|
||||||
mintUrl: mintUrl,
|
|
||||||
state: 'UNPAID',
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
// Subscription operations
|
|
||||||
awaitMintQuotePaid: async (mintUrl, quoteId) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).subscription.awaitMintQuotePaid(mintUrl, quoteId);
|
|
||||||
},
|
|
||||||
|
|
||||||
awaitMeltQuotePaid: async (mintUrl, quoteId) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).subscription.awaitMeltQuotePaid(mintUrl, quoteId);
|
|
||||||
},
|
|
||||||
|
|
||||||
// Manager operations
|
|
||||||
enableMintQuoteWatcher: async (options) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).enableMintQuoteWatcher(options);
|
|
||||||
},
|
|
||||||
|
|
||||||
disableMintQuoteWatcher: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).disableMintQuoteWatcher();
|
|
||||||
},
|
|
||||||
|
|
||||||
enableMintQuoteProcessor: async (options) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).enableMintQuoteProcessor(options);
|
|
||||||
},
|
|
||||||
|
|
||||||
disableMintQuoteProcessor: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).disableMintQuoteProcessor();
|
|
||||||
},
|
|
||||||
|
|
||||||
waitForMintQuoteProcessor: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).waitForMintQuoteProcessor();
|
|
||||||
},
|
|
||||||
|
|
||||||
enableProofStateWatcher: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).enableProofStateWatcher();
|
|
||||||
},
|
|
||||||
|
|
||||||
disableProofStateWatcher: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).disableProofStateWatcher();
|
|
||||||
},
|
|
||||||
|
|
||||||
// Event operations
|
|
||||||
on: (event, handler) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).on(event, handler);
|
|
||||||
},
|
|
||||||
|
|
||||||
once: (event, handler) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).once(event, handler);
|
|
||||||
},
|
|
||||||
|
|
||||||
off: (event, handler) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).off(event, handler);
|
|
||||||
},
|
|
||||||
|
|
||||||
// History operations
|
|
||||||
getHistory: async (limit = 50, offset = 0) => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
return (manager as any).history.getPaginatedHistory(offset, limit);
|
|
||||||
},
|
|
||||||
|
|
||||||
// Utility operations
|
|
||||||
refreshBalances: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
const newBalances = await (manager as any).wallet.getBalances();
|
|
||||||
setBalances(newBalances);
|
|
||||||
},
|
|
||||||
|
|
||||||
refreshMints: async () => {
|
|
||||||
if (!manager) throw new Error('Wallet not initialized');
|
|
||||||
const mintList = await (manager as any).mint.getAllMints();
|
|
||||||
setMints(mintList.map((m: any) => ({
|
|
||||||
url: m.mintUrl,
|
|
||||||
name: m.name,
|
|
||||||
info: m.mintInfo
|
|
||||||
})));
|
|
||||||
},
|
|
||||||
|
|
||||||
// Mnemonic operations
|
|
||||||
setMnemonic,
|
|
||||||
generateMnemonic,
|
|
||||||
getMnemonic,
|
|
||||||
clearError,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
// Error types that align with coco-cashu patterns
|
|
||||||
export class CashuWalletError extends Error {
|
|
||||||
constructor(message: string, public code: string, public details?: unknown) {
|
|
||||||
super(message);
|
|
||||||
this.name = 'CashuWalletError';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CashuInitializationError extends CashuWalletError {
|
|
||||||
constructor(message: string, details?: unknown) {
|
|
||||||
super(message, 'INITIALIZATION_ERROR', details);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CashuMintError extends CashuWalletError {
|
|
||||||
constructor(message: string, mintUrl: string, details?: unknown) {
|
|
||||||
super(message, 'MINT_ERROR', details);
|
|
||||||
this.mintUrl = mintUrl;
|
|
||||||
}
|
|
||||||
public mintUrl: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CashuQuoteError extends CashuWalletError {
|
|
||||||
constructor(message: string, quoteId: string, details?: unknown) {
|
|
||||||
super(message, 'QUOTE_ERROR', details);
|
|
||||||
this.quoteId = quoteId;
|
|
||||||
}
|
|
||||||
public quoteId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CashuTokenError extends CashuWalletError {
|
|
||||||
constructor(message: string, token?: string, details?: unknown) {
|
|
||||||
super(message, 'TOKEN_ERROR', details);
|
|
||||||
this.token = token;
|
|
||||||
}
|
|
||||||
public token?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Core types
|
|
||||||
export interface CashuBalance {
|
|
||||||
[mintUrl: string]: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CashuMint {
|
|
||||||
url: string;
|
|
||||||
name?: string;
|
|
||||||
info?: Record<string, unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CashuMintQuote {
|
|
||||||
quote: string;
|
|
||||||
request: string;
|
|
||||||
expiry: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CashuMeltQuote {
|
|
||||||
quote: string;
|
|
||||||
request: string;
|
|
||||||
expiry: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CashuToken {
|
|
||||||
mint: string;
|
|
||||||
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HistoryEntry {
|
|
||||||
id: string;
|
|
||||||
type: 'mint' | 'melt' | 'send' | 'receive';
|
|
||||||
mintUrl: string;
|
|
||||||
amount: number;
|
|
||||||
unit: string;
|
|
||||||
createdAt: number;
|
|
||||||
metadata?: Record<string, unknown>;
|
|
||||||
quoteId?: string;
|
|
||||||
state?: string;
|
|
||||||
paymentRequest?: string;
|
|
||||||
token?: CashuToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hook state types
|
|
||||||
export interface CashuState {
|
|
||||||
isInitialized: boolean;
|
|
||||||
isLoading: boolean;
|
|
||||||
error: CashuWalletError | null;
|
|
||||||
balances: CashuBalance;
|
|
||||||
mints: CashuMint[];
|
|
||||||
mnemonic: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CashuActions {
|
|
||||||
// Wallet operations
|
|
||||||
receive: (token: string | CashuToken) => Promise<void>;
|
|
||||||
send: (mintUrl: string, amount: number) => Promise<string>;
|
|
||||||
getBalances: () => Promise<CashuBalance>;
|
|
||||||
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
|
|
||||||
|
|
||||||
// Mint operations
|
|
||||||
addMint: (mintUrl: string) => Promise<void>;
|
|
||||||
removeMint: (mintUrl: string) => Promise<void>;
|
|
||||||
getMints: () => Promise<CashuMint[]>;
|
|
||||||
|
|
||||||
// Quote operations
|
|
||||||
createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote>;
|
|
||||||
redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
|
||||||
createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote>;
|
|
||||||
payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
|
||||||
addMintQuote: (mintUrl: string, quoteId: string) => Promise<void>;
|
|
||||||
|
|
||||||
// Subscription operations (NEW)
|
|
||||||
awaitMintQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
|
||||||
awaitMeltQuotePaid: (mintUrl: string, quoteId: string) => Promise<unknown>;
|
|
||||||
|
|
||||||
// Manager operations (NEW)
|
|
||||||
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
|
|
||||||
disableMintQuoteWatcher: () => Promise<void>;
|
|
||||||
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
|
|
||||||
disableMintQuoteProcessor: () => Promise<void>;
|
|
||||||
waitForMintQuoteProcessor: () => Promise<void>;
|
|
||||||
enableProofStateWatcher: () => Promise<void>;
|
|
||||||
disableProofStateWatcher: () => Promise<void>;
|
|
||||||
|
|
||||||
// Event operations (NEW)
|
|
||||||
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
|
||||||
once: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
|
||||||
off: (event: string, handler: (payload: unknown) => void | Promise<void>) => void;
|
|
||||||
|
|
||||||
// Mnemonic operations
|
|
||||||
setMnemonic: (mnemonic: string) => void;
|
|
||||||
generateMnemonic: () => string;
|
|
||||||
getMnemonic: () => string | null;
|
|
||||||
|
|
||||||
// History operations
|
|
||||||
getHistory: (limit?: number, offset?: number) => Promise<HistoryEntry[]>;
|
|
||||||
|
|
||||||
// Utility operations
|
|
||||||
refreshBalances: () => Promise<void>;
|
|
||||||
refreshMints: () => Promise<void>;
|
|
||||||
clearError: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type UseCashuReturn = CashuState & CashuActions;
|
|
||||||
+245
-16
@@ -1,17 +1,246 @@
|
|||||||
// Re-export the new modular useCashu hook and types
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
export { useCashu } from './index';
|
import { useLocalStorage } from '../useLocalStorage';
|
||||||
export type {
|
import * as bip39 from '@scure/bip39';
|
||||||
UseCashuReturn,
|
import { wordlist } from '@scure/bip39/wordlists/english';
|
||||||
CashuBalance,
|
import { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
|
||||||
CashuMint,
|
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
|
||||||
CashuMintQuote,
|
|
||||||
CashuMeltQuote,
|
|
||||||
CashuToken,
|
|
||||||
HistoryEntry,
|
|
||||||
CashuWalletError,
|
|
||||||
CashuInitializationError,
|
|
||||||
CashuMintError,
|
|
||||||
CashuQuoteError,
|
|
||||||
CashuTokenError
|
|
||||||
} from './types';
|
|
||||||
|
|
||||||
|
// Types from coco-cashu-core
|
||||||
|
type CocoManager = Awaited<ReturnType<typeof initializeCoco>>;
|
||||||
|
|
||||||
|
// Singleton pattern to prevent multiple initializations
|
||||||
|
let globalCocoInstance: CocoManager | null = null;
|
||||||
|
let globalRepositories: Repositories | null = null;
|
||||||
|
let globalInitializationPromise: Promise<{ coco: CocoManager; repositories: Repositories }> | null = null;
|
||||||
|
|
||||||
|
export interface UseCashuReturn {
|
||||||
|
// The typed coco manager (direct library access)
|
||||||
|
coco: CocoManager | null;
|
||||||
|
|
||||||
|
// Repositories for direct access to proof data
|
||||||
|
repositories: Repositories | null;
|
||||||
|
|
||||||
|
// React state (for reactivity)
|
||||||
|
balances: { [mintUrl: string]: number };
|
||||||
|
mints: Array<{ url: string; name?: string; info?: unknown }>;
|
||||||
|
totalBalance: number;
|
||||||
|
|
||||||
|
// Status
|
||||||
|
isInitialized: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: Error | null;
|
||||||
|
|
||||||
|
// Mnemonic management
|
||||||
|
mnemonic: string | null;
|
||||||
|
setMnemonic: (mnemonic: string) => void;
|
||||||
|
generateMnemonic: () => string;
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
clearError: () => void;
|
||||||
|
getEncodedToken: typeof getEncodedToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCashu(): UseCashuReturn {
|
||||||
|
const [isInitialized, setIsInitialized] = useState(false);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<Error | null>(null);
|
||||||
|
|
||||||
|
// Mnemonic management with localStorage
|
||||||
|
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
||||||
|
|
||||||
|
// Manager instance ref
|
||||||
|
const cocoRef = useRef<CocoManager | null>(null);
|
||||||
|
const repositoriesRef = useRef<Repositories | null>(null);
|
||||||
|
|
||||||
|
// React state for UI reactivity
|
||||||
|
const [balances, setBalances] = useState<{ [mintUrl: string]: number }>({});
|
||||||
|
const [mints, setMints] = useState<Array<{ url: string; name?: string; info?: unknown }>>([]);
|
||||||
|
|
||||||
|
const clearError = useCallback(() => {
|
||||||
|
setError(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const generateMnemonic = useCallback(() => {
|
||||||
|
return bip39.generateMnemonic(wordlist);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setMnemonic = useCallback((newMnemonic: string) => {
|
||||||
|
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
||||||
|
throw new Error('Invalid mnemonic');
|
||||||
|
}
|
||||||
|
setMnemonicState(newMnemonic);
|
||||||
|
// Reinitialize manager with new mnemonic
|
||||||
|
setIsInitialized(false);
|
||||||
|
}, [setMnemonicState]);
|
||||||
|
|
||||||
|
// Initialize the coco manager
|
||||||
|
const initializeCocoManager = useCallback(async () => {
|
||||||
|
if (isInitialized || isLoading) return;
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
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);
|
||||||
|
setIsLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there's already an initialization in progress, wait for it
|
||||||
|
if (globalInitializationPromise) {
|
||||||
|
console.log('Waiting for existing initialization...');
|
||||||
|
const { coco, repositories } = await globalInitializationPromise;
|
||||||
|
cocoRef.current = coco;
|
||||||
|
repositoriesRef.current = repositories;
|
||||||
|
setIsInitialized(true);
|
||||||
|
setIsLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate or retrieve mnemonic
|
||||||
|
let currentMnemonic = mnemonic;
|
||||||
|
if (!currentMnemonic) {
|
||||||
|
currentMnemonic = bip39.generateMnemonic(wordlist);
|
||||||
|
setMnemonicState(currentMnemonic);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create seed from mnemonic
|
||||||
|
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
||||||
|
|
||||||
|
// Initialize repositories with proper initialization
|
||||||
|
const repo = new IndexedDbRepositories({ name: "cashu-wallet" });
|
||||||
|
await repo.init(); // Ensure repository is properly initialized
|
||||||
|
|
||||||
|
// Create initialization promise
|
||||||
|
globalInitializationPromise = (async () => {
|
||||||
|
const coco = await initializeCoco({
|
||||||
|
repo,
|
||||||
|
seedGetter: async () => seed,
|
||||||
|
logger: new ConsoleLogger("coco", { level: "debug" }) // Use debug level for better logging
|
||||||
|
});
|
||||||
|
return { coco, repositories: repo };
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Initialize coco manager using the new API
|
||||||
|
const { coco, repositories } = await globalInitializationPromise;
|
||||||
|
|
||||||
|
// Store as singleton
|
||||||
|
console.log('Storing new coco instance as singleton');
|
||||||
|
globalCocoInstance = coco;
|
||||||
|
globalRepositories = repositories;
|
||||||
|
globalInitializationPromise = null;
|
||||||
|
cocoRef.current = coco;
|
||||||
|
repositoriesRef.current = repositories;
|
||||||
|
|
||||||
|
// Enable built-in services for automatic quote processing and state watching
|
||||||
|
try {
|
||||||
|
console.log('Enabling coco services...');
|
||||||
|
await coco.enableMintQuoteWatcher({ watchExistingPendingOnStart: false });
|
||||||
|
console.log('Mint quote watcher enabled');
|
||||||
|
|
||||||
|
await coco.enableMintQuoteProcessor();
|
||||||
|
console.log('Mint quote processor enabled');
|
||||||
|
|
||||||
|
await coco.enableProofStateWatcher();
|
||||||
|
console.log('Proof state watcher enabled');
|
||||||
|
|
||||||
|
console.log('All coco services enabled successfully');
|
||||||
|
} catch (err) {
|
||||||
|
// Don't fail initialization if watchers can't be enabled
|
||||||
|
console.warn('Failed to enable some coco services:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsInitialized(true);
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
|
||||||
|
setError(new Error(errorMessage));
|
||||||
|
globalInitializationPromise = null; // Reset on error
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
||||||
|
|
||||||
|
// Initialize on mount and when mnemonic changes
|
||||||
|
useEffect(() => {
|
||||||
|
initializeCocoManager();
|
||||||
|
}, [initializeCocoManager]);
|
||||||
|
|
||||||
|
// Auto-refresh balances and mints on manager events
|
||||||
|
useEffect(() => {
|
||||||
|
const coco = cocoRef.current;
|
||||||
|
if (!coco) return;
|
||||||
|
|
||||||
|
const refreshBalances = async () => {
|
||||||
|
try {
|
||||||
|
const newBalances = await coco.wallet.getBalances();
|
||||||
|
setBalances(newBalances);
|
||||||
|
} catch (err) {
|
||||||
|
// Silent failure - errors are handled by the manager
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
// Listen to events
|
||||||
|
const unsubs = [
|
||||||
|
coco.on('proofs:saved', refreshBalances),
|
||||||
|
coco.on('proofs:state-changed', refreshBalances),
|
||||||
|
coco.on('send:created', refreshBalances),
|
||||||
|
coco.on('receive:created', refreshBalances),
|
||||||
|
coco.on('mint:added', refreshMints),
|
||||||
|
coco.on('mint:updated', refreshMints),
|
||||||
|
];
|
||||||
|
|
||||||
|
return () => unsubs.forEach(unsub => unsub());
|
||||||
|
}, [isInitialized]);
|
||||||
|
|
||||||
|
// Calculate total balance
|
||||||
|
const totalBalance = Object.values(balances).reduce((sum, balance) => sum + balance, 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
// The typed coco manager (direct library access)
|
||||||
|
coco: cocoRef.current,
|
||||||
|
|
||||||
|
// Repositories for direct access to proof data
|
||||||
|
repositories: repositoriesRef.current,
|
||||||
|
|
||||||
|
// React state (for reactivity)
|
||||||
|
balances,
|
||||||
|
mints,
|
||||||
|
totalBalance,
|
||||||
|
|
||||||
|
// Status
|
||||||
|
isInitialized,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
|
||||||
|
// Mnemonic management
|
||||||
|
mnemonic,
|
||||||
|
setMnemonic,
|
||||||
|
generateMnemonic,
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
clearError,
|
||||||
|
getEncodedToken,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
||||||
import { useLocalStorage } from '../useLocalStorage';
|
|
||||||
import * as bip39 from '@scure/bip39';
|
|
||||||
import { wordlist } from '@scure/bip39/wordlists/english';
|
|
||||||
import { CashuInitializationError, CashuWalletError } from './types';
|
|
||||||
|
|
||||||
// Dynamic imports for coco-cashu packages
|
|
||||||
let Manager: unknown = null;
|
|
||||||
let IndexedDbRepositories: unknown = null;
|
|
||||||
let ConsoleLogger: unknown = null;
|
|
||||||
let getEncodedToken: unknown = null;
|
|
||||||
let _getDecodedToken: unknown = null;
|
|
||||||
|
|
||||||
// Lazy load coco-cashu packages
|
|
||||||
const loadCocoCashu = async () => {
|
|
||||||
if (Manager) return; // Already loaded
|
|
||||||
|
|
||||||
try {
|
|
||||||
const coreModule = await import('coco-cashu-core');
|
|
||||||
const indexedDbModule = await import('coco-cashu-indexeddb');
|
|
||||||
|
|
||||||
Manager = coreModule.Manager;
|
|
||||||
ConsoleLogger = coreModule.ConsoleLogger;
|
|
||||||
getEncodedToken = coreModule.getEncodedToken;
|
|
||||||
_getDecodedToken = coreModule.getDecodedToken;
|
|
||||||
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to load coco-cashu packages:', error);
|
|
||||||
throw new CashuInitializationError(
|
|
||||||
'Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb',
|
|
||||||
{ error }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface UseCashuManagerReturn {
|
|
||||||
manager: unknown | null;
|
|
||||||
repositories: unknown | null;
|
|
||||||
isInitialized: boolean;
|
|
||||||
isLoading: boolean;
|
|
||||||
error: CashuWalletError | null;
|
|
||||||
mnemonic: string | null;
|
|
||||||
setMnemonic: (mnemonic: string) => void;
|
|
||||||
generateMnemonic: () => string;
|
|
||||||
getMnemonic: () => string | null;
|
|
||||||
clearError: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useCashuManager(): UseCashuManagerReturn {
|
|
||||||
const [isInitialized, setIsInitialized] = useState(false);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<CashuWalletError | null>(null);
|
|
||||||
|
|
||||||
// Mnemonic management with localStorage
|
|
||||||
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
|
||||||
|
|
||||||
// Manager instance refs
|
|
||||||
const managerRef = useRef<unknown>(null);
|
|
||||||
const repositoriesRef = useRef<unknown>(null);
|
|
||||||
|
|
||||||
const clearError = useCallback(() => {
|
|
||||||
setError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const generateMnemonic = useCallback(() => {
|
|
||||||
return bip39.generateMnemonic(wordlist);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const getMnemonic = useCallback(() => {
|
|
||||||
return mnemonic;
|
|
||||||
}, [mnemonic]);
|
|
||||||
|
|
||||||
const setMnemonic = useCallback((newMnemonic: string) => {
|
|
||||||
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
|
||||||
throw new CashuWalletError('Invalid mnemonic', 'INVALID_MNEMONIC');
|
|
||||||
}
|
|
||||||
setMnemonicState(newMnemonic);
|
|
||||||
// Reinitialize manager with new mnemonic
|
|
||||||
setIsInitialized(false);
|
|
||||||
}, [setMnemonicState]);
|
|
||||||
|
|
||||||
// Initialize the manager
|
|
||||||
const initializeManager = useCallback(async () => {
|
|
||||||
if (isInitialized || isLoading) return;
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await loadCocoCashu();
|
|
||||||
|
|
||||||
// Generate or retrieve mnemonic
|
|
||||||
let currentMnemonic = mnemonic;
|
|
||||||
if (!currentMnemonic) {
|
|
||||||
currentMnemonic = bip39.generateMnemonic(wordlist);
|
|
||||||
setMnemonicState(currentMnemonic);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create seed from mnemonic
|
|
||||||
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
|
||||||
|
|
||||||
// Initialize repositories
|
|
||||||
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
|
|
||||||
await repositories.init();
|
|
||||||
repositoriesRef.current = repositories;
|
|
||||||
|
|
||||||
// Initialize manager
|
|
||||||
const manager = new (Manager as new (
|
|
||||||
repositories: unknown,
|
|
||||||
seedGetter: () => Promise<Uint8Array>,
|
|
||||||
logger?: unknown
|
|
||||||
) => {
|
|
||||||
wallet: { getBalances: () => Promise<Record<string, number>>; receive: (token: string | unknown) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<unknown> };
|
|
||||||
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
|
|
||||||
quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<unknown>; redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void>; createMeltQuote: (mintUrl: string, invoice: string) => Promise<unknown>; payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> };
|
|
||||||
history: { getPaginatedHistory: (offset: number, limit: number) => Promise<unknown[]> };
|
|
||||||
enableMintQuoteWatcher: (options?: { watchExistingPendingOnStart?: boolean }) => Promise<void>;
|
|
||||||
enableMintQuoteProcessor: (options?: { processIntervalMs?: number; maxRetries?: number; baseRetryDelayMs?: number; initialEnqueueDelayMs?: number }) => Promise<void>;
|
|
||||||
enableProofStateWatcher: () => Promise<void>;
|
|
||||||
on: (event: string, handler: (payload: unknown) => void | Promise<void>) => () => void;
|
|
||||||
})(
|
|
||||||
repositories,
|
|
||||||
async () => seed,
|
|
||||||
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
|
|
||||||
);
|
|
||||||
managerRef.current = manager;
|
|
||||||
|
|
||||||
// Enable built-in services for automatic quote processing and state watching
|
|
||||||
try {
|
|
||||||
await manager.enableMintQuoteWatcher({ watchExistingPendingOnStart: true });
|
|
||||||
await manager.enableMintQuoteProcessor();
|
|
||||||
await manager.enableProofStateWatcher();
|
|
||||||
} catch (err) {
|
|
||||||
// Don't fail initialization if watchers can't be enabled
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsInitialized(true);
|
|
||||||
} catch (err) {
|
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
|
|
||||||
const cashuError = err instanceof CashuWalletError ? err : new CashuInitializationError(errorMessage, { originalError: err });
|
|
||||||
setError(cashuError);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
|
||||||
|
|
||||||
// Initialize on mount and when mnemonic changes
|
|
||||||
useEffect(() => {
|
|
||||||
initializeManager();
|
|
||||||
}, [initializeManager]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
manager: managerRef.current,
|
|
||||||
repositories: repositoriesRef.current,
|
|
||||||
isInitialized,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
mnemonic,
|
|
||||||
setMnemonic,
|
|
||||||
generateMnemonic,
|
|
||||||
getMnemonic,
|
|
||||||
clearError,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,7 @@ export function useZaps(
|
|||||||
|
|
||||||
const author = useAuthor(actualTarget?.pubkey);
|
const author = useAuthor(actualTarget?.pubkey);
|
||||||
const { sendPayment, getActiveConnection } = useNWC();
|
const { sendPayment, getActiveConnection } = useNWC();
|
||||||
const { createMeltQuote, payMeltQuote, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
const { coco, balances, mints, isInitialized: isCashuInitialized } = useCashu();
|
||||||
const [isZapping, setIsZapping] = useState(false);
|
const [isZapping, setIsZapping] = useState(false);
|
||||||
const [invoice, setInvoice] = useState<string | null>(null);
|
const [invoice, setInvoice] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -258,12 +258,12 @@ export function useZaps(
|
|||||||
return balance >= amount;
|
return balance >= amount;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (mintWithBalance) {
|
if (mintWithBalance && coco) {
|
||||||
// Create melt quote to convert Cashu tokens to Lightning payment
|
// Create melt quote to convert Cashu tokens to Lightning payment
|
||||||
const meltQuote = await createMeltQuote(mintWithBalance.url, newInvoice);
|
const meltQuote = await coco.quotes.createMeltQuote(mintWithBalance.url, newInvoice);
|
||||||
|
|
||||||
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
|
// Pay the melt quote (this burns the Cashu tokens and pays the Lightning invoice)
|
||||||
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
|
||||||
|
|
||||||
// Clear states immediately on success
|
// Clear states immediately on success
|
||||||
setIsZapping(false);
|
setIsZapping(false);
|
||||||
|
|||||||
Reference in new issue
Block a user