我是区块链新手。我想调用一个函数来从合约中读取一个变量。我的合同
bool public isVoting = false;
function getIsVoting() public returns (bool) {
return isVoting;
}
在客户,我这样打电话
const isVoting = async () => {
const _isVoting = await ElectionInstance.methods
.getIsVoting()
.call()
.then(console.log);
};
然后我得到了错误,但不知道为什么:
{
"message": "VM Exception while processing transaction: revert",
"code": -32000,
"data": {
"0xdbe5e039374fdc83fe873f5e55d91f05ec5d19e2e3c88351130c3f3672644e08": {
"error": "revert",
"program_counter": 130,
"return": "0x"
},
"stack": "RuntimeError: VM Exception while processing transaction: revertn at Function.RuntimeError.fromResults (/tmp/.mount_ganachnMw5dG/resources/static/node/node_modules/ganache-core/lib/utils/runtimeerror.js:94:13)n at /tmp/.mount_ganachnMw5dG/resources/static/node/node_modules/ganache-core/lib/blockchain_double.js:568:26",
"name": "RuntimeError"
}
}
你能帮我吗,请。我是新来的。
与 web3 不同,Truffle 不使用
methods
关键字。调用失败是因为它试图访问合约的(不存在的)methods
属性。如果要使用链式
call()
,则应使用方法名称作为属性(不带括号)。您还结合了
await
和回调函数then
,这可能会导致一些意外结果(但不会导致事务恢复)。有关更多信息,请参阅 docs 。
或者,您可以将 Solidity 函数标记为
view
,因为它不会将任何数据写入存储。这也将允许您将其用作ElectionInstance.getIsVoting()
函数,而无需在 Truffle 中使用.call()
。