Skip to content

Commit

Permalink
Merge pull request #386 from bob-collective/fix/fee-estimate
Browse files Browse the repository at this point in the history
fix: fee estimate
  • Loading branch information
nud3l authored Oct 16, 2024
2 parents 3739ed7 + a07152b commit 7514a11
Showing 1 changed file with 6 additions and 18 deletions.
24 changes: 6 additions & 18 deletions sdk/src/wallet/utxo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export function getInputFromUtxoAndTx(
* ```
*
* @dev Wtih no amount set, we estimate the fee for all UTXOs by trying to spend all inputs using strategy 'all'. If an amount is set, we use the 'default
* strategy to select the UTXOs.
* strategy to select the UTXOs. If the amount is more than available, an error will be thrown.
*/
export async function estimateTxFee(
fromAddress: string,
Expand Down Expand Up @@ -310,7 +310,7 @@ export async function estimateTxFee(
);

// Create transaction without outputs
const targetOutputs: Output[] = [
const outputs: Output[] = [
{
address: toAddress,
amount: BigInt(amount ? amount : 0),
Expand All @@ -322,23 +322,17 @@ export async function estimateTxFee(
if (opReturnData.toLowerCase().startsWith('0x')) {
opReturnData = opReturnData.slice(2);
}
targetOutputs.push({
outputs.push({
// OP_RETURN https://github.com/paulmillr/scure-btc-signer/issues/26
script: Script.encode(['RETURN', hex.decode(opReturnData)]),
amount: BigInt(0),
});
}

let outputs: Output[] = [];
// Select all UTXOs if no amount is specified
// Add outputs to the transaction after all UTXOs are selected to prevent tx creation failures
let utxoSelectionStrategy = 'all';
if (amount) {
// Add the target outputs to the transaction
// Tx creation might fail if the requested amount is more than the available balance plus fees
// TODO: allow passing other UTXO selection strategies for fee etimates
utxoSelectionStrategy = 'default';
outputs = targetOutputs;
let utxoSelectionStrategy = 'default';
if (amount === undefined) {
utxoSelectionStrategy = 'all';
}

// Outsource UTXO selection to btc-signer
Expand All @@ -365,11 +359,5 @@ export async function estimateTxFee(
throw new Error('Failed to create transaction. Do you have enough funds?');
}

// Add the target outputs after the fact
if (amount === undefined) {
transaction.tx.addOutput(targetOutputs[0]);
transaction.tx.addOutput(targetOutputs[1]);
}

return transaction.fee;
}

0 comments on commit 7514a11

Please sign in to comment.