How to automatically get transaction while sending BTC?


Here is my SendBTC method. I do not want to pass fundingTransaction variable each time I call this method. Currently, I pass fundingTransaction value by looking up to I want to get this funding transaction in this method only. How can I do this?

public static bool SendBTC(string secret, string toAddress, decimal amount, string fundingTransaction)
        Network bitcoinNetwork = Network.TestNet;
        var bitcoinPrivateKey = new BitcoinSecret(secret, bitcoinNetwork);
        var address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy);

        var client = new QBitNinjaClient(bitcoinNetwork);
        var transactionId = uint256.Parse(fundingTransaction);
        var transactionResponse = client.GetTransaction(transactionId).Result;

        var receivedCoins = transactionResponse.ReceivedCoins;

        OutPoint outPointToSpend = null;
        foreach (var coin in receivedCoins)
            if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey)
                outPointToSpend = coin.Outpoint;

        var transaction = Transaction.Create(bitcoinNetwork);
        transaction.Inputs.Add(new TxIn()
            PrevOut = outPointToSpend

        var receiverAddress = BitcoinAddress.Create(toAddress, bitcoinNetwork);

        var txOutAmount = new Money(amount, MoneyUnit.BTC);

        var minerFee = new Money(0.0005m, MoneyUnit.BTC);

        var txInAmount = (Money)receivedCoins[(int)outPointToSpend.N].Amount;
        var changeAmount = txInAmount - txOutAmount - minerFee;

        transaction.Outputs.Add(txOutAmount, receiverAddress.ScriptPubKey);
        transaction.Outputs.Add(changeAmount, bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy).ScriptPubKey);

        transaction.Inputs[0].ScriptSig = address.ScriptPubKey;

        transaction.Sign(bitcoinPrivateKey, receivedCoins.ToArray());

        BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;

        return broadcastResponse.Success;

Abhishek Pandey

Posted 2020-10-19T17:30:10.963

Reputation: 3

No answers