mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
cashu wallet integration
This commit is contained in:
1 parent
c69e440c04
commit
6dacd3d964
6 files changed
+1896
-5
No files matched your search
@@ -0,0 +1,523 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useLocalStorage } from './useLocalStorage';
|
||||
import * as bip39 from '@scure/bip39';
|
||||
import { wordlist } from '@scure/bip39/wordlists/english';
|
||||
|
||||
// Types for the hook interface
|
||||
export interface CashuBalance {
|
||||
[mintUrl: string]: number;
|
||||
}
|
||||
|
||||
export interface CashuMint {
|
||||
url: string;
|
||||
name?: string;
|
||||
info?: any;
|
||||
}
|
||||
|
||||
export interface CashuMintQuote {
|
||||
quote: string;
|
||||
request: string;
|
||||
expiry: number;
|
||||
}
|
||||
|
||||
export interface CashuMeltQuote {
|
||||
quote: string;
|
||||
request: string;
|
||||
expiry: number;
|
||||
}
|
||||
|
||||
export interface CashuToken {
|
||||
mint: string;
|
||||
proofs: any[];
|
||||
}
|
||||
|
||||
export interface CashuState {
|
||||
isInitialized: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
balances: CashuBalance;
|
||||
mints: CashuMint[];
|
||||
mnemonic: string | null;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
id: string;
|
||||
type: 'mint' | 'melt' | 'send' | 'receive';
|
||||
mintUrl: string;
|
||||
amount: number;
|
||||
unit: string;
|
||||
createdAt: number;
|
||||
metadata?: any;
|
||||
quoteId?: string;
|
||||
state?: string;
|
||||
paymentRequest?: string;
|
||||
token?: any;
|
||||
}
|
||||
|
||||
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<any[]>;
|
||||
|
||||
// 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>;
|
||||
|
||||
// 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>;
|
||||
checkAndRedeemPendingQuotes: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// 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 Error('Cashu packages not available. Please install coco-cashu-core and coco-cashu-indexeddb');
|
||||
}
|
||||
};
|
||||
|
||||
export function useCashu(): UseCashuReturn {
|
||||
// State management
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [balances, setBalances] = useState<CashuBalance>({});
|
||||
const [mints, setMints] = useState<CashuMint[]>([]);
|
||||
|
||||
// Mnemonic management with localStorage
|
||||
const [mnemonic, setMnemonicState] = useLocalStorage<string | null>('cashu-mnemonic', null);
|
||||
|
||||
// Manager instance ref
|
||||
const managerRef = useRef<any>(null);
|
||||
const repositoriesRef = useRef<any>(null);
|
||||
|
||||
// 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({});
|
||||
await repositories.init();
|
||||
repositoriesRef.current = repositories;
|
||||
|
||||
// Initialize manager
|
||||
const manager = new Manager(
|
||||
repositories,
|
||||
async () => seed,
|
||||
new ConsoleLogger(undefined, { level: 'info' })
|
||||
);
|
||||
managerRef.current = manager;
|
||||
|
||||
// Load initial data
|
||||
await refreshBalances();
|
||||
await refreshMints();
|
||||
|
||||
// Check for any pending quotes that might have been paid
|
||||
await checkAndRedeemPendingQuotes();
|
||||
|
||||
setIsInitialized(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize Cashu wallet';
|
||||
setError(errorMessage);
|
||||
console.error('Cashu initialization error:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isInitialized, isLoading, mnemonic, setMnemonicState]);
|
||||
|
||||
// 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 refreshBalances();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to receive token';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [refreshBalances]);
|
||||
|
||||
const send = useCallback(async (mintUrl: string, amount: number): Promise<string> => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
const token = await managerRef.current.wallet.send(mintUrl, amount);
|
||||
await refreshBalances();
|
||||
|
||||
// Encode the token into a Cashu token string
|
||||
const encodedToken = getEncodedToken(token);
|
||||
return encodedToken;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to send tokens';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [refreshBalances]);
|
||||
|
||||
const getBalances = useCallback(async (): Promise<CashuBalance> => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
return await managerRef.current.wallet.getBalances();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get balances';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const getProofs = useCallback(async (mintUrl: string): Promise<any[]> => {
|
||||
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;
|
||||
if (!proofRepo) {
|
||||
throw new Error('Proof repository not available');
|
||||
}
|
||||
|
||||
// Get ready proofs for this mint (proofs available to spend)
|
||||
const readyProofs = await proofRepo.getReadyProofs(mintUrl);
|
||||
console.log(`✅ Found ${readyProofs.length} ready proofs for mint ${mintUrl}`);
|
||||
|
||||
return readyProofs;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get proofs';
|
||||
console.error('❌ Error getting proofs:', err);
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Mint operations
|
||||
const addMint = useCallback(async (mintUrl: string) => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
await managerRef.current.mint.addMint(mintUrl);
|
||||
await refreshMints();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to add mint';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [refreshMints]);
|
||||
|
||||
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');
|
||||
throw new Error('Remove mint functionality not yet implemented');
|
||||
}, []);
|
||||
|
||||
const getMints = useCallback(async (): Promise<CashuMint[]> => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
const mintList = await managerRef.current.mint.getAllMints();
|
||||
return 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
|
||||
}));
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get mints';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Quote operations
|
||||
const createMintQuote = useCallback(async (mintUrl: string, amount: number): Promise<CashuMintQuote> => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
const quote = await managerRef.current.quotes.createMintQuote(mintUrl, amount);
|
||||
return {
|
||||
quote: quote.quote,
|
||||
request: quote.request,
|
||||
expiry: quote.expiry
|
||||
};
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to create mint quote';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const redeemMintQuote = useCallback(async (mintUrl: string, quoteId: string) => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
console.log('🔄 redeemMintQuote: Redeeming quote for mint:', mintUrl, 'quote:', quoteId);
|
||||
await managerRef.current.quotes.redeemMintQuote(mintUrl, quoteId);
|
||||
console.log('✅ redeemMintQuote: Quote redeemed successfully, refreshing balances...');
|
||||
await refreshBalances();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to redeem mint quote';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [refreshBalances]);
|
||||
|
||||
const createMeltQuote = useCallback(async (mintUrl: string, invoice: string): Promise<CashuMeltQuote> => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
const quote = await managerRef.current.quotes.createMeltQuote(mintUrl, invoice);
|
||||
return {
|
||||
quote: quote.quote,
|
||||
request: quote.request,
|
||||
expiry: quote.expiry
|
||||
};
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to create melt quote';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const payMeltQuote = useCallback(async (mintUrl: string, quoteId: string) => {
|
||||
if (!managerRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
await managerRef.current.quotes.payMeltQuote(mintUrl, quoteId);
|
||||
await refreshBalances();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to pay melt quote';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, [refreshBalances]);
|
||||
|
||||
// Mnemonic operations
|
||||
const setMnemonic = useCallback((newMnemonic: string) => {
|
||||
if (!bip39.validateMnemonic(newMnemonic, wordlist)) {
|
||||
throw new Error('Invalid mnemonic');
|
||||
}
|
||||
setMnemonicState(newMnemonic);
|
||||
// Reinitialize manager with new mnemonic
|
||||
setIsInitialized(false);
|
||||
initializeManager();
|
||||
}, [setMnemonicState, initializeManager]);
|
||||
|
||||
const generateMnemonic = useCallback(() => {
|
||||
return bip39.generateMnemonic(wordlist);
|
||||
}, []);
|
||||
|
||||
const getMnemonic = useCallback(() => {
|
||||
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);
|
||||
}, []);
|
||||
|
||||
// History operations
|
||||
const getHistory = useCallback(async (limit: number = 50, offset: number = 0): Promise<HistoryEntry[]> => {
|
||||
if (!managerRef.current || !repositoriesRef.current) throw new Error('Wallet not initialized');
|
||||
|
||||
try {
|
||||
console.log('📜 Getting transaction history...');
|
||||
|
||||
// Access the history repository (correct property name is historyRepository)
|
||||
const historyRepo = (repositoriesRef.current as any).historyRepository;
|
||||
if (!historyRepo) {
|
||||
throw new Error('History repository not available');
|
||||
}
|
||||
|
||||
// Get paginated history entries
|
||||
const entries = await historyRepo.getPaginatedHistoryEntries(limit, offset);
|
||||
console.log(`✅ Found ${entries.length} history entries`);
|
||||
|
||||
return entries;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get history';
|
||||
console.error('❌ Error getting history:', err);
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
// State
|
||||
isInitialized,
|
||||
isLoading,
|
||||
error,
|
||||
balances,
|
||||
mints,
|
||||
mnemonic,
|
||||
|
||||
// Actions
|
||||
receive,
|
||||
send,
|
||||
getBalances,
|
||||
getProofs,
|
||||
addMint,
|
||||
removeMint,
|
||||
getMints,
|
||||
createMintQuote,
|
||||
redeemMintQuote,
|
||||
createMeltQuote,
|
||||
payMeltQuote,
|
||||
setMnemonic,
|
||||
generateMnemonic,
|
||||
getMnemonic,
|
||||
getHistory,
|
||||
refreshBalances,
|
||||
refreshMints,
|
||||
checkAndRedeemPendingQuotes,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user