Calculate Miners Fee before Signing Raw Transaction? I am attempting to automate the process of sending coins from multiple transactions to a single output and single change address using createrawtransaction

I am a bit lost though, because how can I calculate the output amount to the change address without knowing the total size of the signed transaction to calculate the miners fee...

For instance

I have 3 input transactions, they total 0.1 BTC.

I have 1 output address that I want to send 0.05 BTC to.

I have 1 output change address that I want to send the rest of the BTC to.

How do I calculate the amount for the change address without knowing how much the miners fee will be?
Generally, you don't have to.

The normal workflow is:


Use listunspent to identify the outputs you want to use (if any).
Use createrawtransaction to construct a raw transaction with the outputs you want to create (excluding change) and inputs you want to use (if any).
Use fundrawtransaction to let bitcoind add a change output back to itself (and additional inputs, if needed), taking the expected total size of the transaction and current feerate on the network into account.
Use signrawtransaction(withwallet/withkey) to add signatures to the raw transactions if you're satisfied with the result.
Use sendrawtransaction to broadcast the transaction on the network.


Fundrawtransaction is the key here. It will do size estimation and fee estimation for the transaction, and construct change reflecting the difference between the inputs and outputs, minus fees.

Generally you don't care about which inputs to spend, and you can also just leave the inputs list to createrawtransaction empty. In that case fundrawtransaction will do the complete coin selection for you.

The same can be done with the more modern PSBT format. The relevant RPCs then are walletcreatefundedpsbt, walletprocesspsbt, finalizepsbt, sendrawtransaction.