I am trying to make transaction via bitcoinj (version 0.14.3) and i am expecting to get change back after payment. I am working with testnet, it's not real bitcoins. I have next code:
Transaction tx = new Transaction(this.networkParameters);
Coin coinToSent = Coin.valueOf(Config.APP_COST);
Coin coinToChange = Coin.valueOf(walletBalance.getValue() - coinToSent.getValue());
tx.addOutput(coinToSent, appAddress);
tx.addOutput(coinToChange, changeAddress);
SendRequest request = SendRequest.forTx(tx);
try {
this.walletAppKit.wallet().completeTx(request);
} catch (InsufficientMoneyException e) {
e.printStackTrace();
return false;
}
this.walletAppKit.wallet().commitTx(request.tx);
this.walletAppKit.peerGroup().broadcastTransaction(request.tx);
So, i am putting two outputs into transaction:
- Address to sending money
- Address of my wallet for getting change back
To the first address i send some money. And to the second address i send next value: all available money on my wallet minus money received to first address.
But after broadcasting i had an unexpected result. After making a few transactions with this scheme, I've noticed wrong values withdrawing from my wallet. What is surprising, sometimes money is withdrawing but sometimes money coming to wallet.
Here is the link to testnet explorer
Can someone explain what i am doing wrong and how to fix it?