Contract destruction

At this final step, let's have some fun.

What about introducing a nuclear launch button in our contract that, once pushed by the auction owner, will make the contract disappear from the blockchain? The contract destruction will be ensured by the destruct_auction() method, which can be invoked if all participants have withdrawn their bids, as follows:

function destruct_auction() external only_owner returns (bool) {
require(now > auction_end, "You can't destruct the contract,The auction is still open");
for (uint i = 0; i < bidders.length; i++)
{
assert(bids[bidders[i]] == 0);
}
selfdestruct(auction_owner);
return true;
}

The first thing that we can see here is that Solidity defines for-loops like standard languages, and you can access the length of a dynamic size array by using the .length member. 

More importantly, Solidity defines a special function, selfdestruct(address), to destroy the current contract (it will no longer be accessible) and send all its funds to the address given as the argument. This is a space- and cost-saving feature as, when you are finished with a contract, it will cost you far less gas using selfdestruct than just sending the contract funds using address.transfer(this.balance).

But wait! Isn't the blockchain immutable?

The answer needs a little dive into the Ethereum block structure, which is out of the scope of this book. However, it's worth noting that the selfdestruct method clears all the contract's data, and frees up space from the current and future state tree (the mapping between the contract's account and its states), but not from the previous blocks. The contract bytecode will remain in an old block but its account will no longer be accessible in the state tree; therefore, the data is still immutable. In other words, after calling selfdestruct, the state tree will be updated without the destroyed contract states.

In old Solidity code, you will notice the use of the suicide(address recipient) method, which is used as an alias to selfdestruct.

 All set! We have finished our auction smart contract. Now let's enjoy compiling and running our first achievement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset