contract-development – How Smart Contracts Persist Data and Upgrade Code

blockchaincontract-deploymentcontract-developmentstorage

I have finished a course on solidity and the blockchain itself and there are some concepts I don't have clear yet. Could anyone confirm these assumptions?:

  1. When we deploy a smart contract, its code becomes immutable but a chunk of memory is assigned to it that is the so called storage memory.
  2. When someone wants to make a call to a contract function, a new transaction is queued into the trasaction pool for someone to "execute it" (By incluiding it in a mined block in POW). When a miner does this, the contract funcion is executed and it could change the state of the contract (storage memory we talked before).

Beside these 2 questions there's one about updating contracts that I'm confused about:

If we want to update our contract, we can't update the contract code we deployed before because it is inmutable. So, a new contract must be deployed and a new address for the contract will be generated. But, what happens with all the data (storage) we had in the previous contract? Is it all lost? Is there anyway to migrate it to the new contract?

Best Answer

For the first 2 question, here is what I know:

  1. Yes and no, when you create a new contract, you send the bytecode of that contract to the ethereum so everybody will know about the contract so you can store the contract bytecode elsewhere with geth. So technique the bytecode is always on the ethereum through the contract creation transaction, but you will have to store the contract bytecode elsewhere or you will have to lookup the first transaction that the contract was created. (resource: https://ethereum.stackexchange.com/a/69651/50595)
  2. This already answered your question: https://ethereum.stackexchange.com/a/66463/50595

For extra question: like you say above the contract is immutable, meaning once it is on the blockchain, you can't remove it, the bytecode will stay there forever. The only way to migrate to new contract is that you tell everyone to move to the new address. SO BE EXTRA CAREFUL ABOUT SECURITY FOR SMART CONTRACT. I always imagine that I am coding a millions dollar firmware more than just a simple smart contract.

P/S: If you want your contract to be upgradable you can follow this tutorial: https://simpleaswater.com/upgradable-smart-contracts/. I don't like upgradable smart contract much but your choice.

Related Topic