1

Hello everyone, I start learning programming, sorry for my mistakes.

I need to send all balance (100 ether) from account 1 to the account 2. But he does not have enough money for the transfer. I understand that I first need to get the balance of account 1, get the gas and price of gas, fold this and move this to the "value:" But I do not quite understand how to do it right.

const privKey = ' ';
const addressFrom = ' ';
const addressTo = ' ';
const web3 = new Web3('http://127.0.0.1:7545');

var balance = web3.eth.getBalance(addressFrom);


// Transaction
const deploy = async () => {
  console.log(
    'Transaction from: ' + addressFrom, 'to: ' + addressTo
    );

  const createTransaction = await web3.eth.accounts.signTransaction(
  {
    from: addressFrom,
    to: addressTo,
    value: web3.utils.toWei('100','ether'),
    gas: '21000',
  }, privKey);
1

1 Answer 1

1

What you have to do is from the sender balance you have to subtract the fee for the transaction. Transfering ETH cost always 21000 gas and the formula for calculating the fee is FEE = GAS_USED_BY_THE_TX * GASPRICE. Now by knowing this we can calculate the fee for the transaction:

var txFee = await web3.eth.getGasPrice() * 21000;

Have in mind that the variable txFee is in Wei and the outcome of method web3.eth.getBalance() is also in Wei. So next thing we do is to subtract the fee out of the balance and the outcome is the value that has to be sent:

var balance = await web3.eth.getBalance(<SOME_ADDRESS>);
var valueToBeSent = balance - txFee;

After the transaction is completed the sender should be having 0 ETH balance.

1
  • Thank you Miroslav! You helped me a lot
    – Enzo
    Sep 1, 2021 at 11:39

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