I am using [email protected]. I am trying to implement the sendSignedTransaction method, but it keeps on giving me below error.
reason: 'err: insufficient funds for gas * price + value:
I am sure I do have funds for txn. If I use the v1.10.2 and make corresponding syntax changes in the way I import web3, the txn is successfully executed.
Here is my code:
const { Web3 } = require("web3");
const Tx = require('ethereumjs-tx').Transaction;
const web3 = new Web3('<goerli_http_endpoint>');
async function fun() {
account1 = '<myAcc1>';
privateKey1 = '<myPk>';
account2 = '<myAcc2>';
let amountToSend = web3.utils.toWei('0.001', 'ether');
let acquiredPrice = web3.utils.toWei('10', "gwei");
web3.eth.getTransactionCount(account1).then(async nonce => {
// create tx object
txObj = {
nonce: web3.utils.toHex(nonce),
from: account1,
to: account2,
value: web3.utils.toHex(amountToSend),
gasPrice: web3.utils.toHex(acquiredPrice),
gasLimit: web3.utils.toHex(21000)
}
// sign tx
let tx = new Tx(txObj, { 'chain': 'goerli' });
tx.sign(Buffer.from(privateKey1, "hex"));
// serialize tx
const serializedTx = tx.serialize();
const rawTx = '0x' + serializedTx.toString('hex');
// send tx
web3.eth.sendSignedTransaction(rawTx)
.on('receipt', txReceipt => {
console.log("Receipt:", txReceipt)
})
.on('transactionHash', txHash => {
console.log("Hash:", txHash)
})
.on('error', error => {
console.log("Error:", error)
})
}).catch(error => {
console.log(error)
});
}
The same above code works if I execute it with web3 v1.10.2 and making the following single change.
const { Web3 } = require("web3"); // for v4.2.0
const Web3 = require("web3"); // for v1.10.2
Could anyone please tell me the right way to do it using v4.2.0.