Smart Contracts

Share

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.”

Therefore, we can say that smart contract is 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.

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) that 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 in Ethereum. 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 and it 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 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 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).

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;
   }
}


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 that 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, but 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.

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

The Remix IDE

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!




Share

Fungible vs Non-fungible Tokens on the Blockchain

Share

In this article, let’s us examine the differences between the fungible token and the non-fungible token. The differences are shown in the table below:

Fungible TokensNon-fungible Tokens
Interchangeable
A fungible token can be exchanged with any other fungible token of the same type. It it like exchanging a dollar bill with another dollar bill and the value is still the same.
Non-Interchangeable
A non-fungible token cannot be exchanged with another non-fungible token of the same type. It is like your passport or ID, they cannot be exchanged.
Uniform
Each fungible token is identical to all other fungible tokens of the same type. For example, your one dollar bill is the same as John’s one dollar bill.
Unique
Each token is unique and different from all other tokens of the same type. For example, your bank account is not the same as John’s bank account
Divisible
A fungible token can be divided into smaller units and the total value is still the same. For example, you can divide a dollar bill into two 50 cents or five 20 cents  and the total value is still the same.
Non-divisible
Non-fungible token cannot be divided into smaller units. The basic unit is one token and one token only. For example, your driving license.
ERC-20 Standard
The Ethereum Standard used for issuance tokens to be used as cryptocurrencies.
ERC-721 Standard
The Ethereum Standard used for issuance of unique, non-fungible token. The most well known case is CryptoKitties, it is a virtual collectible where each kitty is unique.

Non-fungible tokens can be used in KYC (Know Your Customer) procedures, for academic degrees and other educational certificates, collectibles, badges, voting & elections, loyalty programs, in-game items, copyright, supply chain tracking, medical data, software licenses, warranties, and more. The non-fungible tokens are suitable for developing dapps and business applications like supply chain management. I will discuss the techniques in creating dapps as well as creating a supply chain management ecosystem using Hyperledger frameworks in my future articles.

Share

Creating your own token for ICO

Share

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 testnet 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:

Share

What is Ethereum?

Share

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.


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.

At the core of it is the Ethereum Virtual Machine (“EVM”), which can execute code of arbitrary algorithmic complexity. In computer science terms, Ethereum is “Turing complete”, which means It enables anyone to run any program, regardless of the programming language given enough time and memory.  Some of the commonly used programming languages for creating the decentralized applications are JavaScript, Java, Python and more. In addition, the default scripting language for writing the smart contracts is Solidity.

The Ethereum Virtual Machine makes the process of creating blockchain applications much easier and efficient than ever before. Instead of having to build an entirely original blockchain for each new application, Ethereum enables the development of potentially thousands of different applications all on one platform. Cryptokitties is one of the most well known decentralized applications (dapps) among the many dapps developed so far. You can check out many interesting dapps at https://www.dapp.com/.  I have also developed a prototype dapp that I named it Kittychain Shop where the user can adopt a kitty, as shown in the figure below.

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 executes the instructions according to the smart contracts.   Ethereum node runs the EVM in order to maintain consensus across the blockchain. Similar to Bitcoin, Ethereum peers achieve consensus via the proof of work algorithm. 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, banks, or governments. However, Ethereum is more than just cryptocurrency. Beyond financial applications, we can create 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.

Share

What is Merkle Tree in Blockchain?

Share

In my article ‘Blockchain in a Nutshell’, I have mentioned Merkle tree as one of the metadata in a block of the blockchain. What actually is the Merkle tree?

In computer science, the Merkle tree is a branching data structure that is used to store hashes of individual data in a large dataset. The purpose is to make the verification of the dataset efficient and fast. It is an anti-tamper mechanism to ensure that the large dataset has not been tampered with.

In blockchain,  the Merkle tree(also known as the hash tree) encodes the blockchain data in an efficient and secure manner. Every transaction occurring on the blockchain network is subjected to a hashing algorithm to produce a hash, as shown in the figure below. Therefore, every transaction has a hash associated with it.

As there are thousands of transactions stored on a particular block, it will be very time consuming if every node has to deal with hundreds of thousands of transaction across the blockchain, synchronization and mining will take a long time. To solve this issue, all the transactions hashes in the block are also hashed. As illustrated in the following figure, two hashes are hashed into a single hash.

These hashes are not stored in a sequential order on the block, rather in the form of a tree-like structure such that each hash is linked to its parent following a parent-child tree-like relation. The hashing will go on until it produces a singular hash,  the Merkle root. This Merkle root is the hash of the block and it is stored on the header of the block. The process is illustrated in the following diagram:

The Merkle Tree structure will enable the quick verification of blockchain data and quick movement of large amounts of data from one computer node to the other on the peer-to-peer blockchain network.

Share