After going through the questions here and here I came up with the code below to transfer the entire balance from one address to another using web3.js.
export async function sendTransaction(
secretKey: string,
amount: number,
to?: string
) {
try {
const wallet = new ethers.Wallet(secretKey, provider);
const valueAfterGas = amount - gasLimit;
const gasPrice = await web3.eth.getGasPrice();
const tx = await wallet.sendTransaction({
to: to,
value: valueAfterGas,
gasLimit: gasLimit * Number(gasPrice),
});
return tx;
} catch (error) {
log(No transaction for ${amount} to ${to});
errorHandler(error);
}
}
This code doesn't work and I get RPC errors saying -
Error: cannot estimate gas; transaction may fail or may require manual gas limit
Error: processing response error
How can this be fixed? I am using web3 version 4.4, if your solution requires a different version I can downgrade if it can be specified.