Calculating price primarily based on price price for bitcoin transaction
There are some enhancements which you can make to this algorithm.
The primary is to pick out UTXOs primarily based on their efficient worth. The efficient worth is the worth of the UTXO with the quantity in charges required to spend it subtracted from it. On this means, every UTXO you spend pays for itself. That is referred to as the efficient worth as a result of that’s the worth that truly impacts the outputs. You do that by calculating how giant spending that UTXO might be, then multiplying by your price price to get its price. This price is then subtracted from the UTXO quantity.
Then you possibly can calculate the charges for the remainder of the transaction, i.e. the fastened overhead (tx model, locktime, and so on.) and the outputs. Since these are all decided earlier than you select the UTXOs to spend, it is nice to calculate this worth earlier than you select UTXOs. The UTXOs you select will not impact this price. This quantity in charges can then be added to the quantity you are attempting to pick out for, i.e. add it to the quantity being despatched.
By utilizing the efficient values of inputs (so inputs pay for themselves) after which rising the quantity that you’re making an attempt choose (so the price of the remainder of the transaction is roofed), you possibly can take away the necessity to loop (step 7) with a purpose to select the UTXOs you need. Now once you select the UTXOs, you already know that every enter has paid for itself, and that you’ve got chosen sufficient worth to cowl the outputs and their value.
One other enchancment is to not kind the UTXOs. In actual fact, it’s higher to decide on UTXOs randomly. You possibly can obtain this by shuffling the checklist of UTXOs as an alternative of sorting them. Sorting UTXOs has a number of long term results that can negatively impression you sooner or later. Notably, by sorting UTXOs, you’ll find yourself creating very small change, which signifies that future transactions could have many UTXOs with small values, which will increase their price. Sorting by smallest first will see this impact sooner. Sorting by largest first will see this impact over time.