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

 
        
			org.web3j
			core
			2.2.2
		
 

Create Web3j object to connect ethereum server.

 
Web3j web3j = Web3j.build(new 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 = Web3j.build(new HttpService(envConfiguration.getTestnetServerIp()));
			LOGGER.info("--------------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();


			LOGGER.info("Creating  Parity...");

			LOGGER.info("Getting wallet ..." + wallet.getAddress() + "  and balance is "
					+ web3j.ethGetBalance(wallet.getAddress(), DefaultBlockParameterName.fromString("latest")).send()
							.getBalance());
                        // Minimum gas is 21000 used for transaction
			BigInteger gas = BigInteger.valueOf(21000);
			LOGGER.info("gas:::" + gas);

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

			LOGGER.info("gasprice:::" + gasprice);

			BigInteger gaslimit = BigInteger.valueOf(4800000);
			LOGGER.info("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));
			LOGGER.info("Compare result:: " + compareResult);

			LOGGER.info(":::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" );
				LOGGER.info("credentials:::from address:::" + credentials.getAddress());

			
				LOGGER.info("--------------Wallet keystore location is "
						+ envConfiguration.getTestnetkeyStorePath().trim() + "/" + wallet.getWalletFileName());
				EthGetTransactionCount ethGetTransactionCount = parity
						.ethGetTransactionCount(parity.ethAccounts().send().getAccounts().get(0),
								DefaultBlockParameterName.LATEST)
						.sendAsync().get();
				LOGGER.info("--------------ethGetTransactionCount" + ethGetTransactionCount.getTransactionCount());
				
				// get the next available nonce
				BigInteger nonce = ethGetTransactionCount.getTransactionCount();
				LOGGER.info("----------nonce" + nonce);

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

				balance = balance.subtract((gasInDecimal.multiply(gaspriceInDecimal)).divide(new BigDecimal(xth)));
				LOGGER.info("::::gasInDecimal:>>>>>>>>>>>>>>>>>>>>>>>>>>>>:" + gasInDecimal
						+ "::gaspriceInDecimal:::::::" + gaspriceInDecimal);
				LOGGER.info(":::Transferred amount is::::>>>>>>>>>>>>>>>>>>>>>" + balance);
	

				LOGGER.info("Enter into account Unlocked ..>>>>>>>>>>>>>>>>>>>>>>.");
				
				TransactionReceipt transactionReceipt = Transfer.sendFunds(parity, credentials, "Receiver Eth address",
						balance, Unit.ETHER);
				LOGGER.info("trn recpt " + transactionReceipt.getTransactionHash() + " new balance is "
						+ parity.ethGetBalance(wallet.getAddress(), DefaultBlockParameterName.fromString("latest"))
								.send().getBalance());

			
				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..