Solidity contract clean up function

The only way code is removed from the blockchain is when a contract owner calls the self destruct operation. The remaining Ether stored in that contract are sent to a designated target and then the storage and code is removed from the state of the block chain.

Calling selfdestruct(address) sends all of the contract’s current balance to the address specified. This is useful when you are finished with a contract and want to remove if from the block chain. It costs a lot less gas than just sending the balance with address.send(this.balance).

The selfdestruct opcode uses negative gas because you are freeing up space on the blockchain by clearing all of the contract’s data. This negative gas is deducted from the total gas cost of the transaction. If you’re doing some clean-up selfdestruct can reduce your gas costs.

The function below allows one to cleanup and self destruct your contract on the blockchain. As a rebate you are with negative gas.

  //  This function allows you to clean up / delete contract
  function kill() public {
      require(msg.sender == owner);
      selfdestruct(msg.sender);
  }

Try it in Remix

For more information read the docs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Next Review – Memory vs Storage in Solidity smart contracts

Ledger Nano X - The secure hardware wallet

Leave a Reply