mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
cashu wallet restore and addressed some test errors
This commit is contained in:
1 parent
cfd1e7269f
commit
aff1b0add5
6 files changed
+240
-48
No files matched your search
@@ -10,9 +10,8 @@ import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
|||||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||||
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
||||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
|
||||||
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
||||||
import { nostrPubkeyToBitcoinAddress, UTXO } from '@/lib/bitcoin';
|
import { nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
|
||||||
import { QRModal } from '@/components/ui/qr-modal';
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { WalletHeader } from './WalletHeader';
|
import { WalletHeader } from './WalletHeader';
|
||||||
import { TransactionCard } from './PaymentCard';
|
import { TransactionCard } from './PaymentCard';
|
||||||
@@ -54,8 +53,6 @@ export function CashuWallet() {
|
|||||||
// Bitcoin operations hook
|
// Bitcoin operations hook
|
||||||
const {
|
const {
|
||||||
utxos,
|
utxos,
|
||||||
isLoadingUtxos,
|
|
||||||
feeRate,
|
|
||||||
isConsolidating,
|
isConsolidating,
|
||||||
bitcoinMaxAmount,
|
bitcoinMaxAmount,
|
||||||
fetchBitcoinUtxos,
|
fetchBitcoinUtxos,
|
||||||
@@ -141,6 +138,8 @@ export function CashuWallet() {
|
|||||||
handleReceive,
|
handleReceive,
|
||||||
handleSend,
|
handleSend,
|
||||||
handleConfirmInvoicePayment,
|
handleConfirmInvoicePayment,
|
||||||
|
handleRestoreFromSeedPhrase,
|
||||||
|
isRestoring,
|
||||||
mintQuoteUnsubscribeRef,
|
mintQuoteUnsubscribeRef,
|
||||||
} = useWalletTransactions({
|
} = useWalletTransactions({
|
||||||
coco,
|
coco,
|
||||||
@@ -461,6 +460,10 @@ export function CashuWallet() {
|
|||||||
sentTokenQRCode={sentTokenQRCode}
|
sentTokenQRCode={sentTokenQRCode}
|
||||||
showSeedPhraseInfo={showSeedPhraseInfo}
|
showSeedPhraseInfo={showSeedPhraseInfo}
|
||||||
setShowSeedPhraseInfo={setShowSeedPhraseInfo}
|
setShowSeedPhraseInfo={setShowSeedPhraseInfo}
|
||||||
|
onRestoreFromSeedPhrase={handleRestoreFromSeedPhrase}
|
||||||
|
isRestoring={isRestoring}
|
||||||
|
mints={mints}
|
||||||
|
activeMintUrl={activeMintUrl}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Bottom Drawer Modals */}
|
{/* Bottom Drawer Modals */}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ interface UTXOSelectorProps {
|
|||||||
export function UTXOSelector({
|
export function UTXOSelector({
|
||||||
utxos,
|
utxos,
|
||||||
showSats,
|
showSats,
|
||||||
bitcoinAddress,
|
|
||||||
dropdownOpen,
|
dropdownOpen,
|
||||||
setDropdownOpen,
|
setDropdownOpen,
|
||||||
onShowConsolidationModal,
|
onShowConsolidationModal,
|
||||||
@@ -89,7 +88,7 @@ export function UTXOSelector({
|
|||||||
No UTXOs available
|
No UTXOs available
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
) : (
|
) : (
|
||||||
utxos.map((utxo, index) => (
|
utxos.map((utxo) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
key={`utxo-${utxo.txid}-${utxo.vout}`}
|
key={`utxo-${utxo.txid}-${utxo.vout}`}
|
||||||
className="flex items-center justify-between p-3 text-base"
|
className="flex items-center justify-between p-3 text-base"
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft } from 'lucide-react';
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2 } from 'lucide-react';
|
||||||
import { QRModal } from '@/components/ui/qr-modal';
|
import { QRModal } from '@/components/ui/qr-modal';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { UTXO } from '@/lib/bitcoin';
|
import { UTXO } from '@/lib/bitcoin';
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
// Helper function to prevent complex template literals
|
// Helper function to prevent complex template literals
|
||||||
const getLightningAddress = (userPubkey?: string, npubCashUserInfo?: { name?: string } | null): string => {
|
const getLightningAddress = (userPubkey?: string, npubCashUserInfo?: { name?: string } | null): string => {
|
||||||
@@ -71,6 +74,12 @@ interface WalletModalProps {
|
|||||||
// Seed Phrase Info Modal
|
// Seed Phrase Info Modal
|
||||||
showSeedPhraseInfo: boolean;
|
showSeedPhraseInfo: boolean;
|
||||||
setShowSeedPhraseInfo: (show: boolean) => void;
|
setShowSeedPhraseInfo: (show: boolean) => void;
|
||||||
|
|
||||||
|
// Restore functionality
|
||||||
|
onRestoreFromSeedPhrase: (seedPhrase: string, mintUrl: string) => Promise<void>;
|
||||||
|
isRestoring: boolean;
|
||||||
|
mints: Array<{ url: string; name?: string }>;
|
||||||
|
activeMintUrl: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function WalletModals({
|
export function WalletModals({
|
||||||
@@ -101,8 +110,15 @@ export function WalletModals({
|
|||||||
sentTokenQRCode,
|
sentTokenQRCode,
|
||||||
showSeedPhraseInfo,
|
showSeedPhraseInfo,
|
||||||
setShowSeedPhraseInfo,
|
setShowSeedPhraseInfo,
|
||||||
|
onRestoreFromSeedPhrase,
|
||||||
|
isRestoring,
|
||||||
|
mints,
|
||||||
|
activeMintUrl,
|
||||||
}: WalletModalProps) {
|
}: WalletModalProps) {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Restore state
|
||||||
|
const [seedPhraseInput, setSeedPhraseInput] = useState('');
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Proof Breakdown Modal */}
|
{/* Proof Breakdown Modal */}
|
||||||
@@ -351,7 +367,7 @@ export function WalletModals({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Seed Phrase Info Modal */}
|
{/* Seed Phrase Restore Modal */}
|
||||||
{showSeedPhraseInfo && (
|
{showSeedPhraseInfo && (
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||||
@@ -368,48 +384,90 @@ export function WalletModals({
|
|||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div className="flex items-center mb-4 pr-8">
|
<div className="flex items-center mb-4 pr-8">
|
||||||
<Key className="h-5 w-5 mr-2" />
|
<Key className="h-5 w-5 mr-2" />
|
||||||
<h2 className="text-lg font-semibold">What is a Seed Phrase?</h2>
|
<h2 className="text-lg font-semibold">Restore from Seed Phrase</h2>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-muted-foreground mb-6">
|
|
||||||
Your seed phrase is a secure way to backup and restore your wallet
|
<p className="text-muted-foreground mb-4">
|
||||||
|
Enter your seed phrase to restore tokens from the active mint.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="space-y-4 text-sm">
|
{activeMintUrl && (
|
||||||
<div>
|
<div className="bg-muted p-3 rounded-md mb-4">
|
||||||
<h4 className="font-semibold mb-2">🔐 Recovery Key</h4>
|
<p className="text-sm text-muted-foreground">
|
||||||
<p className="text-muted-foreground">
|
<strong>Active Mint:</strong> {mints.find(m => m.url === activeMintUrl)?.name || new URL(activeMintUrl).hostname}
|
||||||
Your seed phrase is a 12-word recovery key that allows you to restore your wallet
|
|
||||||
on any device. It's generated using industry-standard BIP39 wordlists.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<h4 className="font-semibold mb-2">💾 Backup Important</h4>
|
<Label htmlFor="seed-phrase">Seed Phrase</Label>
|
||||||
<p className="text-muted-foreground">
|
<Input
|
||||||
Write down your seed phrase and store it securely offline. Anyone with access
|
id="seed-phrase"
|
||||||
to your seed phrase can control your wallet and funds.
|
type="text"
|
||||||
</p>
|
placeholder="Enter your 12-word seed phrase..."
|
||||||
</div>
|
value={seedPhraseInput}
|
||||||
|
onChange={(e) => setSeedPhraseInput(e.target.value)}
|
||||||
<div>
|
className="mt-1"
|
||||||
<h4 className="font-semibold mb-2">🛡️ Security Tips</h4>
|
/>
|
||||||
<ul className="text-muted-foreground space-y-1 ml-4">
|
|
||||||
<li>• Never share your seed phrase with anyone</li>
|
|
||||||
<li>• Store it offline in a secure location</li>
|
|
||||||
<li>• Don't take screenshots or store it digitally</li>
|
|
||||||
<li>• Use it only to restore your wallet</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-muted p-3 rounded-md">
|
<div className="bg-muted p-3 rounded-md">
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
<strong>Note:</strong> The seed phrase shown above is masked for privacy.
|
<strong>Note:</strong> This will restore tokens from the provided seed phrase and add them to your current wallet balance.
|
||||||
Click the copy button to access the actual phrase for backup purposes.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6">
|
||||||
|
<Button
|
||||||
|
onClick={async () => {
|
||||||
|
if (!seedPhraseInput.trim()) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Missing Information",
|
||||||
|
description: "Please enter your seed phrase.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!activeMintUrl) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "No Active Mint",
|
||||||
|
description: "Please select a mint first.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await onRestoreFromSeedPhrase(seedPhraseInput.trim(), activeMintUrl);
|
||||||
|
setSeedPhraseInput('');
|
||||||
|
setShowSeedPhraseInfo(false);
|
||||||
|
} catch (error) {
|
||||||
|
toast({
|
||||||
|
variant: "destructive",
|
||||||
|
title: "Restore Failed",
|
||||||
|
description: error instanceof Error ? error.message : "Failed to restore from seed phrase",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={isRestoring || !seedPhraseInput.trim() || !activeMintUrl}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
{isRestoring ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Restoring...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Restore Tokens'
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
|
|||||||
import type { Manager } from 'coco-cashu-core';
|
import type { Manager } from 'coco-cashu-core';
|
||||||
import type { Token } from '@cashu/cashu-ts';
|
import type { Token } from '@cashu/cashu-ts';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
import * as bip39 from '@scure/bip39';
|
||||||
|
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
||||||
|
import { initializeCoco, ConsoleLogger } from 'coco-cashu-core';
|
||||||
|
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
|
||||||
|
|
||||||
interface UseWalletTransactionsProps {
|
interface UseWalletTransactionsProps {
|
||||||
coco: Manager | null;
|
coco: Manager | null;
|
||||||
@@ -54,6 +58,9 @@ export function useWalletTransactions({
|
|||||||
expiry: number;
|
expiry: number;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
|
// Restore state
|
||||||
|
const [isRestoring, setIsRestoring] = useState(false);
|
||||||
|
|
||||||
// Ref to store the mint quote redeemed event unsubscribe function
|
// Ref to store the mint quote redeemed event unsubscribe function
|
||||||
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||||
|
|
||||||
@@ -378,6 +385,102 @@ export function useWalletTransactions({
|
|||||||
}
|
}
|
||||||
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]);
|
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]);
|
||||||
|
|
||||||
|
// Handle restore from seed phrase
|
||||||
|
const handleRestoreFromSeedPhrase = useCallback(async (seedPhrase: string, mintUrl: string) => {
|
||||||
|
if (!coco) {
|
||||||
|
throw new Error('Wallet not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRestoring(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Clean and validate the seed phrase
|
||||||
|
const cleanedSeedPhrase = seedPhrase.trim().toLowerCase();
|
||||||
|
|
||||||
|
// Check if it's a valid mnemonic format
|
||||||
|
if (!bip39.validateMnemonic(cleanedSeedPhrase, wordlist)) {
|
||||||
|
// Try to provide more specific error information
|
||||||
|
const words = cleanedSeedPhrase.split(/\s+/);
|
||||||
|
if (words.length !== 12) {
|
||||||
|
throw new Error(`Seed phrase must have exactly 12 words, but found ${words.length} words`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if all words are valid
|
||||||
|
const invalidWords = words.filter(word => !wordlist.includes(word));
|
||||||
|
if (invalidWords.length > 0) {
|
||||||
|
throw new Error(`Invalid words found: ${invalidWords.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Invalid seed phrase format. Please check that all words are spelled correctly.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify this is a different seed from the current wallet
|
||||||
|
const currentMnemonic = localStorage.getItem('cashu-mnemonic');
|
||||||
|
if (currentMnemonic && currentMnemonic.toLowerCase() === cleanedSeedPhrase) {
|
||||||
|
throw new Error('This is the same seed phrase as your current wallet. Please enter a different seed phrase to restore from.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert seed phrase to seed
|
||||||
|
const restoredSeed = bip39.mnemonicToSeedSync(cleanedSeedPhrase);
|
||||||
|
|
||||||
|
// Get current balance before restore
|
||||||
|
const balancesBefore = await coco.wallet.getBalances();
|
||||||
|
const balanceBefore = balancesBefore[mintUrl] || 0;
|
||||||
|
|
||||||
|
// Create a temporary coco instance with the restored seed to fetch proofs
|
||||||
|
const tempRepo = new IndexedDbRepositories({ name: `cashu-wallet-restore-${Date.now()}` });
|
||||||
|
await tempRepo.init();
|
||||||
|
|
||||||
|
const tempCoco = await initializeCoco({
|
||||||
|
repo: tempRepo,
|
||||||
|
seedGetter: async () => restoredSeed,
|
||||||
|
logger: new ConsoleLogger(`restore-${Date.now()}`, { level: "debug" })
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Restore the proofs in the temporary wallet
|
||||||
|
await tempCoco.wallet.restore(mintUrl);
|
||||||
|
|
||||||
|
// Get the restored balance from the temporary wallet
|
||||||
|
const tempBalances = await tempCoco.wallet.getBalances();
|
||||||
|
const restoredAmount = tempBalances[mintUrl] || 0;
|
||||||
|
|
||||||
|
if (restoredAmount <= 0) {
|
||||||
|
toast({
|
||||||
|
title: "No Tokens Found",
|
||||||
|
description: "No tokens were found for this seed phrase on the selected mint.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the restored tokens from the temporary wallet
|
||||||
|
const token = await tempCoco.wallet.send(mintUrl, restoredAmount);
|
||||||
|
|
||||||
|
// Receive the token in the main wallet
|
||||||
|
await coco.wallet.receive(token);
|
||||||
|
|
||||||
|
// Verify the transfer
|
||||||
|
const balancesAfter = await coco.wallet.getBalances();
|
||||||
|
const balanceAfter = balancesAfter[mintUrl] || 0;
|
||||||
|
const actualRestored = balanceAfter - balanceBefore;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Restore Successful",
|
||||||
|
description: `Restored ${actualRestored} sats from the seed phrase and added to your current wallet.`,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// Clean up temporary database (optional - happens automatically on next session)
|
||||||
|
// The temporary IndexedDB will be isolated to the unique name we provided
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Restore failed:', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
setIsRestoring(false);
|
||||||
|
}
|
||||||
|
}, [coco, toast]);
|
||||||
|
|
||||||
// Cleanup mint quote listener on component unmount
|
// Cleanup mint quote listener on component unmount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -422,6 +525,9 @@ export function useWalletTransactions({
|
|||||||
handleReceive,
|
handleReceive,
|
||||||
handleSend,
|
handleSend,
|
||||||
handleConfirmInvoicePayment,
|
handleConfirmInvoicePayment,
|
||||||
|
// Restore functionality
|
||||||
|
handleRestoreFromSeedPhrase,
|
||||||
|
isRestoring,
|
||||||
// Refs
|
// Refs
|
||||||
mintQuoteUnsubscribeRef,
|
mintQuoteUnsubscribeRef,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,6 +6,34 @@ import { useToast } from '@/hooks/useToast';
|
|||||||
import { useQRCode } from '@/hooks/useQRCode';
|
import { useQRCode } from '@/hooks/useQRCode';
|
||||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||||
|
|
||||||
|
// Blockstream API response types
|
||||||
|
interface BlockstreamTransactionStatus {
|
||||||
|
confirmed: boolean;
|
||||||
|
block_height?: number;
|
||||||
|
block_hash?: string;
|
||||||
|
block_time?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockstreamTransactionInput {
|
||||||
|
prevout?: {
|
||||||
|
scriptpubkey_address?: string;
|
||||||
|
value: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockstreamTransactionOutput {
|
||||||
|
scriptpubkey_address?: string;
|
||||||
|
value: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockstreamTransaction {
|
||||||
|
txid: string;
|
||||||
|
fee?: number;
|
||||||
|
status: BlockstreamTransactionStatus;
|
||||||
|
vin: BlockstreamTransactionInput[];
|
||||||
|
vout: BlockstreamTransactionOutput[];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch Bitcoin transaction history for an address from Blockstream API
|
* Fetch Bitcoin transaction history for an address from Blockstream API
|
||||||
*/
|
*/
|
||||||
@@ -16,17 +44,17 @@ async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransac
|
|||||||
throw new Error('Failed to fetch Bitcoin transactions');
|
throw new Error('Failed to fetch Bitcoin transactions');
|
||||||
}
|
}
|
||||||
|
|
||||||
const txs = await response.json();
|
const txs: BlockstreamTransaction[] = await response.json();
|
||||||
|
|
||||||
// Transform Blockstream API response to our BitcoinTransaction format
|
// Transform Blockstream API response to our BitcoinTransaction format
|
||||||
return txs.map((tx: any, index: number) => {
|
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
|
// For simplicity, we'll consider it received if the address appears in outputs
|
||||||
// and sent if it appears in inputs
|
// and sent if it appears in inputs
|
||||||
const isReceived = tx.vout.some((output: any) =>
|
const isReceived = tx.vout.some((output: BlockstreamTransactionOutput) =>
|
||||||
output.scriptpubkey_address === address
|
output.scriptpubkey_address === address
|
||||||
);
|
);
|
||||||
const isSent = tx.vin.some((input: any) =>
|
const isSent = tx.vin.some((input: BlockstreamTransactionInput) =>
|
||||||
input.prevout?.scriptpubkey_address === address
|
input.prevout?.scriptpubkey_address === address
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -37,17 +65,17 @@ async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransac
|
|||||||
if (isReceived) {
|
if (isReceived) {
|
||||||
// Sum all outputs to this address
|
// Sum all outputs to this address
|
||||||
amount = tx.vout
|
amount = tx.vout
|
||||||
.filter((output: any) => output.scriptpubkey_address === address)
|
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
|
||||||
.reduce((sum: number, output: any) => sum + output.value, 0);
|
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0);
|
||||||
} else if (isSent) {
|
} else if (isSent) {
|
||||||
// Sum all inputs from this address minus outputs to this address
|
// Sum all inputs from this address minus outputs to this address
|
||||||
const inputsFromAddress = tx.vin
|
const inputsFromAddress = tx.vin
|
||||||
.filter((input: any) => input.prevout?.scriptpubkey_address === address)
|
.filter((input: BlockstreamTransactionInput) => input.prevout?.scriptpubkey_address === address)
|
||||||
.reduce((sum: number, input: any) => sum + input.prevout.value, 0);
|
.reduce((sum: number, input: BlockstreamTransactionInput) => sum + (input.prevout?.value || 0), 0);
|
||||||
|
|
||||||
const outputsToAddress = tx.vout
|
const outputsToAddress = tx.vout
|
||||||
.filter((output: any) => output.scriptpubkey_address === address)
|
.filter((output: BlockstreamTransactionOutput) => output.scriptpubkey_address === address)
|
||||||
.reduce((sum: number, output: any) => sum + output.value, 0);
|
.reduce((sum: number, output: BlockstreamTransactionOutput) => sum + output.value, 0);
|
||||||
|
|
||||||
amount = inputsFromAddress - outputsToAddress;
|
amount = inputsFromAddress - outputsToAddress;
|
||||||
fee = tx.fee || 0;
|
fee = tx.fee || 0;
|
||||||
@@ -62,7 +90,7 @@ async function fetchBitcoinTransactions(address: string): Promise<BitcoinTransac
|
|||||||
address: address,
|
address: address,
|
||||||
confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified
|
confirmations: tx.status.confirmed ? (tx.status.block_height ? 1 : 0) : 0, // Simplified
|
||||||
blockHeight: tx.status.block_height,
|
blockHeight: tx.status.block_height,
|
||||||
timestamp: tx.status.block_time * 1000, // Convert to milliseconds
|
timestamp: (tx.status.block_time ?? 0) * 1000, // Convert to milliseconds
|
||||||
status: tx.status.confirmed ? 'confirmed' : 'unconfirmed'
|
status: tx.status.confirmed ? 'confirmed' : 'unconfirmed'
|
||||||
} as BitcoinTransaction;
|
} as BitcoinTransaction;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -289,7 +289,5 @@ export function calculateMaxSendAmount(utxos: UTXO[], feeRate: number): number {
|
|||||||
// Calculate maximum amount (total input minus fees)
|
// Calculate maximum amount (total input minus fees)
|
||||||
const maxAmount = totalInput - estimatedFee;
|
const maxAmount = totalInput - estimatedFee;
|
||||||
|
|
||||||
// Ensure we don't go below dust limit
|
|
||||||
const dustLimit = 546; // Standard dust limit for Bitcoin
|
|
||||||
return Math.max(0, maxAmount);
|
return Math.max(0, maxAmount);
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user