The following contract shows how to use selfdestruct
, in this example the usage is restricted to the owner of the smart contract :
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Destruct {
address owner;
modifier onlyOwner() {
require(msg.sender == owner, "Not the owner");
_;
}
constructor() {
owner = msg.sender;
}
function callSelfDestruct() onlyOwner public {
selfdestruct(payable(owner));
}
}
I'm building projects to learn solidity, and I currently want to build
a smart contract which I can kill if I need to.
While maintaining a clean state is a good thing (i.e., selfdestruct
the contracts that won't see any more usage to free some space on the global state) you should also be aware that this will most definitely be seen as a security risk by potential users.
I found the selfdestruct() function but I'm a bit confused about how
it works
selfdestruct
is very particular in the blockchain space, basically when called it will forward all the contract balance to the target address specified in its arguments (owner
in the example above). This balance forwarding will bypass every check, will not trigger any receive()
or fallback()
. So no matter what type of account is behind the target address, its balance will be increased by the self-destructing contract's balance.
When the tx is committed to the state (that is after its execution is finished) the contract's code will be removed from the global state, it's not disabled, it's deleted.
how can I activate the selfdestruct() function when I want to?
You must include the call in your contract's code, as in the example above.
Following this example, whenever the owner wants to selfdestruct
the contract, it must call the callSelfDestruct
function.
On a side note, you should be aware that there are ongoing effort to remove / disable the selfdestruct
behavior, do not rely on it working in the future.
I hope that answers your question.