mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
On-Chain Sent and Consolidation History, UTXO balance update
This commit is contained in:
1 parent
e0031c6b14
commit
516461ae6e
2 files changed
+140
-52
No files matched your search
@@ -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';
|
import type { HistoryEntry } from 'coco-cashu-core';
|
||||||
|
|
||||||
export interface BitcoinTransaction {
|
export interface BitcoinTransaction {
|
||||||
id: string;
|
id: string;
|
||||||
txid: string;
|
txid: string;
|
||||||
type: 'sent' | 'received';
|
type: 'sent' | 'received' | 'consolidate';
|
||||||
amount: number; // in satoshis
|
amount: number; // in satoshis
|
||||||
fee?: number; // in satoshis, only for sent transactions
|
fee?: number; // in satoshis, only for sent transactions
|
||||||
address: string;
|
address: string;
|
||||||
@@ -170,7 +170,7 @@ export function TransactionHistory({
|
|||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{tx.type === 'received' ? 'Received' : 'Sent'}
|
{tx.type === 'received' ? 'Received' : tx.type === 'consolidate' ? 'Consolidate' : 'Sent'}
|
||||||
</span>
|
</span>
|
||||||
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
|
<span className={`text-xs px-2 py-1 rounded-full bg-muted ${getBitcoinStatusColor(tx.status)}`}>
|
||||||
{tx.status}
|
{tx.status}
|
||||||
@@ -197,10 +197,10 @@ export function TransactionHistory({
|
|||||||
<div className="text-right ml-4 flex items-start gap-2">
|
<div className="text-right ml-4 flex items-start gap-2">
|
||||||
<div>
|
<div>
|
||||||
<div className="font-semibold">
|
<div className="font-semibold">
|
||||||
{tx.type === 'sent' ? '-' : '+'}
|
{tx.type === 'sent' ? '-' : tx.type === 'consolidate' ? '' : '+'}
|
||||||
{formatBitcoinAmount(tx.amount)}
|
{formatBitcoinAmount(tx.amount)}
|
||||||
</div>
|
</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">
|
<div className="text-xs text-muted-foreground mt-1">
|
||||||
Fee: {formatBitcoinAmount(tx.fee)}
|
Fee: {formatBitcoinAmount(tx.fee)}
|
||||||
</div>
|
</div>
|
||||||
@@ -209,6 +209,8 @@ export function TransactionHistory({
|
|||||||
<div className="mt-1">
|
<div className="mt-1">
|
||||||
{tx.type === 'received' ? (
|
{tx.type === 'received' ? (
|
||||||
<ArrowDownLeft className="h-4 w-4 text-green-500" />
|
<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" />
|
<ArrowUpRight className="h-4 w-4 text-red-500" />
|
||||||
)}
|
)}
|
||||||
|
|||||||
+133
-47
@@ -1,5 +1,5 @@
|
|||||||
import { useQuery } from '@tanstack/react-query';
|
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 { fetchUTXOs, getFeeRates, createBitcoinTransaction, broadcastTransaction, calculateMaxSendAmount, npubToBitcoinAddress, nostrPubkeyToBitcoinAddress, type UTXO } from '@/lib/bitcoin';
|
||||||
import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory';
|
import type { BitcoinTransaction } from '@/components/wallet/TransactionHistory';
|
||||||
import { useToast, toast } from '@/hooks/useToast';
|
import { useToast, toast } from '@/hooks/useToast';
|
||||||
@@ -26,7 +26,8 @@ interface BlockstreamTransactionOutput {
|
|||||||
value: number;
|
value: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BlockstreamTransaction {
|
// Transaction list item (from /address/:address/txs) - minimal data
|
||||||
|
interface BlockstreamTransactionListItem {
|
||||||
txid: string;
|
txid: string;
|
||||||
fee?: number;
|
fee?: number;
|
||||||
status: BlockstreamTransactionStatus;
|
status: BlockstreamTransactionStatus;
|
||||||
@@ -34,27 +35,79 @@ interface BlockstreamTransaction {
|
|||||||
vout: BlockstreamTransactionOutput[];
|
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
|
* 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[]> {
|
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');
|
throw new Error('Failed to fetch Bitcoin transactions');
|
||||||
}
|
}
|
||||||
|
|
||||||
const txs: BlockstreamTransaction[] = await response.json();
|
const txList: BlockstreamTransactionListItem[] = await listResponse.json();
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
// Transform Blockstream API response to our BitcoinTransaction format
|
|
||||||
return txs.map((tx: BlockstreamTransaction, index: number) => {
|
|
||||||
// Determine if this is a sent or received transaction
|
// Determine if this is a sent or received transaction
|
||||||
// For simplicity, we'll consider it received if the address appears in outputs
|
// Check if address appears in outputs (received)
|
||||||
// and sent if it appears in inputs
|
const isReceived = txData.vout.some((output) =>
|
||||||
const isReceived = tx.vout.some((output: BlockstreamTransactionOutput) =>
|
|
||||||
output.scriptpubkey_address === address
|
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
|
input.prevout?.scriptpubkey_address === address
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -62,36 +115,61 @@ async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransac
|
|||||||
let amount = 0;
|
let amount = 0;
|
||||||
let fee: number | undefined = undefined;
|
let fee: number | undefined = undefined;
|
||||||
|
|
||||||
if (isReceived) {
|
// Calculate inputs and outputs for this address
|
||||||
// Sum all outputs to this address
|
const inputsFromAddress = txData.vin
|
||||||
amount = tx.vout
|
.filter((input) => input.prevout?.scriptpubkey_address === address)
|
||||||
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
|
.reduce((sum, input) => sum + (input.prevout?.value || 0), 0);
|
||||||
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 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) {
|
} else if (isSent) {
|
||||||
// Sum all inputs from this address minus outputs to this address
|
// Sent transaction (may also have change output)
|
||||||
const inputsFromAddress = tx.vin
|
// Amount sent to others = inputs - change - fee
|
||||||
.filter((input: BlockstreamTransactionInput) => input.prevout?.scriptpubkey_address === address)
|
const amountSentToOthers = inputsFromAddress - outputsToAddress - fee;
|
||||||
.reduce((sum: number, input: BlockstreamTransactionInput) => sum + (input.prevout?.value || 0), 0);
|
|
||||||
|
|
||||||
const outputsToAddress = tx.vout
|
// Check if this is a consolidation (self-send where all outputs go back to same address)
|
||||||
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
|
// A consolidation happens when amount sent to others is 0 or very small (dust threshold)
|
||||||
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0);
|
const dustThreshold = 546; // Standard Bitcoin dust limit
|
||||||
|
const isConsolidation = amountSentToOthers <= dustThreshold && outputsToAddress > 0;
|
||||||
|
|
||||||
amount = inputsFromAddress - outputsToAddress;
|
if (isConsolidation) {
|
||||||
fee = tx.fee || 0;
|
// 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 {
|
return {
|
||||||
id: `${tx.txid}-${index}`,
|
id: `${txData.txid}-${index}`,
|
||||||
txid: tx.txid,
|
txid: txData.txid,
|
||||||
type: isReceived ? 'received' : 'sent',
|
type,
|
||||||
amount: Math.abs(amount),
|
amount: Math.abs(amount),
|
||||||
fee: fee,
|
fee: fee,
|
||||||
address: address,
|
address: address,
|
||||||
confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified
|
confirmations: txData.status.confirmed ? (txData.status.block_height ? 1 : 0) : 0, // Simplified
|
||||||
blockHeight: tx.status.block_height,
|
blockHeight: txData.status.block_height,
|
||||||
timestamp: (tx.status.block_time ?? 0) * 1000, // Convert to milliseconds
|
timestamp: (txData.status.block_time ?? 0) * 1000, // Convert to milliseconds
|
||||||
status: tx.status.confirmed ? 'confirmed' : 'unconfirmed'
|
status: txData.status.confirmed ? 'confirmed' : 'unconfirmed'
|
||||||
} as BitcoinTransaction;
|
} as BitcoinTransaction;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -144,28 +222,39 @@ export function useBitcoinOperations(bitcoinAddress: string | null) {
|
|||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { generateQRCode } = useQRCode();
|
const { generateQRCode } = useQRCode();
|
||||||
const { hasNsecAccess, getPrivateKey } = useNsecAccess();
|
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
|
// State for Bitcoin operations
|
||||||
const [utxos, setUtxos] = useState<UTXO[]>([]);
|
|
||||||
const [isLoadingUtxos, setIsLoadingUtxos] = useState(false);
|
|
||||||
const [feeRate, setFeeRate] = useState<number>(1);
|
const [feeRate, setFeeRate] = useState<number>(1);
|
||||||
const [isConsolidating, setIsConsolidating] = useState(false);
|
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
|
// Calculate max send amount
|
||||||
const bitcoinMaxAmount = utxos.length > 0 ? calculateMaxSendAmount(utxos, feeRate) : 0;
|
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 () => {
|
const fetchBitcoinUtxos = useCallback(async () => {
|
||||||
if (!bitcoinAddress) return;
|
if (!bitcoinAddress) return;
|
||||||
|
|
||||||
setIsLoadingUtxos(true);
|
|
||||||
try {
|
try {
|
||||||
const [fetchedUtxos, feeRates] = await Promise.all([
|
// Refetch balance which includes UTXOs
|
||||||
fetchUTXOs(bitcoinAddress),
|
await refetchBitcoinBalance();
|
||||||
getFeeRates()
|
|
||||||
]);
|
// Also update fee rates
|
||||||
setUtxos(fetchedUtxos);
|
const feeRates = await getFeeRates();
|
||||||
setFeeRate(feeRates.fastestFee);
|
setFeeRate(feeRates.fastestFee);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching UTXOs:', error);
|
console.error('Error fetching UTXOs:', error);
|
||||||
@@ -174,10 +263,8 @@ export function useBitcoinOperations(bitcoinAddress: string | null) {
|
|||||||
title: "UTXO Error",
|
title: "UTXO Error",
|
||||||
description: "Failed to fetch Bitcoin UTXOs",
|
description: "Failed to fetch Bitcoin UTXOs",
|
||||||
});
|
});
|
||||||
} finally {
|
|
||||||
setIsLoadingUtxos(false);
|
|
||||||
}
|
}
|
||||||
}, [bitcoinAddress]);
|
}, [bitcoinAddress, refetchBitcoinBalance, toast]);
|
||||||
|
|
||||||
// Handle Send Max
|
// Handle Send Max
|
||||||
const handleSendMax = (setBitcoinAmount: (amount: string) => void) => {
|
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)`,
|
description: `Transaction ${txId.slice(0, 8)}... confirmed (Fee: ${fee} sats)`,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Refresh UTXOs and balance
|
// Refresh UTXOs and balance (refetchBitcoinBalance updates UTXOs automatically)
|
||||||
refetchBitcoinBalance();
|
refetchBitcoinBalance();
|
||||||
fetchBitcoinUtxos();
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('UTXO consolidation error:', error);
|
console.error('UTXO consolidation error:', error);
|
||||||
|
|||||||
Reference in new issue
Block a user