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
Generated
+82
-5
@@ -40,12 +40,15 @@
|
|||||||
"@radix-ui/react-toggle": "^1.1.0",
|
"@radix-ui/react-toggle": "^1.1.0",
|
||||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||||
"@radix-ui/react-tooltip": "^1.1.4",
|
"@radix-ui/react-tooltip": "^1.1.4",
|
||||||
|
"@scure/bip39": "^2.0.0",
|
||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.0",
|
"cmdk": "^1.0.0",
|
||||||
|
"coco-cashu-core": "file:../coco/packages/core",
|
||||||
|
"coco-cashu-indexeddb": "file:../coco/packages/indexeddb",
|
||||||
"date-fns": "^3.6.0",
|
"date-fns": "^3.6.0",
|
||||||
"embla-carousel-react": "^8.3.0",
|
"embla-carousel-react": "^8.3.0",
|
||||||
"input-otp": "^1.2.4",
|
"input-otp": "^1.2.4",
|
||||||
@@ -92,6 +95,38 @@
|
|||||||
"vitest": "^3.1.4"
|
"vitest": "^3.1.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"../coco/packages/core": {
|
||||||
|
"name": "coco-cashu-core",
|
||||||
|
"version": "1.0.0-rc9",
|
||||||
|
"dependencies": {
|
||||||
|
"@cashu/cashu-ts": "^2.7.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bun": "latest",
|
||||||
|
"esbuild": "latest",
|
||||||
|
"tsdown": "^0.14.1",
|
||||||
|
"typescript": "^5.9.2",
|
||||||
|
"typescript-eslint": "^8.40.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": "^5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"../coco/packages/indexeddb": {
|
||||||
|
"name": "coco-cashu-indexeddb",
|
||||||
|
"version": "0.8.0",
|
||||||
|
"dependencies": {
|
||||||
|
"dexie": "^4.0.8"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bun": "latest",
|
||||||
|
"tsdown": "^0.14.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"coco-cashu-core": "workspace:^",
|
||||||
|
"typescript": "^5"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@adobe/css-tools": {
|
"node_modules/@adobe/css-tools": {
|
||||||
"version": "4.4.3",
|
"version": "4.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.3.tgz",
|
||||||
@@ -3037,18 +3072,39 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@scure/bip39": {
|
"node_modules/@scure/bip39": {
|
||||||
"version": "1.2.1",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.0.0.tgz",
|
||||||
"integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==",
|
"integrity": "sha512-F2Tza4KyTSFO/13JymY6a6UHfSLzx0YGbkQGz7wjGx2BYJLyG/qXELKnFFsDfeIK+WfV2v2+5XOQftvL4d8RBA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "~1.3.0",
|
"@noble/hashes": "2.0.0",
|
||||||
"@scure/base": "~1.1.0"
|
"@scure/base": "2.0.0"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@scure/bip39/node_modules/@noble/hashes": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-h8VUBlE8R42+XIDO229cgisD287im3kdY6nbNZJFjc6ZvKIXPYXe6Vc/t+kyjFdMFyt5JpapzTsEg8n63w5/lw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 20.19.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@scure/bip39/node_modules/@scure/base": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@swc/core": {
|
"node_modules/@swc/core": {
|
||||||
"version": "1.11.24",
|
"version": "1.11.24",
|
||||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
||||||
@@ -4426,6 +4482,14 @@
|
|||||||
"react-dom": "^18 || ^19 || ^19.0.0-rc"
|
"react-dom": "^18 || ^19 || ^19.0.0-rc"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/coco-cashu-core": {
|
||||||
|
"resolved": "../coco/packages/core",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
|
"node_modules/coco-cashu-indexeddb": {
|
||||||
|
"resolved": "../coco/packages/indexeddb",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/color-convert": {
|
"node_modules/color-convert": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||||
@@ -6046,6 +6110,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/nostr-tools/node_modules/@scure/bip39": {
|
||||||
|
"version": "1.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz",
|
||||||
|
"integrity": "sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@noble/hashes": "~1.3.0",
|
||||||
|
"@scure/base": "~1.1.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/nostr-wasm": {
|
"node_modules/nostr-wasm": {
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz",
|
||||||
|
|||||||
@@ -15,6 +15,9 @@
|
|||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||||
|
"@scure/bip39": "^2.0.0",
|
||||||
|
"coco-cashu-core": "file:../coco/packages/core",
|
||||||
|
"coco-cashu-indexeddb": "file:../coco/packages/indexeddb",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
|
|||||||
import Index from "./pages/Index";
|
import Index from "./pages/Index";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
|
import { CashuWallet } from "./components/CashuWallet";
|
||||||
|
|
||||||
export function AppRouter() {
|
export function AppRouter() {
|
||||||
return (
|
return (
|
||||||
@@ -11,6 +12,7 @@ export function AppRouter() {
|
|||||||
<ScrollToTop />
|
<ScrollToTop />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Index />} />
|
<Route path="/" element={<Index />} />
|
||||||
|
<Route path="/wallet" element={<CashuWallet />} />
|
||||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||||
<Route path="/:nip19" element={<NIP19Page />} />
|
<Route path="/:nip19" element={<NIP19Page />} />
|
||||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
|
||||||
Reference in new issue
Block a user