1

I am new to ethereum and Solidity.

I thought state variables are supposed to retain their value between calls.

In the Solidity documentation, in the section State Variables, it says that state variables are created like this:

contract SimpleStorage {
    uint storedData; // State variable
    // ...
}

I created the following contract to test the theory.

contract Test {
    uint256 times_called;

    function tc () public returns (uint256) {
        times_called += 1;
        return times_called;
    }
}

I am calling it with web3 like this:

const test = new web3.eth.Contract (contract_abi, contract_address, { from: from_address, data: contract_bytecode });
var value = await test.methods.tc ().call ();

It returns 1 every time.

Have I not declared a state variable here? Or am I mistaken about how state variables are supposed to work?

2

In this code:

contract Test {
    uint256 times_called;

    function tc () public returns (uint256) {
        times_called += 1;
        return times_called;
    }
}

times_called is a state variable because it is (correctly) declared in the global section. (There are other ways but this will do for now because you are early in your journey).

State variables are persistent. Their storage is laid out when the contract is compiled, so each variable has a "slot" on the chain where the value will persist.

The reason you are getting 1 is that you are using .call() on the client side. This is a client-side instruction that tells it to use the function on a read-only basis. So, even though the contract is correct, you are not getting the state-change you expect.

This is a confusing topic, so have a look over here: https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2

Hope it helps.

| improve this answer | |

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.