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?
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;
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: