Web3j Ether Transfer – How to Send Ether Using Web3j to an Address on Android

androidencryptionjavaraw-transactionweb3j

EDIT: I am using android platform

I think I'm a bit confused conceptually. I would appreciate it if someone could answer these few questions for me as I'm trying to make an app so that I can be clear on exactly what's going on here. I'm trying to read and decipher the documentation at the same time.

-I have generated my address and private key using web3j ECKeyPair class

Now I need to be able to send that ether to an address using that data and I'm not sure how I'm supposed to go about doing it

  • I think I'm supposed to use something called a rawtransaction but again my understanding is hazy

  • I would also like to be able to encrypt my private key however I saw that it encrypts the data into a keystore file. Is there any way to clear out the unneccesary data here as I'm only trying to encrypt the private key using a password.

If a more knowledgeable member than myself could clear up the steps involved in "signing a transaction" so that ether can be sent from one address to another, you'd be a huge help to my design project.

I also don't understand how transactions can be signed offline as I thought the point in signing a transaction was so it could be verified by the network

Thank you.

Best Answer

You basically need to to three steps:

  1. Construct transaction object
  2. Sign it with private key
  3. Publish signed transaction

For step 1 you do something like this:

var from = "0x..."; // The address you are sending ether from
var tx = {
  nonce: web3.eth.getTransactionCount (from),
  chainId: 1, // 1 means Mainnet, more chain IDs here: https://chainid.network/
  to: "0x...", // The address you are sending ether to
  data: "",
  value: value, // The amount of ether to send (in Wei)
  gasPrice: web3.eth.getGasPrice(),
  gas: 21000 // Enough for simple transfer
};

For step 2 you do:

var signedTx = web3.eth.accounts.signTransaction (tx, privateKey);

For step 3 you do:

web3.eth.sendSignedTransaction(signedTx);

See Web3js documentation for more info.

Sorry, my answer is about Web3js, not Web3j. But, for Web3j steps are basically the same:

  1. Prepare transaction object (RawTransaction)
  2. Sign it (TransactionEncoder)
  3. Publish it (ethSendRawTransaction)

See official documentation for details.