MetacoSA / QBitNinja

An Open Source and powerful blockchain API
MIT License
68 stars 42 forks source link

Cant transfer money from multiple transactions #116

Open Krendel338 opened 4 years ago

Krendel338 commented 4 years ago

Hello guys, I hope you help me. I need to transfer btc from multiple transactions of one address to another address of another wallet. I tried to do this following the manual. I do not get errors, but the transaction does not occur. I post my code, thanks in advance for your time. ` private static string SendTransaction2(string privateKey, string destination, decimal amount, decimal fee) { var bitcoinPrivateKey = new BitcoinSecret(privateKey, Network.Main); var network = bitcoinPrivateKey.Network; var address = bitcoinPrivateKey.GetAddress();

        var client = new QBitNinjaClient(network);

        var balance = client.GetBalance(new BitcoinPubKeyAddress(bitcoinPrivateKey.GetAddress().ToString(), network)).Result;

        var tids = balance.Operations.Select(t => t.TransactionId);
        var transaction = Transaction.Create(network);

        List<ICoin> receivedCoins = new List<ICoin>();
        foreach (var tid in tids)
        {
            receivedCoins.AddRange(client.GetTransaction(tid).Result.ReceivedCoins);

        }

        OutPoint outPointToSpend = null;
        Money txInAmount = 0;
        foreach (var coin in receivedCoins)
        {
            if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey)
            {
                outPointToSpend = coin.Outpoint;
                transaction.Inputs.Add(new TxIn()
                {
                    PrevOut = outPointToSpend
                });
                txInAmount += (Money)receivedCoins[(int)outPointToSpend.N].Amount;
            }
        }

        if (txInAmount == Money.Zero)
            return "null money";

        var hallOfTheMakersAddress = new BitcoinPubKeyAddress(destination, network);

        var hallOfTheMakersAmount = new Money(amount, MoneyUnit.BTC);
        var minerFee = new Money(fee, MoneyUnit.BTC);
        var changeAmount = txInAmount - hallOfTheMakersAmount - minerFee;

        transaction.Outputs.Add(hallOfTheMakersAmount, hallOfTheMakersAddress.ScriptPubKey);
        transaction.Outputs.Add(changeAmount, bitcoinPrivateKey.ScriptPubKey);

        foreach (var transactionInput in transaction.Inputs)
        {
            transactionInput.ScriptSig = bitcoinPrivateKey.ScriptPubKey;
        }

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

        BroadcastResponse broadcastResponse = client.Broadcast(transaction).Result;
        if (!broadcastResponse.Success)
            return "Error message: " + broadcastResponse.Error.Reason;
        return transaction.GetHash().ToString();
    }

`