The Constructor
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.
Extend our Smart Contract:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.1;
contract StartStopUpdateExample {
address public owner;
constructor() {
owner = msg.sender;
}
function sendMoney() public payable {
}
function withdrawAllMoney(address payable _to) public {
require(owner == msg.sender, "You cannot withdraw.");
_to.transfer(address(this).balance);
}
}
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!
Testing our new Smart Contract
Weāre going to do the following:
-
Deploy the new Smart Contract
-
Send Ether to the Smart Contract
-
Try to use another Account to withdraw
Note: Donāt switch back, use the other Account to call withdrawAllMoney
-
Observe the Error Message
-
Switch back to the original Account
Note: I used the second account in my account-dropdown to deploy the Smart Contract, so I am switching back to this one
-
Withdraw and see it works
Amazing, right! A very simplistic access rule that denies access to anyone except the one who deployed the Smart Contract.
Of course, you can spin that further. You can create a whole Access Model around this. OpenZeppelin did this in their Ownable Modelsā
So, whatās next? Letās see if we can pause our Smart Contract!
The Ethereum Virtual Machine has no functionality to pause Smart Contracts on a protocol-level. So, we need to think of a solution āin codeā.
Can you think of something? Maybe a boolean that pauses any deposits and withdrawals when itās true?
Give it a try!
Alright, off to Pausing Smart Contractsā¦