0

I am not sure if I asked right. What I don't understand is if a tx changes value of a state variable , it has to be mined and confirmed and brodcasted to network in order for the rest of network to know it. But that is a rather long time. So what happens to other write function calls that do something with that state variable in meantime?

int balance=10; 
function change()
{
if(balance>=10) balance=balance-10;

}

if you invoke change twice within 1 sec what will happen? It seems like balance can go -10.

1

Ethereum has a "World state" that is a sort of snapshot of every contract ever created. This state is recorded in every block.

Miners start mining from the previous mined block and execute all transaction sequentially. Every transaction executes on a well known World state, and every change is recorded in it. The final state after executing all block's transactions is recorded in its header.

In the example it will work like this

  1. On contract deployment balance = 10 is recorded in the world state.
  2. On first transaction execution balance = 10 so contract flow will enter if section and evaluate balance = balance - 10, result balance = 0 is recorded in the world state.
  3. On second transaction balance = 0, since balance >= 10 is false it doesn't execute the decrement operation.
3
  • "On second transaction balance = 0" but it won't be 0 in time. just assume second transaction request was made to a far away node . that node stil thinks balance =10 because it hasn't received the block that will contain the first transaction
    – lazyCoding
    Oct 30 '20 at 10:01
  • @lazyCoding In this case one of them will execute first (balance = 10), and then the other one (balance = 0). Ethereum mantains the consistency of the "World state" it is not possible that both transactions execute with balance = 10. If that happens there will be a fork in the blockchain, and by Ethereum consensus mechanism one of them will be the main chain after several blocks. The discarded transaction then can be applied again over the main.
    – Ismael
    Oct 30 '20 at 13:39
  • 6 months later I will accept this answer. At the time I didin't quite understand because my ethereum knowledge was very limited back then. but now I know it is indeed the right answer. What confused me was that I thought the nodes were executing transactions independantly which would be ridicioulus. All nodes have to oparate on the last block which includes -the hash of - the very latest version of "World State" which means it will know balance=0.
    – lazyCoding
    Mar 18 at 13:59

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.