What is the self destruct operation in Ethereum?
Ethereum
Ethereum is the first blockchain to implement smart contracts which are programs and deployed to the blockchain. They are saved at a particular address and executed when defined conditions are fulfilled.
Code deployed to the Ethereum blockchain (smart contract) can either be written in the Solidity or Vyper programming languages. In this Answer, we'll talk about the self destruct operation in Solidity.
Solidity is heavily inspired by other programming languages such as Javascript, C++, and Python. However, it has some distinct features which separate it from these languages. One such feature is the self destruct operation.
The self destruct operation is used to remove code from the blockchain or to delete smart contracts from the blockchain. When using the self destruct operation, it is important to note that:
The history of the smart contract still remains on the blockchain.
Further interaction with the contract is impossible.
Ether can be sent to a specified target after executing the self destruct operation on a contract.
Note: Extreme care must be taken when using the self destruct operation.
Syntax
The self destruct operation is done using selfdestruct keyword, which is wrapped in a function. The selfdestruct keyword takes a single parameter of type address payable , to which it sends the remaining Ether balance in the contract. The code syntax is as follows:
function killContract(address payable someAddress) external {selfdestruct(someAddress);}
Example
Let’s check out an example of how the self destruct operation works. Below is a sample Solidity code that receives Ether and has a self destruct function.
//SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.5.0;contract testSelfdestruct {address payable owner = payable(msg.sender);receive() external payable{}function killContract() external {selfdestruct(owner);}}
Explanation
Line 1: We state the SPDX license identifier as unlicensed.
Line 2: We tell the compiler that our code will compile with solidity version 0.5.0 or higher.
Line 3: We declare a smart contract with the keyword
contractand name the smart contracttestSelfdestruct.Line 4: We declare a state variable of type
address payablenamedownerand set it to the address that connects to the contract.Line 5: This line makes sure that this smart contract can receive Ether.
Lines 6-8: We declare a function named
killContract. This function doesn't take any parameters and has anexternalfunction visibility, which all Solidity functions must possess. Inside this function, we use theselfdestructkeyword and pass in the earlier declaredownervariable. WhenkillContractis called, all the Ether left in the contract is sent toownerand the contract is removed from the blockchain.