0

My code is:

function sendEth(fromAddress, secret, toAddress, amount) {
  let params = {
    to: toAddress,
    from: fromAddress,
    value: web3.utils.toWei(amount + '', 'ether')
  };
  console.log(params);

  return Promise.all([web3.eth.estimateGas(params), web3.eth.getGasPrice()])
    .then((response) => {
      const estimatedGas = response[0];
      const gasPrice = response[1];
      params.gas = estimatedGas;
      params.gasPrice = web3.utils.toWei(1.1 * gasPrice + ''); // Use 10% more gas than recommended
      params.value = web3.utils.toWei(params.value - params.gas * params.gasPrice + '');

      return web3.eth.accounts.signTransaction(params, secret);
    })
    .then((signedTx) => {
      return web3.eth.sendSignedTransaction(signedTx.rawTransaction);
    });
}

But I get an error:

 Error: while converting number to string, invalid number value '-1.1549989999999999e+23', should be a number matching (^-?[0-9.]+).
2

Javascript doesn't support numbers with arbitrary precision that are required when doing calculation with ether values (ether has 18 decimals!).

Web3 v1.0 it will wrap numeric values in bn.js objects. Instead of using regular mathematical operators (+, -, *, /, etc) you have to use arithmetic methods from bn.js:

Instead of a * b + c you have to do a.mul(b).add(c). To convert to bn.js format web3 provides function web3.utils.toBN().

For example your gas calculations can be done like this:

params.gasPrice = web3.utils.toBN(gasPrice)
    .mul(web3.utils.toBN(11))
    .div(web3.utils.toBN(10));  // gasPrice * 1.1

params.value = web3.utils.toBN(params.value)
    .sub(
        web3.utils.toBN(params.gas).mul(
            web3.utils.toBN(params.gasPrice)
        )
    );     // value - (gas * gasPrice)
  • There's no way to do times 1.1 directly? – Shamoon Jun 4 '18 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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