Keeping UTXOs Changes in Memory
The spendUTXO
method in the UTXOs Manager allows you to mark UTXOs as spent and manage changes in memory. This guide explains how to use this method and reset the UTXO memory when needed.
Methods
1. Marking UTXOs as Spent
spentUTXO(spent: UTXOs, newUTXOs: UTXOs): void;
- Parameters:
spent: UTXOs
: The UTXOs that have been used in a transaction.newUTXOs: UTXOs
: New UTXOs created by the transaction, if any, else an empty array.
2. Resetting Memory
clean(): void;
Example Usage
Marking UTXOs as Spent
const utxosManager = provider.utxoManager;
// Fetch UTXOs for an address
const address = "bcrt1qfqsr3m7vjxheghcvw4ks0fryqxfq8qzjf8fxes";
const requiredAmount = BigInt(100000); // 100,000 satoshis
const utxos = await utxosManager.getUTXOsForAmount({
address,
amount: requiredAmount,
});
// Use the UTXOs in a transaction and mark them as spent
utxosManager.spentUTXO(utxos, []); // Add new UTXOs if they are created
console.log("UTXOs marked as spent");
// Fetch the UTXOs again
const newUTXOs = await utxosManager.getUTXOsForAmount({
address,
amount: requiredAmount,
});
// Check if the UTXOs are different
console.log("UTXOs are different:", newUTXOs !== utxos); // true
Resetting the UTXO Memory
If you want to reset the in-memory state (e.g., to fetch fresh UTXOs), you can call the clean
method:
utxosManager.clean();
console.log("UTXO memory reset");
Best Practices
- Always call
spentUTXO
after using UTXOs in a transaction to avoid reusing them. - Resetting the UTXO memory using
clean
will clear all tracked spent and pending UTXOs. Use it cautiously if you need to preserve the current state.
What’s Next?
Explore additional UTXO Manager capabilities: