I've just learned that one can easily obtain the return-value of a non-constant function, by using myContract.func.call()
(instead of myContract.func()
, which retrieves a response object).
Up until now, I've always added inside func
an event containing the return-value, and then parsed the response object returned from myContract.func()
in order to extract that value.
This has also been the guidance in dozens of answers across his website!
Questions:
- How is it possible that so many people here have missed this?
- Is it possibly just a tweak added in Truffle, or can one rely on it when writing an operational Web3.js script?
For the record, I am using Truffle v4.1.14, which relies on Web3 v0.20.6.
Here is the contract that I've used for testing this:
pragma solidity 0.4.24;
contract MyContract {
uint public kkk;
function func() public returns (uint) {
kkk += 100;
return kkk;
}
}
And here is the actual test:
contract("Test", function(accounts) {
it("MyContract", async function() {
const myContract = await artifacts.require("MyContract").new();
const x = await myContract.func();
const y = await myContract.func.call();
console.log(x);
console.log(y.toFixed());
});
});
Thank you!
.call()
it shouldn't create a transaction, any change should not be persistent. Are you testing with ganache or geth/parity? – Ismael Aug 26 '19 at 21:01kkk()
after everything and check its value? – goodvibration Aug 27 '19 at 4:20