Blockchain Development — Day 3

In the last article, “Understanding variables in Solidity” we looked at a number of variables, in particular the Address. In this article, we are going to demonstrate an example of a smart contract that will we can send money to, check it’s balance and then withdraw the money to an address only if the address calling the function is the owner, commonly known as the Owner Model.

Creating a smart contract with an Owner

Create a new file, name it MySmartContract.sol and add the licence and version statements.

Create an address variable to store the owner of the contract

Next we will create a constructor that stores the address that deployed the contract as the owner. A constructor is a special function that is only called once when the contract is deployed. We will use the msg object’s sender property.

Go ahead and save the contract, compile and deploy. Click the contractOwner button to see the address that deployed the contract is now the owner.

Send money to smart contract

Next, we are going to create a function that allows any address to send money to the contract.

We can use the keyword payable to specify that the function can receive Ether.

In the getBalance function, the keyword thisrefers to this class (MySmartContract).

Go ahead and deploy the contract and test you can send ether to the contract and check the balance of the contract

Withdraw all money from smart contract

Now, create a withdrawAll function that passes the address we wish to send the money too.

Deploy and test out the contract. You will notice that anyone can run this withdrawAll function. Lets only allow to sendcontract owner to execute this function. We use the requireto check for conditions and throw an exception if the condition is not met. In this case, we check that the address calling the function is the same as the contract owner. If it fails, it will rollback the transaction. This contract now meets the Owner model where it checks if address calling the function is the owner before allowing it to proceed further.

That’s covers this simple smart contract that allows money to be sent to it, and only allows the owner to withdraw all the money from the smart contract.

If you found this article helpful, please give me a Clap, as this brightens my day knowing I may have helped someone in their journey in making stuff! Also if you want to be notified for future releases in this series, “Follow” me. You may also send me a message if you need any further help.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jean-Noel Seneque

Jean-Noel Seneque

179 Followers

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com