code cleanup round 2

This commit is contained in:
lemonknowsall committed 2025-10-15 00:10:24 -07:00
1 parent aaf12120e6
commit 2ac097d8de
9 files changed
+326 -669

No files matched your search

-247
View File
@@ -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,
};
}
-142
View File
@@ -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
View File
@@ -1,17 +1,246 @@
// Re-export the new modular useCashu hook and types
export { useCashu } from './index';
export type {
UseCashuReturn,
CashuBalance,
CashuMint,
CashuMintQuote,
CashuMeltQuote,
CashuToken,
HistoryEntry,
CashuWalletError,
CashuInitializationError,
CashuMintError,
CashuQuoteError,
CashuTokenError
} from './types';
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 { initializeCoco, ConsoleLogger, getEncodedToken, type Repositories } from 'coco-cashu-core';
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
// 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,
};
}
-164
View File
@@ -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,
};
}
+4 -4
View File
@@ -30,7 +30,7 @@ export function useZaps(
const author = useAuthor(actualTarget?.pubkey);
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 [invoice, setInvoice] = useState<string | null>(null);
@@ -258,12 +258,12 @@ export function useZaps(
return balance >= amount;
});
if (mintWithBalance) {
if (mintWithBalance && coco) {
// 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)
await payMeltQuote(mintWithBalance.url, meltQuote.quote);
await coco.quotes.payMeltQuote(mintWithBalance.url, meltQuote.quote);
// Clear states immediately on success
setIsZapping(false);