9

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?

Dave Sag
  • 879
  • 1
  • 11
  • 22
  • 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 07:22

1 Answers1

10

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.

pabloruiz55
  • 7,686
  • 2
  • 17
  • 38
  • I'm using call because solcov wants me to. Something to do with how it instruments solidity code. – Dave Sag Dec 17 '17 at 10:44
  • Small internet. Just wasted a lot of time on that, woke up, fresh mind, now I understand the issue :) https://ethereum.stackexchange.com/questions/16796/truffle-console-how-can-i-get-and-print-the-value-returned-by-a-contract-funct – Mars Robertson Jul 12 '18 at 07:44