简体   繁体   中英

Weird wei to ether conversion using web3

I am trying to do some gas transaction cost calculations in a karma test to assert the final balance and I can not understand why the output of this two code snippets is different

Values for variables in order are:

59916559960000000000 3000000000000000000 394980000000000

And the snippets are:

let currentBalance =  web3.utils.fromWei(customerBalance.toString(), 'ether')  
         + web3.utils.fromWei(customerRefundableEther.toString(), 'ether') 
         - web3.utils.fromWei(transactionFee.toString(), 'ether');

let currentBalance = (customerBalance / 1e18)
                     +(customerRefundableEther / 1e18) 
                     - (transactionFee / 1e18);

The second snippet is the correct balance at the user account and the assert is successful. Is not the conversion from wei to ether: value / 1e18?. I can't understand why but the difference between this snippets are more than 3 ether units.

I am using web3 version 1.0.0-beta26.

Thank you in advance.

I believe the issue is that web3.utils.fromWei returns a string, and + for strings performs concatenation.

Maybe just do web3.utils.fromWei(customerBalance + customerRefundableEther - transactionFee, 'ether') ?

EDIT

It appears maybe customerBalance et al. are BigNumber instances. In that case:

web3.utils.fromWei(customerBalance.add(customerRefundableEther)
  .sub(transactionFee).toString(), 'ether')

EDIT 2

Working code with numbers:

> const customerBalance = 59916559960000000000;
> const customerRefundableEther = 3000000000000000000;
> const transactionFee = 394980000000000;
> web3.utils.fromWei((customerBalance + customerRefundableEther - transactionFee).toString(), 'ether');
62.91616498000001

Working code with strings, just in case the issue is that they start off as strings:

> const customerBalance = '59916559960000000000';
> const customerRefundableEther = '3000000000000000000';
> const transactionFee = '394980000000000';
> web3.utils.fromWei(web3.utils.toBN(customerBalance).add(web3.utils.toBN(customerRefundableEther)).sub(web3.utils.toBN(transactionFee)), 'ether')
'62.91616498'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM