Blockchain Programming: Solidity. Programming the Smart Contracts
In over 10 years of its development, blockchain has significantly expanded from a straightforward system of transferring value via coins to the basis for Web 3.0 and decentralized applications. This happened mainly due to an outbreak of new projects after Ethereum introduced its ERC20 standard and smart contracts.
Smart contracts were widely used in fundraising for ICOs to ensure transparency for participants. This made them famous, but that wasn’t the only implementation. There are successful cases for smart contracts in creating distributed autonomous organizations, managing rights and conducting governance. The need for them is so apparent that there even are attempts to create smart contracts for Bitcoin.
If you want to make it in blockchain engineering, you will have to know how smart contracts work and how to build them. Fortunately, Ethereum provides everything necessary for it, including its own programming language – Solidity. This language was specifically created for working with Ethereum Virtual Machine. It’s pretty easy to understand, but there are some distinctive features that you will have to keep in mind. Today we will dive deep into the world of smart contracts and code some of them. Let’s roll!
How does Ethereum work?
First and foremost, we need to understand the basics of Ethereum’s blockchain and how it functions. This will help us in understanding the difference between coding centralized apps and decentralized ones (which smart contracts basically are).
In its core, Ethereum has a virtual machine. You probably encountered them earlier when launching old games in an emulator or running some OS-specific software on the non-native OS. In simple terms, a virtual machine is a computer inside a computer, which uses the hardware of the original machine. In the case of Ethereum, the EVM uses resources of computers connected to the network (nodes). Like any other VM, Ethereum’s one has its own RAM and ROM, which are used by programs running on top of it. The only significant exception is that the EVM’s ROM memory is blockchain, so once something gets there, it cannot be removed.
Why is this important? Creating smart contracts is an incredible responsibility because in case there is a vulnerability, users’ money can be stolen or lost. While you can amend or completely replace the code on a centralized server, you can’t do so on a decentralized VM. In addition, every action performed with a smart contract requires paying fees to the network. Why? Because the EVM has to process a given task, and it can only do it by utilizing some nodes’ processing power. The fees are called Gas and are paid in Gwei, which are similar to Bitcoin’s Satoshi.
How does a smart contract work?
If you have ever used Ethereum, then you generated a wallet in the network at least once. Your wallet is basically an account that is represented by an address. A smart contract is an account too, but it differs from a regular account.
Once you create a wallet, you can connect it to any of the available networks, and the only thing that will change is your balance. This is because user addresses are not internal to any network – they exist in parallel. On the other hand, an instance of a smart contract is included in a given blockchain and can’t be viewed in another chain. To be able to launch a contract on the Main Network after testing it in, let’s say Rinkeby, its creator will need to deploy a new instance of the contract. This will require compiling the source code once again. A contract creator can make as many instances of the code as they wish, as long as they have enough ETH to pay Gas for interacting with the network.
Just like a centralized application, a smart contract has a dedicated place for storing its resources and a placeholder for code (picture it as a web page that you download from the internet, it will have a .html file and some folders with pictures and other stuff). There is also an indication of how much ETH a contract has on its balance; this is crucial for various use cases like fundraising, wills, etc. The full schematic is presented in the picture below.
How to build a smart contract?
Now that we know the principles of how Ethereum functions and how smart contracts run within it, we can create one by ourselves. First, we will need to set up the proper environment. You can go two routes, either writing the code in browser with the Remix IDE provided by Ethereum Foundation or downloading a coding app of your choice along with some packages for it. For the purpose of this tutorial, we will show you both Remix and Atom (a universal coding app for Mac & Windows).
The first smart contract that we are going to make will take the names of different car models and their horsepower. What we want to see is two input and two output fields for the values we have. Since we are going to change the inputs, we need to set variables of two types: a string for the names and an integer for the horsepower.
Before our contract, we will put a line that specifies the language version, as this will help the compiler to adapt the code properly. Compiling the code is necessary because once we get to the deployment stage, the code will be adapted to the machine code that the EVM will be able to read and process. In addition, an application binary interface will be created that could be used further in creating a full-fledged decentralized application. You can always check the latest version of Solidity on its official website. To specify it, type ‘pragma solidity’ and the version after the ‘^’ sign.
To set borders for our contract, let’s give it a name followed by a parenthesis. First, we will declare two variables: ‘model’ and ‘HP’. The first one will be a string that represents a car model and the second one will be an integer that represents a given car model’s horsepower. There are two things to mention about variables in terms of Solidity. The former is that we should declare whether or not third parties should be able to see them by putting ‘public’ or ‘private’ next to them. The latter is that the integers in Solidity can be signed or unsigned. An unsigned integer can only be possible and is written as ‘uint’. A signed integer can be both positive & negative and is written as ‘int’.
After we have our variables specified, it’s time to write some functions that our smart contract will perform. Firstly, we need to make placeholders for our model and HP. We will use a couple of set public functions and attach our variables to them. Secondly, we need to outline a couple of get public functions that will return an input. Take a look at how our smart contract looks.
How to make a token on Ethereum?
Many people were attracted to the blockchain industry because of the outrageous gains on the crypto market at the end of 2017. This was mainly the outcome of the advent of the new ERC20 token standard that a huge number of startups used to launch their tokens and raise money for development. Despite the decline in the hype, some companies are still launching their tokens on Ethereum and are selling to contributors, proving that the demand is still there. If you have always dreamt of building a startup and launching your token, this part will be very interesting.
Creating a token means using the ERC20 standard, which can be quickly googled. Don’t forget to set the version of Solidity before the standard itself. There will be a set of functions and a couple of events that are supposed to log actions into the Ethereum’s ledger. Among the functions, you will find the set of necessary ones: one for defining the total supply, one for checking the balance of a given wallet, and one for transferring tokens between wallets. As Ethereum allows controlling wallets from other wallets, you will also find functions that define a target wallet and allow balance for transfer and approve a transaction. Save this into a separate .sol file.
It’s time to outline our own token. Start with specifications of the version of Solidity. Then import the interface and attach it to a new smart contract via ‘is’. Going further we will:
-
First, outline the symbol, the name and the number of decimals in variables. The number of decimals lets the user transfer and store parts of a token, the most common number of decimals is 18. All of these shall be visible to users, so we make them public.
-
Second, we will define the total supply. In the case of this tutorial, it will be fixed and equal to one billion.
-
Third, let’s make mappings for checking balances on wallets and allowances in case of any third party will control an address.
-
Fourth, we will set a function that will be executed only once upon the contract’s deployment (constructor) that will give our address all the tokens we will create.
-
Fifth, we need to create a number of functions that constrain what we have in the interface. The total supply will be taken from the variable we declared before. The balances will be checked according to the mapping. The transfer will only be allowed if a user has some ETH and they are sending less or equal to what than they actually have. Controlling another wallet will be done according to the previously defined mapping and check for allowed amount. Check the code we got below.
How to launch a smart contract?
You now know how to code simple smart contracts on Solidity. Let’s try to understand how they can be launched on the Ethereum network. First, we need to compile the code. For this purpose, you can either use Remix’s integrated compiler or do it on your machine with the help of Truffle framework. Let’s go the easy route first.
Before we begin it’s necessary that you create an Ethereum account if you haven’t so far. For this, we recommend using Metamask extension which can be installed on top of Chrome, Opera, Firefox and Brave browsers. Once you create a wallet, make sure that you save the seed phrase because it will be the only way to access a wallet from other machines or in case you have to reinstall the extension. The advantage of Metamask is that you can switch between various networks. This will come in handy as we are going to use a test network for our experiments. Open the extension and choose Ropsten network. Then, go to the faucet and request some ETH, remember that every operation with the EVM costs Wei.
Open remix.ethereum.org. You will see a code for a ballot – close the tab with it. Remix has a dedicated browser for .sol files and an integrated compiler. At the top of the browser, there is a cross icon that allows creating new files. Let’s create a file and copy our first smart contract with vehicles and their horsepower. On the right part of the screen, you will see the compiler with a few tabs. In the first tab select a compiler version that corresponds with the version of Solidity you specified and initiate compilation process. If there are no errors, you will be presented with a ‘success’ message. Select the second tab and you will see a section where you should specify an appropriate environment (in our case Web3) and check that your address is correct (it should come down from Metamask). If everything is correct, press ‘deploy’ and you will get a pop-up from Metamask with a transaction. Confirm it and voila, your smart contract is deployed to the network.
Now to something more interesting. If you used a text editor on your computer to write the code, you can deploy it locally by using Node.js. First, download it from the official website or install via a Command Line (Windows) or Terminal (OSX). In our case, we will use OSX, but the process is similar.
Second, install the Solidity framework Truffle via ‘npm install’.
Third, make a new folder and create a repo via ‘init’ command.
Fourth, install HDWalletProvider into this repo via Node.js too.
Fifth, copy files with the ERC20 interface and your token contract to the ‘contracts’ folder in your repo. Sixth, create the following JavaScript file in your ‘Migrations’ folder within the repo.
Seventh, you need to modify your Truffle config file. However, there is one extra step required prior to doing so. You will input your wallet’s mnemonic (which you saved earlier) and an API for Ropsten testnet. To get the latter, go to Infura and register a project. On the project’s page, you will see its ID. Use it as an API.
Finally, you are ready to launch your smart contract. Here’s what the command and the process look like. Should there be any issues, you will be presented with them instead.
What can you do with a smart contract?
Good work, you have the first two smart contracts deployed. Now what? For starters, you need to verify and publish them. Let’s find them first in any of Ethereum’s block explorers. We will be using Etherscan.
The quickest way to access your contracts is through the transactions from your wallet. Access Metamask, press three dots, and it will let you view your account in Etherscan. Your address now has at least one transaction for contract creation. Accessing a transaction, you will find a destination address, which is essentially a contract’s address. Once you end up on the contract’s page, you will see a few tabs. Go to the ‘Code’ tab and proceed to the verification page. Here input all the relevant information and press the button to start the verification process.
After you verify the first smart contract that we created, you can now interact with it. Go to the ‘Write contract’ tab and you will see the placeholders that we specified. Let’s connect Etherscan to Metamask and input Toyota Soarer and 280 HP. Refresh the page and you will see the data in the ‘Read’ section.
Summary
To sum up, building smart contracts is a necessary skill for every blockchain engineer out there. The first platform to introduce smart contracts was Ethereum; the Foundation also presented the community with a specially written language called Solidity. Despite the novelty of the concept and the language itself, building smart contracts has nothing exceptional to it. People who have previous experience with object-oriented programming languages, especially JavaScript, will feel very comfortable getting around.
Smart contracts are just programs, but they have distinctive features that every developer should keep in mind. For instance, because smart contracts run on top of a decentralized VM, their data is getting immutably recorded into the blockchain. Hence, there is no room for mistakes, and testing a smart contract is crucial before it gets deployed to the Main Network. Another characteristic of a smart contract is that every action is done through transactions, which require the EVM’s processing power. As a consequence, deploying smart contracts and interacting with them costs money.
Today we explained the principles of functioning for Ethereum Main and test networks, showed you various tools for creating smart contracts, and outlined the process of making two types of contracts. We also demonstrated different ways of launching smart contracts on the network and further interaction with them. We believe that with this knowledge you will be ready to start out as a blockchain engineer and build exceptional smart contracts and decentralized apps based on them. Enjoy!