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.
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);}
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);}}
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 contract
and name the smart contract testSelfdestruct
.
Line 4: We declare a state variable of type address payable
named owner
and 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 an external
function visibility, which all Solidity functions must possess. Inside this function, we use the selfdestruct
keyword and pass in the earlier declared owner
variable. When killContract
is called, all the Ether left in the contract is sent to owner
and the contract is removed from the blockchain.