0

So I have been looking at solidity recently and got a hold of the voting app. Pretty simple to get a hold of. But here is what I am confused about (coming from the background of developing for the web/mobile):

In the context of a simple solidity based voting app that is holding the votes for a proposal

  1. One can increase the vote when the method call is made. But there seems to be no explicit call to the 'blockchain' (and in that I am treating it like a database) to persist it. So does the EVM automatically write to the blockchain every-time I change a variable's value to the blockchain or does it do that once the function call ends and variable values have been finalized.

  2. How does it decide which variables are to be written to the blockchain and which aren't. I might be using a simple counter variable (i=0) to keep track of a loop, say break out of the loop if it gets executed more than a 100 times. The counter is something I don't intend to persist to the blockchain.

    1. In some places it has also been suggested that a state is maintained inside a smart contract, if so how can the state be same for multiple users using the same application?
2

Smart contracts have storage, which is persistent state. In Solidity, "state variables" are declared at the contract level and refer to locations in storage.

By default, variables declared within a function are located in memory. Memory is not persisted.

Consider the following example code:

contract Test {
     uint256 counter;

     function increment(uint256 times) public {
         for (uint256 i = 0; i < times; i++) {
             counter += 1;
         }
     }
}

Here, counter refers to location 0 in storage, so any changes to it during a transaction are persisted in the blockchain.

The loop variable i exists only in memory, so it does not affect storage.

To answer your individual questions:

  1. State, persisted in the blockchain, is persisted when you modify a value in storage.
  2. I covered this a little, but https://solidity.readthedocs.io/en/v0.4.23/types.html#reference-types might help with the details of variable locations. (You might want to read that entire chapter.)
  3. Yes, state is sort of maintained "inside" a smart contract. It's attached to that contract (that address), so all users interacting with it will see the same state.

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.