1

I found the same question but it was asked over 4 years ago but it doesn't seem to work anymore?

How do I send the entire ether balance from one account to another account?

const Web3 = require('web3')
require('dotenv').config()

async function main() { const { RPC_URL, PRIVATE_KEY, TO } = process.env;

const web3 = new Web3(new Web3.providers.HttpProvider(RPC_URL))
const pubkey = await web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY).address;

const balance = await web3.eth.getBalance(pubkey);

const currentGas = await web3.eth.getGasPrice();
const requiredGasPrice = await web3.eth.estimateGas({to: TO});
const gas = currentGas * requiredGasPrice;

const nonce = await web3.eth.getTransactionCount(pubkey, 'latest');

const transaction = {
    'to': TO,
    'value': balance - gas,
    'gas': requiredGasPrice,
    'gasPrice': currentGas,
    'nonce': nonce
};    

const signedTx = await web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY);

web3.eth.sendSignedTransaction(signedTx.rawTransaction, function (error, hash) {
    if (!error) {
        console.log(" The hash of your transaction is: ", hash);
    } else {
        console.log("❗ Something went wrong while submitting your transaction: ", error)
    }
});

}

main();

I can't seem to be able to calculate the gas so that it will be able to send all the ether from the wallet.

What do I calculate the gas for the transaction to send funds.

enter image description here

Little Ball
  • 111
  • 3
  • Is target address a contract? Why gasPrice = await web3.eth.estimateGas()? gas and gasPrice are different concepts. gasPrice * 21000 and balance - gas web3js doesn't return numbers but BN objects so for mathematical operations you have to use https://github.com/indutny/bn.js/#arithmetics. – Ismael Dec 29 '21 at 15:34

2 Answers2

0

Use the estimateGas method to calculate the gas.

web3.eth.estimateGas
Mad Jackal
  • 1,195
  • 2
  • 5
  • 8
  • I've modified const gas = await web3.eth.estimateGas but I get a NaN error, I also turned it into a function and I get a read property of undefined, how exactly do I change it in relation to my code? Thank you – Little Ball Dec 29 '21 at 08:29
0

In addition to the answer above I will add that you can calculate the fee needed for the transaction to execute by taking the gas which is needed for simple ether transfer 21000 and multiply it by the current gas price await web3.eth.getGasPrice():

const currentGas = await web3.eth.getGasPrice();
const requiredGasPrice = await web3.eth.estimateGas({to: TO});
const gas = currentGas * requiredGasPrice;

And then pass the gasPrice variable to the transaction object:

const transaction = {
    'to': TO,
    'value': balance - gas,
    'gas': requiredGasPrice,
    'gasPrice': currentGas,
    'nonce': nonce
};

You can also add condition to check if balance is greater than gas. This way you will know this particular wallet will have the enough balance to cover the transaction fee.

Miroslav Nedelchev
  • 3,519
  • 2
  • 10
  • 12
  • I followed the exact same as you suggested but on this line: const gasPrice = await web3.eth.estimateGas() I get the following error: TypeError: Cannot read properties of undefined (reading 'to') – Little Ball Dec 29 '21 at 08:38
  • The error should not be on this line, read the error again. You can check that by console logging gasPrice right after it creation. Did you changed the to property inside the transaction object? It seems like the error is pointing to there. – Miroslav Nedelchev Dec 29 '21 at 08:44
  • `\node_modules\web3-core-helpers\lib\formatters.js:119 if (options.to) { // it might be contract creation ^

    TypeError: Cannot read properties of undefined (reading 'to')`

    This is the error, I can try to reinstall my node modules again

    EDIT: reinstalled node modules but same error

    – Little Ball Dec 29 '21 at 08:46
  • This error has nothing to do with the calculation of the gas price. Once again, because you didn't answer to my question, did you tested the line 'to': TO,? Are you sure that TO is a valid ethereum address? You can console log it right before the creation of the transaction object. – Miroslav Nedelchev Dec 29 '21 at 08:52
  • The code doesn't execute that far, it just stops at the estimateGas, I console log at every line and it doesn't go past that function – Little Ball Dec 29 '21 at 08:56
  • Weird, what web3 version are you using? I just tested the await web3.eth.estimateGas() on web3 version 1.6.1 and the outcome is correct. Maybe your dependencies are outdated? – Miroslav Nedelchev Dec 29 '21 at 08:57
  • My version according to my package.json is "web3": "^1.6.1". This is really weird, I will edit the main post with the most recent code just incase I did something wrong – Little Ball Dec 29 '21 at 08:59
  • 1
    @LittleBall I updated my code, I forgot that you need to pass to property to web3.eth.estimateGas. But why would you need to pass that property - because sending ether to normal wallet address always requires 21000 gas, but if the receiver is contract address then this contract address might have additional logic attached to the action when the contract is receiving the ether and then the required gas for the transaction to execute wont be anymore 21000, but higher. Take my code, everything should be ok now. – Miroslav Nedelchev Dec 29 '21 at 09:06
  • @LittleBall let me know if you succeed. – Miroslav Nedelchev Dec 29 '21 at 12:29
  • I thought it was working but the transaction is stuck pending, I went to see the transaction and the gas price seems to be too low and is stuck in pending. I will update the post with the screenshot of the transaction – Little Ball Dec 29 '21 at 18:05
  • It's pending, because you haven't updated the transaction object as it should. Look at your screenshot, the transaction is signed with 0.000021 gwei which means this transaction will be stucked forever until you resubmit it with higher gas price and the same nonce as the stucked transaction. In the transaction object the gasPrice property has to be the outcome of await web3.eth.getGasPrice() as it's shown in my example. – Miroslav Nedelchev Dec 29 '21 at 18:40
  • I copied the code from your example and I get this error now Error: Returned error: insufficient funds for gas * price + value, I have updated my post with the newest version of my code – Little Ball Dec 29 '21 at 19:05