mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
address test errors
This commit is contained in:
1 parent
6dacd3d964
commit
af1cbaeacc
3 files changed
+132
-122
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { useLightningAddress } from '@/hooks/useLightningAddress';
|
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 { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger} from '@/components/ui/dropdown-menu';
|
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() {
|
export function CashuWallet() {
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -131,7 +131,7 @@ export function CashuWallet() {
|
|||||||
// HELPER FUNCTIONS - History
|
// HELPER FUNCTIONS - History
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
const loadHistory = async () => {
|
const loadHistory = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoadingHistory(true);
|
setIsLoadingHistory(true);
|
||||||
const entries = await getHistory(50, 0);
|
const entries = await getHistory(50, 0);
|
||||||
@@ -141,7 +141,7 @@ export function CashuWallet() {
|
|||||||
} finally {
|
} finally {
|
||||||
setIsLoadingHistory(false);
|
setIsLoadingHistory(false);
|
||||||
}
|
}
|
||||||
};
|
}, [getHistory]);
|
||||||
|
|
||||||
const getHistoryIcon = (type: string) => {
|
const getHistoryIcon = (type: string) => {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
@@ -433,7 +433,7 @@ export function CashuWallet() {
|
|||||||
|
|
||||||
// Group proofs by denomination
|
// Group proofs by denomination
|
||||||
const denominations: { [key: number]: number } = {};
|
const denominations: { [key: number]: number } = {};
|
||||||
proofs.forEach((proof: any) => {
|
proofs.forEach((proof: { amount?: number }) => {
|
||||||
const amount = proof.amount || 0;
|
const amount = proof.amount || 0;
|
||||||
denominations[amount] = (denominations[amount] || 0) + 1;
|
denominations[amount] = (denominations[amount] || 0) + 1;
|
||||||
});
|
});
|
||||||
@@ -477,7 +477,7 @@ export function CashuWallet() {
|
|||||||
if (isInitialized && historyEntries.length === 0) {
|
if (isInitialized && historyEntries.length === 0) {
|
||||||
loadHistory();
|
loadHistory();
|
||||||
}
|
}
|
||||||
}, [isInitialized]);
|
}, [isInitialized, historyEntries.length, loadHistory]);
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// RENDER - Loading State
|
// RENDER - Loading State
|
||||||
@@ -577,7 +577,7 @@ export function CashuWallet() {
|
|||||||
onClick={() => setActiveMintUrl(mint.url)}
|
onClick={() => setActiveMintUrl(mint.url)}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="font-medium">{getCleanMintLabel(mint as any)}</span>
|
<span className="font-medium">{getCleanMintLabel(mint)}</span>
|
||||||
</div>
|
</div>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
|
|||||||
+123
-113
@@ -11,7 +11,7 @@ export interface CashuBalance {
|
|||||||
export interface CashuMint {
|
export interface CashuMint {
|
||||||
url: string;
|
url: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
info?: any;
|
info?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CashuMintQuote {
|
export interface CashuMintQuote {
|
||||||
@@ -28,7 +28,7 @@ export interface CashuMeltQuote {
|
|||||||
|
|
||||||
export interface CashuToken {
|
export interface CashuToken {
|
||||||
mint: string;
|
mint: string;
|
||||||
proofs: any[];
|
proofs: Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CashuState {
|
export interface CashuState {
|
||||||
@@ -47,11 +47,11 @@ export interface HistoryEntry {
|
|||||||
amount: number;
|
amount: number;
|
||||||
unit: string;
|
unit: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
metadata?: any;
|
metadata?: Record<string, unknown>;
|
||||||
quoteId?: string;
|
quoteId?: string;
|
||||||
state?: string;
|
state?: string;
|
||||||
paymentRequest?: string;
|
paymentRequest?: string;
|
||||||
token?: any;
|
token?: CashuToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CashuActions {
|
export interface CashuActions {
|
||||||
@@ -59,7 +59,7 @@ export interface CashuActions {
|
|||||||
receive: (token: string | CashuToken) => Promise<void>;
|
receive: (token: string | CashuToken) => Promise<void>;
|
||||||
send: (mintUrl: string, amount: number) => Promise<string>;
|
send: (mintUrl: string, amount: number) => Promise<string>;
|
||||||
getBalances: () => Promise<CashuBalance>;
|
getBalances: () => Promise<CashuBalance>;
|
||||||
getProofs: (mintUrl: string) => Promise<any[]>;
|
getProofs: (mintUrl: string) => Promise<Array<{ amount?: number; secret?: string; C?: string; [key: string]: unknown }>>;
|
||||||
|
|
||||||
// Mint operations
|
// Mint operations
|
||||||
addMint: (mintUrl: string) => Promise<void>;
|
addMint: (mintUrl: string) => Promise<void>;
|
||||||
@@ -90,11 +90,11 @@ export interface CashuActions {
|
|||||||
export type UseCashuReturn = CashuState & CashuActions;
|
export type UseCashuReturn = CashuState & CashuActions;
|
||||||
|
|
||||||
// Dynamic imports for coco-cashu packages
|
// Dynamic imports for coco-cashu packages
|
||||||
let Manager: any;
|
let Manager: unknown = null;
|
||||||
let IndexedDbRepositories: any;
|
let IndexedDbRepositories: unknown = null;
|
||||||
let ConsoleLogger: any;
|
let ConsoleLogger: unknown = null;
|
||||||
let getEncodedToken: any;
|
let getEncodedToken: unknown = null;
|
||||||
let getDecodedToken: any;
|
let _getDecodedToken: unknown = null;
|
||||||
|
|
||||||
// Lazy load coco-cashu packages
|
// Lazy load coco-cashu packages
|
||||||
const loadCocoCashu = async () => {
|
const loadCocoCashu = async () => {
|
||||||
@@ -107,7 +107,7 @@ const loadCocoCashu = async () => {
|
|||||||
Manager = coreModule.Manager;
|
Manager = coreModule.Manager;
|
||||||
ConsoleLogger = coreModule.ConsoleLogger;
|
ConsoleLogger = coreModule.ConsoleLogger;
|
||||||
getEncodedToken = coreModule.getEncodedToken;
|
getEncodedToken = coreModule.getEncodedToken;
|
||||||
getDecodedToken = coreModule.getDecodedToken;
|
_getDecodedToken = coreModule.getDecodedToken;
|
||||||
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
|
IndexedDbRepositories = indexedDbModule.IndexedDbRepositories;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load coco-cashu packages:', 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);
|
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
||||||
|
|
||||||
// Manager instance ref
|
// Manager instance ref
|
||||||
const managerRef = useRef<any>(null);
|
const managerRef = useRef<unknown>(null);
|
||||||
const repositoriesRef = useRef<any>(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
|
// Initialize the manager
|
||||||
const initializeManager = useCallback(async () => {
|
const initializeManager = useCallback(async () => {
|
||||||
@@ -151,15 +231,23 @@ export function useCashu(): UseCashuReturn {
|
|||||||
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
const seed = bip39.mnemonicToSeedSync(currentMnemonic);
|
||||||
|
|
||||||
// Initialize repositories
|
// Initialize repositories
|
||||||
const repositories = new IndexedDbRepositories({});
|
const repositories = new (IndexedDbRepositories as new (options: Record<string, unknown>) => { init: () => Promise<void> })({});
|
||||||
await repositories.init();
|
await repositories.init();
|
||||||
repositoriesRef.current = repositories;
|
repositoriesRef.current = repositories;
|
||||||
|
|
||||||
// Initialize manager
|
// 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,
|
repositories,
|
||||||
async () => seed,
|
async () => seed,
|
||||||
new ConsoleLogger(undefined, { level: 'info' })
|
new (ConsoleLogger as new (name: unknown, options: { level: string }) => unknown)(undefined, { level: 'info' })
|
||||||
);
|
);
|
||||||
managerRef.current = manager;
|
managerRef.current = manager;
|
||||||
|
|
||||||
@@ -178,53 +266,20 @@ export function useCashu(): UseCashuReturn {
|
|||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
}, [isInitialized, isLoading, mnemonic, setMnemonicState, refreshBalances, refreshMints, checkAndRedeemPendingQuotes]);
|
||||||
|
|
||||||
// Initialize on mount
|
// Initialize on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
initializeManager();
|
initializeManager();
|
||||||
}, [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
|
// Wallet operations
|
||||||
const receive = useCallback(async (token: string | CashuToken) => {
|
const receive = useCallback(async (token: string | CashuToken) => {
|
||||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
await managerRef.current.wallet.receive(token);
|
await (managerRef.current as { wallet: { receive: (token: string | CashuToken) => Promise<void> } }).wallet.receive(token);
|
||||||
await refreshBalances();
|
await refreshBalances();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
|
||||||
@@ -238,11 +293,11 @@ export function useCashu(): UseCashuReturn {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
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();
|
await refreshBalances();
|
||||||
|
|
||||||
// Encode the token into a Cashu token string
|
// Encode the token into a Cashu token string
|
||||||
const encodedToken = getEncodedToken(token);
|
const encodedToken = (getEncodedToken as (token: CashuToken) => string)(token);
|
||||||
return encodedToken;
|
return encodedToken;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
|
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');
|
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await managerRef.current.wallet.getBalances();
|
return await (managerRef.current as { wallet: { getBalances: () => Promise<CashuBalance> } }).wallet.getBalances();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
|
||||||
setError(errorMessage);
|
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');
|
if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
|
console.log('🔍 Getting proofs from wallet for mint:', mintUrl);
|
||||||
|
|
||||||
// Access the proof repository
|
// 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) {
|
if (!proofRepo) {
|
||||||
throw new Error('Proof repository not available');
|
throw new Error('Proof repository not available');
|
||||||
}
|
}
|
||||||
@@ -279,7 +334,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
|
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
|
||||||
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${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) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
|
||||||
console.error('❌ Error getting proofs:', err);
|
console.error('❌ Error getting proofs:', err);
|
||||||
@@ -294,7 +349,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
await managerRef.current.mint.addMint(mintUrl);
|
await (managerRef.current as { mint: { addMint: (mintUrl: string) => Promise<unknown> } }).mint.addMint(mintUrl);
|
||||||
await refreshMints();
|
await refreshMints();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
|
||||||
@@ -303,7 +358,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
}
|
}
|
||||||
}, [refreshMints]);
|
}, [refreshMints]);
|
||||||
|
|
||||||
const removeMint = useCallback(async (mintUrl: string) => {
|
const removeMint = useCallback(async (_mintUrl: string) => {
|
||||||
// Note: coco-cashu doesn't have a direct remove mint method
|
// Note: coco-cashu doesn't have a direct remove mint method
|
||||||
// This would need to be implemented at the repository level
|
// This would need to be implemented at the repository level
|
||||||
setError('Remove mint functionality not yet implemented');
|
setError('Remove mint functionality not yet implemented');
|
||||||
@@ -314,10 +369,10 @@ export function useCashu(): UseCashuReturn {
|
|||||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||||
|
|
||||||
try {
|
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
|
return mintList
|
||||||
.filter((mint: any) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
|
.filter((mint: { mintUrl?: string }) => mint && mint.mintUrl) // Filter out invalid mints - use mintUrl not url
|
||||||
.map((mint: any) => ({
|
.map((mint: { mintUrl: string; name?: string; mintInfo?: Record<string, unknown> }) => ({
|
||||||
url: mint.mintUrl, // Map mintUrl to url for consistency
|
url: mint.mintUrl, // Map mintUrl to url for consistency
|
||||||
name: mint.name,
|
name: mint.name,
|
||||||
info: mint.mintInfo
|
info: mint.mintInfo
|
||||||
@@ -335,7 +390,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
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 {
|
return {
|
||||||
quote: quote.quote,
|
quote: quote.quote,
|
||||||
request: quote.request,
|
request: quote.request,
|
||||||
@@ -354,7 +409,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
|
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...');
|
console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...');
|
||||||
await refreshBalances();
|
await refreshBalances();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -369,7 +424,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
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 {
|
return {
|
||||||
quote: quote.quote,
|
quote: quote.quote,
|
||||||
request: quote.request,
|
request: quote.request,
|
||||||
@@ -387,7 +442,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
setError(null);
|
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();
|
await refreshBalances();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
|
||||||
@@ -415,51 +470,6 @@ export function useCashu(): UseCashuReturn {
|
|||||||
return mnemonic;
|
return mnemonic;
|
||||||
}, [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(() => {
|
const clearError = useCallback(() => {
|
||||||
setError(null);
|
setError(null);
|
||||||
}, []);
|
}, []);
|
||||||
@@ -472,7 +482,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
console.log('📜 Getting transaction history...');
|
console.log('📜 Getting transaction history...');
|
||||||
|
|
||||||
// Access the history repository (correct property name is historyRepository)
|
// 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) {
|
if (!historyRepo) {
|
||||||
throw new Error('History repository not available');
|
throw new Error('History repository not available');
|
||||||
}
|
}
|
||||||
@@ -481,7 +491,7 @@ export function useCashu(): UseCashuReturn {
|
|||||||
const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset);
|
const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset);
|
||||||
console.log(`✅ Found ${entries.length} history entries`);
|
console.log(`✅ Found ${entries.length} history entries`);
|
||||||
|
|
||||||
return entries;
|
return entries as unknown as HistoryEntry[];
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
|
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
|
||||||
console.error('❌ Error getting history:', err);
|
console.error('❌ Error getting history:', err);
|
||||||
|
|||||||
@@ -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.'}`);
|
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.');
|
throw new Error('Invalid request. Please check your parameters and try again.');
|
||||||
}
|
}
|
||||||
} else if (response.status === 404) {
|
} else if (response.status === 404) {
|
||||||
@@ -133,7 +133,7 @@ async function handleAPIError(response: Response) {
|
|||||||
try {
|
try {
|
||||||
const errorData = await response.json();
|
const errorData = await response.json();
|
||||||
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
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.`);
|
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user