Calculating payment primarily based on payment price for bitcoin transaction
There are some enhancements which you can make to this algorithm.
The primary is to pick 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 manner, 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 massive spending that UTXO might be, then multiplying by your payment price to get its payment. This payment is then subtracted from the UTXO quantity.
Then you’ll be able to calculate the charges for the remainder of the transaction, i.e. the mounted overhead (tx model, locktime, and so forth.) and the outputs. Since these are all decided earlier than you select the UTXOs to spend, it is wonderful to calculate this worth earlier than you select UTXOs. The UTXOs you select will not impact this payment. This quantity in charges can then be added to the quantity you are attempting to pick for, i.e. add it to the quantity being despatched.
By utilizing the efficient values of inputs (so inputs pay for themselves) after which growing the quantity that you’re attempting choose (so the price of the remainder of the transaction is roofed), you’ll be able to take away the necessity to loop (step 7) in an effort to select the UTXOs you need. Now while you select the UTXOs, that every enter has paid for itself, and that you’ve got chosen sufficient worth to cowl the outputs and their price.
One other enchancment is to not type the UTXOs. In truth, it’s higher to decide on UTXOs randomly. You may obtain this by shuffling the record of UTXOs as a substitute of sorting them. Sorting UTXOs has a number of long term results that may negatively influence 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 payment. Sorting by smallest first will see this impact sooner. Sorting by largest first will see this impact over time.