Skip to main content

Command Palette

Search for a command to run...

Self Destruct

Published
2 min readView as Markdown
Self Destruct

Self Destruct

  1. In Solidity, the selfdestruct function is a built-in function that allows a contract to be destroyed and its remaining Ether to be sent to a designated address.

  2. The selfdestruct function takes one argument, which is the address where the remaining Ether will be sent. After the selfdestruct function is called, the contract will be removed from the blockchain and its storage will be cleared.

Here's an example of how selfdestruct can be used:

contract MyContract {
    address payable public owner;

    constructor() {
        owner = payable(msg.sender);
    }

    function close() public {
        require(msg.sender == owner, "Only the owner can close this contract");
        selfdestruct(owner);
    }
}
  1. In this example, the MyContract contract has a close function that can be called by the owner of the contract to destroy it and send its remaining Ether to the owner's address. The require statement ensures that only the owner can call the close function.

  2. When the selfdestruct function is called, the remaining Ether in the contract is sent to the owner address. After the selfdestruct function is called, the contract is removed from the blockchain and its storage is cleared.

  3. It's important to note that calling the selfdestruct function is a permanent and irreversible action. Once a contract is destroyed, it cannot be recovered, and any data stored in the contract will be lost. Therefore, the selfdestruct function should be used with caution and only when it is necessary to do so.

More from this blog