10-Terminate a contract and remove the code

When you deploy a smart contract, you need to lock some tokens to store the source code on the blockchain.

By example, in this wallet, 226 ASTR are reserved for the storage of the source code of several smart contracts.

If you deployed a wrong version of the smart contract or if you upgraded your smart contract, many tokens may be locked for unnecessary source code and you can unlock them by removing the unnecessary source code from the blockchain. In this tutorial, we will see how we can do it.

Terminate the existence of the smart contract

You cannot remove the source code from the blockchain if there is ongoing smart contract using this source code.

You must use the ink_env::terminate_contract function to termine the existence of the smart contract.

pub fn terminate_contract<E>(beneficiary: E::AccountId) -> !where
    E: Environment,

This function removes the calling account and transfers all remaining balance to the given beneficiary.

Note: This function never returns. Either the termination was successful and the execution of the destroyed contract is halted. Or it failed during the termination which is considered fatal and results in a trap and rollback.

Note: Only authorized user or the contract owner should be able to terminate the contract. See the tutorial https://polkaverse.com/11143/6-security-and-access-control-with-open-brush-38539 to manage permissions.

After terminating the contract, the contract address will not be found anymore in Contracts-UI

But all past transactions will be keep on the blockchain and can be listed on subscan.

Remove the source code from the blockchain

You can use the function removeCode from the Contracts pallet to remove the code stored under the code hash and refund the deposit to it’s owner.

Found the code hash linked to your contract

When you deploy a smart contract, you can see the code hash in Contracts UI

or you can use subscan to find it.

Conclusion​

Terminating a contract and removing the code from the blockchain is a part of the life cycle of smart contracts and allows developers to unlock the token reserved for the storage of the unnecessary source code.

Git repository

https://github.com/GuiGou12358/astar-tutorials/tree/main/tuto6

Source

https://docs.rs/ink%5Fenv/4.3.0/ink%5Fenv/fn.terminate%5Fcontract.html

0
GuiGouPost author

Crypto-enthusiast, Defi & NFT believer, Dotsam Fam Astar Tech Amb & Phala Amb Web2 builder gradually migrating to Web3

Tutorials to write Smart Contracts in Rust and Ink!

0 comments

Tutorials to write Smart Contracts in Rust and Ink!