Receive
+
+
+ Receive tokens, Lightning invoices, or Bitcoin
+
+
Transactions
+
+
+ View your transaction history
+
+
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(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 (
{/* Title */}
-
+
{operation === 'send' ? (
mode === 'tokens'
? 'Generate Cashu token to send'
@@ -234,7 +281,24 @@ export function TransactionCard({
- ) : 'Pay invoices or addresses'
+ ) : pendingBitcoinSwapAddress ? (
+
+
+ Reverse Swap to:{' '}
+ {truncateAddress(pendingBitcoinSwapAddress)}
+
+
+
+ ) : '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'
)}
-
+
{/* Content */}
@@ -402,6 +466,63 @@ export function TransactionCard({
+ ) : pendingBitcoinSwapAddress ? (
+ // Reverse Swap Amount Input with Slider
+
+
+
{
+ 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 && (
+
{swapAmountError}
+ )}
+ {!swapAmountError && bitcoinSwapAmount && (
+
+ Amount must be between 25,000 and 25,000,000 sats
+
+ )}
+ {swapStatus && (
+
{swapStatus}
+ )}
+
+
+
+
handleSliderMouseUp('swap')}
+ onMouseLeave={() => handleSliderMouseUp('swap')}
+ onTouchEnd={() => handleSliderMouseUp('swap')}
+ >
+
+
+
+
+ {swapSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
+
+
+
+
+
) : pendingLightningAddress ? (
// Lightning Address Amount Input with Slider
@@ -443,10 +564,10 @@ export function TransactionCard({
) : (
- // Lightning Invoice/Address Input
+ // Lightning Invoice/Address/Bitcoin Address Input
{
const value = e.target.value;
diff --git a/src/components/wallet/WalletModals.tsx b/src/components/wallet/WalletModals.tsx
index 477fcce..cbb300d 100644
--- a/src/components/wallet/WalletModals.tsx
+++ b/src/components/wallet/WalletModals.tsx
@@ -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({
{/* Header */}
-
+ Scan QR Code
+
+
+ Position the QR code within the camera view to scan
+
+
{/* Camera container with square aspect ratio */}
diff --git a/src/hooks/cashu/useWalletTransactions.ts b/src/hooks/cashu/useWalletTransactions.ts
index 577d358..94cc974 100644
--- a/src/hooks/cashu/useWalletTransactions.ts
+++ b/src/hooks/cashu/useWalletTransactions.ts
@@ -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(null);
const [pendingInvoice, setPendingInvoice] = useState(null);
+
+ // 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);
// Transaction output state
const [sentToken, setSentToken] = useState(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,
diff --git a/src/hooks/useReverseSwap.ts b/src/hooks/useReverseSwap.ts
new file mode 100644
index 0000000..2623920
--- /dev/null
+++ b/src/hooks/useReverseSwap.ts
@@ -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 {
+ 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 {
+ 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 {
+ 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}`);
+ }
+}
diff --git a/src/lib/bitcoin.ts b/src/lib/bitcoin.ts
index f608ff1..6c217a4 100644
--- a/src/lib/bitcoin.ts
+++ b/src/lib/bitcoin.ts
@@ -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)
*/