cashu wallet integration

This commit is contained in:
lemonknowsall committed 2025-10-05 23:02:14 -07:00
1 parent c69e440c04
commit 6dacd3d964
6 files changed
+1896 -5

No files matched your search

+2
View File
@@ -4,6 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { CashuWallet } from "./components/CashuWallet";
export function AppRouter() {
return (
@@ -11,6 +12,7 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/wallet" element={<CashuWallet />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
File diff suppressed because it is too large. Load diff
+523
View File
@@ -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,
};
}
+159
View File
@@ -0,0 +1,159 @@
import { useState, useCallback } from 'react';
// LNURL Protocol Types
interface LNURLPayResponse {
status: 'OK' | 'ERROR';
tag: 'payRequest';
commentAllowed?: number;
minSendable: number; // millisats
maxSendable: number; // millisats
metadata: string;
callback: string;
}
interface LNURLInvoiceResponse {
status: 'OK' | 'ERROR';
reason?: string;
pr?: string; // BOLT11 invoice
}
interface GetInvoiceParams {
lightningAddress: string;
amountSats: number;
comment?: string;
}
interface UseLightningAddressReturn {
getInvoice: (params: GetInvoiceParams) => Promise<string>;
isLoading: boolean;
error: string | null;
}
/**
* Hook for resolving Lightning addresses to invoices
*
* @example
* ```tsx
* const { getInvoice, isLoading, error } = useLightningAddress();
*
* const invoice = await getInvoice({
* lightningAddress: '[email protected]',
* amountSats: 1000,
* comment: 'Thanks for the coffee!'
* });
* ```
*/
export function useLightningAddress(): UseLightningAddressReturn {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/**
* Fetches a Lightning invoice for the given address and amount
*
* @param params - Lightning address, amount in sats, and optional comment
* @returns BOLT11 invoice string
* @throws Error if resolution fails
*/
const getInvoice = useCallback(async (params: GetInvoiceParams): Promise<string> => {
const { lightningAddress, amountSats, comment } = params;
setIsLoading(true);
setError(null);
try {
// Validate inputs
if (!lightningAddress || !lightningAddress.includes('@')) {
throw new Error('Invalid Lightning address format. Expected: [email protected]');
}
if (amountSats <= 0) {
throw new Error('Amount must be greater than 0');
}
// Parse Lightning address
const [username, domain] = lightningAddress.split('@');
if (!username || !domain) {
throw new Error('Invalid Lightning address format');
}
// Step 1: Fetch LNURL-pay info
const lnurlEndpoint = `https://${domain}/.well-known/lnurlp/${username}`;
const lnurlResponse = await fetch(lnurlEndpoint, {
headers: { 'Accept': 'application/json' },
});
if (!lnurlResponse.ok) {
throw new Error(`Failed to resolve Lightning address: ${lnurlResponse.status}`);
}
const lnurlData: LNURLPayResponse = await lnurlResponse.json();
if (lnurlData.status !== 'OK') {
throw new Error('LNURL endpoint returned error status');
}
if (lnurlData.tag !== 'payRequest') {
throw new Error(`Unexpected LNURL tag: ${lnurlData.tag}`);
}
// Validate amount against min/max bounds
const minSats = lnurlData.minSendable / 1000;
const maxSats = lnurlData.maxSendable / 1000;
if (amountSats < minSats) {
throw new Error(`Amount ${amountSats} sats is below minimum ${minSats} sats`);
}
if (amountSats > maxSats) {
throw new Error(`Amount ${amountSats} sats exceeds maximum ${maxSats} sats`);
}
// Step 2: Request invoice from callback URL
const amountMsats = amountSats * 1000;
const callbackUrl = new URL(lnurlData.callback);
callbackUrl.searchParams.set('amount', amountMsats.toString());
// Add comment if provided and allowed
if (comment && lnurlData.commentAllowed && comment.length <= lnurlData.commentAllowed) {
callbackUrl.searchParams.set('comment', comment);
}
const invoiceResponse = await fetch(callbackUrl.toString(), {
headers: { 'Accept': 'application/json' },
});
if (!invoiceResponse.ok) {
throw new Error(`Failed to get invoice: ${invoiceResponse.status}`);
}
const invoiceData: LNURLInvoiceResponse = await invoiceResponse.json();
if (invoiceData.status !== 'OK') {
throw new Error(invoiceData.reason || 'Invoice generation failed');
}
if (!invoiceData.pr) {
throw new Error('No invoice returned from provider');
}
setIsLoading(false);
return invoiceData.pr;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
setError(errorMessage);
setIsLoading(false);
throw err;
}
}, []);
return {
getInvoice,
isLoading,
error,
};
}
export type { GetInvoiceParams };