【问题标题】:Why is (startingBalance - endBalance) > (gasUsed * gasPrice) for an Ethereum transaction?为什么 (startingBalance - endBalance) > (gasUsed * gasPrice) 用于以太坊交易?
【发布时间】:2018-03-12 03:58:19
【问题描述】:

我正在尝试在 truffle 框架中编写 javascript 测试,以验证转移资金的交易后 eth 余额的变化。

我想排除 gas 费用,以便我可以断言余额变化的确切金额。

以下是我尝试确定在 gas 上花费的 eth 数量的方法:

let startingBalance = await web3.eth.getBalance(me);
let tx = await contract.method.sendTransaction({from: me, gasPrice: 1});
let endBalance = await web3.eth.getBalance(me);
let receipt = await web3.eth.getTransactionReceipt(tx);
await (startingBalance - endBalance).should.be.equal(receipt.gasUsed);

我的理由是,因为:

  • 交易不会改变资金
  • 我明确地将交易 gasPrice 设置为 1

receipt.gasUsed 应该等于余额变化。

但是针对 testrpc 运行,测试抱怨余额比gasUsed * gasPrice 减少了大约 2000 年。

是否还有其他因素可能导致 eth 余额变化?

谢谢!

【问题讨论】:

    标签: ethereum truffle


    【解决方案1】:

    startingBalanceendBalanceBigNumber 对象。将您的测试更改为

    await (startingBalance.minus(endBalance)).should.be.equal(receipt.gasUsed);

    【讨论】:

    • 谢谢!那是我的问题。我必须添加 .toNumber() 因为 gasUsed 不是 BigNumber。令人惊讶的是 operator-() 的作用与 minus() 不同。
    • 没问题。请接受答案,以便关闭问题。
    • 对不起。这是我第一次提出关于 SO 的问题。我花了一段时间才找到“接受”的地方。 :)
    【解决方案2】:

    我不会相信 testrpc。尝试在测试网上运行您的代码

    【讨论】:

    • 嗯。我启动了一个本地 geth 测试网,迁移了我的合约。但是在运行测试时,getTransactionReceipt() 返回 null。至少我能够在 testrpc 中获得交易收据。而且我的许多特殊测试也未能得到预期的拒绝。很奇怪。
    猜你喜欢
    • 2017-01-27
    • 1970-01-01
    • 2018-12-09
    • 2021-10-02
    • 2019-12-09
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多