I understand that web3 smart contracts are decentralised and the code once written cannot be updated. They are immutable. Imagine my app stores user profile in a smart contract. It has name in it for now. Let's say we want to update the smart contract and now it takes not only name but also profilePictureURL. How do I go about it? In a traditional web2 setup, I would run migrations or update the schema for the table. How do things happen in web3 for updates in smart contract schema? Thank you
2 Answers
Immutability doesn't mean you can change the data inside, it means you can't change the code.
To change the name you need to include a setter function.
For example:
string name = NaMe;
function changeName(string calldata _name) external {
name = _name;
}
Now if you didn't include this function before deployment, then that's a problem as the code is immutable.
-
Hey Thanks for the reply. I understand that we can store data in a smart contract. However, the question is how can I change the state variables of the contract. Like adding a new state variable in the smart contract. What's the strategy there? Oct 16 at 5:16
-
No, you can't add new variables in a smart contract. You can only modify the existing. One way to add more variables is having upgradeable proxies, but those come with a higher risk of attacks. Oct 16 at 6:03
To update contracts you can consider upgradeability in contracts
Refer this: https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Proxy
This way you will be able to add new functions and state variables to the same contract without redeploying.
But you have to be careful about this approach, as you cant remove already initialised states & add new states at the end to maintain the storage. If you are using hardhat... this should help: https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable
Also u can ask here to other solidity devs, they are very active - https://t.me/blockchainworldCo