Hi @omkar_c,
You don’t need to do it that way. It is a more long-winded (or some would say more clearly broken-down step-by-step) version of the following equally valid solution:
selfdestruct(msg.sender);
We can use msg.sender
to reference the contract owner’s address, because the onlyOwner modifier restricts access to the destroy() function to the contract owner, and so msg.sender
can only ever be the contract owner address anyway.
In Solidity v0.7, msg.sender
is a payable address type by default, and so there is no need to explicitly convert it whenever we need it to be payable, e.g. in selfdestruct() . However, in Solidity v0.8, msg.sender
is now non-payable by default, but instead of converting it to a payable address via a separate variable, we can perform the conversion within the selfdestruct() function call itself…
selfdestruct(payable(msg.sender));
Alternatively, you can reference the owner
variable by either:
(1) Declaring the owner
state variable in Ownable with a payable address type, instead of with the default, non-payable address type; or
(2) If you only need this address to be payable for the purposes of executing selfdestruct(), you can leave the owner
state variable as non-payable, and explicitly convert the address to payable locally, within the function where you actually need to use it as payable. You can even do this directly within the selfdestruct() function call itself, as follows:
function destroy() public onlyOwner {
selfdestruct(payable(owner));
}
Have a look at this post for further details about the use of a separate receiver
variable in the model solution.
And just to clarify… we are not destroying the contract owner’s address. We’re destroying the smart contract. The owner’s address is passed to selfdestruct() because, as well as destroying the contract, calling selfdestruct() will transfer the contract’s remaining ether balance to its mandatory payable address parameter. To receive ether an address must be payable.
Let me know if anything is unclear, or if you have any further questions.