How to Code Your First Smart Contract with Solidity

daltonic

Gospel Darlington

Posted on April 15, 2022

How to Code Your First Smart Contract with Solidity

Code Your First Smart Contract

Introduction

I get it, you have heard a lot of vibes from the web3.0 world, everyone is talking about it. Your friends are planning on learning this technology and you are not sure how to go about it. You went online to see how to get started and all the guys on YouTube are too technical about this topic. You just want something simple that you can get along with. Well, if that sounds like you, you don’t have to worry anymore. In this tutorial and the subsequent ones, I will be journeying you through the world of web3.0 development starting with how to build your first smart contract with solidity.

Check out my YouTube channel for FREE web3 tutorials now.

Why smart contracts are hard to learn

Learning the technology of smart contracts can be frustrating especially if you are new to the space. Even a seasoned developer can be surprised how he or she could be rattled by the complexity of smart contract development. The following are some reasons why smart contract developments can be challenging…

It has a plethora of new programming terminologies
One of the first blows often faced by newbies in this space is the catalog of words they need to understand to be productive with the technology. Starting from blockchain, the underlying technology on which a smart contract is based. Explaining it to newbies can be overwhelmingly confusing.

Think about it, you will have to understand what blockchain, solidity, and smart contracts are. What gas fees are, blocks, immutability, Ethereum virtual machine, and so on.

Let’s face it, the Lingua Franca of blockchain development is vast and more words are popping up every day because of the exponential advancements in the space.

Insufficient study materials
Whether FREE or Premium, the amount of materials needed to offset the growing demand for this technology is in short supply.

Free materials in this space that will grow you into a professional blockchain developer are limited. Yes, it is right for these guys producing these learning content to make some money from it. That is why you will see quite a few professional courses online which can help you.

Also, if you decide to go into the FREE material lane to learn blockchain and smart contract development, you will have to do a lot of tree-cutting to find a comfortable spot in the space.

Mass skepticism on blockchain solutions
There is a thick cloud of doubt and skepticism about this blockchain technology. Even though it is gaining quite a lot of attention lately, the mindset of people and even countries all over the world are limiting the full acceptance of this technology.

We can’t blame the world though, because of the abuse of blockchain digital currencies.

What is a smart contract

To simply state, a smart contract is a piece of program that runs on the blockchain. Let’s use this analogy, the blockchain can be seen as an ocean, and smart contracts are like fishes. A smart contract, for now, can only run on a blockchain network such as the Ethereum Virtual Machine (EVM). A smart contract is useless unless it's deployed to the network.

How smart contracts works

Intuitive as its name sounds, a smart contract works like a real contract document between two or more parties. A smart contract has specifications on what it will do and how it will do it.

A smart contract contains a piece of code written in a blockchain programming language such as solidity which once deployed into the blockchain network, can no longer be pulled out or modified.

Once a smart contract is written or coded, a little amount of money which is called the gas fee is needed to put the contract on the network. Every transaction that happens on the blockchain network requires a validation mechanism to prove that such transactions occurred. In the blockchain, the validation mechanism is what is called the consensus model.

There are a handful of these models such as proof of work and proof of stake, and each consensus model affects the scalability, security, and speed of such blockchain.

We don’t want to go into many technicalities, let’s retain simplicity for the sake of this topic.

What smart contracts can do

A blockchain that supports the integration of smart contracts is a goldmine. Smart contracts change the game and allow you to write programs that will forever run in the blockchain. There are many use-cases of smart contracts in the blockchain world, listed below are a few of them.

  • Creating digital currencies (Tokens).
  • Facilitating financial transactions (DeFi).
  • Identity management and online privacy (Digital wallets).
  • Digital assets and collectibles (NFTs and Metaverse).
  • Building decentralized applications (Web 3.0).
  • Running governmental structures (DAO).
  • etc.

Smart contract example usage

Now, let’s get to the meat of this tutorial, we will build a simple that accepts donations from people along with a withdrawal mechanism. Here is the full version of the smart contract.

//SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;

contract Donors {
    mapping (address => uint256) public paymentsOf;
    mapping (address => uint256) public donationsBy;

    address payable public owner;
    uint256 public balance;
    uint256 public withdrawn;
    uint256 public totalDonations = 0;
    uint256 public totalWithdrawal = 0;

    event Donation(
        uint256 id,
        address indexed to,
        address indexed from,
        uint256 amount,
        uint256 timestamp
    );

    event Withdrawal(
        uint256 id,
        address indexed to,
        address indexed from,
        uint256 amount,
        uint256 timestamp
    );

    constructor() {
        owner = payable(msg.sender);
    }

    function donate() payable public {
        require(msg.value > 0, "Donation cannot be zero!");

        paymentsOf[msg.sender] += msg.value;
        donationsBy[msg.sender] += 1;
        balance += msg.value;
        totalDonations++;

        emit Donation(
            totalDonations, 
            address(this), 
            msg.sender, 
            msg.value, 
            block.timestamp
        );
    }

    function withdraw(uint256 amount) external returns (bool) {
        require(msg.sender == owner, "Unauthorized!");
        require(balance >= amount, "Insufficient balance");

        balance -= amount;
        withdrawn += amount;
        owner.transfer(amount);
        totalWithdrawal++;

        emit Withdrawal(
            totalWithdrawal,
            msg.sender, 
            address(this),
            amount, 
            block.timestamp
        );
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, let’s explain what’s going on in this smart contract…

//SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
Enter fullscreen mode Exit fullscreen mode

At the top, we have the above piece of code which specifies the license identifier and the range of compiler versions that can be used for our smart contract.

The license identifier tells us whether the smart contract source code is open source or not, and the extent to which you can use it. You can find all the licenses available for use here.

contract Donors {
  // codes goes here...
}
Enter fullscreen mode Exit fullscreen mode

The above code block defines the structure of a smart contract. If you have done a little object-oriented programming, it will not take you long to recognize similar patterns in smart contract development. This is because the solidity programming language borrowed a lot of syntax from popular programming languages such as JavaScript, C++, and Python.

// Key value store
mapping (address => uint256) public paymentsOf;
mapping (address => uint256) public donationsBy;
Enter fullscreen mode Exit fullscreen mode

This is a variable type in the solidity programming language that represents keys with their associated values. It is almost similar to an associative array in PHP or an Object in JavaScript.

In the above code, we are simply instructing our smart contract to associate every address with the amount donated.

// Declaring smart contract variables
address payable public owner;
uint256 public balance;
uint256 public withdrawn;
uint256 public totalDonations = 0;
uint256 public totalWithdrawal = 0;
Enter fullscreen mode Exit fullscreen mode

The above code snippet declares the variables to be used in the course of the smart contract.

The address is a data type that holds the wallet address of a person or a smart contract itself. Uint256 simply holds unsigned, positive, or non-negative integers, that is, from 0 to 2²⁵⁶–1.

Payable implies that this account or address can receive money, which in this case is ethers.

Public simply means that this variable can be accessed outside this smart contract, again this principle is similar to OOP.

// Log information
event Donation(
    uint256 id,
    address indexed to,
    address indexed from,
    uint256 amount,
    uint256 timestamp
);

event Withdrawal(
    uint256 id,
    address indexed to,
    address indexed from,
    uint256 amount,
    uint256 timestamp
);
Enter fullscreen mode Exit fullscreen mode

What are events? Events are constructs in the solidity programming language that logs or emits data about a particular transaction and stored in the blockchain in union with the smart contract’s address.

In the code block above, we want that each donation or withdrawal, information such as the withdrawal or donation count, amount, and timestamp should be captured and logged on to the EVM (Ethereum virtual machine) for future reference.

constructor() {
  owner = payable(msg.sender);
}
Enter fullscreen mode Exit fullscreen mode

This is the first function to run once this smart contract is instantiated or deployed. For this example, the deployer becomes the owner of the smart contract, or at least the account used for deploying the smart contract.

function donate() payable public {
    require(msg.value > 0, "Donation cannot be zero!");

    // Assigning payment records...
    paymentsOf[msg.sender] += msg.value;
    donationsBy[msg.sender] += 1;
    balance += msg.value;
    totalDonations++;

    emit Donation(
        totalDonations, 
        address(this), 
        msg.sender, 
        msg.value, 
        block.timestamp
    );
}
Enter fullscreen mode Exit fullscreen mode

The function above is payable and public, meaning, it can receive money and is publicly accessible to donors.

A necessary check is required to make sure that people are sending money. Sending zero ethers will result in an exception and the transaction will be reverted.

Once the donate function validates the presence of money, it will next assign some payment records to the declared variables. From there we can keep an account of who donated money to us, how much, the number of times this person donated money to us, and the available balance for withdrawal.

A Donation event is lastly emitted before the function finishes its duty.

function withdraw(uint256 amount) external returns (bool) {
    require(msg.sender == owner, "Unauthorized!");
    require(balance >= amount, "Insufficient balance");

    // Assigning payment records...
    balance -= amount;
    withdrawn += amount;
    owner.transfer(amount);
    totalWithdrawal++;

    emit Withdrawal(
        totalWithdrawal,
        msg.sender, 
        address(this),
        amount, 
        block.timestamp
    );
    return true;
}
Enter fullscreen mode Exit fullscreen mode

This function is responsible for paying the owner or deployer of the smart contract a stipulated amount of money.

We added some checks for validating that the owner is the one withdrawing the money and not some random stranger. We also checked to make sure that the amount to be withdrawn is not more than the available balance.

Lastly, a Donation event is performed before the function is completed.
Next, you can jump into the Remix editor and run the smart contract as seen in the image below…

Smart  Contract on Remix

Congratulations, you’ve just crushed your first smart contract with Solidity.

Watch my FREE web3 tutorials on YouTube now.

Conclusion

It's been fun showing you how to code your first smart contract in solidity, hopefully, you’ve gained some understanding of how to write smart contracts.

If you want some private tutoring time with me, kindly check out my website for all the details.

Don’t forget to follow me and give a clap to this tutorial, expecting to see you in the next one…

About the Author

Gospel Darlington kick-started his journey as a software engineer in 2016. Over the years, he has grown full-blown skills in JavaScript stacks such as React, ReactNative, VueJs, and now blockchain.

He is currently freelancing, building apps for clients, and writing technical tutorials teaching others how to do what he does.

Gospel Darlington is open and available to hear from you. You can reach him on LinkedIn, Facebook, Github, or on his website.

💖 💪 🙅 🚩
daltonic
Gospel Darlington

Posted on April 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related