<p>There are some improvements that you can make to this algorithm.</p>
<p>The first is to select UTXOs based on their effective value. The effective value is the value of the UTXO with the amount in fees required to spend it subtracted from it. In this way, each UTXO you spend pays for itself. This is called the effective value because that is the value that actually affects the outputs. You do this by calculating how large spending that UTXO will be, then multiplying by your fee rate to get its fee. This fee is then subtracted from the UTXO amount.</p>
<p>Then you can calculate the fees for the rest of the transaction, i.e. the fixed overhead (tx version, locktime, etc.) and the outputs. Since these are all determined before you choose the UTXOs to spend, it's fine to calculate this value before you choose UTXOs. The UTXOs you choose won't have an effect on this fee. This amount in fees can then be added to the amount you are trying to select for, i.e. add it to the amount being sent.</p>
<p>By using the effective values of inputs (so inputs pay for themselves) and then increasing the amount that you are trying select (so the cost of the rest of the transaction is covered), you can remove the need to loop (step 7) in order to choose the UTXOs you want. Now when you choose the UTXOs, you know that each input has paid for itself, and that you have chosen enough value to cover the outputs and their cost.</p>
<p>Another improvement is to not sort the UTXOs. In fact, it is better to choose UTXOs randomly. You can achieve this by shuffling the list of UTXOs instead of sorting them. Sorting UTXOs has several longer term effects that will negatively impact you in the future. Notably, by sorting UTXOs, you will end up creating very small change, which means that future transactions will have many UTXOs with small values, which increases their fee. Sorting by smallest first will see this effect sooner. Sorting by largest first will see this effect over time.</p>

CC BY-SA 4.0
2022-08-11T16:35:05.920Z
"and the outputs" -- I guess initially we assume there will be a change output. But if that turns out to be unneeded after UTXO selection, and so then we don't include a change output, will our feerate be a bit too high? Do we just go ahead anyway, or do we try to lower the feerate (go back to UTXO selection)?
Larry Ruane
CC BY-SA 4.0
2022-08-11T20:07:51.063Z
@LarryRuane You would just have a slightly higher feerate. Consider it this way: you were willing to pay that fee to have a change output, but it turns out you don't need one. It's still the same amount spent in fees, but your transaction now gets a small bonus of a higher feerate. If you go back and try to select a changeless solution, it may be completely different from the first one and may not actually be better. Selections with different parameters are independent of each other and it's really not that useful to use a previous selection to try to inform another one.
Ava Chow
CC BY-SA 4.0
2021-03-18T21:28:02.567Z
2021-03-18T21:28:02.567Z
Ava Chow
<p>If you don't account for the fees of the inputs until after selecting the inputs, <strong>your target is shifting while you're selecting</strong> with each input you add. Since your transaction building starts with a known target feerate, and you know the size of the transaction header data and outputs, you can calculate their fees in advance.</p>
<p>Then, since you know the feerate and you can predict the input weight for every UTXO before picking it, instead of counting UTXOs with their full value towards your selection target, only count them with their <em>effective value</em>:
<code>eff_value = value - feerate×input_weight</code></p>
<p>That way, every input that you pick has already paid its own fee and <strong>your target does not shift</strong> while you're picking inputs.</p>
<p>Smallest-first is one of the most consolidatory approaches you can take to UTXO management: it always maximizes the input count for the current UTXO pool and transaction building request. That way, you keep your UTXO count lean, but in almost every attempt you're using more UTXOs than necessary <em>at that time</em>.</p>
<p>You can be more thrifty by being selective when to use that strategy—e.g. at low feerates use smallest-first and at high feerates use random selection or largest-first. That way, you spend a greater portion of your UTXOs at lower feerates decreasing your overall cost.</p>
<p>If you're spending a lot of time thinking about coin selection and UTXO management, you may find other questions with the tag <a href="/questions/tagged/coin-selection" class="post-tag" title="show questions tagged &#39;coin-selection&#39;" rel="tag">coin-selection</a>, the topic <a href="https://bitcoin.stackexchange.com/q/32145/5406">What are the trade-offs between the different algorithms for deciding which UTXOs to spend?</a>, and my Master thesis, “An Evaluation of Coin Selection Strategies <a href="https://murch.one/erhardt2016coinselection.pdf" rel="nofollow noreferrer">[PDF]</a> (2016)” interesting.</p>

CC BY-SA 4.0
2022-08-12T22:45:07.927Z
I've heard the term "negative effective value" but it always confused me. Your answer makes it make sense. If our (exogenous) feerate is high, a particular UTXO may have a negative effective value, so we shouldn't use it. But later, our feerate may be sufficiently lower such that this UTXO has a positive effective value. If a UTXO's effective feerate is negative at minrelayfee, does that make it dust?
Larry Ruane
CC BY-SA 4.0
2022-08-14T14:00:48.173Z
@LarryRuane: If a UXTO has a negative effective value at minRelayTxFee it would be dust, but the dust limit is even higher: https://bitcoin.stackexchange.com/a/41082/5406
Murch
CC BY-SA 4.0
2022-08-11T18:52:44.890Z
2022-08-11T20:47:12.577Z
2022-08-11T20:47:12.577Z
Murch
<p>I'm writing an algorithm for calculating fee based on fee rate and amount to be sent (requested amount) in order to propose the fee to user;</p>
<ol>
<li>Sorting UTXOs ascending based on value</li>
<li>Take enough UTXOs so sum is larger than requested amount</li>
<li>Calculate change, add to outputs</li>
<li>Build tx</li>
<li>Calculate fee based on tx byte size times fee rate</li>
<li>Is Change larger than calculated fee? (can we &quot;fit&quot; fee into change)</li>
<li>If no: go back to step 2 and add more UTXOs to get to fee</li>
<li>If yes: reduce the Change for fee and build final transaction</li>
</ol>
<p>This works well in most cases, but if you have large number of UTXOs with small values and fee rate is large (e.g. 88 sat/byte), you can end up with very large transaction, i.e. very large fee for sending very small amount of coins.</p>
<p>I have tried to make a change in algorithm where after X number of iterations, I would give up and try to take enough UTXOs for requested amount and deduct fee from that amount and send what ever is left.
But I ended up in long loop again, as UTXOs were small, transaction large and in every iteration I didn't had enough to pay the fee.</p>
<p>As this is obviously bad implementation, is there any other way to calculate fee bases on fee rate?</p>

<transaction-fees><coin-selection>
Calculating fee based on fee rate for bitcoin transaction
Andrija
# Calculating fee based on fee rate for bitcoin transaction

(Asked by: username_0 on 2021-03-18)

I'm writing an algorithm for calculating fee based on fee rate and amount to be sent (requested amount) in order to propose the fee to user;

1. Sorting UTXOs ascending based on value
2. Take enough UTXOs so sum is larger than requested amount
3. Calculate change, add to outputs
4. Build tx
5. Calculate fee based on tx byte size times fee rate
6. Is Change larger than calculated fee? (can we "fit" fee into change)
7. If no: go back to step 2 and add more UTXOs to get to fee
8. If yes: reduce the Change for fee and build final transaction

This works well in most cases, but if you have large number of UTXOs with small values and fee rate is large (e.g. 88 sat/byte), you can end up with very large transaction, i.e. very large fee for sending very small amount of coins.

I have tried to make a change in algorithm where after X number of iterations, I would give up and try to take enough UTXOs for requested amount and deduct fee from that amount and send what ever is left.
But I ended up in long loop again, as UTXOs were small, transaction large and in every iteration I didn't had enough to pay the fee.

As this is obviously bad implementation, is there any other way to calculate fee bases on fee rate?

**Tags:** transaction-fees, coin-selection


---

## 2 answers

### Answer by username_1 on 2021-03-18. Score: 3

There are some improvements that you can make to this algorithm.

The first is to select UTXOs based on their effective value. The effective value is the value of the UTXO with the amount in fees required to spend it subtracted from it. In this way, each UTXO you spend pays for itself. This is called the effective value because that is the value that actually affects the outputs. You do this by calculating how large spending that UTXO will be, then multiplying by your fee rate to get its fee. This fee is then subtracted from the UTXO amount.

Then you can calculate the fees for the rest of the transaction, i.e. the fixed overhead (tx version, locktime, etc.) and the outputs. Since these are all determined before you choose the UTXOs to spend, it's fine to calculate this value before you choose UTXOs. The UTXOs you choose won't have an effect on this fee. This amount in fees can then be added to the amount you are trying to select for, i.e. add it to the amount being sent.

By using the effective values of inputs (so inputs pay for themselves) and then increasing the amount that you are trying select (so the cost of the rest of the transaction is covered), you can remove the need to loop (step 7) in order to choose the UTXOs you want. Now when you choose the UTXOs, you know that each input has paid for itself, and that you have chosen enough value to cover the outputs and their cost.

Another improvement is to not sort the UTXOs. In fact, it is better to choose UTXOs randomly. You can achieve this by shuffling the list of UTXOs instead of sorting them. Sorting UTXOs has several longer term effects that will negatively impact you in the future. Notably, by sorting UTXOs, you will end up creating very small change, which means that future transactions will have many UTXOs with small values, which increases their fee. Sorting by smallest first will see this effect sooner. Sorting by largest first will see this effect over time.

> **Comments:**
> **username_2**: "and the outputs" -- I guess initially we assume there will be a change output. But if that turns out to be unneeded after UTXO selection, and so then we don't include a change output, will our feerate be a bit too high? Do we just go ahead anyway, or do we try to lower the feerate (go back to UTXO selection)?  
> **username_1**: @username_2 You would just have a slightly higher feerate. Consider it this way: you were willing to pay that fee to have a change output, but it turns out you don't need one. It's still the same amount spent in fees, but your transaction now gets a small bonus of a higher feerate. If you go back and try to select a changeless solution, it may be completely different from the first one and may not actually be better. Selections with different parameters are independent of each other and it's really not that useful to use a previous selection to try to inform another one.  

---

### Answer by username_3 on 2022-08-11. Score: 2

If you don't account for the fees of the inputs until after selecting the inputs, **your target is shifting while you're selecting** with each input you add. Since your transaction building starts with a known target feerate, and you know the size of the transaction header data and outputs, you can calculate their fees in advance.

Then, since you know the feerate and you can predict the input weight for every UTXO before picking it, instead of counting UTXOs with their full value towards your selection target, only count them with their *effective value*:
`eff_value = value - feerate×input_weight`

That way, every input that you pick has already paid its own fee and **your target does not shift** while you're picking inputs.

Smallest-first is one of the most consolidatory approaches you can take to UTXO management: it always maximizes the input count for the current UTXO pool and transaction building request. That way, you keep your UTXO count lean, but in almost every attempt you're using more UTXOs than necessary *at that time*.

You can be more thrifty by being selective when to use that strategy—e.g. at low feerates use smallest-first and at high feerates use random selection or largest-first. That way, you spend a greater portion of your UTXOs at lower feerates decreasing your overall cost.

If you're spending a lot of time thinking about coin selection and UTXO management, you may find other questions with the tag [coin-selection](/questions/tagged/coin-selection "show questions tagged 'coin-selection'"), the topic [What are the trade-offs between the different algorithms for deciding which UTXOs to spend?](https://bitcoin.stackexchange.com/q/32145/5406), and my Master thesis, “An Evaluation of Coin Selection Strategies [[PDF]](https://username_3.one/erhardt2016coinselection.pdf) (2016)” interesting.

> **Comments:**
> **username_2**: I've heard the term "negative effective value" but it always confused me. Your answer makes it make sense. If our (exogenous) feerate is high, a particular UTXO may have a negative effective value, so we shouldn't use it. But later, our feerate may be sufficiently lower such that this UTXO has a positive effective value. If a UTXO's effective feerate is negative at minrelayfee, does that make it dust?  
> **username_3**: @username_2: If a UXTO has a negative effective value at minRelayTxFee it would be dust, but the dust limit is even higher: https://bitcoin.stackexchange.com/a/41082/5406  

---

