Blockchain Programming: Solidity. Programming the Smart Contracts

  • Alex Morris
    📚 WikiCoin

    The ERC20 standard blew up the crypto space in 2018. Many people were attracted to it, including developers. If you want to join this movement of smart contracts, take a look at our tutorial!


Blockchain Programming: Solidity. Programming the Smart Contracts
Contents

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!

👉MUST READ Blockchain Programming: How Many Programming Languages Do You Need for Blockchain?
Blockchain Programming: How Many Programming Languages Do You Need for Blockchain?

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.

👉MUST READ Cryptocurrency Transaction Speed as of 2019
Cryptocurrency Transaction Speed as of 2019

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.

Ethereum EVM & Wallet schematic
Image by U.Today

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.

👉MUST READ No Dice: Ethereum Loses dApps Race to EOS and Tron
No Dice: Ethereum Loses dApps Race to EOS and Tron

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.

Vehicle model & horsepower smart contract
Image by U.Today

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.

👉MUST READ How to Create Your Own Cryptocurrency and Why Would You Want to Start
How to Create Your Own Cryptocurrency and Why Would You Want to Start

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.

UTD ERC20 token
Image by U.Today

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.

👉MUST READ Top 16 Ethereum Wallets 2019
Top 16 Ethereum Wallets 2019

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.

Installing Node.js.
Image by U.Today

Second, install the Solidity framework Truffle via ‘npm install’.

Installing Truffle
Image by U.Today

Third, make a new folder and create a repo via ‘init’ command.

Creating a Truffle repo
Image by U.Today

Fourth, install HDWalletProvider into this repo via Node.js too.

Installing HDWalletProvider
Image by U.Today

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.

JS deployment file
Image by U.Today

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.

Truffle config
Image by U.Today

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.

Smart contract being deployed locally
Image by U.Today

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.

Code verification
Image by U.Today

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.

Smart contract works
Image by U.Today

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.

👉MUST READ Blockchain Developer Salaries. Top Job Offers of Blockchain Companies
Blockchain Developer Salaries. Top Job Offers of Blockchain Companies

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!

Cover image via www.123rf.com
In this Telegram channel you’ll find fresh news, interviews, infographics, forecasts & other helpful stuff. Join U.Today's channel.
👓 Recommended articles

5 Best Upcoming Cryptocurrencies to Watch in 2019 - Updated

  • Denys Serhiichuk
    📚 WikiCoin

    Almost every day new coins are being added on the Coinmarketcap. The list of coins is not limited to Bitcoin, Ethereum and other popular digital assets. Traders and investors are looking for alternatives to maximize their profits in 2019. We created the list of cryptocurrencies which are already widely discussed today. Hope you will choose the right one.


5 Best Upcoming Cryptocurrencies to Watch in 2019 - Updated
Contents

Today, in the cryptocurrency ranking on Coinmarketcap, more than 2,000 digital assets are represented. Of course, not all of them have real value and potential for further development. We cannot be 100% sure which coins will be profitable in 2019, as the crypto market is too volatile and unpredictable.

<>

<>As we can see, the dominance of Bitcoin is starting to losing its grip tightness, creating space for altcoins to grow. In this case, what are the prospects for “young” cryptocurrencies in 2019? Let's try to identify the top five coins that should shoot up in the near future.

OmiseGo

OMG is the digital coin of the OmiseGO blockchain platform. The project is based on open source code. Developers initially focused on the creation of new tools to eliminate society's dependence on banks.

The OMG platform is designed to help conduct financial transactions, even for those people who live in countries with no traditional financial infrastructure in the form of banks. This service is the result of the development of the Asian company Omise, which is the leading payment provider.

👉MUST READ Top 10 Most Profitable Cryptocurrencies of All Times
Top 10 Most Profitable Cryptocurrencies of All Times

OmiseGo prospects for 2019

OmiseGo cryptocurrency project is a really interesting platform with good prospects for further development.

Once the official OmiseGo wallet is released, there is supposed to be a “bear” trend of this currency. After that, an influx of new users is expected, which will make the coin more stable. Despite the fact that <>coin’s chart still showing us downtrend, the project still has good opportunities to return to its maximum highs. It is predicted that by the end of 2019 the rate of OMG can grow to <>$15-20. Of course, such forecasts are overly optimistic, but if the Chinese government keeps improving regulations of the crypto market, then Omise may achieve such indicators.

<>Despite the fact that in 2019 that the price reached its historical minimum, the situation on the crypto market seems positive for Omise. Perhaps this is a reversal of the trend and Coin has a bright future ahead. We advise you to look at altcoin closely to buy it at the lows.

VeChain

It is a public blockchain ecosystem, the main task of which is to digitize all the data that is obligatory for a successful business. First of all, we are talking about establishing a decentralized database of products, as well as creating a platform for monitoring their quality and process of delivery. The project solves issues for the market of the Internet of Things, which is a trend nowadays.

The platform has already released its own blockchain, VeChainThor, and is working to improve it.

VET coin has become available for trading since August 3, 2018.  Nevertheless, we can summarize that the coin feels pretty confident in the market.

Growth factors:

  • Positive feedback from users

  • The platform has successfully completed the transition to its own blockchain

  • VET shows stability relative to other altcoins

  • VeChain has lots of serious partners who are ready to provide investments

ICON

ICON (ICX) is a blockchain platform designed to work with several different blockchains. In other words, ICON is a cross-chain solution that provides solidity for various blockchain projects. The implementation of ICON should improve the efficiency of the project's economy.

ICON ecosystem

Advantages of ICON:

  • Ensuring full universality in the system of interaction between the platform and users

  • The possibility of making modifications to smart contracts

  • The ability of quick transactions on the exchange

  • Fast information processing

  • Adaptability to working with artificial intelligence

The ICON project has official support from the South Korean government. This may be an indication that large Korean businessmen are seriously interested in the coin. Now a number of financial, medical and educational organizations from South Korea have begun to work closely with ICON in order to improve interaction with consumers. In addition, some other representatives of the business of this country and a number of corporations operating in the Asian market are showing interest in this project.

<>Now ICON is within the price of the bottom, but it does not seem like it will continue for a long time. The perspective of the coin, previous indicators, market sentiment indicates that $0.4 is a temporary value.

👉MUST READ ICON Price Prediction: How Much Will ICX Cost in 2018?
ICON Price Prediction: How Much Will ICX Cost in 2018?

Enjin Coin

ENJ cryptocurrency is a digital token platform for creating gambling applications. With Enjin Coin, developers can not only create virtual gaming products but also implement them. The project uses the Ethereum network,so ENJ tokens are in the ERC-20 format.

The biggest advantage Enjin Coin offers the gaming industry is the chance to set and manage virtual goods. Developers of any platform can easily create a currency designed exclusively for their community, which will be supported by Enjin Coin.

Each asset is kept in a single smart contract and registry, so all Enjin Smart Wallets can easily recognize it.

Enjin Coin ecosystem

<>If you look at the altcoin charts, it becomes a clear investor interest. In other words, Engine lives an active life. At the end of February, the active growth of altcoin began. And the gradual fall in prices may be the last good moment to buy before the explosive growth.

AION

AION logo

AION is a third generation blockchain digital token. The essence of such platforms is the creation of an ecosystem where various projects can interact. Roughly speaking, the goal of AION is to create an ecosystem for blockchain startups.

AION is focused on the following issues:

  • The formation of a new infrastructure ensuring the integration of existing blockchain platforms.

  • Using its own scripting language to enable users to create unique digital cryptocurrency projects.

  • The final stage will involve the completion of the cryptosystem optimization process and ensuring its full scalability to speed up the exchange of information between users.

In 2019, the implementation of the network infrastructure is planned to be completed, providing everything needed for fast, efficient inter-network communication and inter-chain applications. In addition, the focus will be on such aspects as:

  • Collaborative networking

  • Complete consensus validator assessment mechanism

  • Launch of the second version of Aion Virtual Machine

The prospects for AION in 2019 will directly depend on the continued relevance of the idea of ​​combining existing blockchains into a single platform. <>The project team is actively developing it, introducing new features and solutions. Despite the low price of altcoin, the tendency to increase prices is already visible. If the development will be successful, AION has all chances to become a hit already in 2019.

👉MUST READ Bitcoin Profit Review: Too Good to Be True
Bitcoin Profit Review: Too Good to Be True

How to choose the most promising cryptocurrency?

The answer is simple: they are always in the spotlight. They are discussed in the media, attracting the attention of large investors, companies, and corporations. Today, the product behind the name of a cryptocurrency project matters a lot. If there is a development, then it is fair to expect an increase in the price of this coin.

Cover image via www.123rf.com
Join our Telegram channel to get news even faster!
👓 Recommended articles