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;
};