From e3cebf3a341a4a35daa0afee23c9354d425b33a6 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Wed, 22 Oct 2025 22:22:39 -0700 Subject: [PATCH] Coin selector and custody badge --- src/components/wallet/CashuWallet.tsx | 22 +++- src/components/wallet/TransactionHistory.tsx | 123 ++++++++++++++++++- src/components/wallet/UTXOSelector.tsx | 103 ++++++++++++---- src/components/wallet/WalletHeader.tsx | 15 +++ src/hooks/useBitcoinBalance.ts | 82 +++++++++++++ 5 files changed, 308 insertions(+), 37 deletions(-) diff --git a/src/components/wallet/CashuWallet.tsx b/src/components/wallet/CashuWallet.tsx index c254349..ac1a6b3 100644 --- a/src/components/wallet/CashuWallet.tsx +++ b/src/components/wallet/CashuWallet.tsx @@ -11,7 +11,7 @@ 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 { useBitcoinBalance, useBitcoinTransactionHistory } from '@/hooks/useBitcoinBalance'; import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress, fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, UTXO } from '@/lib/bitcoin'; import { QRModal } from '@/components/ui/qr-modal'; import { WalletHeader } from './WalletHeader'; @@ -47,7 +47,7 @@ export function CashuWallet() { const { generateQRCode } = useQRCode(); const { copy: copyToClipboard } = useCopyToClipboard(); - // Bitcoin hooks + // Bitcoin hooks - including balance and transaction history const { hasNsecAccess, getPrivateKey } = useNsecAccess(); const bitcoinAddress = user?.pubkey ? nostrPubkeyToBitcoinAddress(user.pubkey) : null; const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress); @@ -137,13 +137,19 @@ export function CashuWallet() { getLightningInvoice, }); - const { + const { historyEntries, isLoadingHistory, } = useHistoryManager({ coco, isInitialized, }); + + // Bitcoin transaction history + const { + data: bitcoinTransactions = [], + isLoading: isBitcoinTransactionsLoading + } = useBitcoinTransactionHistory(bitcoinAddress); // ============================================================================ // UI STATE @@ -175,6 +181,7 @@ export function CashuWallet() { // UTXO state const [utxos, setUtxos] = useState([]); const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false); + const [selectedUtxo, setSelectedUtxo] = useState(null); const [isLoadingUtxos, setIsLoadingUtxos] = useState(false); // Handle drawer close with state reset @@ -488,6 +495,8 @@ export function CashuWallet() { utxos={utxos} utxoDropdownOpen={utxoDropdownOpen} setUtxoDropdownOpen={setUtxoDropdownOpen} + selectedUtxo={selectedUtxo} + setSelectedUtxo={setSelectedUtxo} /> @@ -676,8 +685,11 @@ export function CashuWallet() { diff --git a/src/components/wallet/TransactionHistory.tsx b/src/components/wallet/TransactionHistory.tsx index 17ef35a..2a1c6d8 100644 --- a/src/components/wallet/TransactionHistory.tsx +++ b/src/components/wallet/TransactionHistory.tsx @@ -1,12 +1,35 @@ -import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins } from 'lucide-react'; +import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins, Link } from 'lucide-react'; import type { HistoryEntry } from 'coco-cashu-core'; +export interface BitcoinTransaction { + id: string; + txid: string; + type: 'sent' | 'received'; + amount: number; // in satoshis + fee?: number; // in satoshis, only for sent transactions + address: string; + confirmations: number; + blockHeight?: number; + timestamp: number; + status: 'confirmed' | 'unconfirmed' | 'pending'; +} + interface TransactionHistoryProps { entries: HistoryEntry[]; isLoading: boolean; + // Bitcoin transaction props + bitcoinTransactions?: BitcoinTransaction[]; + isBitcoinLoading?: boolean; + showSats?: boolean; } -export function TransactionHistory({ entries, isLoading }: TransactionHistoryProps) { +export function TransactionHistory({ + entries, + isLoading, + bitcoinTransactions = [], + isBitcoinLoading = false, + showSats = true +}: TransactionHistoryProps) { // Icon indicating transaction type (Lightning vs Cashu) const getTransactionTypeIcon = (type: string) => { switch (type) { @@ -48,19 +71,47 @@ export function TransactionHistory({ entries, isLoading }: TransactionHistoryPro } }; + // Bitcoin transaction formatting functions + const formatBitcoinAmount = (sats: number): string => { + if (showSats) { + return `${sats.toLocaleString()} sats`; + } else { + const btc = sats / 100000000; + return `₿${btc.toFixed(8)}`; + } + }; + + const formatBitcoinAddress = (address: string): string => { + return `${address.slice(0, 8)}...${address.slice(-8)}`; + }; + + const getBitcoinStatusColor = (status: string): string => { + switch (status) { + case 'confirmed': + return 'text-green-500'; + case 'unconfirmed': + return 'text-yellow-500'; + case 'pending': + return 'text-blue-500'; + default: + return 'text-muted-foreground'; + } + }; + return (
- {isLoading ? ( + {isLoading || isBitcoinLoading ? (
- Loading history... + Loading transactions...
- ) : entries.length === 0 ? ( + ) : entries.length === 0 && bitcoinTransactions.length === 0 ? (
No transactions yet
) : ( <> + {/* Cashu/Lightning Transactions */} {entries.map((entry) => (
))} + + {/* Bitcoin Transactions */} + {bitcoinTransactions.map((tx) => ( +
+
+
+
+ +
+
+
+ + {tx.type === 'received' ? 'Received' : 'Sent'} + + + {tx.status} + +
+
+ {formatBitcoinAddress(tx.address)} +
+
+ {new Date(tx.timestamp).toLocaleString()} + {tx.confirmations > 0 && ( + + • {tx.confirmations} confirmation{tx.confirmations !== 1 ? 's' : ''} + + )} +
+ {tx.blockHeight && ( +
+ Block #{tx.blockHeight} +
+ )} +
+
+
+
+
+ {tx.type === 'sent' ? '-' : '+'} + {formatBitcoinAmount(tx.amount)} +
+ {tx.fee && tx.type === 'sent' && ( +
+ Fee: {formatBitcoinAmount(tx.fee)} +
+ )} +
+
+ {tx.type === 'received' ? ( + + ) : ( + + )} +
+
+
+
+ ))} )}
diff --git a/src/components/wallet/UTXOSelector.tsx b/src/components/wallet/UTXOSelector.tsx index 188d4a8..fff70ae 100644 --- a/src/components/wallet/UTXOSelector.tsx +++ b/src/components/wallet/UTXOSelector.tsx @@ -1,5 +1,5 @@ import { Button } from '@/components/ui/button'; -import { ChevronDown, Wallet } from 'lucide-react'; +import { ChevronDown, Wallet, Check } from 'lucide-react'; import { useState, useEffect } from 'react'; import { exchangeRateService } from '@/lib/exchangeRateService'; import { @@ -16,6 +16,8 @@ interface UTXOSelectorProps { bitcoinAddress: string; dropdownOpen: boolean; setDropdownOpen: (open: boolean) => void; + selectedUtxo: UTXO | null; + setSelectedUtxo: (utxo: UTXO | null) => void; } export function UTXOSelector({ @@ -24,6 +26,8 @@ export function UTXOSelector({ bitcoinAddress, dropdownOpen, setDropdownOpen, + selectedUtxo, + setSelectedUtxo, }: UTXOSelectorProps) { const [btcUsdRate, setBtcUsdRate] = useState(null); @@ -33,6 +37,29 @@ export function UTXOSelector({ .catch(() => setBtcUsdRate(null)); }, []); + // Auto-select first UTXO when UTXOs are loaded and none is selected + // Also handle case where selected UTXO is no longer available + useEffect(() => { + if (utxos.length > 0) { + if (!selectedUtxo) { + // No UTXO selected, select the first one + setSelectedUtxo(utxos[0]); + } else { + // Check if currently selected UTXO still exists in the list + const stillExists = utxos.some(utxo => + utxo.txid === selectedUtxo.txid && utxo.vout === selectedUtxo.vout + ); + if (!stillExists) { + // Selected UTXO no longer exists, select the first available one + setSelectedUtxo(utxos[0]); + } + } + } else { + // No UTXOs available, clear selection + setSelectedUtxo(null); + } + }, [utxos, selectedUtxo, setSelectedUtxo]); + const formatBalance = (sats: number): string => { if (showSats) { return `₿${sats.toLocaleString()}`; @@ -47,8 +74,12 @@ export function UTXOSelector({ const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0); - const formatUTXOId = (txid: string, vout: number): string => { - return `${txid.slice(0, 8)}...${txid.slice(-8)}:${vout}`; + const formatUTXOBlock = (utxo: UTXO): string => { + if (utxo.status.block_height) { + return `Block #${utxo.status.block_height}`; + } else { + return 'Unconfirmed'; + } }; return ( @@ -62,12 +93,21 @@ export function UTXOSelector({ >
- - {utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`} - + {selectedUtxo ? ( + <> + + + {formatUTXOBlock(selectedUtxo)} + + + ) : ( + + {utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`} + + )}
- {formatBalance(totalBalance)} + {selectedUtxo ? formatBalance(selectedUtxo.value) : formatBalance(totalBalance)}
@@ -80,28 +120,37 @@ export function UTXOSelector({ No UTXOs available ) : ( - utxos.map((utxo, index) => ( - -
-
-
- {formatUTXOId(utxo.txid, utxo.vout)} -
-
- {utxo.status.confirmed ? 'Confirmed' : 'Unconfirmed'} + utxos.map((utxo, index) => { + const isSelected = selectedUtxo && + selectedUtxo.txid === utxo.txid && + selectedUtxo.vout === utxo.vout; + + return ( + setSelectedUtxo(isSelected ? null : utxo)} + > +
+ {isSelected && ( +
+ +
+ )} +
+
+ {formatUTXOBlock(utxo)} +
-
-
- - {formatBalance(utxo.value)} - -
- - )) +
+ + {formatBalance(utxo.value)} + +
+ + ); + }) )}
diff --git a/src/components/wallet/WalletHeader.tsx b/src/components/wallet/WalletHeader.tsx index 17caf4f..0e1bd3a 100644 --- a/src/components/wallet/WalletHeader.tsx +++ b/src/components/wallet/WalletHeader.tsx @@ -44,6 +44,8 @@ interface WalletHeaderProps { utxos: UTXO[]; utxoDropdownOpen: boolean; setUtxoDropdownOpen: (open: boolean) => void; + selectedUtxo: UTXO | null; + setSelectedUtxo: (utxo: UTXO | null) => void; } // Helper functions to prevent syntax errors in complex expressions @@ -132,6 +134,8 @@ export function WalletHeader({ utxos, utxoDropdownOpen, setUtxoDropdownOpen, + selectedUtxo, + setSelectedUtxo, }: WalletHeaderProps) { const [lightningAddressCopied, setLightningAddressCopied] = useState(false); const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false); @@ -201,6 +205,15 @@ export function WalletHeader({ {formatBalance(totalBalance, showSats, btcUsdRate)} + + {/* Custody Badge */} + + {mode === 'bitcoin' ? 'Self-Custody' : 'Mint-Custody'} +
{/* Lightning Address and Mint Selector Grid */} @@ -329,6 +342,8 @@ export function WalletHeader({ bitcoinAddress={userPubkey ? nostrPubkeyToBitcoinAddress(userPubkey) : ''} dropdownOpen={utxoDropdownOpen} setDropdownOpen={setUtxoDropdownOpen} + selectedUtxo={selectedUtxo} + setSelectedUtxo={setSelectedUtxo} /> )} diff --git a/src/hooks/useBitcoinBalance.ts b/src/hooks/useBitcoinBalance.ts index fe9f22d..3af5301 100644 --- a/src/hooks/useBitcoinBalance.ts +++ b/src/hooks/useBitcoinBalance.ts @@ -1,5 +1,68 @@ import { useQuery } from '@tanstack/react-query'; import { fetchUTXOs, type UTXO } from '@/lib/bitcoin'; +import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory'; + +/** + * Fetch Bitcoin transaction history for an address from Blockstream API + */ +async function fetchBitcoinTransactions(address: string): Promise { + const response = await fetch(`https://blockstream.info/api/address/${address}/txs`); + + if (!response.ok) { + throw new Error('Failed to fetch Bitcoin transactions'); + } + + const txs = await response.json(); + + // Transform Blockstream API response to our BitcoinTransaction format + return txs.map((tx: any, index: number) => { + // Determine if this is a sent or received transaction + // For simplicity, we'll consider it received if the address appears in outputs + // and sent if it appears in inputs + const isReceived = tx.vout.some((output: any) => + output.scriptpubkey_address === address + ); + const isSent = tx.vin.some((input: any) => + input.prevout?.scriptpubkey_address === address + ); + + // Calculate amount for this address + let amount = 0; + let fee = 0; + + if (isReceived) { + // Sum all outputs to this address + amount = tx.vout + .filter((output: any) => output.scriptpubkey_address === address) + .reduce((sum: number, output: any) => sum + output.value, 0); + } else if (isSent) { + // Sum all inputs from this address minus outputs to this address + const inputsFromAddress = tx.vin + .filter((input: any) => input.prevout?.scriptpubkey_address === address) + .reduce((sum: number, input: any) => sum + input.prevout.value, 0); + + const outputsToAddress = tx.vout + .filter((output: any) => output.scriptpubkey_address === address) + .reduce((sum: number, output: any) => sum + output.value, 0); + + amount = inputsFromAddress - outputsToAddress; + fee = tx.fee || 0; + } + + return { + id: `${tx.txid}-${index}`, + txid: tx.txid, + type: isReceived ? 'received' : 'sent', + amount: Math.abs(amount), + fee: isSent ? fee : undefined, + address: address, + confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified + blockHeight: tx.status.block_height, + timestamp: tx.status.block_time * 1000, // Convert to milliseconds + status: tx.status.confirmed ? 'confirmed' : 'unconfirmed' + } as BitcoinTransaction; + }); +} /** * Hook to fetch and manage Bitcoin balance from UTXOs @@ -22,3 +85,22 @@ export function useBitcoinBalance(address: string | null) { staleTime: 10000, // Consider data stale after 10 seconds }); } + +/** + * Hook to fetch and manage Bitcoin transaction history + */ +export function useBitcoinTransactionHistory(address: string | null) { + return useQuery({ + queryKey: ['bitcoin-transactions', address], + queryFn: async (): Promise => { + if (!address) { + return []; + } + + return fetchBitcoinTransactions(address); + }, + enabled: !!address, + refetchInterval: 30000, // Refetch every 30 seconds + staleTime: 10000, // Consider data stale after 10 seconds + }); +}