How To Perform Ethereum Transactions In Spring Boot Application

Posted By : Ishank

Jan 29, 2021

What is an Ethereum Transaction?

 

The transaction is the way of interacting with the Ethereum network. The transaction is the information of our particular request we make on the Ethereum network. It gets stored in a block of chain on the platform

 

 

Prerequisites

 

We need Java 8+, a basic understanding of blockchain, and a fully synced and connected application to the Ethereum main or test node according to requirements. We will be using ETH's main network, spring boot understanding, and IDE. Also, we will use SpringToolSuit, active internet service, your ethereum service URL(maybe localhost or your own server), and some ETHs in your ethereum wallet for testing. 

 

Dependency

 

In Pom.xml, add web3j dependency below. We can use a different/latest version. 

 

Maven:

        <dependency>
            <groupId>org.web3j</groupId>
            <artifactId>core</artifactId>
            <version>3.0.2</version>
        </dependency>

 

Gradle:

compile ('org.web3j:core:3.0.2')

 

Create and add transaction to:-

 

public class TransactionDTO {

    @NotBlank
    private BigDecimal amountToBeSend;

    @NotBlank
    private Double walletBalance;

    @NotBlank
    private String sendToAddress;


    @NotBlank
    private Double fee;


    @NotBlank
    private Double networkFee;

}

 

Now, see the following example for performing a transaction:-

 

/**
 * Auto imports if you are using any IDE like Spring Tool Suite, Eclipse.
 */


public class Transaction {

    private Logger logger = LoggerFactory.getLogger(ETHWalletController.class);

    @Value("${service.url}")//To be declared in application.properties file
    private String serverurl;

    private Callback txReceiptCallback;

    private TransactionReceiptProcessor noOpReceiptProcessor;

    private Web3j web3j;

    private QueuingTransactionReceiptProcessor transactionReceiptProcessor;

    @PostConstruct
    public void init() {

        this.web3j = Web3j.build(new HttpService(serverurl));
        this.txReceiptCallback = new Callback() {
            @Override
            public void accept(TransactionReceipt transactionReceipt) {
            }

            @Override
            public void exception(Exception exception) {

                logger.info(exception.getMessage());
            }
        };
        this.transactionReceiptProcessor = new QueuingTransactionReceiptProcessor(web3j, txReceiptCallback, 10, 60000);
        this.noOpReceiptProcessor = new NoOpProcessor(web3j);
    }

    public Boolean ethExternalTransaction(TransactionDTO transactionDTO,EthWallet ethWallet) {

        Web3j parity = Web3j.build(new HttpService(serverurl));
        try {
            String decrPwd = CryptoUtil.decrypt(ethWallet.getWalletPwd(), ethWallet.getWalletPwdKey());
            Credentials credentials = WalletUtils.loadCredentials(decrPwd,
                    ethWallet.getWalletJsonFile());

            BigInteger amount = parity
                    .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.fromString("latest")).send()
                    .getBalance();
            BigDecimal balance = new BigDecimal(amount);

            BigDecimal conversionRate = BigDecimal.valueOf(Long.valueOf("1000000000000000000"));
            BigDecimal balanceInEther = balance.divide(conversionRate, 8, RoundingMode.FLOOR);
            logger.info(" balance before txn {} amount {} " + balanceInEther,
                   transactionDTO.getAmountToBeSend());
            BigInteger gas = BigInteger.valueOf(70000);
            BigInteger gasprice = parity.ethGasPrice().send().getGasPrice();
            BigInteger txnFee = gas.multiply(gasprice);
            BigInteger xth = new BigInteger("1000000000000000000");
            BigDecimal v1 = new BigDecimal(xth);
            BigDecimal v2 = new BigDecimal(txnFee);
            BigDecimal txnFeeInEther = v2.divide(v1);
            BigDecimal transferAmount = txnFeeInEther.add(transactionDTO.getAmountToBeSend());
            if ((balanceInEther.compareTo(transferAmount)) == 1) {
                TransactionManager rtm = new RawTransactionManager(parity, credentials, ChainId.NONE,
                        noOpReceiptProcessor);
                Transfer ethTransfer = new Transfer(parity, rtm);
                TransactionReceipt transactionReceipt = ethTransfer.sendFunds(transactionDTO.getSendToAddress(),
                        outAppTransactionDTO.getAmountToBeSend().setScale(8, RoundingMode.HALF_UP), Convert.Unit.ETHER)
                        .send();
                if (Optional.ofNullable(transactionReceipt).isPresent()
                        && !StringUtils.isEmpty(transactionReceipt.getTransactionHash())) {
                   //to do
                } else {
                   //to do
                }
            } else {
                //To do
                }
        } catch (Exception ex) {
           //to do
        }
    }

}

Here, the conversion rate and gas price may vary from time to time. It is needed to be tracked from Etherscan gastracker. Our current ethereum transaction can be also tracked on etherscan.

 

In the above example, we have an EthWallet object which contains the password, secret key to decrypt wallet, JSON file, and other web3j library specific required values to load eth wallet and perform a transaction.

 

We are a blockchain development company that provide services for blockchain and smart contract solutions for business with the latest tool and technology. From dApps (decentralized applications) to permissioned blockchain solutions, our expertise a range of domains. We use our expert insights, research methodology, and development experience to accelerate blockchain adoption across businesses and contribute toward the creation of a smarter economy

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

November 21, 2024 at 12:02 pm

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button

Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text