DEV Community

Cover image for tutorial - Delete a contract using selfdestruct()
Yongchang He
Yongchang He

Posted on

tutorial - Delete a contract using selfdestruct()

This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of Solidity.
The purpose of building this blog is to write down the detailed operation history and my memo for learning the dApps.
If you are also interested and want to get hands dirty, just follow these steps below and have fun!~

Prerequisites

  • Remix

getting started

Contract description

There is a function called selfdestruct() in solidity. When the function is being called, the contract that contains the function selfdestruct() will be deleted from the blockchain. The function then forces send ETH back ether to the contract owner, or to a contract address specified by the owner, even if the contract doesn't have a fallback function.

See the following example:


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Kill {
    constructor () payable {}
    fallback() external payable {}
    receive() external payable {}

    function kill () external {
        selfdestruct(payable(msg.sender));
    }
    function testCall() external pure returns (string memory) {
        return "Tst called";
    }
    function contractBal() external view returns (uint) {
        return address(this).balance;
    }
    function ownerBal() external view returns (uint) {
        return msg.sender.balance;
    }
}

contract Helper {
    function getBalance() external view returns (uint) {
        return address(this).balance;
    }
    function kill(Kill _kill) external {
        _kill.kill();
    }
}
Enter fullscreen mode Exit fullscreen mode

The first contract Kill has receive() and fallback() function, which enable the contract to send and transfer ETH to another address. function kill() contains selfdestruct(), which will 'kill' the contract Kill. Function testCall(), contractBal() and ownerBal() return a string, contract ETH balance and owner ETH balance respectively. But the three function will be disfuntional after kill() being executed.

The second contract Helper can be able to 'kill' the contract Kill without having a fallback function, and Helper will receive the ETH balance of contract Kill after it being terminated.

Test contract using Remix

  • 1. Contract Kill

Before kill() being executed:

Image description
After kill() being executed:

Image description

  • 2. Contract Helper

After kill() being executed, the balance of contract Kill is transfered to Helper:

Image description

Top comments (0)