TransWikia.com

State Variables: What are they and how to create them?

Ethereum Asked by Zephyrus on August 26, 2021

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?

One Answer

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.

Correct answer by Rob Hitchens on August 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP