mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
251 lines
8.0 KiB
TypeScript
251 lines
8.0 KiB
TypeScript
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
import { useLocalStorage } from '../useLocalStorage';
|
|
import * as bip39 from '@scure/bip39';
|
|
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
|
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;
|
|
refreshMints: () => Promise<void>;
|
|
}
|
|
|
|
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 refreshMints = useCallback(async () => {
|
|
const coco = cocoRef.current;
|
|
if (!coco) return;
|
|
|
|
try {
|
|
const mintList = await coco.mint.getAllMints();
|
|
setMints(mintList.map((m: any) => ({
|
|
url: m.mintUrl,
|
|
name: m.name,
|
|
info: m.mintInfo
|
|
})));
|
|
} catch (err) {
|
|
console.error('Failed to refresh mints:', err);
|
|
}
|
|
}, []);
|
|
|
|
const setMnemonic = useCallback((newMnemonic: string) => {
|
|
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
|
throw new Error('Invalid mnemonic');
|
|
}
|
|
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
|
|
}
|
|
};
|
|
|
|
// 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, refreshMints]);
|
|
|
|
// 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,
|
|
refreshMints,
|
|
};
|
|
} |