header-langage
简体中文
English
Tiếng Việt
Scan to Download the APP
Partnered With:

Simple Introduction to Solidity|Lecture 26: Delete Contract

Read this article in 4 Minutes
selfdestruct is the emergency button of the smart contract, which destroys the contract and transfers the remaining ETH to the designated account.
Original title: "Introduction to Solidity Minimalist: 26.  Delete Contract"
Original author: 0xAA


I recently Re-learn solidity, consolidate the details, and write an "Introduction to Solidity Minimalist" for beginners (programmers can find another tutorial), update 1-3 lectures every week.


All codes and tutorials are open source on github: github.com/AmazingAng/WTFSolidity


selfdestruct


The selfdestruct (self-destruct) command can be used to delete the smart contract and transfer the remaining ETH of the contract to the specified address. selfdestruct is designed to handle corner cases where contracts go wrong. It was originally named suicide, but the word was too sensitive. Renamed to selfdestruct to protect depressed programmers.


How to use selfdestruct


selfdestruct is very simple to use:



Where _addr is the remaining ETH in the receiving contract the address of.


Example  


< img src="https://image.blockbeats.cn/upload/2022-09-08/c2642344b9ce628b335d5e17bc56c012a2165fb3.png?x-oss-process=image/quality,q_50/format,webp">


In the DeleteContract contract, we wrote a public state variable value, two functions: getBalance() is used to obtain the contract ETH balance, deleteContract( ) is used to self-destruct the contract and transfer ETH to the initiator.


After deploying the contract, we transfer 1 ETH to the DeleteContract contract. At this time, getBalance() will return 1 ETH, and the value variable is 10.


When we call the deleteContract() function, the contract will self-destruct and all variables will be cleared. At this time, the value becomes the default value of 0, and getBalance() also returns empty value.


Summary


selfdestruct is the emergency button of the smart contract, which destroys the contract and transfers the remaining ETH to the specified account. When the famous The DAO attack happened, the founders of Ethereum must have regretted not adding selfdestruct to the contract to stop the hacker's attack.


Original link


Welcome to join the official BlockBeats community:

Telegram Subscription Group: https://t.me/theblockbeats

Telegram Discussion Group: https://t.me/BlockBeats_App

Official Twitter Account: https://twitter.com/BlockBeatsAsia

举报 Correction/Report
Choose Library
Add Library
Cancel
Finish
Add Library
Visible to myself only
Public
Save
Correction/Report
Submit