New to blockchain software development? Read my beginners guide here

What is self-destruct in Solidity

Last updated on December 2022. Created on May 2022 β€’ Tags: ethereumsolidityguides

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!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? πŸ“§

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.