0

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.

Zero
  • 103
  • 3

1 Answers1

1

You miscalculate the valueAfterGas and the gasLimit.

  • gasLimit has nothing to do with the price. It defines how much gas will be consumed in the transaction. For ETH transfer this value is: 21000

  • valueAfterGas = amount - gasLimit * gasPrice; (gasPrice is per 1 GAS unit)

  • you should pass your gasPrice to the transaction.

const tx = await wallet.sendTransaction({
   to: to,
   value: amount - gasLimit * gasPrice,
   gasPrice: gasPrice,
   gasLimit: gasLimit,
});
tenbits
  • 2,304
  • 4
  • 12