One thing we haven't really talked about yet is the constructor.
It's something you need to understand before we proceed!
The constructor is a special function. It is automatically called during Smart Contract deployment. And it can never be called again after that.
It also has a special name! It's simply called constructor() { ... }.
Let's see how that works to our advantage. Let's extend the Smart Contract we wrote before to make it a bit more secure.
Securing our Smart Contract using a simple Ownership-Model¶
We are going to set a storage variable to the address that deployed the Smart Contract. Then we will require() that the person interacting with withdrawAllMoney is the same as the one who deployed the Smart Contract.
So much new stuff in there! Let's dig through it line by line:
constructor(): is a special function that is called only once during contract deployment. It still has the same global objects available as in any other transaction. So in msg.sender is the address of the person who deployed the Smart Contract
require(owner == msg.sender, "You cannot withdraw."): That might be a bit early, but this is how you trigger Errors (or throw Exceptions) in Solidity. If the require evaluates to false it will stop the transaction, roll-back any changes made so far and emit the error message as String.
Everyone can send Ether to our Smart Contract. But only the person who deployed the Smart Contract can withdraw. Secure and Smart - Let's try this!