Sample Smart Contract
Before we begin, letās setup a sample Smart Contract. Just enough to get something working for us to have a simplistic example.
Create a new file in Remix. Iāve named mine āStartingStopping.solā, but obviously, you can name your file any way youād like.
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.1;
contract StartStopUpdateExample {
function sendMoney() public payable {
}
function withdrawAllMoney(address payable _to) public {
_to.transfer(address(this).balance);
}
}
What does it do?
We have two functions:
sendMoney()
: This function can receive Ether, itās a payable function.
withdrawAllMoney(...)
: Very similar to our previous example, this function will automatically withdraw all available funds stored at the address of the Smart Contract to the variable in the as function argument given address. What a sentence! In other words: It sends all Ether to the ā_toā address.
Deploy the Smart Contract
Letās deploy the Smart Contract to the āJavaScript VMā in Remix. Head over to the āDeploy & Run Transactionsā Plugin and hit Deploy:
Perfect! Letās try to send some Funds around!
Use the Smart Contract
As before, weāre going to:
- Send Money to the Smart Contract using Account #1
- Withdraw the Money using any other Account
Already sounds scarily unsecure. If you come from traditional backend development, you should shiver now. But worry not, weāll get to safe heavens soon!
Alright, so, start by sending some funds to the Smart Contractā¦
- Enter 1 Ether into the value field:
- send it to the āsendMoneyā function of your Smart Contract:
- Select the second Account in the Accounts-Dropdown:
- Copy the Address:
- Paste the Address into the āwithdrawAllMoneyā input field:
-
Click the āwithdrawAllMoneyā button.
-
Have a look if you have >100 eth in your Account #2 of the Accounts-Dropdown:
So, just to summarize how insecure that is:
- Someone funded the Smart Contract
- But everyone can withdraw to any address of their choice?
That sounds pretty bad, right?
We can do better than that!!! In the next exercise weāre going to restrict withdrawals to the person who owns the Smart Contract.
Want to give it a try yourself? Great idea!
So, hereās what you need:
-
A variable that stores the address of the person who deployes the Smart Contract.
-
a constructorā. This getās called when the Smart Contract is deployed. Itās named
constructor() {...}
. Inside you set the address to the msg.sender. -
a require in the withdrawAllMoney function. Weāre talking about Exceptions later in the course extensively, so donāt worry too much about the internal workings. Make sure that the Address that calls the withdrawAllMoney function is the same as stored in the variable that is set by the constructor.
Alright, off to the solution: next page!