use reverse swap addition to lightning mode

This commit is contained in:
lemonknowsall committed 2025-10-30 22:44:05 -07:00
1 parent e6cef5b87c
commit 4a278d29e6
8 files changed
+1577 -16

No files matched your search

+42 -1
View File
@@ -18,7 +18,8 @@ import { QRModal } from '@/components/ui/qr-modal';
import { WalletHeader } from './WalletHeader';
import { TransactionCard } from './PaymentCard';
import { WalletModals } from './WalletModals';
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { TransactionHistory } from './TransactionHistory';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronUp, Send, Download, ScanLine } from 'lucide-react';
@@ -132,6 +133,11 @@ export function CashuWallet() {
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
sentToken,
setSentToken,
sentTokenQRCode,
@@ -211,6 +217,9 @@ export function CashuWallet() {
setPendingLightningAddress(null);
setDecodedInvoiceAmount(null);
setPendingInvoice(null);
// Reset reverse swap state
setPendingBitcoinSwapAddress(null);
setBitcoinSwapAmount('');
// Reset Bitcoin state
setBitcoinAmount('');
setBitcoinRecipient('');
@@ -345,6 +354,17 @@ export function CashuWallet() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showQRScanner, startScanning, stopScanning, setModalOpen]);
// Handle focus management when drawers open to prevent aria-hidden warnings
useEffect(() => {
if (showSendModal || showReceiveModal || showHistoryModal) {
// Blur any currently focused element to allow drawer's focus trap to work
const activeElement = document.activeElement as HTMLElement;
if (activeElement && activeElement.blur) {
activeElement.blur();
}
}
}, [showSendModal, showReceiveModal, showHistoryModal]);
// ============================================================================
// EFFECTS - Cleanup
// ============================================================================
@@ -617,6 +637,11 @@ export function CashuWallet() {
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Send</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Send tokens, Lightning payments, or Bitcoin
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
@@ -677,6 +702,12 @@ export function CashuWallet() {
hasNsecAccess={hasNsecAccess}
bitcoinMaxAmount={bitcoinMaxAmount}
onSendMax={() => handleSendMax(setBitcoinAmount)}
// Reverse swap props
pendingBitcoinSwapAddress={pendingBitcoinSwapAddress}
setPendingBitcoinSwapAddress={setPendingBitcoinSwapAddress}
bitcoinSwapAmount={bitcoinSwapAmount}
setBitcoinSwapAmount={setBitcoinSwapAmount}
swapStatus={swapStatus}
/>
</div>
</DrawerContent>
@@ -686,6 +717,11 @@ export function CashuWallet() {
<DrawerContent className="min-h-[40vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Receive</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
Receive tokens, Lightning invoices, or Bitcoin
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<div className="px-4 pb-6 pb-safe-bottom">
<TransactionCard
@@ -740,6 +776,11 @@ export function CashuWallet() {
<DrawerContent className="max-h-[80vh] max-w-4xl mx-auto">
<DrawerHeader>
<DrawerTitle className="text-center text-3xl font-bold">Transactions</DrawerTitle>
<VisuallyHidden.Root asChild>
<DrawerDescription>
View your transaction history
</DrawerDescription>
</VisuallyHidden.Root>
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
+126 -5
View File
@@ -64,6 +64,12 @@ interface TransactionCardProps {
hasNsecAccess?: boolean;
bitcoinMaxAmount?: number;
onSendMax?: () => void;
// Reverse swap props (Lightning mode)
pendingBitcoinSwapAddress?: string | null;
setPendingBitcoinSwapAddress?: (value: string | null) => void;
bitcoinSwapAmount?: string;
setBitcoinSwapAmount?: (value: string) => void;
swapStatus?: string | null;
}
export function TransactionCard({
@@ -103,12 +109,19 @@ export function TransactionCard({
hasNsecAccess,
bitcoinMaxAmount,
onSendMax,
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
}: TransactionCardProps) {
// Slider state for confirmation
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
const [addressSliderValue, setAddressSliderValue] = useState([0]);
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
const [swapSliderValue, setSwapSliderValue] = useState([0]);
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
const [swapAmountError, setSwapAmountError] = useState<string | null>(null);
// Handle slider value changes and auto-submit at 100%
const handleInvoiceSliderChange = (value: number[]) => {
@@ -132,6 +145,13 @@ export function TransactionCard({
}
};
const handleSwapSliderChange = (value: number[]) => {
setSwapSliderValue(value);
if (value[0] === 100) {
onSend();
}
};
const handleSendMaxToggle = () => {
const newState = !sendMaxEnabled;
setSendMaxEnabled(newState);
@@ -148,6 +168,8 @@ export function TransactionCard({
setAddressSliderValue([0]);
} else if (sliderId === 'bitcoin' && bitcoinSliderValue[0] !== 100) {
setBitcoinSliderValue([0]);
} else if (sliderId === 'swap' && swapSliderValue[0] !== 100) {
setSwapSliderValue([0]);
}
};
@@ -171,11 +193,36 @@ export function TransactionCard({
}
}, [pendingBitcoinRecipient]);
useEffect(() => {
if (!pendingBitcoinSwapAddress) {
setSwapSliderValue([0]);
setSwapAmountError(null);
}
}, [pendingBitcoinSwapAddress]);
// Validate swap amount when it changes
useEffect(() => {
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
const amount = parseInt(bitcoinSwapAmount);
if (isNaN(amount) || amount <= 0) {
setSwapAmountError('Please enter a valid amount');
} else if (amount < 25_000) {
setSwapAmountError('Minimum amount is 25,000 sats');
} else if (amount > 25_000_000) {
setSwapAmountError('Maximum amount is 25,000,000 sats');
} else {
setSwapAmountError(null);
}
} else {
setSwapAmountError(null);
}
}, [bitcoinSwapAmount, pendingBitcoinSwapAddress]);
return (
<div className="space-y-8">
{/* Title */}
<div className="text-center">
<p className="text-base text-muted-foreground mt-2">
<div className="text-base text-muted-foreground mt-2">
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
@@ -234,7 +281,24 @@ export function TransactionCard({
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : 'Pay invoices or addresses'
) : pendingBitcoinSwapAddress ? (
<div className="flex items-center justify-center gap-2">
<span className="inline-block px-3 py-1.5 bg-orange-500/10 border border-orange-500/20 rounded-md">
<span className="font-bold text-orange-600 dark:text-orange-400">Reverse Swap to:</span>{' '}
<span className="font-semibold text-foreground">{truncateAddress(pendingBitcoinSwapAddress)}</span>
</span>
<button
onClick={() => {
setPendingBitcoinSwapAddress?.(null);
setBitcoinSwapAmount?.('');
}}
className="p-1.5 rounded-full hover:bg-muted transition-colors"
title="Cancel"
>
<X className="h-4 w-4 text-muted-foreground" />
</button>
</div>
) : 'Pay invoices, addresses, or Bitcoin addresses'
) : (
mode === 'tokens'
? 'Enter Cashu token to redeem'
@@ -242,7 +306,7 @@ export function TransactionCard({
? 'Receive Bitcoin on-chain'
: 'Deposit funds with Lightning'
)}
</p>
</div>
</div>
{/* Content */}
@@ -402,6 +466,63 @@ export function TransactionCard({
</div>
</div>
</div>
) : pendingBitcoinSwapAddress ? (
// Reverse Swap Amount Input with Slider
<div className="space-y-8">
<div className="space-y-2">
<Input
placeholder="Amount (sats)"
type="number"
value={bitcoinSwapAmount || ''}
onChange={(e) => {
setBitcoinSwapAmount?.(e.target.value);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && bitcoinSwapAmount && !swapAmountError && activeMintUrl && !isLoading) {
onSend();
}
}}
disabled={!activeMintUrl || isLoading}
className={`w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield] ${
swapAmountError ? 'border-destructive' : ''
}`}
/>
{swapAmountError && (
<p className="text-sm text-destructive text-center">{swapAmountError}</p>
)}
{!swapAmountError && bitcoinSwapAmount && (
<p className="text-xs text-muted-foreground text-center">
Amount must be between 25,000 and 25,000,000 sats
</p>
)}
{swapStatus && (
<p className="text-sm text-muted-foreground text-center">{swapStatus}</p>
)}
</div>
<div className="mt-6 mb-safe-bottom pb-6">
<div className="relative w-full">
<div
onMouseUp={() => handleSliderMouseUp('swap')}
onMouseLeave={() => handleSliderMouseUp('swap')}
onTouchEnd={() => handleSliderMouseUp('swap')}
>
<Slider
value={swapSliderValue}
onValueChange={handleSwapSliderChange}
max={100}
step={1}
className="w-full h-12"
disabled={!bitcoinSwapAmount || !!swapAmountError || !activeMintUrl || isLoading}
/>
</div>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<span className="text-sm font-medium text-muted-foreground">
{swapSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
</span>
</div>
</div>
</div>
</div>
) : pendingLightningAddress ? (
// Lightning Address Amount Input with Slider
<div className="space-y-8">
@@ -443,10 +564,10 @@ export function TransactionCard({
</div>
</div>
) : (
// Lightning Invoice/Address Input
// Lightning Invoice/Address/Bitcoin Address Input
<div className="space-y-8">
<Input
placeholder="lnbc... or [email protected]"
placeholder="lnbc..., [email protected], or Bitcoin address"
value={lightningInvoice || lightningAddressInput}
onChange={(e) => {
const value = e.target.value;
+8 -2
View File
@@ -5,7 +5,8 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2, Clipboard } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import * as VisuallyHidden from '@radix-ui/react-visually-hidden';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { UTXO } from '@/lib/bitcoin';
@@ -496,7 +497,12 @@ export function WalletModals({
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
{/* Header */}
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogTitle>Scan QR Code</DialogTitle>
<VisuallyHidden.Root asChild>
<DialogDescription>
Position the QR code within the camera view to scan
</DialogDescription>
</VisuallyHidden.Root>
</DialogHeader>
{/* Camera container with square aspect ratio */}
+212 -5
View File
@@ -1,6 +1,9 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/useReverseSwap';
import { nip19 } from 'nostr-tools';
import type { Manager } from 'coco-cashu-core';
import type { Token } from '@cashu/cashu-ts';
import { useToast } from '@/hooks/useToast';
@@ -42,6 +45,12 @@ export function useWalletTransactions({
>(null);
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
// Reverse swap state (Lightning -> Bitcoin)
const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState<string | null>(null);
const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState('');
const [swapStatus, setSwapStatus] = useState<string | null>(null);
const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null);
// Transaction output state
const [sentToken, setSentToken] = useState<string | null>(null);
@@ -225,14 +234,35 @@ export function useWalletTransactions({
// Handle send (token or Lightning)
const handleSend = useCallback(async () => {
if (!coco) return;
console.log('[handleSend] Called with state:', {
hasCoco: !!coco,
sendAmount,
lightningInvoice,
lightningAddressInput,
pendingLightningAddress,
pendingBitcoinSwapAddress,
bitcoinSwapAmount,
activeMintUrl,
mode: 'lightning' // We're in Lightning mode when this is called
});
if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress) {
if (!coco) {
console.log('[handleSend] No coco instance');
return;
}
// Check for reverse swap first (this takes priority in Lightning mode)
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
console.log('[handleSend] Reverse swap detected:', { pendingBitcoinSwapAddress, bitcoinSwapAmount });
// Don't return early - continue to reverse swap logic below
} else if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress && !pendingBitcoinSwapAddress) {
console.log('[handleSend] No input provided - returning early');
return;
}
// Send Cashu token mode
if (sendAmount && activeMintUrl) {
console.log('[handleSend] Handling token send mode');
try {
const amount = parseInt(sendAmount);
if (isNaN(amount) || amount <= 0) {
@@ -257,8 +287,142 @@ export function useWalletTransactions({
}
} else if (activeMintUrl) {
// Lightning mode
// Step 1: Check if we have a pending Lightning address awaiting amount
if (pendingLightningAddress) {
console.log('[handleSend] Entering Lightning mode branch, activeMintUrl:', activeMintUrl);
// Step 1: Check if we have a pending Bitcoin swap address awaiting amount
if (pendingBitcoinSwapAddress) {
console.log('[handleSend] Found pendingBitcoinSwapAddress:', pendingBitcoinSwapAddress);
// Step 2: User entered amount, now initiate reverse swap
if (!bitcoinSwapAmount) {
console.log('[handleSend] Reverse swap pending but no amount provided');
return;
}
console.log('[handleSend] Starting reverse swap with:', {
address: pendingBitcoinSwapAddress,
amount: bitcoinSwapAmount,
activeMintUrl
});
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
console.log('[handleSend] Creating 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
console.log('[handleSend] Paying Lightning invoice:', swapResult.invoice);
setSwapStatus('Paying Lightning invoice...');
const meltQuote = await coco.quotes.createMeltQuote(
activeMintUrl,
swapResult.invoice
);
console.log('[handleSend] Melt quote created, paying...');
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
console.log('[handleSend] Invoice paid successfully');
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);
}
}
} else if (pendingLightningAddress) {
console.log('[handleSend] Handling Lightning address payment');
// Step 2: User entered amount, now resolve address and pay
if (!lightningAddressAmount) return;
@@ -302,10 +466,34 @@ export function useWalletTransactions({
});
}
} else {
// Step 1: Check if input is a Lightning address or invoice
// Step 1: Check if input is a Bitcoin address, Lightning address, or invoice
const input = lightningInvoice.trim() || lightningAddressInput.trim();
if (!input) return;
// Check if it's a Bitcoin address (for reverse swap)
if (isValidBitcoinAddress(input)) {
setPendingBitcoinSwapAddress(input);
setLightningInvoice('');
setLightningAddressInput('');
return;
}
// 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
setLightningInvoice('');
setLightningAddressInput('');
return;
}
}
} catch {
// Not an npub, continue to check other formats
}
// Check if it's a Lightning address (contains @)
if (input.includes('@')) {
setPendingLightningAddress(input);
@@ -350,11 +538,15 @@ export function useWalletTransactions({
lightningAddressInput,
lightningAddressAmount,
pendingLightningAddress,
pendingBitcoinSwapAddress,
bitcoinSwapAmount,
activeMintUrl,
toast,
getEncodedToken,
generateSentTokenQRCode,
getLightningInvoice,
reverseSwapClose,
npubToBitcoinAddress,
]);
// Handle confirmed invoice payment
@@ -491,6 +683,15 @@ export function useWalletTransactions({
};
}, []);
// Cleanup reverse swap WebSocket on unmount
useEffect(() => {
return () => {
if (reverseSwapClose) {
reverseSwapClose();
}
};
}, [reverseSwapClose]);
return {
// Receive state
tokenInput,
@@ -512,6 +713,12 @@ export function useWalletTransactions({
setDecodedInvoiceAmount,
pendingInvoice,
setPendingInvoice,
// Reverse swap state
pendingBitcoinSwapAddress,
setPendingBitcoinSwapAddress,
bitcoinSwapAmount,
setBitcoinSwapAmount,
swapStatus,
// Transaction output state
sentToken,
setSentToken,
+444
View File
@@ -0,0 +1,444 @@
import zkpInit from '@vulpemventures/secp256k1-zkp';
import {
Transaction,
address,
initEccLib,
networks,
} from 'bitcoinjs-lib';
import {
Musig,
OutputType,
SwapTreeSerializer,
TaprootUtils,
constructClaimTransaction,
detectSwap,
targetFee,
} from 'boltz-core';
import { ECPairFactory, type ECPairAPI, type ECPairInterface } from 'ecpair';
import * as ecc from '@bitcoinerlab/secp256k1';
import { Buffer } from 'buffer';
// Initialize ECC library
initEccLib(ecc);
// Boltz API endpoints
const API_ENDPOINT = 'https://api.boltz.exchange';
const WS_ENDPOINT = 'wss://api.boltz.exchange/v2/ws';
// Use mainnet by default
const network = networks.bitcoin;
// Lazy initialization of ECPair factory
let ECPair: ECPairAPI | null = null;
function getECPair(): ECPairAPI {
if (!ECPair) {
ECPair = ECPairFactory(ecc);
}
return ECPair;
}
/**
* Generate random bytes using browser crypto API
*/
function randomBytes(length: number): Buffer {
const array = new Uint8Array(length);
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
window.crypto.getRandomValues(array);
} else {
// Fallback for Node.js environments (shouldn't happen in browser, but just in case)
for (let i = 0; i < length; i++) {
array[i] = Math.floor(Math.random() * 256);
}
}
return Buffer.from(array);
}
/**
* SHA256 hash using browser SubtleCrypto API
*
* Note: window.crypto.subtle requires a secure context (HTTPS or localhost).
* It will be undefined if the page is served over HTTP.
*/
async function sha256(data: Buffer): Promise<Buffer> {
if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
// Convert Buffer to Uint8Array for SubtleCrypto
const uint8Array = new Uint8Array(data);
const hashBuffer = await window.crypto.subtle.digest('SHA-256', uint8Array);
return Buffer.from(hashBuffer);
}
// window.crypto.subtle unavailable - likely due to:
// 1. Page served over HTTP (not HTTPS/localhost)
// 2. Very old browser without support
// 3. Test environment without crypto API
throw new Error(
'SHA256 not available: window.crypto.subtle requires HTTPS or localhost. ' +
'Please serve the application over HTTPS or use localhost for development.'
);
}
/**
* Swap status update from WebSocket
*/
export interface SwapStatusUpdate {
status: 'swap.created' | 'transaction.mempool' | 'invoice.settled' | 'transaction.confirmed';
transaction?: {
hex: string;
};
}
/**
* Reverse swap result
*/
export interface ReverseSwapResult {
/** Lightning invoice to pay */
invoice: string;
/** Swap ID for tracking */
swapId: string;
/** Function to close WebSocket connection */
close: () => void;
}
/**
* Options for creating a reverse swap
*/
export interface ReverseSwapOptions {
/** Amount in satoshis for the Lightning invoice */
invoiceAmount: number;
/** Bitcoin address to receive the on-chain funds */
destinationAddress: string;
/** Callback for swap status updates */
onStatusUpdate?: (update: SwapStatusUpdate) => void;
/** Callback when swap is successfully completed */
onSuccess?: () => void;
/** Callback for errors */
onError?: (error: Error) => void;
/** Network to use (defaults to mainnet) */
network?: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet;
}
/**
* Create a reverse swap (Lightning to on-chain Bitcoin)
*
* This function creates a reverse swap where the user pays a Lightning invoice,
* and receives Bitcoin on-chain at the specified address.
*
* @param options - Reverse swap configuration options
* @returns Promise resolving to swap result with invoice and tracking functions
*
* @example
* ```typescript
* const { invoice, swapId, close } = await createReverseSwap({
* invoiceAmount: 100_000,
* destinationAddress: 'bc1q...',
* onStatusUpdate: (update) => {
* console.log('Swap status:', update.status);
* },
* onSuccess: () => {
* console.log('Swap completed!');
* }
* });
*
* // Display invoice to user for payment
* console.log('Pay this invoice:', invoice);
*
* // Later, close the connection when done
* close();
* ```
*/
export async function createReverseSwap(
options: ReverseSwapOptions
): Promise<ReverseSwapResult> {
const {
invoiceAmount,
destinationAddress,
onStatusUpdate,
onSuccess,
onError,
network: swapNetwork = network,
} = options;
// Create a random preimage for the swap (must be 32 bytes)
const preimage = randomBytes(32);
const keys = getECPair().makeRandom();
// Hash the preimage
const preimageHash = await sha256(preimage);
// Get public key as hex - match original code exactly
// keys.publicKey is a Buffer (or Uint8Array in browser), convert to hex string
// This should be a compressed public key (33 bytes = 66 hex chars)
const claimPublicKeyHex = Buffer.from(keys.publicKey).toString('hex');
// Validate length (compressed public key should be 33 bytes = 66 hex chars)
if (claimPublicKeyHex.length !== 66) {
throw new Error(`Invalid public key hex length: expected 66 chars (33 bytes), got ${claimPublicKeyHex.length}`);
}
const requestBody = {
invoiceAmount,
to: 'BTC',
from: 'BTC',
claimPublicKey: claimPublicKeyHex,
preimageHash: preimageHash.toString('hex'),
};
console.log('[createReverseSwap] Request body:', {
...requestBody,
claimPublicKeyLength: claimPublicKeyHex.length / 2, // Divide by 2 because hex is 2 chars per byte
preimageHashLength: requestBody.preimageHash.length / 2,
});
// Create the reverse swap via API
const createResponse = await fetch(`${API_ENDPOINT}/v2/swap/reverse`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
if (!createResponse.ok) {
const errorText = await createResponse.text();
console.error('[createReverseSwap] API error response:', errorText);
throw new Error(`Failed to create reverse swap: ${errorText}`);
}
const createdResponse = await createResponse.json();
// Set up WebSocket connection for tracking swap progress
const webSocket = new WebSocket(WS_ENDPOINT);
const close = () => {
if (webSocket.readyState === WebSocket.OPEN) {
webSocket.close();
}
};
webSocket.onopen = () => {
webSocket.send(
JSON.stringify({
op: 'subscribe',
channel: 'swap.update',
args: [createdResponse.id],
})
);
};
webSocket.onmessage = async (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.event !== 'update') {
return;
}
const statusUpdate: SwapStatusUpdate = {
status: msg.args[0].status,
transaction: msg.args[0].transaction,
};
onStatusUpdate?.(statusUpdate);
switch (msg.args[0].status) {
case 'swap.created': {
// Boltz is waiting for the invoice to be paid
break;
}
case 'transaction.mempool': {
// Boltz sent an on-chain transaction, now we need to claim it
try {
await claimSwapTransaction(
createdResponse,
keys,
preimage,
destinationAddress,
msg.args[0].transaction.hex,
swapNetwork
);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
onError?.(err);
close();
throw err;
}
break;
}
case 'invoice.settled':
case 'transaction.confirmed': {
// Swap successful
onSuccess?.();
close();
break;
}
}
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
onError?.(err);
close();
}
};
webSocket.onerror = (error) => {
onError?.(new Error('WebSocket error occurred'));
};
webSocket.onclose = () => {
// Connection closed
};
return {
invoice: createdResponse.invoice,
swapId: createdResponse.id,
close,
};
}
/**
* Claim the swap transaction after Boltz sends it to the mempool
*/
async function claimSwapTransaction(
createdResponse: {
id: string;
refundPublicKey: string;
swapTree: string;
},
keys: ECPairInterface,
preimage: Buffer,
destinationAddress: string,
lockupTxHex: string,
swapNetwork: typeof networks.bitcoin | typeof networks.regtest | typeof networks.testnet
): Promise<void> {
const boltzPublicKey = Buffer.from(createdResponse.refundPublicKey, 'hex');
// Create a musig signing session and tweak it with the Taptree of the swap scripts
const zkp = await zkpInit();
// Convert keys.publicKey (Uint8Array) to Buffer for Musig
const keysPublicKeyBuffer = Buffer.from(keys.publicKey);
const musig = new Musig(zkp, keys, randomBytes(32), [
boltzPublicKey,
keysPublicKeyBuffer,
]);
const tweakedKey = TaprootUtils.tweakMusig(
musig,
SwapTreeSerializer.deserializeSwapTree(createdResponse.swapTree).tree
);
// Parse the lockup transaction and find the output relevant for the swap
const lockupTx = Transaction.fromHex(lockupTxHex);
// Convert Transaction outputs to the format expected by detectSwap
// bitcoinjs-lib v7 uses bigint for values, but detectSwap expects number
const txOutputs = lockupTx.outs.map((out) => ({
script: Buffer.from(out.script),
value: Number(out.value), // Convert bigint to number
}));
const swapOutput = detectSwap(tweakedKey, { outs: txOutputs });
if (swapOutput === undefined) {
throw new Error('No swap output found in lockup transaction');
}
// Create a claim transaction to be signed cooperatively via a key path spend
// swapOutput.value is guaranteed to be a number because we converted it above
// (detectSwap preserves the input type, and we passed { value: number })
// TypeScript needs explicit assertion since detectSwap is generic
const swapValueForClaim: number = Number(swapOutput.value);
// Convert txHash to Buffer
const txHashBuffer = Buffer.from(lockupTx.getHash());
// Convert address script to Buffer
const destinationScript = Buffer.from(address.toOutputScript(destinationAddress, swapNetwork));
const claimTx = targetFee(2, (fee) =>
constructClaimTransaction(
[
{
...swapOutput,
value: swapValueForClaim,
keys,
preimage,
cooperative: true,
type: OutputType.Taproot,
txHash: txHashBuffer,
},
],
destinationScript,
fee
)
);
// Get the partial signature from Boltz
const claimResponse = await fetch(
`${API_ENDPOINT}/v2/swap/reverse/${createdResponse.id}/claim`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
index: 0,
transaction: claimTx.toHex(),
preimage: preimage.toString('hex'),
pubNonce: Buffer.from(musig.getPublicNonce()).toString('hex'),
}),
}
);
if (!claimResponse.ok) {
const errorText = await claimResponse.text();
throw new Error(`Failed to get claim signature: ${errorText}`);
}
const boltzSig = await claimResponse.json();
// Aggregate the nonces
musig.aggregateNonces([
[boltzPublicKey, Buffer.from(boltzSig.pubNonce, 'hex')],
]);
// Initialize the session to sign the claim transaction
// Use the already converted value for hashForWitnessV1
musig.initializeSession(
claimTx.hashForWitnessV1(
0,
[swapOutput.script],
[swapValueForClaim],
Transaction.SIGHASH_DEFAULT
)
);
// Add the partial signature from Boltz
musig.addPartial(
boltzPublicKey,
Buffer.from(boltzSig.partialSignature, 'hex')
);
// Create our partial signature
musig.signPartial();
// Witness of the input to the aggregated signature
claimTx.ins[0].witness = [musig.aggregatePartials()];
// Broadcast the finalized transaction
const broadcastResponse = await fetch(
`${API_ENDPOINT}/v2/chain/BTC/transaction`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
hex: claimTx.toHex(),
}),
}
);
if (!broadcastResponse.ok) {
const errorText = await broadcastResponse.text();
throw new Error(`Failed to broadcast transaction: ${errorText}`);
}
}
+29
View File
@@ -54,6 +54,35 @@ export function npubToBitcoinAddress(npub: string): string {
}
}
/**
* Check if a string looks like a Bitcoin address
* Supports P2PKH (starts with 1), P2SH (starts with 3), and P2TR/Taproot (starts with bc1)
*/
export function isValidBitcoinAddress(address: string): boolean {
if (!address || typeof address !== 'string') return false;
const trimmed = address.trim();
// P2PKH addresses (legacy, starts with 1)
if (trimmed.startsWith('1') && trimmed.length >= 26 && trimmed.length <= 35) {
return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed);
}
// P2SH addresses (starts with 3)
if (trimmed.startsWith('3') && trimmed.length >= 26 && trimmed.length <= 35) {
return /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(trimmed);
}
// P2TR/Taproot addresses (bech32, starts with bc1)
if (trimmed.startsWith('bc1')) {
// Taproot addresses are bc1p... (62 chars) or bc1q... (42 chars for P2WPKH)
// For reverse swaps, we're mostly concerned with bc1p (Taproot)
return /^bc1[a-z0-9]{39,59}$/i.test(trimmed);
}
return false;
}
/**
* Interface for UTXO (Unspent Transaction Output)
*/