无法使用 Truffle 和 Ganache 清空 Solidity 合约的余额

Cannot empty balance of Solidity contract using Truffle and Ganache

我在使用 Truffle 测试我是否可以退出合同时遇到问题。这是一个非常简单的测试,但是在调用下面的 withdrawBalance 函数之后。以后用web3.eth.getBalance.

时余额还是一样

我还可以看到在 Ganache 中 owner 没有收到 ETH。

如果我 return 余额来自 withdrawBalance 方法。实际上是0。

contract Room {
    address public owner = msg.sender;

    function withdrawBalance() public {
        require(msg.sender == owner);
        owner.transfer(this.balance);
    }
}

测试文件:

it('should allow withdrawls to original owner', function () {
        var meta;
        return Room.deployed()
            .then(instance => {
                meta = instance;
                return web3.eth.getBalance(meta.address);
            })
            .then((balance) => {
                // Assertion passes as previous test added 6 ETH
                assert.equal(balance.toNumber(), ONE_ETH * 6, 'Contract balance is incorrect.');
                return meta.withdrawBalance.call();
            })
            .then(() => {
                return web3.eth.getBalance(meta.address);
            })
            .then((balance) => {
                // Assertion fails. There is still 6 ETH.
                assert.equal(balance.toNumber(), 0, 'Contract balance is incorrect.');
            });
    });

我的问题是:

  1. 我的测试是否存在某种竞争条件?我怎样才能让余额检查正确?
  2. 为什么合约所有者不在 Ganache 中显示 ETH 余额?还是真的ETH不提了

您正在使用 return meta.withdrawBalance.call(); 而不是 return meta.withdrawBalance.sendTransaction();

.call() 运行 在您的 EVM 本地运行并且是免费的。您 运行 您自己机器上的所有计算以及执行后的任何更改都将恢复到初始状态。

要真正改变区块链的状态,您需要使用 .sendTransaction()。它会消耗 gas,因为矿工会因为他们在执行您的交易期间所做的计算而获得奖励。


总结:

ETH is not being withdrawn.