I am new to Blockchain. I want to call a function to read a variable from contract. My contract
bool public isVoting = false;
function getIsVoting() public returns (bool) {
return isVoting;
}
At client, i call like this
const isVoting = async () => {
const _isVoting = await ElectionInstance.methods
.getIsVoting()
.call()
.then(console.log);
};
then i got the error but did not know why :
{
"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: revert\n 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"
}
}
Unlike web3, Truffle doesn't use the methods
keyword. The call fails because it's trying to access (non-existing) methods
property of the contract.
You should use the method name as a property (without the parenthesis) if you want to use the chained call()
.
You're also combining await
and callback function then
, which can cause some unexpected results (but not the transaction revert).
See the docs for more info.
Optionally, you can mark the Solidity function as view
because it doesn't write any data to storage. This will also allow you to use it as ElectionInstance.getIsVoting()
function without using .call()
in Truffle.
function getIsVoting() public view returns (bool) { // added `view`
return isVoting;
}
const _isVoting = await ElectionInstance
.getIsVoting // no parenthesis
.call();
// no `then`