Solidity Data Types

Solidity is a statically typed programming language, which means that the type of each variable needs to be specified at compile-time. Solidity provides several categories of data types, as listed below:

  • Value types
  • Reference types
  • Mappings

Value Types

These types of data are called value types because variables of these types will always be passed by value. There are several value types in solidity, as listed below:

  • Boolean
  • Integer
  • Fixed Point Number
  • String
  • Address
  • Array
  • Literal
  • Enum

We shall focus on boolean, integer and string data types first and discuss other data types in future articles.

Boolean

Boolean is a data type that only produces two possible values, true or false. They can be used together with some common operators, as follows:

OperatorMeaning
!Logical negation
&&Logical conjunction  “and”
||Logical disjunction “or’
==Equality
!=Inequality

We declare a Boolean variable using the keyword bool

Integer

There are two types of integer, the signed integers, and the unsigned integers. The keyword to declare signed integers is int and the keyword to declare unsigned integers is uint. In addition, we can assign the number of bits a signed integer can hold using int8, int16 until int256. Similarly, we can use uint8 until uint256 for unsigned integers.

We declare an integer variable using the keyword int or uint

We can use various operators to deal with operations that involve integers. The operators are listed as follows:

Comparison Operators<=  < ==  != >=  >
Bit Operators&  |  ^ and   ~
Arithmetic Operators –  * /   % **  << >>

String

The string is a data type that cannot be operated arithmetically. String literals are written with either double or single-quotes, for example, “Abraham”, “007”, “abc%&$” and more.

We declare a string variable using the keyword string .

Example: This example The string two types of variables, unsigned integer and boolean. We also use the keyword if and the operator > to check whether the outcome is true or false.

The code

pragma solidity ^0.4.24;

contract myContract2 {
      uint private a;
      uint private b;
      bool ans;
   
 function getValue1(uint num1) public{
    a = num1;
 }

  function getValue2(uint num2) public{
    b = num2;
 }
 
  function checkAns() public view returns (bool){ 
      if (a>b)
          ans=true;
      else
      ans=false;
      
      return ans;
  }

 
}

After we compiled and deployed the contract, we get the following output. We can test the results by entering different values in getValue1 and getValue2. The results will be either true or false.

The output on Remix iDE

Introduction to Solidity

What is Solidity?

Solidity is a high-level programming language that is used to create and implement smart contracts in Ethereum. The smart contracts created using Solidity can be used for financial transactions, crowdfunding, voting, intelligent supply chain management, improvement of  IoT workflow, ride sharing automation, smart city administration and more.

It has Python, C++ and JavaScript influences and is used for Ethereum Virtual Machine ( EVM ). As a result, it is fairly convenient and easy to grasp for those that are already familiar with the Python, C++ or JavaScript.

The IDE for Developing Smart Contracts

The best tool to write, compile, test and deploy smart contracts is  Remix.  Remix is a browser-based IDE that provides an inbuilt compiler as a well as runtime environment without server-side components.

We can also use other code editors for Solidity. I suggest we use Visual Studio Code or Solidity Plugin for Visual Studio. For the Solidity plugin, you need to download it from https://marketplace.visualstudio.com/items?itemName=ConsenSys.Solidity
Besides that, you need to install Visual Studio 2015.

Writing Your First Smart Contract in Solidity

A smart contract is a data, that can be referred to as its state, and code, which can be referred to as its functions, collection, that resides on a specific address in the Ethereum blockchain.

The first line of the smart contract is always 

pragma solidity ^0.4.24;

pragma is a keyword which is used to instruct the compiler how the source code should be treated. In this example, the pragma specified that the source code is written for the Solidity Library version 0.4.24

To define a contract, we use the statement

contract contractName {

}


You can use any name for the contract, but any meaningful name will be better. For example

Contract  NewCoin{

}

indicates that you intend to create a contract for a new cryptocurrency.

Assigning variables

Next, we would like to introduce some variables into the contract. First of all, let’s assign some string variables and some integer variables.

To assign a string variable, the syntax is

string myName;

In Solidity, there are two types of integers, the signed integer and the unsigned integer.

A signed integer means it can store positive or negative values while an unsigned integer can only store positive values.

To specify that it will be an unsigned integer, we use the keyword uint before the name of the new variable.

To assign an unsigned integer, the syntax is as follows;

uint MyAge;

Access Modifier

You may want to add the access modifier(or visibility modifier) private or public to the variable. Most programming languages put access modifier in front of the datatype  specifier like private string name but in Solidity, we put access modifier between datatype specifier and the variable name, as follows:

string private myName; 
String public myName
uint private MyAge;
uint public  MyAge;

Writing the Smart Contract Code

Now launch Remix IDE. Create your first smart contract by clicking on the little + button on the far left corner of the Remix IDE.  A new dialog will appear and you can create a new Solidity file.

After creating the new file, a new window will appear on a new tab displaying your new file. The file will also be show on the left pane of the IDE under the browser.

Now, let’s create a new contract by entering the following code into the Remix IDE.

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
}

The first line inside the contract itself declares a string name and an unsigned integer variable called age.

We have already created a simple smart contract though it does not do anything yet. You can compile and deploy it if you want to.

Now let’s add some functions to the smart contract

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
   
 function setName(string newName) public{
    name = newName;
 }

  function getName() public view returns (string){ 
    return name; 
  } 
  
  function setAge(uint newAge) public{
      age=newAge;
  }
  function getAge() public view returns (uint){ 
      return age;
  }
}

We create the function setName to allow the user inputs a string value. Set the modifier to public as we want to permit everyone to see it. Otherwise, when you deploy the contract you will not be able to view the function on the Remix IDE.

To return the value of name entered by a user, we create the function getName

The view keyword in public view returns is  the replacement for constant. It indicates that the function will not alter the storage state in any way.

Next, we create the function setAge by declaring  a parameter newAge as an unsigned integer. The setAge function will allow the user input an integer value when you deploy the contract.

To return the value of age entered by the user,  we create the function getAge

Now compile and deploy the Remix IDE, the output is shown in the following figure:

Deployed Contract

When you deploy the contract, a transaction is executed from your wallet address to the contract. A gas fee is charged in the process. You can view the transaction on Etherscan, as shown below:

When you click on the setName function, a transaction will also occur. You need to wait for the transaction to complete before you click on the getName function. You can see that whatever you entered in the setName box will appear on the getName box. You can do the same for the setAge and getAge functions.

Smart Contracts

Introduction

In the blockchain network, a user can send some crypto money to another user in exchange for something of value where the transaction is executed automatically based on a smart contract. In another case, a smart contract is executed when a user acquires a unique virtual kitty from the Cryptokitties collectible marketplace via a bidding process, the highest bidder gets to own the digital asset.

On the other hand, a transaction can occur automatically between two smart devices using an integrated system of IoT technology and blockchain. For example, a smartphone A can top up data for another smartphone B after A received some money from B, the transaction occurs based purely on a smart contract without the awareness of the owners.

According to Investopedia, smart contracts are ,

“self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. Smart contracts permit trusted transactions and agreements to be carried out among disparate, anonymous parties without the need for a central authority, legal system, or external enforcement mechanism. They render transactions traceable, transparent, and irreversible.”

Definition of Smart Contract

Based on the aforementioned descriptions, we can define a smart contract as a computer code that can facilitate the exchange of money, content, property, shares, digital assets or anything of value among disparate and anonymous parties without a middle entity.

When a smart contract is installed in a blockchain system, it behaves like a self-operating computer program that automatically executes when some specific terms and conditions are met. Because smart contracts run on the blockchain, they run exactly as programmed without any possibility of censorship, downtime, fraud or third-party interference.

A Brief History of Smart Contracts

In contrary to popular belief, the smart contract is not invented by Vitalik Buterin, the founder of Ethereum. In actual fact, the idea of the smart contract was first conceived by computer scientist and cryptographer Nick Szabo in 1993 as a kind of digital vending machine. In his famous example, he described how users could input data or value, and receive a finite item from a machine, in this case, a real-world snack or a soft drink. Nick Szabo is so smart that some people believe that he could be Satoshi Nakamoto who invented bitcoin.

In addition, though Ethereum is the first blockchain system that has adopted the smart contract technology, it is not the only one using smart contracts. Many Non-Ethereum blockchain platforms such as Hyperledger Fabric, Hyperledger Sawtooth and Corda implement their own versions of smart contracts. The smart contract in Hyperledger Fabric is known as Chaincode that runs in a container known as docker(I will discuss Chaincode and how to install it in Docker in a future article). 

Today, most blockchain platforms run on Ethereum Virtual Machine(EVM) implement Ethereum smart contract while a few enterprise blockchain platforms implement their own version of smart contracts. However, there could be interoperability between the Ethereum platform and the enterprise platforms. For instance, in the Sawtooth-Ethereum integration project,  EVM (Ethereum Virtual Machine) smart contracts can be deployed to Sawtooth using the Seth transaction family.  I will discuss Hyperledger technologies in another article.

Solidity

Solidity is a high-level programming language that is used to create and implement smart contracts on Ethereum platform. The smart contracts created using Solidity can be used for financial transactions, crowdfunding, voting, supply chain management, IoT implementation, ride sharing automation, smart city administration and more.

Solidity has Python, C++ and JavaScript influences. Therefore, it is fairly convenient and easy to grasp for those that are already familiar with the Python, C++ or JavaScript. 

Writing and Deploying the Smart Contract

The Integrated Development Environment (IDE)

The best tool to write, compile, test and deploy smart contracts is RemixRemix is a browser-based IDE that provides an inbuilt compiler as well as a run-time environment without server-side components. You can access Remix from the following link: https://remix.ethereum.org

We can also use other code editors for Solidity . I suggest we use Visual Studio Code or Solidity Plugin for Visual Studio. For Solidity plugin, you need to download it from https://marketplace.visualstudio.com/items?itemName=ConsenSys.Solidity

Besides that, you need to install Visual Studio 2015. I shall skip the technical details for now. (I will discuss how to use Visual Studio Code in compiling and deploying smart contracts in another article).

The Smart Contract Code

A smart contract is a data, that can be referred to as its state, and code, which can be referred to as its functions, collection, that resides on a specific address in the Ethereum blockchain. Let us begin with the most basic example. It is fine if you do not understand everything right now, we will go into more detail later. Enter the follow codes in the Remix IDE and save the file as MyStorage.sol

pragma solidity ^0.4.25;

contract MyStorage {
   uint storedData;

   function set(uint x) public {
       storedData = x;
   }

   function get() public view returns (uint) {
       return storedData;
   }
}

Understanding the Code

The first line simply tells that the source code is written for Solidity version 0.4.25 or anything newer that does not break functionality .This is to ensure that the contract does not suddenly behave differently with a new compiler version. The keyword pragma is called that way because, in general, pragmas are instructions for the compiler about how to treat the source code.

A contract in the sense of Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. The line uint storedData; declares a state variable called storedData of type uint(unsigned integer of 256 bits). You can think of it as a single slot in a database that can be queried and altered by calling functions of the code that manages the database. In the case of Ethereum, this is always the owning contract. And in this case, the functions set and get can be used to modify or retrieve the value of the variable.

To access a state variable, you do not need to use the prefix this that is commonly used in other programming languages. This is just a simple contract that does not do much yet apart from allowing anyone to store a single number. This number is accessible by anyone in the world without a feasible way to prevent you from publishing this number. Of course, anyone could just call set again with a different value and overwrite your number. However, the number will still be stored in the history of the blockchain. Later, we will see how you can impose access restrictions so that only you can alter the number.

The Remix IDE

Now enter the code in the Remix IDE, as shown in the following figure:

The Metamask Wallet

In addition, you need to install the Metamask wallet using the Chrome or Firefox extension plugin. After installing Metamask, create an account and connect it to Ropsten Test Network, as shown in the figure below:

Besides that, you need to get some free Ethers to run the test. You can get 1 free Ether for Rospten Testnet from  https://faucet.ropsten.be/. Upon loading the website, copy and enter your Metamask wallet address, and click the send me test Ether button, as shown in the following figure:

After a  while, you can see 1 Ether is deposited into your Metamask wallet, as shown in the figure below:

Next, in the Remix IDE, change the environment to Injected web3, the Ropsten Test Network. You can see that your wallet address appears in the account box, as shown in the first Figure. Now click on the Deploy button. After clicking this button, the Metamask wallet will pop up, prompting for confirmation, as shown in the following figure:

After clicking the CONFIRM button, you will see that some Ether had been deducted from your account which showed that the contract has been successfully deployed, as shown in the following Figure:

Besides that, you can also view the transaction on Etherscan, as shown in the following Figure:

Finally, you can also check the deployment of the smart contact in the Remix debug window, as shown in the following figure:

In addition, you can view some extra information on the right column on the Remix windows, like the name of the smart contract(Mystorage) , how much gas limit and how many transaction etc.

If you are sure the smart contract is bugs free, you may want to deploy it to the Ethereum Mainnet. In that case, change the Environment to Web3 Provider. You will be prompted with the following dialog:

Wait, you need to install Go Ethereum, the client commonly referred to as geth, which is the command line interface for running a full Ethereum node implemented in Go. Install Go Ethereum from the following link: https://geth.ethereum.org/downloads/

After installing Go Ethereum, there a few more windows system set up before you can run geth. I will not go through the steps here, a bit tedious, I have documented them in another document. If you are keen I can share it with you in the future. Let’s say your environment is ready, you can key in the following command in the command line:

geth --rpc --rpccorsdomain "https://remix.ethereum.org" console

Your computer will now link to the Ethereum mainnet via Remix, as shown in the following figure:

Now click OK on the Remix dialog and bring up the next dialog that prompts you to connect to the Web3 Provider Endpoint, as shown in the figure below:

Click OK and now you can deploy the contract to the Ethereum Main Network. Notice that now the Environment is Web3 Provider, which is the Ethereum Mainnet, as shown in the following Figure:

Before you can deploy the smart contract to the Ethereum mainnet ,you need to have the actual Ether to deploy the contract. I suggest you don’t do it here unless you have developed the actual use case and ready to go for ICO.

Happy Learning!

Creating Your Own Token for ICO

ICO is a hot topic in the crypto world today. In this article, I will attempt to explain how to create your own token for an ICO project. 

First of all, you need to set up a private Ethereum, before you can proceed to create the token. After setting up the private network, you need to run it. (The detail steps for setting up a private Ethereum network is discussed in another article)

Next, you need to install the Ethereum wallet before you proceed. Follow the steps below to install the Ethereum Wallet.

  1. Install Ethereum Mist Wallet for Windows 10.
  2. Visit the link https://github.com/ethereum/mist/releases
  3. Download Ethereum-Wallet-win64-0-11-0.zip
  4. Create a folder Ethereum under the Program Files folder and extract the zip files there.

Launch the Ethereum wallet after successful installation. Also, create an account in the wallet.

Next, Open the Wallet app and then go to the Contracts tab as shown in the figure below:

Click on DEPLOY NEW CONTRACT and bring up the  Solidity Contract Source code text editor as shown the following figure:

Now type the following smart contract  code in the code editor.

pragma solidity ^0.4.24;

contract BestToken {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
     string public name;
     string public symbol;
     uint8 public decimals;

    /* Initializes contract with initial supply tokens to the creator of the contract */
 constructor(
     uint256 initialSupply,
     string tokenName,
     string tokenSymbol,
     uint8 decimalUnits
     ) public {
     balanceOf[msg.sender] = initialSupply;  // Give the creator all initial tokens
     name = tokenName;                        // Set the name for display purposes
     symbol = tokenSymbol;                   // Set the symbol for display purposes
     decimals = decimalUnits;               // Amount of decimals for display purposes
    }
    

    /* Send coins */
    function transfer(address _to, uint256 _value) public returns (bool success) {
     require(balanceOf[msg.sender] >= _value);   // Check if the sender has enough
     require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
     balanceOf[msg.sender] -= _value;                    // Subtract from the sender
     balanceOf[_to] += _value;                        // Add the same to the recipient
     return true;
    }
}

Don’t worry about the code first, I will explain them in another article.

If the code compiles without any error, you should see a “pick a contract” drop-down list on the right, as shown in the figure below:

Click Pick a contract button and select the “BestToken” contract. On the right column, you’ll see all the parameters you need to personalize your own token. You can tweak them as you like, I use the following parameters: 10,000 as the supply, BestCoin for the token name, “#” as the symbol and 2 decimal places. Your wallet should be looking like this:

Scroll to the end of the page and you’ll see an estimate of the computation cost of that contract and you can select a fee on how much Ether you are willing to pay for it. Any excess Ether you don’t spend will be returned to you so you can leave the default settings if you wish. Press “deploy”, type your account password and wait a few seconds for your transaction to be picked up.

Now click the DEPLOY button to deploy the smart contract, the output dialog is as follows:

Upon entering the password for your account and click send transaction, the contract is successfully deployed, as follows:

Now the new token Best Token is shown in your wallet, as follows:

Tokens are currencies and other fungibles built on the Ethereum platform. In order for accounts to watch for tokens and send them, you have to add their address to this list. Proceed to add BestCoin to the list, as shown in the following figure.

Now the new token BestCoin will be shown in the list, as shown in the figure below.  

Now you can send some funds from BestCoin to a wallet, as shown in the figure below:

What is Ethereum?

According to the Ethereum Foundation, 

Ethereum is a decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference.

These apps run on a custom built blockchain, an enormously powerful shared global infrastructure that can move value around and represent the ownership of property.

Definition of Ethereum

Based on the above descriptions, Ethereum is an open-source blockchain-based decentralized platform featuring smart contracts.  Indeed, Ethereum is a programmable blockchain that enables developers to build and deploy decentralized applications. Rather than providing users with a set of predefined applications like bitcoin, Ethereum allows users to create any kind of applications they wish. In this way, it serves as a platform for many different types of decentralized blockchain applications, including but not limited to cryptocurrencies.

Ethereum Virtual Machine

At the core of the Ethereum platform is the Ethereum Virtual Machine (“EVM”), which possesses its own programming language, known as the ‘EVM bytecode’.  It is the runtime environment that executes all of the smart contracts on the Ethereum network.

The Smart Contract code is written in high-level programming languages such as Solidity. The code is compiled to the EVM bytecode so that the Ethereum Virtual Machine can understand what has been written.

Decentralized Applications(dapps)

The Ethereum Virtual Machine makes the process of creating decentralized applications much easier than ever before. Instead of having to build an entire blockchain for each new application, the EVM enables users to develop decentralized applications all on one platform.

Cryptokitties  is one of the most well known decentralized application (dapp) among many dapps developed so far. You can check out lots of interesting dapps at https://www.dapp.com/.  I have also developed a prototype dapp that I named it Kittychain Shop. In this virtual pet shop, the user can adopt a kitty, as shown in the figure below.

The Ethereum Architecture

Ethereum runs on a distributed public blockchain network. Each and every node connected to the Ethereum network helps to maintain and update the blockchain database. The nodes of the network run the EVM and execute the instructions according to the smart contracts.   Ethereum node runs the EVM in order to maintain consensus across the blockchain.

Ethereum peers achieve consensus via the proof of work algorithm, which is similar to bitcoin. However, they are planning to shift to the proof of stake algorithm in near future to improve scalability. The consensus gives Ethereum a high level of fault tolerance, ensures zero downtime, and makes data stored on the blockchain immutable and secure.

Like Bitcoin, Ethereum allows individuals to exchange cash without involving any middlemen like financial institutions and others. However, Ethereum is more than just cryptocurrency. Beyond financial applications, we can create decentralized applications where trust, security, and permanence are considered important. Among the potential applications are asset registries, voting, governance, Internet of things, supply chain management and more. 


Similar to Bitcoin, we can also carry out mining activity in Ethereum. However, In the Ethereum blockchain, instead of mining for bitcoin, miners work to earn Ether, the default currency of Ethereum. Beyond a tradeable cryptocurrency, Ether is also used by application developers to pay for transaction fees and services on the Ethereum network. For example, the user needs to pay for acquiring a crypto asset in a dapps marketplace using Ether.