On-Chain Sent and Consolidation History, UTXO balance update

This commit is contained in:
lemonknowsall committed 2025-11-03 17:06:22 -08:00
1 parent e0031c6b14
commit 516461ae6e
2 files changed
+140 -52

No files matched your search

+7 -5
View File
@@ -1,10 +1,10 @@
import { Loader2, History, ArrowUpRight, ArrowDownLeft, Zap, Coins, Link } from 'lucide-react';
import { Loader2, History, ArrowUpRight, ArrowDownLeft, ArrowLeftRight, Zap, Coins, Link } from 'lucide-react';
import type { HistoryEntry } from 'coco-cashu-core';
export interface BitcoinTransaction {
id: string;
txid: string;
type: 'sent' | 'received';
type: 'sent' | 'received' | 'consolidate';
amount: number; // in satoshis
fee?: number; // in satoshis, only for sent transactions
address: string;
@@ -170,7 +170,7 @@ export function TransactionHistory({
<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'}
{tx.type === 'received' ? 'Received' : tx.type === 'consolidate' ? 'Consolidate' : 'Sent'}
</span>
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
{tx.status}
@@ -197,10 +197,10 @@ export function TransactionHistory({
<div className="text-right ml-4 flex items-start gap-2">
<div>
<div className="font-semibold">
{tx.type === 'sent' ? '-' : '+'}
{tx.type === 'sent' ? '-' : tx.type === 'consolidate' ? '' : '+'}
{formatBitcoinAmount(tx.amount)}
</div>
{tx.fee !== undefined && tx.fee > 0 && tx.type === 'sent' && (
{tx.fee !== undefined && tx.fee > 0 && (tx.type === 'sent' || tx.type === 'consolidate') && (
<div className="text-xs text-muted-foreground mt-1">
Fee: {formatBitcoinAmount(tx.fee)}
</div>
@@ -209,6 +209,8 @@ export function TransactionHistory({
<div className="mt-1">
{tx.type === 'received' ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : tx.type === 'consolidate' ? (
<ArrowLeftRight className="h-4 w-4 text-blue-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
+133 -47
View File
@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { useState, useCallback } from 'react';
import { useState, useCallback, useEffect } from 'react';
import { fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, npubToBitcoinAddress, nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory';
import { useToast, toast } from '@/hooks/useToast';
@@ -26,7 +26,8 @@ interface BlockstreamTransactionOutput {
value: number;
}
interface BlockstreamTransaction {
// Transaction list item (from /address/:address/txs) - minimal data
interface BlockstreamTransactionListItem {
txid: string;
fee?: number;
status: BlockstreamTransactionStatus;
@@ -34,27 +35,79 @@ interface BlockstreamTransaction {
vout: BlockstreamTransactionOutput[];
}
// Full transaction details (from /tx/:txid) - includes complete prevout data
interface BlockstreamFullTransaction {
txid: string;
fee?: number;
status: BlockstreamTransactionStatus;
vin: Array<{
txid: string;
vout: number;
prevout: {
scriptpubkey_address?: string;
value: number;
};
[key: string]: unknown; // Other fields we don't need
}>;
vout: Array<{
scriptpubkey_address?: string;
value: number;
[key: string]: unknown; // Other fields we don't need
}>;
}
/**
* Fetch Bitcoin transaction history for an address from Blockstream API
* Fetches full transaction details to get complete prevout data for accurate sent/received detection
*/
async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransaction[]> {
const response = await fetch(`https://blockstream.info/api/address/${address}/txs`);
// First, fetch the transaction list
const listResponse = await fetch(`https://blockstream.info/api/address/${address}/txs`);
if (!response.ok) {
if (!listResponse.ok) {
throw new Error('Failed to fetch Bitcoin transactions');
}
const txs: BlockstreamTransaction[] = await response.json();
const txList: BlockstreamTransactionListItem[] = await listResponse.json();
// Transform Blockstream API response to our BitcoinTransaction format
return txs.map((tx: BlockstreamTransaction, index: number) => {
// Fetch full transaction details for each transaction in parallel
// This gives us complete prevout data needed to detect sent transactions
const fullTxPromises = txList.map(async (txItem) => {
const txResponse = await fetch(`https://blockstream.info/api/tx/${txItem.txid}`);
if (!txResponse.ok) {
console.warn(`Failed to fetch full details for transaction ${txItem.txid}`);
// Fallback to list item data if full fetch fails
return null;
}
return await txResponse.json() as BlockstreamFullTransaction;
});
const fullTxs = await Promise.all(fullTxPromises);
// Transform to our BitcoinTransaction format
return fullTxs.map((tx, index) => {
// If we couldn't fetch full details, use list item data
const txItem = txList[index];
const txData = tx || {
txid: txItem.txid,
fee: txItem.fee,
status: txItem.status,
vin: txItem.vin.map(vin => ({
prevout: vin.prevout || undefined
})),
vout: txItem.vout
} as BlockstreamFullTransaction;
// 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: BlockstreamTransactionOutput) =>
// Check if address appears in outputs (received)
const isReceived = txData.vout.some((output) =>
output.scriptpubkey_address === address
);
const isSent = tx.vin.some((input: BlockstreamTransactionInput) =>
// Check if address appears in input prevouts (sent)
const isSent = txData.vin.some((input) =>
input.prevout?.scriptpubkey_address === address
);
@@ -62,36 +115,61 @@ async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransac
let amount = 0;
let fee: number | undefined = undefined;
if (isReceived) {
// Sum all outputs to this address
amount = tx.vout
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0);
// Calculate inputs and outputs for this address
const inputsFromAddress = txData.vin
.filter((input) => input.prevout?.scriptpubkey_address === address)
.reduce((sum, input) => sum + (input.prevout?.value || 0), 0);
const outputsToAddress = txData.vout
.filter((output) => output.scriptpubkey_address === address)
.reduce((sum, output) => sum + output.value, 0);
// Get the transaction fee
fee = txData.fee || 0;
// Determine transaction type and amount
let type: 'sent' | 'received' | 'consolidate';
if (isReceived && !isSent) {
// Pure received transaction - sum all outputs to this address
type = 'received';
amount = outputsToAddress;
} else if (isSent) {
// Sum all inputs from this address minus outputs to this address
const inputsFromAddress = tx.vin
.filter((input: BlockstreamTransactionInput) => input.prevout?.scriptpubkey_address === address)
.reduce((sum: number, input: BlockstreamTransactionInput) => sum + (input.prevout?.value || 0), 0);
// Sent transaction (may also have change output)
// Amount sent to others = inputs - change - fee
const amountSentToOthers = inputsFromAddress - outputsToAddress - fee;
const outputsToAddress = tx.vout
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0);
// Check if this is a consolidation (self-send where all outputs go back to same address)
// A consolidation happens when amount sent to others is 0 or very small (dust threshold)
const dustThreshold = 546; // Standard Bitcoin dust limit
const isConsolidation = amountSentToOthers <= dustThreshold && outputsToAddress > 0;
amount = inputsFromAddress - outputsToAddress;
fee = tx.fee || 0;
if (isConsolidation) {
// For consolidation, show the output amount (the consolidated amount)
type = 'consolidate';
amount = outputsToAddress;
} else {
// Regular send transaction - show amount sent to others
type = 'sent';
amount = amountSentToOthers;
}
} else {
// Fallback (shouldn't happen, but TypeScript requires it)
type = 'received';
amount = outputsToAddress;
}
return {
id: `${tx.txid}-${index}`,
txid: tx.txid,
type: isReceived ? 'received' : 'sent',
id: `${txData.txid}-${index}`,
txid: txData.txid,
type,
amount: Math.abs(amount),
fee: fee,
address: address,
confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified
blockHeight: tx.status.block_height,
timestamp: (tx.status.block_time ?? 0) * 1000, // Convert to milliseconds
status: tx.status.confirmed ? 'confirmed' : 'unconfirmed'
confirmations: txData.status.confirmed ? (txData.status.block_height ? 1 : 0) : 0, // Simplified
blockHeight: txData.status.block_height,
timestamp: (txData.status.block_time ?? 0) * 1000, // Convert to milliseconds
status: txData.status.confirmed ? 'confirmed' : 'unconfirmed'
} as BitcoinTransaction;
});
}
@@ -144,28 +222,39 @@ export function useBitcoinOperations(bitcoinAddress: string | null) {
const { toast } = useToast();
const { generateQRCode } = useQRCode();
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
const { refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
const { data: bitcoinBalanceData, isLoading: isBitcoinBalanceLoading, refetch: refetchBitcoinBalance } = useBitcoinBalance(bitcoinAddress);
// Use UTXOs from useBitcoinBalance which auto-updates every 30 seconds
const utxos = bitcoinBalanceData?.utxos || [];
const isLoadingUtxos = isBitcoinBalanceLoading;
// State for Bitcoin operations
const [utxos, setUtxos] = useState<UTXO[]>([]);
const [isLoadingUtxos, setIsLoadingUtxos] = useState(false);
const [feeRate, setFeeRate] = useState<number>(1);
const [isConsolidating, setIsConsolidating] = useState(false);
// Fetch fee rates on mount and when UTXOs change
useEffect(() => {
getFeeRates()
.then(feeRates => setFeeRate(feeRates.fastestFee))
.catch(() => {
// Fee rate fetch failure is not critical, keep existing rate
});
}, [utxos.length]); // Re-fetch when UTXO count changes
// Calculate max send amount
const bitcoinMaxAmount = utxos.length > 0 ? calculateMaxSendAmount(utxos, feeRate) : 0;
// Fetch UTXOs for Bitcoin mode
// Fetch UTXOs manually (for immediate refresh after transactions)
// This will trigger React Query to refetch, which will update the utxos automatically
const fetchBitcoinUtxos = useCallback(async () => {
if (!bitcoinAddress) return;
setIsLoadingUtxos(true);
try {
const [fetchedUtxos, feeRates] = await Promise.all([
fetchUTXOs(bitcoinAddress),
getFeeRates()
]);
setUtxos(fetchedUtxos);
// Refetch balance which includes UTXOs
await refetchBitcoinBalance();
// Also update fee rates
const feeRates = await getFeeRates();
setFeeRate(feeRates.fastestFee);
} catch (error) {
console.error('Error fetching UTXOs:', error);
@@ -174,10 +263,8 @@ export function useBitcoinOperations(bitcoinAddress: string | null) {
title: "UTXO Error",
description: "Failed to fetch Bitcoin UTXOs",
});
} finally {
setIsLoadingUtxos(false);
}
}, [bitcoinAddress]);
}, [bitcoinAddress, refetchBitcoinBalance, toast]);
// Handle Send Max
const handleSendMax = (setBitcoinAmount: (amount: string) => void) => {
@@ -342,9 +429,8 @@ export function useBitcoinOperations(bitcoinAddress: string | null) {
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
});
// Refresh UTXOs and balance
// Refresh UTXOs and balance (refetchBitcoinBalance updates UTXOs automatically)
refetchBitcoinBalance();
fetchBitcoinUtxos();
} catch (error) {
console.error('UTXO consolidation error:', error);