TransWikia.com

How to automatically get transaction while sending BTC?

Bitcoin Asked by Abhishek Pandey on December 2, 2020

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 https://testnet.smartbit.com.au/. 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;
    }

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP