🚗 #GateSquareCommunityChallenge# Round 1 — Who Will Be The First To The Moon?
Brain challenge, guess and win rewards!
5 lucky users with the correct answers will share $50 GT! 💰
Join:
1️⃣ Follow Gate_Square
2️⃣ Like this post
3️⃣ Drop your answer in the comments
📅 Ends at 16:00, Sep 17 (UTC)
Comprehensive Guide to Upgrading Rust Smart Contracts: From NEAR to Security Considerations
Rust Smart Contracts Upgrade Practice
Smart contracts are essentially programs and inevitably have flaws. Even after extensive testing and auditing, there may still be vulnerabilities. Exploitation of contract vulnerabilities can lead to significant user asset losses. Fixing vulnerabilities and adding new features require contract upgrades. Therefore, the upgradability of contracts is very necessary. This article will introduce the upgrade methods for Rust contracts.
NEAR Contract Upgrade Method
Taking the StatusMessage project as an example, this introduces common upgrade methods for NEAR smart contracts.
1. The contract data structure has not been modified.
If only the contract logic is modified, without involving changes to the data structure, you can directly use near deploy to redeploy the new code. The data in the original contract can be read normally.
2. The contract data structure has been modified.
If the data structure of the contract is modified, directly redeploying will cause a mismatch between the old and new data structures, making it impossible to read the original data.
3. Use Migrate to upgrade smart contracts
NEAR provides the Migrate method to assist with contract upgrades. Add the migrate method in the new contract:
rust #[private] #[init(ignore_state)] Self { let old_state: OldStatusMessage = env::state_read().expect('failed'); Self { taglines: old_state.records, bios: LookupMap::new(b'b'.to_vec)((, } }
Call the migrate method when redeploying:
near deploy
--wasmFile target/wasm32-unknown-unknown/release/status_message.wasm
--initFunction 'migrate'
--initArgs '{}'
--accountId statusmessage.blocksec_upgrade.testnet
This will successfully migrate the old contract data to the new contract.
![])https://img-cdn.gateio.im/webp-social/moments-73f5e5195fa71f1f25f5d35ba1e8b8ec.webp)
Security Considerations for Contract Upgrades
The upgrade function should be an only owner function to ensure that it can only be called by the owner.
It is recommended to set the contract owner to DAO, and manage it together through proposals and voting.
Add #[init(ignore_state)] before the migration function.
Delete the migration function after the migration is complete.
The new data structure is initialized during migration.
Contract upgrades are an important means of ensuring contract security. Developers need to treat them with caution and ensure the safety of the upgrade process.