import { useState, useCallback, useEffect } from 'react'; import { nip19 } from 'nostr-tools'; import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/wallet/useReverseSwap'; import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin'; import type { Manager } from 'coco-cashu-core'; import { useToast } from '@/hooks/useToast'; interface UseReverseSwapOperationsProps { coco: Manager | null; activeMintUrl: string | null; } export function useReverseSwapOperations({ coco, activeMintUrl }: UseReverseSwapOperationsProps) { const { toast } = useToast(); // Reverse swap state (Lightning -> Bitcoin) const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState(null); const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState(''); const [swapStatus, setSwapStatus] = useState(null); const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null); // Detect if input is a Bitcoin address or npub for reverse swap const detectBitcoinAddress = useCallback((input: string): boolean => { // Check if it's a Bitcoin address if (isValidBitcoinAddress(input)) { setPendingBitcoinSwapAddress(input); return true; } // Check if it's an npub (can be converted to Bitcoin address) try { const decoded = nip19.decode(input); if (decoded.type === 'npub') { const bitcoinAddr = npubToBitcoinAddress(input); if (bitcoinAddr) { setPendingBitcoinSwapAddress(input); // Store npub, will convert later return true; } } } catch { // Not an npub, continue } return false; }, []); // Handle reverse swap execution const handleReverseSwap = useCallback(async () => { if (!coco || !pendingBitcoinSwapAddress || !bitcoinSwapAmount || !activeMintUrl) { return; } try { const amount = parseInt(bitcoinSwapAmount); if (isNaN(amount) || amount <= 0) { toast({ variant: 'destructive', title: 'Invalid Amount', description: 'Please enter a valid amount', }); return; } // Validate reverse swap amount limits (25,000 - 25,000,000 sats) if (amount < 25_000 || amount > 25_000_000) { toast({ variant: 'destructive', title: 'Invalid Amount', description: 'Reverse swap amount must be between 25,000 and 25,000,000 sats', }); return; } // Determine destination address (could be Bitcoin address or npub) let destinationAddress = pendingBitcoinSwapAddress; try { // Try to decode as npub first const decoded = nip19.decode(pendingBitcoinSwapAddress); if (decoded.type === 'npub') { destinationAddress = npubToBitcoinAddress(pendingBitcoinSwapAddress); } } catch { // Not an npub, assume it's already a Bitcoin address } // Initiate reverse swap setSwapStatus('Creating reverse swap...'); const swapResult = await createReverseSwap({ invoiceAmount: amount, destinationAddress, onStatusUpdate: (update: SwapStatusUpdate) => { switch (update.status) { case 'swap.created': setSwapStatus('Waiting for invoice payment...'); break; case 'transaction.mempool': setSwapStatus('Swap transaction sent to blockchain...'); break; case 'invoice.settled': case 'transaction.confirmed': setSwapStatus('Swap completed!'); break; } }, onSuccess: () => { const displayAddress = destinationAddress.length > 26 ? destinationAddress.slice(0, 12) + '...' + destinationAddress.slice(-12) : destinationAddress; toast({ title: 'Reverse Swap Completed', description: `Successfully swapped ${amount} sats to Bitcoin address ${displayAddress}!`, }); setSwapStatus(null); setPendingBitcoinSwapAddress(null); setBitcoinSwapAmount(''); if (reverseSwapClose) { reverseSwapClose(); setReverseSwapClose(null); } }, onError: (error: Error) => { toast({ variant: 'destructive', title: 'Reverse Swap Failed', description: error.message, }); setSwapStatus(null); setPendingBitcoinSwapAddress(null); setBitcoinSwapAmount(''); if (reverseSwapClose) { reverseSwapClose(); setReverseSwapClose(null); } }, }); // Store close function for cleanup setReverseSwapClose(() => swapResult.close); // Pay the Lightning invoice from the swap using the active mint setSwapStatus('Paying Lightning invoice...'); const meltQuote = await coco.quotes.createMeltQuote( activeMintUrl, swapResult.invoice ); await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote); toast({ title: 'Invoice Paid', description: `Lightning invoice paid. Swap in progress...`, }); } catch (err) { console.error('Reverse swap error:', err); toast({ variant: 'destructive', title: 'Reverse Swap Failed', description: err instanceof Error ? err.message : 'Unknown error', }); setSwapStatus(null); setPendingBitcoinSwapAddress(null); setBitcoinSwapAmount(''); if (reverseSwapClose) { reverseSwapClose(); setReverseSwapClose(null); } } }, [coco, pendingBitcoinSwapAddress, bitcoinSwapAmount, activeMintUrl, toast, reverseSwapClose]); // Cleanup reverse swap WebSocket on unmount useEffect(() => { return () => { if (reverseSwapClose) { reverseSwapClose(); } }; }, [reverseSwapClose]); return { // State pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress, bitcoinSwapAmount, setBitcoinSwapAmount, swapStatus, // Functions detectBitcoinAddress, handleReverseSwap, }; }