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();
}
}
The first contract Kill has
receive()
andfallback()
function, which enable the contract to send and transfer ETH to another address. functionkill()
containsselfdestruct()
, which will 'kill' the contract Kill. FunctiontestCall()
,contractBal()
andownerBal()
return a string, contract ETH balance and owner ETH balance respectively. But the three function will be disfuntional afterkill()
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:
- 2. Contract Helper
After kill()
being executed, the balance of contract Kill is transfered to Helper:
Top comments (0)