How To Create A Smart Contract: The Ultimate Guide (2022)
Smart contracts and their derivatives are essential components of the Web3 space – for businesses offering a product powered by Ethereum, knowing how to create a smart contract will be relevant in taking advantage of one of the most valuable features the blockchain has to offer.
As there are multiple blockchains out there, this guide on how to create smart contracts will focus on Ethereum.
While complex, you won’t need programming experience to grasp the concepts discussed here.
Table of contents:
- What Are Smart Contracts on the Ethereum Blockchain?
- Top 6 Smart Contract Development Tools by Type
- What to Do Before Creating a Smart Contract?
- How to Create a Smart Contract with Remix IDE
- How to Compile a Smart Contract with Remix IDE
- How to Connect MetaMask to Remix IDE
- How to Deploy to Goerli Testnet Using MetaMask and Remix
- The 12 Benefits of Creating Smart Contracts
What are smart contracts on the Ethereum blockchain?
Smart contracts refer to programs deployed to the Ethereum blockchain. In addition to providing a distributed ledger (like all blockchains), Ethereum also provides a general-purpose computation model built on top of its blockchain, which is where smart contracts come into play.
How Ethereum stores & executes smart contracts
Executing smart contracts on the Ethereum blockchain is not free and requires users to spend Ether, the native currency of Ethereum, to deploy and run smart contracts. Ethereum code execution unit is called gas and is measured in gwei.
Note: in addition to the Ether cryptocurrency, Ethereum also features (smaller) gwei and wei denominations. One Ether corresponds to 10e9 gwei and 10e18 wei.
The Ethereum ecosystem features two kinds of networks: mainnet and testnet. The first is used for real transactions and the latter is a simulator for testing contracts in a real environment.
Like traditional web apps, smart contracts consist of data and functions.
Unlike traditional web programs living on a single server owned by an authority, smart contracts can live at specific addresses on a public blockchain, which is not owned by a central authority.
Ethereum Smart contracts can be used for all kinds of purposes, such as sending and storing funds in Ether. They’re functionally inert on the blockchain until external accounts or other smart contracts call their functions. Ethereum Smart contract code is executed in a runtime environment called the Ethereum Virtual Machine(EVM).
The EVM recognizes only bytecode, therefore you need to compile a smart contract before deploying it to the mainnet. Smart contracts’ code execution that changes the state of the Ethereum blockchain requires gas to be paid in gwei.
Smart contracts are generally isolated from the real world, but they can read real-world data through decentralized oracle networks(DON) and decentralized data sources. Smart contracts bridged with real-world data are called hybrid contracts.
How developers interface with Ethereum smart contracts
The main programming language used for developing Ethereum smart contracts is Solidity which shares many elements with other, more familiar object-oriented programming languages. Solidity uses Events to notify apps’ front-ends (which can be awaiting certain events) about state changes on the blockchain.
Smart contracts’ source code written in Solidity always starts with a declaration of the version of the Solidity compiler to be used which helps prevent issues with future compiler versions introducing changes that may hinder your code. License Identifiers are often added to smart Ethereum open-source projects as seen in the below smart contract sample.
Following the version, pragma is the contract statement with the name of your smart contract. It encapsulates a set of data and instructions of our DApp.
Here is a simple Solidity contract named WelcomeToWeb3 that greets callers:
// SPDX-License-Identifier: MIT pragma solidity ^0.8; contract WelcomeToWeb3 { string message = "Welcome to Web3"; function contractGreeting() public view returns(string memory) { return message; } }
Smart contracts are developed with a combination of software development tools. Having some information on each of them will help you better understand the smart contract creation process.
Top 6 smart contract development tools by type
Smart contracts development requires a coding setup which refers to all the pieces needed to come together so that you can write your code.
A coding setup for developing smart contracts includes the following: a crypto wallet, an IDE (Integrated Development Environment), a package manager, a library, a framework, and a blockchain simulator.
Although there are many IDEs on the market, we will be using Remix IDE for the following example as it’s beginner-friendly.
#1 – Integrated Development Environment(Remix IDE)
Remix is a browser-based IDE for developing Ethereum smart contracts.
When creating a smart contract using Remix, you don’t have to install the below-mentioned tools —such as frameworks, package managers, and libraries. All you may need is just an optional crypto wallet and one of the blockchain simulators mentioned in the below blockchain simulator section.
Remix’s interface is similar to other IDEs’ interfaces such as Visual Studio. It auto-generates buttons for each function in your code. Remix’s interface features four sections:
- A. Main Panel: Lists some useful shortcuts and opens up an editor whenever a file is selected or created in the File Explorer. It also features a menu tab that corresponds to files selected in File Explorer when creating a contract.
- B. Terminal: Allows you to run scripts and provides you with details about transactions.
- C. Side Panel: Acts as a graphical placeholder, showing text fields and dropdown lists from the highlighted plugin in the Icon Bar. For example, if you click on the File Explorer icon in the top-left corner, the Side Panel will live update with workspaces in a drop-down list with folders and files.
- D. Icons Bar: Located on the far left-hand side, it lists all the icons of the plugins you activated, the search icon, the Plugins Manager, and the Settings.
#2 – MetaMask Wallet
Source: MetaMask
MetaMask is a browser-based crypto wallet for enabling financial interactions with the Ethereum blockchain.
It helps users securely create and manage Ethereum accounts, switch between networks, and interact with websites’ front-end using a Web3 library. It also easily integrates with Remix IDE which allows you to deploy your smart contract from Remix.
#3 – NPM Package Manager
Source: npm
A package manager helps you add additional dependencies to your dev projects and keeps track of them.
One of the most popular package managers is Node Package Manager, known in the industry as just npm. When you use npm, all of your dependencies will be listed in a config file named package.json.
You can use npm to easily add frameworks and libraries to your web development project.
Follow the link to find Web3 frameworks and libraries you may add to your project using npm.
#4 – Frameworks(Truffles and Hardhat)
A framework in programming is a tool developed by a third party. It gives you a developer environment and solutions to common problems so as to help you accelerate your work.
The best frameworks for Ethereum smart contracts development are Truffles and Hardhat because they enable you to compile, test, and deploy smart contracts to the Ethereum blockchain.
Click here for more information on Hardhat and here to learn more about Truffles.
#5 – Libraries(Web3.js and Ether.js )
A library is a set of functions developed by a third party for solving specific problems. All programming languages have libraries for specific purposes.
The most well-known libraries in the Web3 space are written in scripting languages such as Python and JavaScript. You can add them to your app front-end using npm in order to simplify the interaction with a blockchain.
Ethereum ecosystem provides you with both Ether.js and Web3.js which hides the complexity of JSON-RPC language with a convenient and easily readable scripting language interface written in JavaScript.
#6 – Ethereum Blockchain Simulators
You are not required to add libraries and frameworks to your project when using Remix IDE, but you will need a blockchain simulator that enables you to produce realistic tests of your smart contract.
Here is a list of Ethereum blockchain simulators:
- Testnets: blockchain live test networks for testing smart contracts.
- Ganache: a local blockchain simulator installed on your computer.
- JVM: Remix’s browser-based blockchain. It stands for JavaScript Virtual Machine.
In order to interact with the previously-mentioned blockchain simulators, we will need a currency. Fortunately, these simulators enable us to use fake ETHs called test ETHs.
What to do before creating a smart contract?
When creating a smart contract, the first thing you need to set up is your coding setup. Our coding setup is simple and includes only Remix IDE, MetaMask, and a testnet named Goerli.
Testnets are networks that let your contract behave as it would on the mainnet which consists of nodes that share the same copy of a ledger. Thus, any interaction with the whole testnet only requires test ETHs to query one of its nodes by indicating the following:
- The address of the smart contract
- The function you want to call
- In some cases, the variables you want to pass to a contract’s function.
In practice, you can set up your own node to interact with the Ethereum blockchain or a testnet. But Instead of setting up our own node as a Web3 node provider and maintaining it, you can use a free third-party service like Infura that offers you a node-ready-out-of-the-box infrastructure.
The good news is that MetaMask uses Infura’s infrastructure as a Web3 provider on the backend and also gives you the possibility to choose your own Web3 provider.
As such, we will not need to sign up to their Infura’s website to get an API key in order to use one of their nodes.
How to install MetaMask
You can easily add MetaMask as an extension to your web browser.
MetaMask wallet’s downloading page automatically detects the browsing you are using and updates its install button with a link to your browser’s webstore.
Here’s how you install MetaMask:
- Visit MetaMask’s download page.
- Click on the “Install MetaMask…” button to go to your browser’s store.
- Click on the right-hand side “add to Chrome” button (provided you’re using Google Chrome.)
- Click on the “Add extension” button.
- Next, click on the “Get Started” button.
- Agree or reject the data collection and usage terms.
- Create a new wallet or import an existing wallet. When you import an existing wallet, you will be required to enter the 12-word Secret Recovery Phrase.
- Enter a password for your wallet. The password enables you to perform transactions and access MetaMask whereas the Secret Recovery Phrase allows you to get back your wallet when you install it to another device.
- Accept the agreement terms to click on the create button.
- Click on “Remind Me Later” in the next step and MetaMask will automatically create a new account for you named “Account 1”.
Note: make it easy for yourself by pinning MetaMask to your toolbar in your browser so you can quickly access it whenever needed.
How to display testnets in MetaMask
MetaMask allows you to use both the mainnet and testnets. It features the popular testnets and also allows you to set up and configure custom testnets used in your projects.
Here’s how to display the testnets in MetaMask:
- Click on the “Networks” button at the top of the home page (it’s usually “Ethereum Mainnet” by default)
- Click on the “Show/hide test networks” link to go to the Settings page.
- Click the switch under “Show test networks” to turn on.
- Click on the MetaMask’s icon to go back to the homepage then click on the “Networks” button again.
- Select Goerli as a network.
- Click on the highlighted Account to copy its address.
Note: If you don’t see your desired network in the list and you want to add it to MetaMask, just click on the networks button, add network, enter the required information and click save.
How to get Test ETHs
Ethereum replaced its Proof-Of-Work(POW) consensus mechanism with Proof-Of-Stake (POS). A consensus mechanism is used by blockchain systems to achieve agreement on data – we’re using Goerli testnet because it upgraded to Proof-Of-Stake.
Goerli as an Ethereum testnet provides you with Goerli Faucet which enables you to get fake ETHs or test ETHs called Goerli ETHs. You can get them for free but you need to sign up to Alchemy’s website.
Here’s how you get Goreli’s test ETHs:
- Visit Goerli Faucet’s website.
- Select Goerli as testnet.
- Enter your MetaMask Account’s Address (you’ll need to register first but it’s quick and can be done for free)
- Click on the “Send Me ETH” button.
How to create a smart contract with Remix IDE
Once you have completed the previous tasks, you will be able to create your smart contract.
To illustrate all the concepts discussed in this guide, we will create a simple smart contract that enables users to store one favorite number on the blockchain.
Here’s how you create a smart contract:
- Visit Remix’s website.
- Go to the Icon Bar located on the far left-hand side.
- Click on the “File Explorer” icon.
- Right-click on the contracts folder.
- Click on “New File.”
- Name your file favoritecontract.sol. An empty code editor will live-update the Main Panel and a tab with your new file’s name and you can now declare variables and functions.
- Copy and paste the following code into your Remix’s code editor:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** *@title A Contract for Associating One Favorite Number with Users’ Accounts. *@author Said Habou Adi *@notice You can use this contract to associate one favorite number to the caller's account. *@dev This contract's main public function takes a uint and associates it with the caller's account. */ contract FavoriteNumber { mapping(address => uint) public accountFavNumber; mapping(address => uint) countingFavNumber; ///@param _number to be associated with caller's account function recordMyFavNumber(uint _number) public { require(countingFavNumber[msg.sender] == 0); accountFavNumber[msg.sender] = _number; countingFavNumber[msg.sender]++; } ///@return Caller's account’s favorite number function myFavoriteNumber() public view returns(uint) { return accountFavNumber[msg.sender]; } }
How to compile a smart contract with Remix IDE
Once a contract is written, it will need to be compiled before it can be deployed.
Here’s how you compile a smart contract to work with our ongoing example:
- Go to the Icon Bar.
- Click on the “Solidity compiler” icon and the Side-panel will update with the appropriate functions.
- Confirm your contract’s name in the blue button then click to compile.
How to connect MetaMask to Remix IDE
Upon completing the previous tasks, you will need to connect to MetaMask from Remix in order to deploy your smart contract thanks to the power of MetaMask and Infura.
With MetaMask open, this is how you will connect to Remix:
- Click on the MetaMask icon in the toolbar.
- Click on the vertical dots (i.e., kebab menu).
- Click on the “Connected sites” item.
- Click on “Manually connect to the current site.”
- Select the account with Goerli ETHs.
- Click on Next.
- Click on Connect.
Once connected, your MetaMask wallet’s homepage will show a very small green circle indicating that it’s connected to the current site(Remix IDE).
How to Deploy to Goerli Testnet using MetaMask and Remix
With Remix open, this is how you deploy a smart contract to a testnet using Remix IDE and MetaMask:
- Click on the “Deploy & Run Transactions” icon located in the icon bar.
- Click on the “Environment” drop-down menu
- Select the “Injected” option as seen above.
- Click on the “Deploy” button below which will create a popup with details about the deployment transactions.
- Click on the “Confirm” button to automatically execute the deployment transactions.
- Next, scroll down and click on the angle bracket under deployed contracts so it expands to show auto-generated buttons representing our contract functions as shown in the following screenshot:
You can now interact with the deployed contract by passing your favorite number to the recordMyFavNumber() function and clicking on its button to store your number on the blockchain.
To see your number, call the function named myFavoriteNumber(). You may enter your address or another address with a favorite number in the accountFavNumber() text field.
The 12 Benefits of Creating Smart Contracts
Though smart contracts face minor challenges like any technology, their benefits outweigh their disadvantages. Smart contracts offer both technical and financial benefits to developers, artists, and Web3 enthusiasts interested in privacy and transparency.
Smart contracts solve a major problem when stacked against Web2 apps as they’re not vulnerable to a single point of failure like centralized server apps. This ensures no restrictions or downtime.
Smart contracts take advantage of a public blockchain and offer the following technical benefits:
- Fully operational Dapp (Decentralized Application). You can build an application that takes advantage of blockchain-based systems to store data in a decentralized manner.
- Proof of ownership. You can create ERC-721 smart contracts to get ownership of digital assets.
- Censorship-resistant technology. A central authority cannot temper with recorded data.
- Instant traceability. You can monitor the whole activity of a specific Ethereum account.
- Great transparency. Blockchains’ activities can be viewed on block explorers including smart contracts’ code.
- Inherently user privacy mind. The identity behind Web3 activities is just a public address.
In addition to the previously mentioned benefits, smart contracts deliver even more financial benefits. It’s essentially “programmable money” that can reliably store and send funds, which reduces administrative work in finance while substantially reducing errors. The other financial benefits include:
- Storing crypto assets. Smart contracts can store cryptocurrencies such as Ether.
- Conditional, automated payments.: You can write code that triggers payment once specific conditions are met. For example, you can store Ether in your smart contract and send it to an account 3 years later.
- 24/7 financial operations. The blockchain is always running so users can withdraw money in smart contracts virtually whenever.
- Storage for inflation-resistant currency. Despite the speculation around cryptocurrencies, they can be used as a more stable alternative to gold and traditional savings.
- Tokenization. you can create your own ERC-20 tokens.
- Low transaction fees. Most transaction fees are lower than those of traditional banking fees.
Conclusion
Smart contracts are next-generation applications that will impact several industries including the financial sector.
Having a solid knowledge of smart contract creation will solidify your knowledge of the Web3 space and help you launch your career in the growing realm of Web3.
If you want to learn more about smart contracts, you can check out our article that explains how using the wrong visibility modifiers can introduce security breaches in your code.
Bobby Gill
Blue Label Labs Is Hiring
We are looking for exceptional people to join our exceptional team and build great things together.
See Our Current Open Positions