So let's say my wallet is 1 eth, I need to completely empty it and I'm going to do it this way

Var value = web3.toWei(1) - gas

Is that right?


2 Answers 2


Yes. You will need to figure out how much gas (in ETH) the transaction will cost, but luckily simple ETH transfers are exactly 21,000 gas (I think, double check this number). This means to know how much ETH will be spent on gas you will need to multiply that by the chosen gas price (e.g., 10^10).

So your calculation will need to look something like this:

var gasPrice = 20*10**9;
var gas = 21000;
var attoethForGas = gasPrice * gas;
var amountToSend = web3.toWei(1) - attoethForGas;
  • If I take this gas as 5000 and I can't completely empty my account(unused gas is refunded)
    – ali
    Aug 1, 2017 at 3:10
  • @D.Doy I updated the answer to include a code example, let me know if that helps clear things up. Aug 1, 2017 at 3:13
  • Thank you for your answer, but it seems that it didn't prevent the refund from gas too big. If it were to be cleared, do I have to make gas small enough?
    – ali
    Aug 1, 2017 at 5:43
  • Hmm, I'm not sure what your problem might be, I'm reasonably confident that the above is the way to send everything. Can you share the code you have that isn't working? There should be no gas refund for an ETH transfer, even if it zeros out the balance. Aug 1, 2017 at 14:20

In order to calculate an exact value to send, you must use precise calculations which JavaScript doesn't give you out of the box. Luckily, web3.js already returns a special BigNumber object from eth.getBalance(). In order to execute precise math, you need to use BigNumber methods instead of using default arithmetic operators. For example:

gasPrice = new BigNumber(web3.toWei('0.6', 'gwei'))
cost = gasPrice.mul(21000)
value = eth.getBalance(eth.accounts[0]).sub(cost)

Constants were pulled from these sources at time of posting:

  • ethgasstation.info is actually down at the moment, 0.6 gwei was just a fairly stable price I saw before it went down.
    – carver
    Aug 1, 2017 at 17:44

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.