SelfDestruct
- It helps clearly define the contract’s exact purpose and can be used to introduce a loophole or honeypot in the contract, indicating its vulnerability.
- Example: After certain amount of ethers are collected, then it will first call a transfer function to transfer all the ether to another address and then self-destruct like it never existed.
Note:
This function is DEPRECATED starting from Cancun Hardfork, but we can still use it but it will NOT Destroy the underlying opcode in the blockchain but only transfer the ethers to the owner.
Example:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.25;
contract SelfDestructExample {
address public owner;
// Set the contract deployer as the owner
constructor() {
owner = msg.sender;
}
// Function to destroy the contract and transfer remaining ether to the owner
function destroy() public {
require(msg.sender == owner, "Only the contract owner can destroy the contract");
selfdestruct(payable(owner)); // Self Destroy the contract and transfer remaining ether to the owner
}
}
Explanation:
- The given code is just an example and it would be required to implement the functionality to collect ether, so that they can be transferred to the owner upon calling selfdestruct function
- The above code will transfer the remaining ether in the contract to the owner and will self destroy and remove itself from the blockchain.
Output:
Unlock the Power of Solidity: Exploring the Essential Keywords for Smart Contract Development
Solidity is a smart contract programming language built solely to develop smart contracts that can be deployed on blockchains. C++ and JavaScript inspired it, an Object Oriented and High-Level language (HLL), that helps developers define the behaviour and rules for a Decentralized Application (Dapp). Smart contract facilitates autonomous, secure, and efficient transaction execution on the blockchain without needing any intermediary (self-executable) and solidity provides the base framework for achieving the same.
It is essential to understand the common keywords used in solidity to solidify your core understanding of the language so in this article, we’ll pin down some prominent keywords that help us develop these smart contracts by embracing the true power of solidity language.
Table of Content
- Contract
- Constructor
- Data Types
- Delete
- Enum
- Function
- Interface
- Import
- Struct
- Visiblity Specifiers
- Exception Handling
- Pragma Directive
- License Defintion
- Modifier
- Data Location
- Global Variables
- Fallback Function
- SelfDestruct
- ‘assembly’ and ‘inline assembly’