[英]Cannot empty balance of Solidity contract using Truffle and Ganache
I'm having issues with using Truffle to test that I can withdraw from my contract.我在使用 Truffle 测试我是否可以退出合同时遇到问题。 It's a very simple test but after the below withdrawBalance
function is called.这是一个非常简单的测试,但在调用下面的withdrawBalance
函数之后。 The balance remains the same when I later use web3.eth.getBalance
.当我稍后使用web3.eth.getBalance
时,余额保持不变。
I can also see that in Ganache the owner
does not receive the ETH.我还可以看到,在 Ganache 中, owner
没有收到 ETH。
If I however return the balance from the withdrawBalance
method.但是,如果我从withdrawBalance
方法返回余额。 It is actually 0.实际上是0。
contract Room {
address public owner = msg.sender;
function withdrawBalance() public {
require(msg.sender == owner);
owner.transfer(this.balance);
}
}
The test file:测试文件:
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.');
});
});
My questions are:我的问题是:
You are using return meta.withdrawBalance.call();
您正在使用return meta.withdrawBalance.call();
instead of return meta.withdrawBalance.sendTransaction();
而不是return meta.withdrawBalance.sendTransaction();
. .
.call()
is running locally in your EVM and is free. .call()
在您的 EVM 中本地运行并且是免费的。 You run all the computations on your own machine and any changes after execution get reverted to the initial state.您在自己的机器上运行所有计算,执行后的任何更改都会恢复到初始状态。
To actually change the state of the blockchain you need to use .sendTransaction()
.要实际更改.sendTransaction()
链的状态,您需要使用.sendTransaction()
。 It costs gas, because miners get rewarded for the computations which they make during execution of your transaction.它会消耗gas,因为矿工在执行交易期间会因他们进行的计算而获得奖励。
Summarizing:总结:
ETH is not being withdrawn. ETH 没有被撤回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.