IntoTheSolidity ~ Self Destruction Pattern

Design-Patterns-min.jpg
img ref

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Some quite known design patterns in solidity are

  • Contract Self Destruction
  • Factory Contract
  • Name Registry
  • Mapping Iterator
  • Sending ether from contract: Withdrawal pattern

In this write-up, I will be focusing on Contract Self Destruction design pattern

This patterns is quite useful in below scenario

Stop Execution -
Some times from the business prospective i.e. a Bidding contract (After the win, no more bids allowed to be placed) or a Loan contract should not accept when tenure is completed

Eliminate Bugs -
When contract has some serious bugs or we need to make it unavailable.

Lower Gas Price -
Contract can be self destruct using selfdestruct() function which takes as payable address parameter, Calling selfdestruct(address) sends all of the contract's current balance to address. This is useful when you are finished with a contract, because it costs far less gas than just sending the balance with address.send(this.balance). In fact, the SELFDESTRUCT opcode uses negative gas because the operation frees up space on the blockchain by clearing all of the contract's data.

This negative gas deducts from the total gas cost of the transaction, so if you're doing some clean-up operations first, SELFDESTRUCT can reduce your gas costs.

Points to Note :

  • SELFDESTRUCT is an opcode in EVM
  • It was known as suicide opcode, which has become selfdestruct in the meantime as per EIP6.
  • All available funds will be sent to the payable address provided in selfdestruct function.
  • New transaction cannot be created for destroyed contract
  • Contract data will be cleared and will no more available so make a backup accordingly before destructing the contract
  • Sending funds to any destroyed contracts will lead to loss of funds, to Prevent funds loss
    • Developer should remove all the reference to dead contract from dapps
    • Call a getter function to make sure the contract is not dead.

Sample code can be found here.
https://github.com/devrajsinghrawat/Web3nSolidity/blob/master/SampleCodeSnippets/DP_SelfDestruct.sol

Testing the contract

Interesting related Fact

There was a famous Parity hack on accidently calling selfdestruct function on library used in Parity Technologies Multi-Sig Wallet

https://medium.com/firmonetwork/3-famous-smart-contract-hacks-you-should-know-dffa6b934750

Hope you enjoyed the write-up, Do let me know you view or if any corrections in comments sections.

#0xDev

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center