I am using the below code for executing ETH transactions with web3.js

Is it an optimized code? is there any room for improvements, what else can I add, or how can I handle exceptions/errors

const transactEthereum = async (privKey, addressFrom, addressTo, amount) => {

   // Configuring the connection to an Ethereum node
    const network = process.env.ETHEREUM_NETWORK;
    const web3 = new Web3(
        new Web3.providers.HttpProvider(

    const tx = {

        from: addressFrom,
        to: addressTo,
        value: amount


    // Assigning the right amount of gas
    tx.gas = await web3.eth.estimateGas(tx);

    // nonce starts counting from 0
    tx.nonce = await web3.eth.getTransactionCount(addressFrom, 'latest');

   const createTransaction = await web3.eth.accounts.signTransaction(

   // Deploy transaction
   const createReceipt = await web3.eth.sendSignedTransaction(

      `Transaction successful with hash: ${createReceipt.transactionHash}`

   return createReceipt.transactionHash;

  • The code is perfectly fine. It will work well in the majority of the situations. There are a few thing that you may want to improve: the web3 provider is down, there's a pending transaction, the network is congested and the gas price is too high, there isn't enough ether to pay the transaction fees, the target is a contract that reverts. If none of those cases applies to your use case then the code will work correctly.
    – Ismael
    Commented Apr 23, 2022 at 20:09
  • @Ismael how can I do those things code wise, I am new to web3.js
    – ershad7
    Commented Apr 26, 2022 at 17:50
  • It shouldn't be a problem for most cases. If the transaction takes too long to confirm then you could diagnose, and allow the user to send a replacement transaction. See this answer ethereum.stackexchange.com/a/44875 for an explanation how to do it.
    – Ismael
    Commented Apr 28, 2022 at 2:42


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.