0

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( https://${network}.infura.io/v3/${process.env.INFURA_PROJECT_ID} ) );

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( tx, privKey );

// Deploy transaction const createReceipt = await web3.eth.sendSignedTransaction( createTransaction.rawTransaction );

console.log( Transaction successful with hash: ${createReceipt.transactionHash} );

return createReceipt.transactionHash;

};

ershad7
  • 3
  • 3
  • 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 Apr 23 '22 at 20:09
  • @Ismael how can I do those things code wise, I am new to web3.js – ershad7 Apr 26 '22 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 https://ethereum.stackexchange.com/a/44875/ for an explanation how to do it. – Ismael Apr 28 '22 at 02:42

0 Answers0