How to Create an Ethereum Smart Contract using Solidity

By now, there is a high probability that you have come across the buzzword “smart contracts,” which are associated with blockchain platforms like Ethereum. However, what precisely is a smart contract, and how does one make one? This article will show you how to use the Solidity programming language to create an Ethereum smart contract.

Smart contracts are just like the regular contracts used in the real world to seal business agreements and deals. However, unlike standard contracts that can be written or spoken, smart contracts are in digital format and stored on blockchain platforms such as Ethereum. With blockchain as the underlying technology, smart contracts are immutable and distributed among all nodes on the network.

Some terms surrounding “smart contracts” might seem complex to grasp. Don’t freak out! This post will take you in a step-by-step manner. We will look at Ethereum as a Blockchain platform, how Ethereum executes smart contracts, Solidity programming language, and finally, write our first simple Smart Contract.

What is Ethereum?

Before looking at Ethereum, you need to understand “what a blockchain is” clearly.

A blockchain is an immutable public digital ledger. It is decentralized and distributed across numerous computers on a peer-to-peer network. Blockchains technologies are mainly used in recording transactions since information cannot be changed and is spread across all computers on the blockchain.

There are several blockchain platforms available today. Ethereum is the most popular of all.

Ethereum is an open-source blockchain platform launched in 2015 by Canadian programmer Vitalik Buterin. It brings a new concept known as EVM (Ethereum Virtual Machine). If you come from a ‘Java’ or ‘DotNet background, you might already know what we are talking about here. You will need JVM (Java Virtual Machine) to run any Java application. In the same way, you will need EVM to run an application on the Ethereum network.

Smart contracts are programs written to run on the Ethereum network. To write these programs or smart contracts, Ethereum developers developed an object-oriented programming language called Solidity. It’s a strictly typed programming language, highly influenced by Javascript, Python, and C++.

Tip: Ethereum is not a cryptocurrency. It’s a blockchain platform. However, it has its cryptocurrency, known as Ether (ETH). Please don’t confuse between the two.

What is a Smart Contract?

Although the term “smart contract” became more prominent with the rise of blockchain platforms like Ethereum, this term dates back to 1994. It was coined by computer scientist Nick Szabo who described smart contracts as:

a computerized transaction protocol that executes the terms of a contract. I call these new contracts “smart” because they are far more functional than their inanimate paper-based ancestors. No use of artificial intelligence is implied.” (Retrieved from https://www.mdpi.com/2071-1050/11/21/6181/pdf)

This post will use a simple example to understand a smart contract better.

Assume John goes to a shop and purchases a mini-laptop for $200. However, since he doesn’t have the money at that particular moment, he tells the seller (James) that he will bring him the money tomorrow. James takes out his record book and writes John’s name and the amount he will pay. In this case, $200.

When John returns the next day with the money ($200), James tells him they had agreed on $250, not $200. Since John cannot prove that, he ends up paying $250. That is the major problem with real-world contracts. You must trust that the other party will not go against the contract terms.

When smart contracts are well written and audited, it eliminates malicious exceptions, fraudulent losses, and the need to trust the other party since they are immutable and distributed across the nodes on the network. Smart contracts are written in Solidity, compiled into a JSON file, and then deployed to a particular address on the Ethereum blockchain.

The Remix Editor

Similar to programs you write in other languages, you will need an IDE to write your smart contracts. You can decide to use an IDE like Visual Studio Code, JetBrains IDEs, or any other. However, the best editor for Solidity is the Remix Editor. It’s an online editor with a pretty intuitive interface similar to VSCode. You can access the Remix Editor on your browser is this link.

Gas Fees

Most transactions that take place on the blockchain require computational power to execute. The unit of measurement used to describe the computational power needed for every transaction is called “Gas.” The amount of gas required for every transaction varies depending on the complexity of the computation.

In the Ethereum blockchain, gas is calculated using Ether (ETH), the native cryptocurrency for Ethereum. When you deploy a smart contract on the Ethereum main blockchain, you will require some real cryptocurrency (ETH for this case). Luckily, there are other “test networks” where you can deploy your smart contract using “Test Ether.”

“Test Ether” is of no value, and you can get it for free. In this post, you will deploy your smart contract on a test network where you won’t have to worry about buying some real ETH tokens.

Write Your First Smart Contract

Up to this point, you have all the necessary information to write and deploy a smart contract on the Ethereum blockchain. We will write a smart contract that creates and returns a Greeting. Also, since you must pay gas fees for most transactions on the blockchain, you will deploy the smart contract on a test network.

Follow the steps below.

Step 1. Launch the Remix Editor

On your browser, navigate to this link – Remix Editor. You should see a window similar to the image below.

Remix Editor

The default Remix workspace contains some sample contracts and scripts you can access from the left-side panel.

Step 2: Create a New File

Click on the “contracts” folder on the left panel to reveal all the sample contracts in the default Remix workspace. You can decide to edit and rename any of these sample contracts. However, we recommend getting started from scratch.

Click on the “new file” icon as shown in the image below and type the name of your contract. Remember to add the “.sol” extension, the file format for Solidity programs. This post will use the name “Greeting.sol.”

New Solidity Program

Step 3: Write your Smart Contract

Tip: This section will show you how to write a smart contract line-by-line. If you want the complete source code, skip to the bottom of this section.

The first line we will write is:

//SPDX-License-Identifier: MIT

That specifies the license you are using for your smart contract. Unless otherwise, feel free always to use the MIT open-source license.

The second line we will write is:

pragma solidity ^0.8.11;

Here, you specify the version of Solidity that you are using to write your contract. It is helpful since the compiler will know which version it will use to compile your code. After you have written those two lines, you can officially start coding your contract.

First, define the contract using the “contract” keyword. It’s always a good practice to name your contract similar to the file name.

contract Greeting {
//
}

Inside this “Greeting” contract, you will declare state variables. These are variables stored on the blockchain and persist between multiple invocations of the smart contract code. You must declare its “type” and the “access modifier.”

string public name;
string public greetingPrefix = "Hello ";

By declaring the “access modifier” as public, the variable is accessible to anybody and everyone.

Next, you will declare a constructor function where you will set the name. We will use the “constructor” keyword and provide the “type” of the argument we will pass. In this case, it’s a “string.”

constructor (string memory initialName) {
    //Here you set the state variable "name" to the constructor argument.
    name = initialName;
}

Next, you will write a “Setter” function to set the name. In Solidity, you use the “function” keyword, followed by the “function name” and “function arguments.”

//You will need to provide the type of your function argument. In this case, its a string
//You will also use the "public" keyword to make the function accesible to anyone on the network

function setName(string memory newName) public{
      name = newName;
}

Next, you will write a corresponding “getter” function.

//This function doesn't take any arguments as its only returning some information from the smart contract.
//Its "public" to the network
//The "view" keyword specifies that the function will only 'read' data on the blockchain but won't perform any 'write' functions
//You will also need to provide the "type" of the return value. In this case, it's a 'string.'

function getGreeting() public view returns (string memory) {
        //Here, you use a function 'abi.encodePacked' to concatenate the two state variable you defined (greetingPrefix, name)
        //String concatenation in Solidity is NOT straightforward as in other languages like Javscript.

        return string(abi.encodePacked(greetingPrefix, name));
    }

The final program should look as shown below.

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

contract Greeting {
    string public name;
    string public greetingPrefix = "Hello ";

    constructor (string memory initialName){
        name = initialName;
    }

    function setName(string memory  newName) public{
        name = newName;
    }

    function getGreeting() public view returns (string memory) {
        return string(abi.encodePacked(greetingPrefix, name));
    }
}

Step 4: Compile your Code

First, you must ensure that the compiler version is set to the version you specified in your code. You can do that by clicking on the “Solidity Compiler” icon on the left pane, as shown in the image below.

Solidity Compiler

Select the compiler version you want to use from the dropdown menu. Once done, click the “Compile Greeting.sol” button to compile your code. If the compilation process were a success, you would see a “green” tick next to the “Solidity Compiler” icon. Else, if there was an error, you will see a warning next to that line on the code.

Step 5: Deploy your Smart Contract

To deploy your smart contract to the blockchain, click on the “Deploy and run transactions” icon, as shown in the image below. Please note that you will deploy your smart contract on the test network, not the main Ethereum blockchain, as that will require “Gas fees.”

Deploy a Smart Contract

Under the “Environment” section, select “Remix VM (previously called Javascript VM)” for testing purposes. Next, under the “Account” section, select the address where you want to deploy the smart contract. Since these are test accounts, each account is loaded with 100 ETH. Since we will not be sending any Ether in our smart contract, don’t worry about the other options like “Gas Limit” and “Wei.”

Before clicking on “Deploy,” enter the “initial name” on the field next to the Deploy button. Remember, the constructor in your smart contract is taking a name argument.

Set initial name

When done, click “Deploy.” Still, on the left panel, scroll down to the “Deployed Contracts” section. You should see your “Greeting contract” there. Click on it to reveal all the available options.

Deployed Contract

You will notice that it lists all the functions in the smart contract. Click on any of the functions to see its value. You can also set a new name by typing it in the “string newName” field and clicking on the “setName” function.

Tip: When you define a state variable in Solidity, you automatically get a “getter function” for that variable. That’s why you see the name value when you click on the “name” option in the deployed contract.

You will also notice that for every write function you do (setting a new name), some ETH is deducted from the account where you deployed your smart contract. That shows you the importance of testing your smart contract before deploying it to the main blockchain. Constant debugging can take up some “Gas fees.”

That’s it! You have successfully written and deployed your first smart contract on Ethereum.

Wrapping Up!

This post gave you a solid introduction to how to write Ethereum smart contracts using Solidity. It used a simple example that didn’t require many complicated functions and utilities. However, several tools will come in handy when writing a smart contract that involves sending and receiving tokens.

  • Truffle: A development and testing framework for writing Ethereum smart contracts.
  • Web3.js: An Ethereum-Javascript API that allows you to develop programs that interact with the Ethereum blockchain.
  • Visual Studio Code (VSCode)
  • Ganache CLI
  • Parity
  • Node JS

Was this article helpful?

You can also share your thoughts by replying on Twitter of Become A Better Programmer or to my personal account.