diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index 62dec02..b0544c4 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -10,6 +10,9 @@ import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; import { useMintManager } from '@/hooks/cashu/useMintManager'; import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions'; import { useHistoryManager } from '@/hooks/cashu/useHistoryManager'; +import { useNsecAccess } from '@/hooks/useNsecAccess'; +import { useBitcoinBalance } from '@/hooks/useBitcoinBalance'; +import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; import { TransactionCard } from './PaymentCard'; @@ -43,6 +46,11 @@ export function CashuWallet() { const { toast } = useToast(); const { generateQRCode } = useQRCode(); const { copy: copyToClipboard } = useCopyToClipboard(); + + // Bitcoin hooks + const { hasNsecAccess, getPrivateKey } = useNsecAccess(); + const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; + const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress); const { setMint: setNpubCashMint, @@ -152,7 +160,7 @@ export function CashuWallet() { // ============================================================================ const [showSats, setShowSats] = useState(true); - const [mode, setMode] = useState<'tokens' | 'lightning'>('lightning'); + const [mode, setMode] = useState<'tokens' | 'lightning' | 'bitcoin'>('lightning'); const [showProofBreakdown, setShowProofBreakdown] = useState(false); const [proofBreakdown, setProofBreakdown] = useState<{ mintUrl: string; @@ -168,6 +176,13 @@ export function CashuWallet() { const [showReceiveModal, setShowReceiveModal] = useState(false); const [showHistoryModal, setShowHistoryModal] = useState(false); + // Bitcoin state + const [bitcoinAmount, setBitcoinAmount] = useState(''); + const [bitcoinRecipient, setBitcoinRecipient] = useState(''); + const [pendingBitcoinRecipient, setPendingBitcoinRecipient] = useState(null); + const [showBitcoinAddressQR, setShowBitcoinAddressQR] = useState(false); + const [bitcoinAddressQRCode, setBitcoinAddressQRCode] = useState(''); + // Handle drawer close with state reset const handleSendDrawerClose = (open: boolean) => { setShowSendModal(open); @@ -180,6 +195,10 @@ export function CashuWallet() { setPendingLightningAddress(null); setDecodedInvoiceAmount(null); setPendingInvoice(null); + // Reset Bitcoin state + setBitcoinAmount(''); + setBitcoinRecipient(''); + setPendingBitcoinRecipient(null); } }; @@ -195,11 +214,108 @@ export function CashuWallet() { // Ref to track if we've fetched npub.cash user info const hasCheckedNpubCashRef = useRef(false); + // ============================================================================ + // BITCOIN HANDLERS + // ============================================================================ + + const handleBitcoinSend = async () => { + if (!hasNsecAccess || !bitcoinAmount || !pendingBitcoinRecipient || !bitcoinAddress) { + toast({ + variant: "destructive", + title: "Bitcoin Send Error", + description: "Missing required information for Bitcoin transaction", + }); + return; + } + + try { + const privateKey = getPrivateKey(); + if (!privateKey) { + throw new Error('Unable to access private key'); + } + + const amountSats = parseInt(bitcoinAmount); + if (isNaN(amountSats) || amountSats <= 0) { + throw new Error('Invalid amount'); + } + + // Determine if the recipient is a Bitcoin address or npub + let recipientAddress: string; + if (pendingBitcoinRecipient.startsWith('bc1') || pendingBitcoinRecipient.startsWith('1') || pendingBitcoinRecipient.startsWith('3')) { + // It's already a Bitcoin address + recipientAddress = pendingBitcoinRecipient; + } else if (pendingBitcoinRecipient.startsWith('npub')) { + // It's an npub, convert to Bitcoin address + recipientAddress = npubToBitcoinAddress(pendingBitcoinRecipient); + } else { + // Assume it's a hex pubkey + recipientAddress = nostrPubkeyToBitcoinAddress(pendingBitcoinRecipient); + } + + // Fetch UTXOs and fee rates + const [utxos, feeRates] = await Promise.all([ + fetchUTXOs(bitcoinAddress), + getFeeRates() + ]); + + // Create and sign transaction + const { txHex, fee } = await createBitcoinTransaction( + privateKey, + recipientAddress, + amountSats, + utxos, + feeRates.fastestFee + ); + + // Broadcast transaction + const txId = await broadcastTransaction(txHex); + + toast({ + title: "Bitcoin Sent!", + description: `Transaction ${txId.slice(0, 8)}... confirmed`, + }); + + // Reset form and refresh balance + setBitcoinAmount(''); + setBitcoinRecipient(''); + setPendingBitcoinRecipient(null); + refetchBitcoinBalance(); + setShowSendModal(false); + + } catch (error) { + console.error('Bitcoin send error:', error); + toast({ + variant: "destructive", + title: "Bitcoin Send Failed", + description: error instanceof Error ? error.message : 'Unknown error occurred', + }); + } + }; + + const handleBitcoinReceive = async () => { + if (!bitcoinAddress) return; + + try { + const qr = await generateQRCode(bitcoinAddress); + setBitcoinAddressQRCode(qr); + setShowBitcoinAddressQR(true); + } catch (error) { + console.error('QR generation error:', error); + toast({ + variant: "destructive", + title: "QR Code Error", + description: "Failed to generate QR code", + }); + } + }; + // ============================================================================ // COMPUTED VALUES // ============================================================================ - const totalBalance: number = (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); + const totalBalance: number = mode === 'bitcoin' + ? (bitcoinBalanceData?.balance || 0) + : (Object.values(balances) as number[]).reduce((sum: number, balance: number) => sum + balance, 0); // ============================================================================ // EFFECTS - Error Handling @@ -322,6 +438,10 @@ export function CashuWallet() { setLightningAddressQRCode(qr); setShowLightningAddressQR(true); }} + onShowBitcoinAddressQR={(qr) => { + setBitcoinAddressQRCode(qr); + setShowBitcoinAddressQR(true); + }} generateQRCode={generateQRCode} // MintSelector props activeMintUrl={activeMintUrl} @@ -432,10 +552,14 @@ export function CashuWallet() { setQuoteAmount={() => {}} activeMintUrl={activeMintUrl} onSend={() => { - const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== ''; - handleSend(); - if (mode === 'tokens' || wasPendingBefore) { - setShowSendModal(false); + if (mode === 'bitcoin') { + handleBitcoinSend(); + } else { + const wasPendingBefore = pendingLightningAddress !== null && pendingLightningAddress !== ''; + handleSend(); + if (mode === 'tokens' || wasPendingBefore) { + setShowSendModal(false); + } } }} onReceive={() => {}} @@ -444,7 +568,16 @@ export function CashuWallet() { setShowSendModal(false); }} isResolvingAddress={isResolvingAddress} - isLoading={isLoading || isNpubCashLoading} + isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading} + // Bitcoin props + bitcoinAddress={bitcoinAddress || ''} + bitcoinAmount={bitcoinAmount} + setBitcoinAmount={setBitcoinAmount} + bitcoinRecipient={bitcoinRecipient} + setBitcoinRecipient={setBitcoinRecipient} + pendingBitcoinRecipient={pendingBitcoinRecipient} + setPendingBitcoinRecipient={setPendingBitcoinRecipient} + hasNsecAccess={hasNsecAccess} /> @@ -480,11 +613,25 @@ export function CashuWallet() { activeMintUrl={activeMintUrl} onSend={() => {}} onReceive={() => { - handleReceive(); - setShowReceiveModal(false); + if (mode === 'bitcoin') { + handleBitcoinReceive(); + setShowReceiveModal(false); + } else { + handleReceive(); + setShowReceiveModal(false); + } }} isResolvingAddress={false} - isLoading={isLoading || isNpubCashLoading} + isLoading={isLoading || isNpubCashLoading || isBitcoinBalanceLoading} + // Bitcoin props + bitcoinAddress={bitcoinAddress || ''} + bitcoinAmount="" + setBitcoinAmount={() => {}} + bitcoinRecipient="" + setBitcoinRecipient={() => {}} + pendingBitcoinRecipient={null} + setPendingBitcoinRecipient={() => {}} + hasNsecAccess={hasNsecAccess} /> @@ -503,6 +650,17 @@ export function CashuWallet() { + + {/* Bitcoin Address QR Modal */} + setShowBitcoinAddressQR(false)} + title="Bitcoin Address" + description="Scan this QR code to send Bitcoin to your address" + qrCodeUrl={bitcoinAddressQRCode} + content={bitcoinAddress || ''} + icon="qr" + /> diff --git a/src/components/wallet/PaymentCard.tsx b/src/components/wallet/PaymentCard.tsx index 1ac08f6..213062b 100644 --- a/src/components/wallet/PaymentCard.tsx +++ b/src/components/wallet/PaymentCard.tsx @@ -5,7 +5,7 @@ import { Send, Download, ArrowRight, Zap, Loader2, X } from 'lucide-react'; import { useState, useEffect } from 'react'; interface TransactionCardProps { - mode: 'tokens' | 'lightning'; + mode: 'tokens' | 'lightning' | 'bitcoin'; operation: 'send' | 'receive'; // Send props sendAmount: string; @@ -34,6 +34,15 @@ interface TransactionCardProps { onConfirmInvoice?: () => void; isResolvingAddress: boolean; isLoading: boolean; + // Bitcoin props + bitcoinAddress?: string; + bitcoinAmount?: string; + setBitcoinAmount?: (value: string) => void; + bitcoinRecipient?: string; + setBitcoinRecipient?: (value: string) => void; + pendingBitcoinRecipient?: string | null; + setPendingBitcoinRecipient?: (value: string | null) => void; + hasNsecAccess?: boolean; } export function TransactionCard({ @@ -63,10 +72,19 @@ export function TransactionCard({ onConfirmInvoice, isResolvingAddress, isLoading, + bitcoinAddress, + bitcoinAmount, + setBitcoinAmount, + bitcoinRecipient, + setBitcoinRecipient, + pendingBitcoinRecipient, + setPendingBitcoinRecipient, + hasNsecAccess, }: TransactionCardProps) { // Slider state for confirmation const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]); const [addressSliderValue, setAddressSliderValue] = useState([0]); + const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]); // Handle slider value changes and auto-submit at 100% const handleInvoiceSliderChange = (value: number[]) => { @@ -83,6 +101,13 @@ export function TransactionCard({ } }; + const handleBitcoinSliderChange = (value: number[]) => { + setBitcoinSliderValue(value); + if (value[0] === 100) { + onSend(); + } + }; + // Reset sliders when states change const resetSliders = () => { setInvoiceSliderValue([0]); @@ -102,6 +127,12 @@ export function TransactionCard({ } }, [pendingLightningAddress]); + useEffect(() => { + if (!pendingBitcoinRecipient) { + setBitcoinSliderValue([0]); + } + }, [pendingBitcoinRecipient]); + return (
{/* Title */} @@ -110,6 +141,10 @@ export function TransactionCard({ {operation === 'send' ? ( mode === 'tokens' ? 'Generate Cashu token to send' + : mode === 'bitcoin' && !pendingBitcoinRecipient + ? 'Send Bitcoin on-chain' + : mode === 'bitcoin' && pendingBitcoinRecipient + ? '' : pendingInvoice && decodedInvoiceAmount ? (
@@ -148,6 +183,8 @@ export function TransactionCard({ ) : ( mode === 'tokens' ? 'Enter Cashu token to redeem' + : mode === 'bitcoin' + ? 'Receive Bitcoin on-chain' : 'Deposit funds with Lightning' )}

@@ -155,7 +192,7 @@ export function TransactionCard({ {/* Content */}
- {!activeMintUrl && ( + {!activeMintUrl && mode !== 'bitcoin' && (
{operation === 'send' ? (mode === 'tokens' ? 'Select a mint to send tokens' : 'Select a mint to pay Lightning invoices') @@ -166,7 +203,96 @@ export function TransactionCard({ {operation === 'send' ? ( // Send Mode - mode === 'tokens' ? ( + mode === 'bitcoin' ? ( + // Bitcoin Send +
+ {!hasNsecAccess ? ( +
+
+ ⚠️ Login with nsec required to send Bitcoin +
+
+ ) : pendingBitcoinRecipient ? ( + // Step 2: Amount Input with Slider +
+
+ + Sending to:{' '} + {pendingBitcoinRecipient} + + +
+ setBitcoinAmount?.(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && bitcoinAmount && pendingBitcoinRecipient && !isLoading) { + onSend(); + } + }} + 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]" + /> +
+
+ +
+ + {bitcoinSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'} + +
+
+
+
+ ) : ( + // Step 1: Recipient Input +
+ setBitcoinRecipient?.(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && bitcoinRecipient && !isLoading) { + setPendingBitcoinRecipient?.(bitcoinRecipient); + } + }} + className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2" + /> +
+ +
+
+ )} +
+ ) : mode === 'tokens' ? ( // Cashu Token Send
+
+
+ {bitcoinAddress} +
+
+
+ +
+
+ ) : mode === 'tokens' ? ( // Cashu Token Receive
void; - mode: 'tokens' | 'lightning'; - setMode: (mode: 'tokens' | 'lightning') => void; + mode: 'tokens' | 'lightning' | 'bitcoin'; + setMode: (mode: 'tokens' | 'lightning' | 'bitcoin') => void; userPubkey?: string; npubCashUsername?: string; onCopyToClipboard: (text: string) => Promise; onShowLightningAddressQR: (qrCode: string) => void; + onShowBitcoinAddressQR: (qrCode: string) => void; generateQRCode: (text: string) => Promise; // MintSelector props activeMintUrl: string | null; @@ -49,6 +51,7 @@ export function WalletHeader({ npubCashUsername, onCopyToClipboard, onShowLightningAddressQR, + onShowBitcoinAddressQR, generateQRCode, // MintSelector props activeMintUrl, @@ -64,6 +67,7 @@ export function WalletHeader({ setDropdownOpen, }: WalletHeaderProps) { const [lightningAddressCopied, setLightningAddressCopied] = useState(false); + const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false); const [btcUsdRate, setBtcUsdRate] = useState(null); const { toast } = useToast(); @@ -74,14 +78,24 @@ export function WalletHeader({ }, []); const toggleMode = () => { - const newMode = mode === 'tokens' ? 'lightning' : 'tokens'; + let newMode: 'tokens' | 'lightning' | 'bitcoin'; + if (mode === 'lightning') { + newMode = 'tokens'; + } else if (mode === 'tokens') { + newMode = 'bitcoin'; + } else { + newMode = 'lightning'; + } + setMode(newMode); toast({ - title: `${newMode === 'tokens' ? 'Cashu' : 'Lightning'} Enabled!`, + title: `${newMode === 'tokens' ? 'Cashu' : newMode === 'lightning' ? 'Lightning' : 'Bitcoin'} Enabled!`, description: newMode === 'tokens' ? 'Send and receive with Cashu eCash' - : 'Send and receive with Lightning', + : newMode === 'lightning' + ? 'Send and receive with Lightning' + : 'Send and receive with on-chain Bitcoin', }); }; @@ -93,12 +107,14 @@ export function WalletHeader({
@@ -128,7 +144,7 @@ export function WalletHeader({
{/* Lightning Address Row */} - {userPubkey && ( + {userPubkey && mode !== 'bitcoin' && (
)} + + {/* Bitcoin Address Row */} + {userPubkey && mode === 'bitcoin' && (() => { + const bitcoinAddress = nostrPubkeyToBitcoinAddress(userPubkey); + return bitcoinAddress ? ( +
+ + +
+ ) : null; + })()} {/* Mint Selector Row */} -
- -
+ {mode !== 'bitcoin' && ( +
+ +
+ )}
diff --git a/src/hooks/useBitcoinBalance.ts b/src/hooks/useBitcoinBalance.ts new file mode 100644 index 0000000..fe9f22d --- /dev/null +++ b/src/hooks/useBitcoinBalance.ts @@ -0,0 +1,24 @@ +import { useQuery } from '@tanstack/react-query'; +import { fetchUTXOs, type UTXO } from '@/lib/bitcoin'; + +/** + * Hook to fetch and manage Bitcoin balance from UTXOs + */ +export function useBitcoinBalance(address: string | null) { + return useQuery({ + queryKey: ['bitcoin-balance', address], + queryFn: async (): Promise<{ balance: number; utxos: UTXO[] }> => { + if (!address) { + return { balance: 0, utxos: [] }; + } + + const utxos = await fetchUTXOs(address); + const balance = utxos.reduce((sum, utxo) => sum + utxo.value, 0); + + return { balance, utxos }; + }, + enabled: !!address, + refetchInterval: 30000, // Refetch every 30 seconds + staleTime: 10000, // Consider data stale after 10 seconds + }); +} diff --git a/src/hooks/useNsecAccess.ts b/src/hooks/useNsecAccess.ts new file mode 100644 index 0000000..45407da --- /dev/null +++ b/src/hooks/useNsecAccess.ts @@ -0,0 +1,51 @@ +import { useNostrLogin } from '@nostrify/react/login'; +import { nip19 } from 'nostr-tools'; + +/** + * Hook to check if the current user is logged in with nsec and get the private key. + * Only works when user is logged in with nsec (not extension or bunker). + */ +export function useNsecAccess() { + const { logins } = useNostrLogin(); + + const currentLogin = logins[0]; + + // Check if user is logged in with nsec + const hasNsecAccess = currentLogin?.type === 'nsec'; + + // Get the private key in hex format (only if nsec login) + const getPrivateKey = (): string | null => { + if (!hasNsecAccess || !currentLogin) return null; + + try { + // The nsec is stored in the login data as 'data.nsec' property + const loginData = currentLogin as { data?: { nsec: string } }; + const nsec = loginData.data?.nsec; + + if (!nsec) { + console.error('No nsec found in login data'); + return null; + } + + const decoded: { type: string; data: Uint8Array | string | object } = nip19.decode(nsec) as { type: string; data: Uint8Array | string | object }; + + // Type guard to ensure we have an nsec + if (decoded.type !== 'nsec') { + console.error('Invalid nsec format, got type:', decoded.type); + return null; + } + + // Convert Uint8Array to hex string + return Buffer.from(decoded.data as Uint8Array).toString('hex'); + } catch (error) { + console.error('Failed to decode nsec:', error); + return null; + } + }; + + return { + hasNsecAccess, + getPrivateKey, + loginType: currentLogin?.type, + }; +} diff --git a/src/lib/bitcoin.ts b/src/lib/bitcoin.ts new file mode 100644 index 0000000..8837763 --- /dev/null +++ b/src/lib/bitcoin.ts @@ -0,0 +1,247 @@ +import * as bitcoin from 'bitcoinjs-lib'; +import { nip19 } from 'nostr-tools'; +import * as ecc from '@bitcoinerlab/secp256k1'; +import { ECPairFactory, type ECPairAPI } from 'ecpair'; + +// Initialize ECC library immediately +bitcoin.initEccLib(ecc); + +// Lazy initialization to avoid issues in test environment +let ECPair: ECPairAPI | null = null; + +function getECPair(): ECPairAPI { + if (!ECPair) { + ECPair = ECPairFactory(ecc); + } + return ECPair; +} + +/** + * Convert Nostr pubkey (hex) to Bitcoin Taproot address + */ +export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string { + try { + const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex'); + + const { address } = bitcoin.payments.p2tr({ + internalPubkey: pubkeyBuffer, + network: bitcoin.networks.bitcoin, + }); + + return address || ''; + } catch (error) { + console.error('Error generating Bitcoin address:', error); + return ''; + } +} + +/** + * Convert npub to Bitcoin Taproot address + */ +export function npubToBitcoinAddress(npub: string): string { + try { + const decoded = nip19.decode(npub); + + if (decoded.type !== 'npub') { + throw new Error('Invalid npub format'); + } + + const pubkeyHex = decoded.data as string; + return nostrPubkeyToBitcoinAddress(pubkeyHex); + } catch (error) { + console.error('Error converting npub to Bitcoin address:', error); + throw error; + } +} + +/** + * Interface for UTXO (Unspent Transaction Output) + */ +export interface UTXO { + txid: string; + vout: number; + value: number; // in satoshis + status: { + confirmed: boolean; + block_height?: number; + block_hash?: string; + block_time?: number; + }; +} + +/** + * Fetch UTXOs for a Bitcoin address from Blockstream API + */ +export async function fetchUTXOs(address: string): Promise { + const response = await fetch(`https://blockstream.info/api/address/${address}/utxo`); + + if (!response.ok) { + throw new Error('Failed to fetch UTXOs'); + } + + return response.json(); +} + +/** + * Get recommended fee rates from Blockstream API + */ +export async function getFeeRates(): Promise<{ + fastestFee: number; + halfHourFee: number; + hourFee: number; + economyFee: number; + minimumFee: number; +}> { + const response = await fetch('https://blockstream.info/api/fee-estimates'); + + if (!response.ok) { + throw new Error('Failed to fetch fee estimates'); + } + + const data = await response.json(); + + return { + fastestFee: Math.ceil(data['1'] || 1), + halfHourFee: Math.ceil(data['3'] || 1), + hourFee: Math.ceil(data['6'] || 1), + economyFee: Math.ceil(data['144'] || 1), + minimumFee: Math.ceil(data['504'] || 1), + }; +} + +/** + * Broadcast a transaction to the Bitcoin network + */ +export async function broadcastTransaction(txHex: string): Promise { + const response = await fetch('https://blockstream.info/api/tx', { + method: 'POST', + body: txHex, + }); + + if (!response.ok) { + const error = await response.text(); + throw new Error(`Failed to broadcast transaction: ${error}`); + } + + return response.text(); // Returns the transaction ID +} + +/** + * Create and sign a Bitcoin transaction + * @param privateKeyHex - Private key in hex format (from Nostr nsec) + * @param toAddress - Recipient Bitcoin address + * @param amountSats - Amount to send in satoshis + * @param utxos - Available UTXOs + * @param feeRate - Fee rate in sat/vB + * @returns Signed transaction hex + */ +export async function createBitcoinTransaction( + privateKeyHex: string, + toAddress: string, + amountSats: number, + utxos: UTXO[], + feeRate: number +): Promise<{ txHex: string; fee: number }> { + // Create key pair from private key + const privateKeyBuffer = Buffer.from(privateKeyHex, 'hex'); + const keyPair = getECPair().fromPrivateKey(privateKeyBuffer); + + // Get x-only public key (32 bytes) for Taproot + // Remove the first byte (compression flag) from the 33-byte compressed pubkey + const internalPubkey = keyPair.publicKey.slice(1, 33); + + // Get sender's address for change + const { address: changeAddress } = bitcoin.payments.p2tr({ + internalPubkey, + network: bitcoin.networks.bitcoin, + }); + + if (!changeAddress) { + throw new Error('Failed to generate change address'); + } + + // Create transaction builder + const psbt = new bitcoin.Psbt({ network: bitcoin.networks.bitcoin }); + + // Add inputs (UTXOs) + let totalInput = 0; + for (const utxo of utxos) { + psbt.addInput({ + hash: utxo.txid, + index: utxo.vout, + witnessUtxo: { + script: bitcoin.payments.p2tr({ + internalPubkey, + network: bitcoin.networks.bitcoin, + }).output!, + value: BigInt(utxo.value), + }, + tapInternalKey: internalPubkey, + }); + + totalInput += utxo.value; + } + + // Estimate transaction size + // P2TR input: ~57.5 vBytes, P2TR output: ~43 vBytes + const estimatedSize = utxos.length * 57.5 + 2 * 43 + 10.5; // 2 outputs (recipient + change) + overhead + const estimatedFee = Math.ceil(estimatedSize * feeRate); + + // Calculate change + const change = totalInput - amountSats - estimatedFee; + + if (change < 0) { + throw new Error( + `Insufficient funds. Need ${amountSats + estimatedFee} sats, have ${totalInput} sats` + ); + } + + // Add output for recipient + psbt.addOutput({ + address: toAddress, + value: BigInt(amountSats), + }); + + // Add change output if significant (> dust limit) + const dustLimit = 546; // Standard dust limit for Bitcoin + if (change > dustLimit) { + psbt.addOutput({ + address: changeAddress, + value: BigInt(change), + }); + } + + // Create a Taproot signer + // For Taproot key-path spending, we need to tweak the private key + const tweakedSigner = keyPair.tweak( + bitcoin.crypto.taggedHash('TapTweak', internalPubkey) + ); + + // Sign all inputs + for (let i = 0; i < utxos.length; i++) { + psbt.signInput(i, tweakedSigner); + } + + // Finalize and extract transaction + psbt.finalizeAllInputs(); + const tx = psbt.extractTransaction(); + + return { + txHex: tx.toHex(), + fee: estimatedFee, + }; +} + +/** + * Convert satoshis to BTC + */ +export function satsToBTC(sats: number): string { + return (sats / 100000000).toFixed(8); +} + +/** + * Convert BTC to satoshis + */ +export function btcToSats(btc: number): number { + return Math.round(btc * 100000000); +} diff --git a/src/lib/polyfills.ts b/src/lib/polyfills.ts index edb726e..7d8f27e 100644 --- a/src/lib/polyfills.ts +++ b/src/lib/polyfills.ts @@ -1,3 +1,12 @@ +/** + * Polyfill for Buffer in browser environment + * + * Many Node.js libraries like bitcoinjs-lib expect Buffer to be globally available. + * This polyfill makes the buffer package's Buffer available globally. + */ +import { Buffer } from 'buffer'; +globalThis.Buffer = Buffer; + /** * Polyfill for AbortSignal.any() *