【问题标题】:Weird wei to ether conversion using web3使用 web3 进行奇怪的 wei 到 ether 的转换
【发布时间】:2018-08-31 08:03:49
【问题描述】:

我正在尝试在 karma 测试中进行一些气体交易成本计算以断言最终余额,但我无法理解为什么这两个代码 sn-ps 的输出不同

变量的值依次为:

59916559960000000000 3000000000000000000 394980000000000

sn-ps 是:

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

第二个sn-p是用户账户的正确余额,断言成功。不是从wei到ether的转换:value / 1e18?。我不明白为什么,但这个 sn-ps 之间的差异超过 3 个以太单位。

我正在使用 web3 版本 1.0.0-beta26。

提前谢谢你。

【问题讨论】:

    标签: javascript ethereum karma-mocha web3js web3


    【解决方案1】:

    我认为问题在于web3.utils.fromWei 返回一个字符串,而+ for strings 执行连接。

    也许只做web3.utils.fromWei(customerBalance + customerRefundableEther - transactionFee, 'ether')

    编辑

    看起来可能是customerBalance 等人。是BigNumber 实例。在这种情况下:

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

    编辑 2

    带数字的工作代码:

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

    使用字符串的工作代码,以防万一问题是它们以字符串开始:

    > 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'
    

    【讨论】:

    • 这样做我收到一个错误:允许购买航班并兑换忠诚度积分:错误:[number-to-bn] 同时将数字“5.991655996e+38”转换为 BN.js 实例,错误: 无效的数值。值必须是整数、十六进制字符串、BN 或 BigNumber 实例。请注意,不支持小数。将尝试转换为十六进制
    • 哦,抱歉,是customerBalanceBigNumber 实例吗?
    • 如果是,web3.utils.fromWei(customerBalance.add(customerRefundableEther).sub(transactionFee).toString(), 'ether')
    • 但是 1.0.0 api 将余额作为数字给出,他们没有方法。
    • 那么customerRefundableEther等是什么类型?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2014-08-13
    • 2012-10-05
    • 2021-05-03
    • 2018-04-14
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多