I have a simple solidity smart contract with method like:
function foo(uint a) public {
b = bytes32(1);
emit Event(a, b);
emit Event2(a, b);
}
(full code is here: https://remix.ethereum.org/#optimize=false&version=soljson-v0.4.25+commit.59dbf8f1.js)
and invoke it using web3.js code :
contract = testContract.at('xxxAddress')
// contract.foo(6); // Failed, Why?
//Success
contract.foo.sendTransaction(6, {from: eth.accounts[1]},function(error, result) {
console.log("Got err:", error, ", result: ", result)
}
);
but, why straightforward contract.foo(6) failed? Can any expert explain it?
The call to a function that modifies the blockchain needs to send as a transaction since it requires gas to run. This is why you need to send a transaction and not just call the function. You can find more about it here.