address test errors

This commit is contained in:
lemonknowsall committed 2025-10-06 00:15:20 -07:00
1 parent 6dacd3d964
commit af1cbaeacc
3 files changed
+132 -122

No files matched your search

+7 -7
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useLightningAddress } from '@/hooks/useLightningAddress';
@@ -8,7 +8,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, DollarSign, ArrowLeftRight, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp } from 'lucide-react';
import { Loader2, Wallet, Plus, Send, Download, Bitcoin, RefreshCw, Copy, Check, ChevronDown, History, ArrowUpRight, ArrowDownLeft, Zap, X, Coins, ChevronUp } from 'lucide-react';
export function CashuWallet() {
// ============================================================================
@@ -131,7 +131,7 @@ export function CashuWallet() {
// HELPER FUNCTIONS - History
// ============================================================================
const loadHistory = async () => {
const loadHistory = useCallback(async () => {
try {
setIsLoadingHistory(true);
const entries = await getHistory(50, 0);
@@ -141,7 +141,7 @@ export function CashuWallet() {
} finally {
setIsLoadingHistory(false);
}
};
}, [getHistory]);
const getHistoryIcon = (type: string) => {
switch (type) {
@@ -433,7 +433,7 @@ export function CashuWallet() {
// Group proofs by denomination
const denominations: { [key: number]: number } = {};
proofs.forEach((proof: any) => {
proofs.forEach((proof: { amount?: number }) => {
const amount = proof.amount || 0;
denominations[amount] = (denominations[amount] || 0) + 1;
});
@@ -477,7 +477,7 @@ export function CashuWallet() {
if (isInitialized && historyEntries.length === 0) {
loadHistory();
}
}, [isInitialized]);
}, [isInitialized, historyEntries.length, loadHistory]);
// ============================================================================
// RENDER - Loading State
@@ -577,7 +577,7 @@ export function CashuWallet() {
onClick={() => setActiveMintUrl(mint.url)}
>
<div className="flex items-center gap-2">
<span className="font-medium">{getCleanMintLabel(mint as any)}</span>
<span className="font-medium">{getCleanMintLabel(mint)}</span>
</div>
</DropdownMenuItem>
))}
+123 -113
View File
@@ -11,7 +11,7 @@ export interface CashuBalance {
export interface CashuMint {
url: string;
name?: string;
info?: any;
info?: Record<string, unknown>;
}
export interface CashuMintQuote {
@@ -28,7 +28,7 @@ export interface CashuMeltQuote {
export interface CashuToken {
mint: string;
proofs: any[];
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
}
export interface CashuState {
@@ -47,11 +47,11 @@ export interface HistoryEntry {
amount: number;
unit: string;
createdAt: number;
metadata?: any;
metadata?: Record<string, unknown>;
quoteId?: string;
state?: string;
paymentRequest?: string;
token?: any;
token?: CashuToken;
}
export interface CashuActions {
@@ -59,7 +59,7 @@ export interface CashuActions {
receive: (token: string | CashuToken) => Promise<void>;
send: (mintUrl: string, amount: number) => Promise<string>;
getBalances: () => Promise<CashuBalance>;
getProofs: (mintUrl: string) => Promise<any[]>;
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
// Mint operations
addMint: (mintUrl: string) => Promise<void>;
@@ -90,11 +90,11 @@ export interface CashuActions {
export type UseCashuReturn = CashuState & CashuActions;
// Dynamic imports for coco-cashu packages
let Manager: any;
let IndexedDbRepositories: any;
let ConsoleLogger: any;
let getEncodedToken: any;
let getDecodedToken: any;
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 () => {
@@ -107,7 +107,7 @@ const loadCocoCashu = async () => {
Manager = coreModule.Manager;
ConsoleLogger = coreModule.ConsoleLogger;
getEncodedToken = coreModule.getEncodedToken;
getDecodedToken = coreModule.getDecodedToken;
_getDecodedToken = coreModule.getDecodedToken;
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
} catch (error) {
console.error('Failed to load coco-cashu packages:', error);
@@ -127,8 +127,88 @@ export function useCashu(): UseCashuReturn {
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
// Manager instance ref
const managerRef = useRef<any>(null);
const repositoriesRef = useRef<any>(null);
const managerRef = useRef<unknown>(null);
const repositoriesRef = useRef<unknown>(null);
// Utility operations - defined first so they can be used in other callbacks
const refreshBalances = useCallback(async () => {
if (!managerRef.current) return;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await (managerRef.current as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
setBalances(newBalances);
console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints');
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
}, []);
const refreshMints = useCallback(async () => {
if (!managerRef.current) return;
try {
const mintList = await (managerRef.current as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
const formattedMints = mintList
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
// Check and redeem all pending mint quotes
const checkAndRedeemPendingQuotes = useCallback(async () => {
if (!managerRef.current || !repositoriesRef.current) return;
try {
console.log('🔍 Checking for pending mint quotes in IndexedDB...');
// Access the mint quotes repository directly
const mintQuotesRepo = (repositoriesRef.current as { mintQuoteRepository?: { getPendingMintQuotes: () => Promise<Array<Record<string, unknown>>> } })?.mintQuoteRepository;
if (!mintQuotesRepo) {
console.log('⚠️ Mint quotes repository not available');
return;
}
// Get all pending mint quotes (non-ISSUED quotes)
const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes();
console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`);
// Filter for UNPAID quotes (these might have been paid but not redeemed)
const unpaidQuotes = pendingQuotes.filter((q: { state?: string }) => q.state === 'UNPAID');
console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`);
let claimedCount = 0;
for (const quote of unpaidQuotes) {
try {
const q = quote as { quote: string; mintUrl: string; amount: number };
console.log(`🔄 Attempting to redeem quote ${q.quote} from ${q.mintUrl}...`);
await (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(q.mintUrl, q.quote);
claimedCount++;
console.log(`✅ Successfully claimed ${q.amount} sats from quote ${q.quote}`);
} catch {
const q = quote as { quote: string };
// Quote not paid yet or already claimed - this is expected, just skip
console.log(`⏭️ Quote ${q.quote} not ready yet (invoice not paid or already claimed)`);
}
}
if (claimedCount > 0) {
console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`);
await refreshBalances();
}
} catch (err) {
console.error('❌ Error checking pending quotes:', err);
}
}, [refreshBalances]);
// Initialize the manager
const initializeManager = useCallback(async () => {
@@ -151,15 +231,23 @@ export function useCashu(): UseCashuReturn {
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
// Initialize repositories
const repositories = new IndexedDbRepositories({});
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(
const manager = new (Manager as new (
repositories: unknown,
seedGetter: () => Promise<Uint8Array>,
logger?: unknown
) => {
wallet: { getBalances: () => Promise<CashuBalance>; receive: (token: string | CashuToken) => Promise<void>; send: (mintUrl: string, amount: number) => Promise<CashuToken> };
mint: { addMint: (mintUrl: string) => Promise<unknown>; getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> };
quotes: { 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> };
})(
repositories,
async () => seed,
new ConsoleLogger(undefined, { level: 'info' })
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
);
managerRef.current = manager;
@@ -178,53 +266,20 @@ export function useCashu(): UseCashuReturn {
} finally {
setIsLoading(false);
}
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
}, [isInitialized, isLoading, mnemonic, setMnemonicState, refreshBalances, refreshMints, checkAndRedeemPendingQuotes]);
// Initialize on mount
useEffect(() => {
initializeManager();
}, [initializeManager]);
// Utility operations - defined first so they can be used in other callbacks
const refreshBalances = useCallback(async () => {
if (!managerRef.current) return;
try {
console.log('🔄 refreshBalances: Getting balances from wallet...');
const newBalances = await managerRef.current.wallet.getBalances();
console.log('💰 refreshBalances: Raw balances from wallet:', newBalances);
setBalances(newBalances);
console.log('✅ refreshBalances: State updated with balances:', Object.keys(newBalances).length, 'mints');
} catch (err) {
console.error('❌ refreshBalances: Failed to refresh balances:', err);
}
}, []);
const refreshMints = useCallback(async () => {
if (!managerRef.current) return;
try {
const mintList = await managerRef.current.mint.getAllMints();
const formattedMints = mintList
.filter((mint: any) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: any) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
}));
setMints(formattedMints);
} catch (err) {
console.error('Failed to refresh mints:', err);
}
}, []);
// Wallet operations
const receive = useCallback(async (token: string | CashuToken) => {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
setError(null);
await managerRef.current.wallet.receive(token);
await (managerRef.current as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).wallet.receive(token);
await refreshBalances();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
@@ -238,11 +293,11 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
const token = await managerRef.current.wallet.send(mintUrl, amount);
const token = await (managerRef.current as { wallet: { send: (mintUrl: string, amount: number) => Promise<CashuToken> } }).wallet.send(mintUrl, amount);
await refreshBalances();
// Encode the token into a Cashu token string
const encodedToken = getEncodedToken(token);
const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token);
return encodedToken;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
@@ -255,7 +310,7 @@ export function useCashu(): UseCashuReturn {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
return await managerRef.current.wallet.getBalances();
return await (managerRef.current as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
setError(errorMessage);
@@ -263,14 +318,14 @@ export function useCashu(): UseCashuReturn {
}
}, []);
const getProofs = useCallback(async (mintUrl: string): Promise<any[]> => {
const getProofs = useCallback(async (mintUrl: string): Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>> => {
if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized');
try {
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
// Access the proof repository
const proofRepo = (repositoriesRef.current as any).proofRepository;
const proofRepo = (repositoriesRef.current as { proofRepository?: { getReadyProofs: (mintUrl: string) => Promise<Array<Record<string, unknown>>> } })?.proofRepository;
if (!proofRepo) {
throw new Error('Proof repository not available');
}
@@ -279,7 +334,7 @@ export function useCashu(): UseCashuReturn {
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`);
return readyProofs;
return readyProofs as Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
console.error('❌ Error getting proofs:', err);
@@ -294,7 +349,7 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
await managerRef.current.mint.addMint(mintUrl);
await (managerRef.current as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint(mintUrl);
await refreshMints();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
@@ -303,7 +358,7 @@ export function useCashu(): UseCashuReturn {
}
}, [refreshMints]);
const removeMint = useCallback(async (mintUrl: string) => {
const removeMint = useCallback(async (_mintUrl: string) => {
// Note: coco-cashu doesn't have a direct remove mint method
// This would need to be implemented at the repository level
setError('Remove mint functionality not yet implemented');
@@ -314,10 +369,10 @@ export function useCashu(): UseCashuReturn {
if (!managerRef.current) throw new Error('Wallet not initialized');
try {
const mintList = await managerRef.current.mint.getAllMints();
const mintList = await (managerRef.current as { mint: { getAllMints: () => Promise<Array<{ mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }>> } }).mint.getAllMints();
return mintList
.filter((mint: any) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: any) => ({
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
url: mint.mintUrl, // Map mintUrl to url for consistency
name: mint.name,
info: mint.mintInfo
@@ -335,7 +390,7 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
const quote = await managerRef.current.quotes.createMintQuote(mintUrl, amount);
const quote = await (managerRef.current as { quotes: { createMintQuote: (mintUrl: string, amount: number) => Promise<CashuMintQuote> } }).quotes.createMintQuote(mintUrl, amount);
return {
quote: quote.quote,
request: quote.request,
@@ -354,7 +409,7 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
await managerRef.current.quotes.redeemMintQuote(mintUrl, quoteId);
await (managerRef.current as { quotes: { redeemMintQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.redeemMintQuote(mintUrl, quoteId);
console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...');
await refreshBalances();
} catch (err) {
@@ -369,7 +424,7 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
const quote = await managerRef.current.quotes.createMeltQuote(mintUrl, invoice);
const quote = await (managerRef.current as { quotes: { createMeltQuote: (mintUrl: string, invoice: string) => Promise<CashuMeltQuote> } }).quotes.createMeltQuote(mintUrl, invoice);
return {
quote: quote.quote,
request: quote.request,
@@ -387,7 +442,7 @@ export function useCashu(): UseCashuReturn {
try {
setError(null);
await managerRef.current.quotes.payMeltQuote(mintUrl, quoteId);
await (managerRef.current as { quotes: { payMeltQuote: (mintUrl: string, quoteId: string) => Promise<void> } }).quotes.payMeltQuote(mintUrl, quoteId);
await refreshBalances();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
@@ -415,51 +470,6 @@ export function useCashu(): UseCashuReturn {
return mnemonic;
}, [mnemonic]);
// Check and redeem all pending mint quotes
const checkAndRedeemPendingQuotes = useCallback(async () => {
if (!managerRef.current || !repositoriesRef.current) return;
try {
console.log('🔍 Checking for pending mint quotes in IndexedDB...');
// Access the mint quotes repository directly
const mintQuotesRepo = (repositoriesRef.current as any).mintQuoteRepository;
if (!mintQuotesRepo) {
console.log('⚠️ Mint quotes repository not available');
return;
}
// Get all pending mint quotes (non-ISSUED quotes)
const pendingQuotes = await mintQuotesRepo.getPendingMintQuotes();
console.log(`📋 Found ${pendingQuotes.length} pending quotes in database`);
// Filter for UNPAID quotes (these might have been paid but not redeemed)
const unpaidQuotes = pendingQuotes.filter((q: any) => q.state === 'UNPAID');
console.log(`⏳ Found ${unpaidQuotes.length} UNPAID quotes to check`);
let claimedCount = 0;
for (const quote of unpaidQuotes) {
try {
console.log(`🔄 Attempting to redeem quote ${quote.quote} from ${quote.mintUrl}...`);
await managerRef.current.quotes.redeemMintQuote(quote.mintUrl, quote.quote);
claimedCount++;
console.log(`✅ Successfully claimed ${quote.amount} sats from quote ${quote.quote}`);
} catch (err) {
// Quote not paid yet or already claimed - this is expected, just skip
console.log(`⏭️ Quote ${quote.quote} not ready yet (invoice not paid or already claimed)`);
}
}
if (claimedCount > 0) {
console.log(`🎉 Auto-claimed ${claimedCount} paid quotes!`);
await refreshBalances();
}
} catch (err) {
console.error('❌ Error checking pending quotes:', err);
}
}, [refreshBalances]);
const clearError = useCallback(() => {
setError(null);
}, []);
@@ -472,7 +482,7 @@ export function useCashu(): UseCashuReturn {
console.log('📜 Getting transaction history...');
// Access the history repository (correct property name is historyRepository)
const historyRepo = (repositoriesRef.current as any).historyRepository;
const historyRepo = (repositoriesRef.current as { historyRepository?: { getPaginatedHistoryEntries: (limit: number, offset: number) => Promise<Array<Record<string, unknown>>> } })?.historyRepository;
if (!historyRepo) {
throw new Error('History repository not available');
}
@@ -481,7 +491,7 @@ export function useCashu(): UseCashuReturn {
const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset);
console.log(`✅ Found ${entries.length} history entries`);
return entries;
return entries as unknown as HistoryEntry[];
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
console.error('❌ Error getting history:', err);
+2 -2
View File
@@ -122,7 +122,7 @@ async function handleAPIError(response: Response) {
}
}
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
} catch (parseError) {
} catch {
throw new Error('Invalid request. Please check your parameters and try again.');
}
} else if (response.status === 404) {
@@ -133,7 +133,7 @@ async function handleAPIError(response: Response) {
try {
const errorData = await response.json();
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
} catch (parseError) {
} catch {
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
}
}