What is self-destruct in Solidity
A guide on Solidity's selfdestruct function
Table of Contents for What is self-destruct in Solidity
Update: Dec 2022 - selfdestruct is being deprecated
There is a function in Solidity that is used to destroy a contract.
As well as destroying the contract, selfdestruct
will send any remaining ether balance in that contract address and send it to another (specified) address.
Example of using selfdestruct in Solidity
The following contract shows an example of how to use the self-destruct functionality in Solidity.
It sets up an address (whoToPayOnDestruct
) when the contract is deployed. Then when killContract()
is run, it will self-destruct and send any ether to the address in whoToPayOnDestruct
.
pragma solidity ^0.8.14;
contract ExampleContract {
address whoToPayOnDestruct;
constructor(address _whoToPayOnDestruct) {
whoToPayOnDestruct = _whoToPayOnDestruct
}
function killContract() public {
selfdestruct(payable(whoToPayOnDestruct));
}
}
Note that even after calling self-destruct, the contract data/history is still on the blockchain.
History of the selfdestruct function
Originally the opcode for selfdestruct in the EVM was called SUICIDE
. However, this was changed in EIP-6.
Use selfdestruct to send eth to a smart contract, even if it has no receive() or fallback() function
Some deployed smart contracts are written in a way which makes it hard to send ether to. For example if they have no payable
functions, and no receive()
or fallback()
function.
In those cases you can use selfdestruct()
to send eth to them.
Further resources on selfdestruct in Solidity
Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!
Next post
π Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
β½ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
π§ͺ Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
π Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
π Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
π¦ Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about