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

1
  • 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 github.com/indutny/bn.js/#arithmetics.
    – Ismael
    Commented Dec 29, 2021 at 15:34

2 Answers 2

0

Use the estimateGas method to calculate the gas.

web3.eth.estimateGas
1
  • 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 Commented Dec 29, 2021 at 8: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.

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') Commented Dec 29, 2021 at 8: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. Commented Dec 29, 2021 at 8:44
  • <mypath>\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 Commented Dec 29, 2021 at 8: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. Commented Dec 29, 2021 at 8:52
  • 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. Commented Dec 29, 2021 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.