Ether transfer from one account to another account using Web3j and Java

Posted By : Sudhakar Pandey | 28-Sep-2017

This article explains about transfer ether from one account to another account. We need to do following steps for ether transfer- You need to add web3j dependency in maven as


Create Web3j object to connect ethereum server.

Web3j web3j = HttpService("Ethereum server ip with port"));

After that you need to calculate transaction fee which is essential for doing transaction. Transaction fee will be equal to gas * gas price, i.e. minimum gas required for transation is 21000. After that we need to create credenials object as

Credentials credentials = WalletUtils.loadCredentials(
						"Password of sender account",
						"Ethereum server blockchain keystore path" + "/" + "Sender account wallet file name");


Then we need to validate amount which we want to transfer in another amount either this amount is exists in sender amount or not. After that used below function for transfer


 public Map transferEtherAccountToAccount(BigDecimal balance) throws IOException {
	Map result = new HashMap<>();
		try {
			Web3j web3j = HttpService(envConfiguration.getTestnetServerIp()));"--------------Enter into transferEtherAccountToAccount function");

                        // Find the wallet from database which is used as sender address
			UserWallet wallet = userWalletRepository.findByAddress(address);
			BigInteger amount = web3j.ethGetBalance(wallet.getAddress(), DefaultBlockParameterName.fromString("latest")).send()
					.getBalance();"Creating  Parity...");"Getting wallet ..." + wallet.getAddress() + "  and balance is "
					+ web3j.ethGetBalance(wallet.getAddress(), DefaultBlockParameterName.fromString("latest")).send()
                        // Minimum gas is 21000 used for transaction
			BigInteger gas = BigInteger.valueOf(21000);"gas:::" + gas);

			BigInteger xth = new BigInteger("1000000000000000000");":::Transferred amount is::::" + amount);
                        // Pick gas price from geth console
			BigInteger gasprice = web3j.ethGasPrice().send().getGasPrice();"gasprice:::" + gasprice);

			BigInteger gaslimit = BigInteger.valueOf(4800000);"gaslimit:::" + gaslimit);

                        // Calculate transaction fees for transaction 
			BigInteger txnFee = gas.multiply(gasprice);

                        // Validate balance to perform transaction fees
			int compareResult = amount.compareTo(gas.multiply(gasprice));"Compare result:: " + compareResult);":::Transferred amount is :::" + amount);
			if ((compareResult != 0 && compareResult != -1)
					&& wallet.getAddress() != web3.ethAccounts().send().getAccounts().get(0)) {

				Credentials credentials = WalletUtils.loadCredentials("Password of sender account", "sender account path with file name" );"credentials:::from address:::" + credentials.getAddress());"--------------Wallet keystore location is "
						+ envConfiguration.getTestnetkeyStorePath().trim() + "/" + wallet.getWalletFileName());
				EthGetTransactionCount ethGetTransactionCount = parity
						.sendAsync().get();"--------------ethGetTransactionCount" + ethGetTransactionCount.getTransactionCount());
				// get the next available nonce
				BigInteger nonce = ethGetTransactionCount.getTransactionCount();"----------nonce" + nonce);

				BigDecimal gasInDecimal = new BigDecimal(gas);
				BigDecimal gaspriceInDecimal = new BigDecimal(gasprice);

				balance = balance.subtract((gasInDecimal.multiply(gaspriceInDecimal)).divide(new BigDecimal(xth)));"::::gasInDecimal:>>>>>>>>>>>>>>>>>>>>>>>>>>>>:" + gasInDecimal
						+ "::gaspriceInDecimal:::::::" + gaspriceInDecimal);":::Transferred amount is::::>>>>>>>>>>>>>>>>>>>>>" + balance);"Enter into account Unlocked ..>>>>>>>>>>>>>>>>>>>>>>.");
				TransactionReceipt transactionReceipt = Transfer.sendFunds(parity, credentials, "Receiver Eth address",
						balance, Unit.ETHER);"trn recpt " + transactionReceipt.getTransactionHash() + " new balance is "
						+ parity.ethGetBalance(wallet.getAddress(), DefaultBlockParameterName.fromString("latest"))

				result.put("responseMessage", "success");
				return result;

			} else {
				result.put("message", "error");
				result.put("responseMessage", "failure");
				return result;

		} catch (Exception e) {
			result.put("trnInfo", null);
			result.put("message", e.getMessage());
			result.put("responseMessage", "failure");
			return result;

Thanks I hope this will be helpful!!!

About Author

Author Image
Sudhakar Pandey

Sudhakar pandey is java developer and passoinate about learning to new technology, He have exposure about spring, hibernate, REST services, Multithreading , JSP/ Servlet. On the database side He have exposure about MySql, Oracle, Postgres.

Request for Proposal

Name is required

Comment is required

Sending message..