Coin selector and custody badge

This commit is contained in:
lemonknowsall committed 2025-10-22 22:22:39 -07:00
1 parent 015e7b8b90
commit e3cebf3a34
5 files changed
+308 -37

No files matched your search

+17 -5
View File
@@ -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<UTXO[]>([]);
const [utxoDropdownOpen, setUtxoDropdownOpen] = useState(false);
const [selectedUtxo, setSelectedUtxo] = useState<UTXO | null>(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() {
</DrawerHeader>
<ScrollArea className="h-[80vh] px-4 pb-4">
<TransactionHistory
entries={historyEntries}
isLoading={isLoadingHistory}
entries={mode === 'bitcoin' ? [] : historyEntries}
isLoading={mode === 'bitcoin' ? isBitcoinTransactionsLoading : isLoadingHistory}
bitcoinTransactions={mode === 'bitcoin' ? bitcoinTransactions : []}
isBitcoinLoading={isBitcoinTransactionsLoading}
showSats={showSats}
/>
</ScrollArea>
</DrawerContent>
+118 -5
View File
@@ -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 (
<div className="space-y-2">
{isLoading ? (
{isLoading || isBitcoinLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
<span>Loading history...</span>
<span>Loading transactions...</span>
</div>
) : entries.length === 0 ? (
) : entries.length === 0 && bitcoinTransactions.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
No transactions yet
</div>
) : (
<>
{/* Cashu/Lightning Transactions */}
{entries.map((entry) => (
<div
key={entry.id}
@@ -104,6 +155,68 @@ export function TransactionHistory({ entries, isLoading }: TransactionHistoryPro
</div>
</div>
))}
{/* Bitcoin Transactions */}
{bitcoinTransactions.map((tx) => (
<div
key={tx.id}
className="rounded-lg p-4 hover:bg-muted/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex items-start gap-3 flex-1">
<div className="mt-1">
<Link className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">
{tx.type === 'received' ? 'Received' : 'Sent'}
</span>
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
{tx.status}
</span>
</div>
<div className="text-sm text-muted-foreground mt-1">
{formatBitcoinAddress(tx.address)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{new Date(tx.timestamp).toLocaleString()}
{tx.confirmations > 0 && (
<span className="ml-2">
• {tx.confirmations} confirmation{tx.confirmations !== 1 ? 's' : ''}
</span>
)}
</div>
{tx.blockHeight && (
<div className="text-xs text-muted-foreground">
Block #{tx.blockHeight}
</div>
)}
</div>
</div>
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{tx.type === 'sent' ? '-' : '+'}
{formatBitcoinAmount(tx.amount)}
</div>
{tx.fee && tx.type === 'sent' && (
<div className="text-xs text-muted-foreground mt-1">
Fee: {formatBitcoinAmount(tx.fee)}
</div>
)}
</div>
<div className="mt-1">
{tx.type === 'received' ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
</div>
</div>
</div>
</div>
))}
</>
)}
</div>
+76 -27
View File
@@ -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<number | null>(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({
>
<div className="flex items-center justify-between w-full min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
{selectedUtxo ? (
<>
<Check className="h-5 w-5 text-primary flex-shrink-0" />
<span className="truncate font-medium min-w-0 flex-1">
{formatUTXOBlock(selectedUtxo)}
</span>
</>
) : (
<span className="truncate font-medium min-w-0 flex-1">
{utxos.length === 0 ? 'No UTXOs' : `${utxos.length} UTXO${utxos.length !== 1 ? 's' : ''}`}
</span>
)}
</div>
<span className="text-muted-foreground font-medium flex-shrink-0 ml-2">
{formatBalance(totalBalance)}
{selectedUtxo ? formatBalance(selectedUtxo.value) : formatBalance(totalBalance)}
</span>
</div>
<ChevronDown className="h-5 w-5 ml-2 flex-shrink-0" />
@@ -80,28 +120,37 @@ export function UTXOSelector({
No UTXOs available
</DropdownMenuItem>
) : (
utxos.map((utxo, index) => (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOId(utxo.txid, utxo.vout)}
</div>
<div className="text-xs text-muted-foreground">
{utxo.status.confirmed ? 'Confirmed' : 'Unconfirmed'}
utxos.map((utxo, index) => {
const isSelected = selectedUtxo &&
selectedUtxo.txid === utxo.txid &&
selectedUtxo.vout === utxo.vout;
return (
<DropdownMenuItem
key={`utxo-${utxo.txid}-${utxo.vout}`}
className="flex items-center justify-between p-3 text-base"
onClick={() => setSelectedUtxo(isSelected ? null : utxo)}
>
<div className="flex items-center gap-3 flex-1 min-w-0">
{isSelected && (
<div className="flex-shrink-0">
<Check className="h-5 w-5 text-primary" />
</div>
)}
<div className="flex-1 min-w-0">
<div className="font-medium truncate text-sm">
{formatUTXOBlock(utxo)}
</div>
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
))
<div className="flex items-center gap-2 flex-shrink-0">
<span className="px-3 py-1 text-sm font-medium text-muted-foreground">
{formatBalance(utxo.value)}
</span>
</div>
</DropdownMenuItem>
);
})
)}
</div>
</DropdownMenuContent>
+15
View File
@@ -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({
</span>
{formatBalance(totalBalance, showSats, btcUsdRate)}
</button>
{/* Custody Badge */}
<span className={`px-2 py-1 text-xs font-medium rounded-full ${
mode === 'bitcoin'
? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
}`}>
{mode === 'bitcoin' ? 'Self-Custody' : 'Mint-Custody'}
</span>
</div>
{/* 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}
/>
</div>
)}
+82
View File
@@ -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<BitcoinTransaction[]> {
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<BitcoinTransaction[]> => {
if (!address) {
return [];
}
return fetchBitcoinTransactions(address);
},
enabled: !!address,
refetchInterval: 30000, // Refetch every 30 seconds
staleTime: 10000, // Consider data stale after 10 seconds
});
}