¿Cómo puedo configurar correctamente el gas/valor para enviar una transacción con web3.js?

mi código es:

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);
    });
}

Pero me sale un error:

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

Respuestas (1)

Javascript no admite números con precisión arbitraria que se requieren al realizar cálculos con valores de éter (¡el éter tiene 18 decimales!).

Web3 v1.0 envolverá valores numéricos en objetos bn.js. En lugar de usar operadores matemáticos regulares (+, -, *, /, etc.), debe usar métodos aritméticos de bn.js:

En lugar de a * b + ctienes que hacer a.mul(b).add(c). Para convertir al formato bn.js, web3 proporciona la función web3.utils.toBN().

Por ejemplo, sus cálculos de gas se pueden hacer así:

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)
No hay manera de hacerlo times 1.1directamente?