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.
gasPrice = await web3.eth.estimateGas()
? gas and gasPrice are different concepts.gasPrice * 21000
andbalance - gas
web3js doesn't return numbers but BN objects so for mathematical operations you have to use github.com/indutny/bn.js/#arithmetics.