Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 30, 2022 03:35 pm GMT

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: MITpragma 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();    }}

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


Original Link: https://dev.to/yongchanghe/tutorial-delete-a-contract-using-selfdestruct-5809

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To