Getting UTXOs for an Address with a Required Amount
The getUTXOsForAmount
method allows you to fetch Unspent Transaction Outputs (UTXOs) for a specific Bitcoin address that cover a required amount. This method simplifies the process of selecting UTXOs for transaction creation, ensuring that the total value of the UTXOs meets the specified amount.
Method
getUTXOsForAmount({
address,
amount,
optimize?,
mergePendingUTXOs?,
filterSpentUTXOs?,
throwErrors?,
}: RequestUTXOsParamsWithAmount): Promise<UTXOs>;
-
Parameters:
address: string
: The Bitcoin address to fetch UTXOs for.amount: bigint
: The required amount (in satoshis) to cover with UTXOs.optimize?: boolean
(Optional):- If
true
, optimizes UTXO selection for efficiency and minimal transaction fees.
- If
mergePendingUTXOs?: boolean
(Optional):- If
true
, includes pending UTXOs awaiting confirmation.
- If
filterSpentUTXOs?: boolean
(Optional):- If
true
, filters out any already spent UTXOs.
- If
throwErrors?: boolean
(Optional):- If
true
, throws an error if sufficient UTXOs are not found.
- If
-
Returns:
Promise<UTXOs>
: An array ofUTXO
objects that cover the specified amount.
Object Definitions
UTXO
ObjectProperty | Type | Description |
---|---|---|
transactionId | string | The ID of the transaction containing the UTXO. |
outputIndex | number | The index of the UTXO in the transaction outputs. |
value | bigint | The amount of Bitcoin (in satoshis) held by the UTXO. |
scriptPubKey | ScriptPubKey | The locking script for the UTXO. |
Example Usage
Fetching UTXOs for a Required Amount
const address = "bcrt1qexampleaddress...";
const amount = BigInt(100000); // 100,000 satoshis (0.001 BTC)
const utxos = await provider.utxoManager.getUTXOsForAmount({ address, amount });
console.log("Fetched UTXOs for amount:", utxos);
Handling Insufficient UTXOs
try {
const utxos = await provider.utxoManager.getUTXOsForAmount({
address,
amount,
throwErrors: true,
});
console.log("UTXOs:", utxos);
} catch (error) {
console.error("Insufficient UTXOs:", error.message);
}
Best Practices
- Ensure the
amount
parameter is specified as abigint
and accurately represents the required value in satoshis. - Use the
throwErrors
parameter to explicitly handle cases where sufficient UTXOs cannot be found. - If the
mergePendingUTXOs
option is enabled, unconfirmed UTXOs will also be included in the result.
What’s Next?
After fetching UTXOs for a specific amount, you can: