Post
Topic
Board Development & Technical Discussion
Re: Getting transaction size/fees before sending
by
cryptoworld99
on 27/07/2021, 23:32:01 UTC
Hi

I assume you're coding in PHP? if not i can rewrite it in another lang for you, but here is a working example i've built for you to specify an exact fee for a bitcoin transaction.. this also works for other alt coins.  Thank me later. Cool

Code:

   $unspentTransactions = $bitcoin->listunspent(0, 9999999); //First we find out all our unspent transactions from where we can withdraw

    $collectedTransactions = [];

    foreach ($unspentTransactions as $unspentTransaction) {

        if ($collectedAmount < $amountToSend) {
            $collectedTransactions[] = [
                'txid'  => $unspentTransaction['txid'],
                'vout'  => $unspentTransaction['vout']
            ];

           $collectedAmount += $unspentTransaction['amount'];
        } else {

            break;
        }
    }



$change_amount = $collectedAmount-$amount-$fee;


if ($change_amount <= 0.00000000) {


       $output2 = array(

          "".$recipient."" =>"".$amount-$fee.""
    );


   }

   else {

       $output2 = array(


          "".$recipient."" =>"".$amount."",

          "".$change_addr."" =>"".$change_amount."",
         
    );

   }
 

    $maketxnraw = $bitcoin->createrawtransaction($collectedTransactions, $output2);

    $signtxn = $bitcoin->signrawtransactionwithwallet($maketxnraw);

    $returnsignedhex = $signtxn['hex'];
   
    $sendpayment = $bitcoin->sendrawtransaction($returnsignedhex);

    $txid = $sendpayment;