5

I'm using Truffle 4.0.1 and Node 9.2.1

In my solidity smart contract I have a function

function finalize() public onlyOwner {
    require(!isFinalized);

    finalization(); // does some stuff
    Finalized();

    isFinalized = true;
}

In my test I have the following

await contract.finalize.call()
const isFinalized = await contract.isFinalized.call()
console.log('isFinalized', isFinalized)

which outputs

isFinalized false

If I change my code to read

const tx = await contract.finalize()
const isFinalized = await contract.isFinalized.call()
console.log('isFinalized', isFinalized)

then it outputs

isFinalized true

Why is there a difference?

  • not really a duplicate as my context is more about testing, although that question does explain what's going on, so thanks. – Dave Sag Dec 12 '17 at 7:22
2

In the first example, when you execute await contract.finalize.call() using call() executes the function without modifying the state, which makes the changes to state variables being made inside the function call "not getting saved".

You should use .call() to execute constant/view/pure functions that don't modify state variables. With truffle you can even forgo the .call().

If the Solidity function is marked as view/constant/pure, truffle will know you are trying just to read a value and not modifying anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.