Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and Test-RPC – DEVELOPPARADISE
25/06/2018

Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and Test-RPC

In my last article on Blockchain Development, we learned about setting up the development environment before we start coding or developing our first smart contract. We installed necessary packages and tools that would be needed for development. In this article, we’ll explore Solidity and develop our first smart contract of “Hello World”.

Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

Image credit: https://pixabay.com

Series

You can go through the first article in the series to know how to setup the development environment. Following are the two article series to learn smart contract development.

  1. Blockchain Development (Part 1): Development Environment Setup for Smart Contracts
  2. Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

Smart Contracts and Solidity

Developing smart contracts is nothing but writing code in the supported language of the blockchain implementation for which we need to develop a smart contract. For example, Ethereum supports the language named “Solidity”. The code after been written needs to be compiled to bytecode. There are many compilers available for it and few are available online as well. In this article, we will use Solidity to write code and a framework named “Truffle” that we installed in my last article. Truffle provides us with an inbuilt compiler to compile the smart contract. After successful compilation, the smart contract needs to be uploaded/deployed and mined. Once it is successfully mined, one can start interacting with it. The interaction could be done via user interfaces for the contracts or straightaway via HTTP post method operations. Solidity provides us the flexibility to write code following object-oriented principles. It is the language that is very much like the style of JavaScript. A developer coming from the background of an object-oriented programming language can quickly grasp Solidity and its syntax. Solidity supports both normal and multiple inheritances and its data types and coding structs are very much like any other object-oriented language. For example, “bool” is the keyword to support Boolean data types that can hold either “true” or “false” as a value. Strings, as usual, are used with double quotes but have very limited string manipulation capability that we find in other languages like C#, JavaScript or Java. Solidity has both signed and unsigned integers having a range of 8 bit to 256 bits. One of the important types that Solidity uses is address type. It is used to store addresses used in Ethereum for an account or for a smart contract. Solidity has support for access modifiers like public, private, internal or external. Access modifiers help to provide an abstraction to the code and more control on who can access the code from where. If it needs to be accessed from everywhere, Public is used. If the code needs to be accessed within a contract then we use Private. Internal means that a contract and its deriving contracts (i.e. child types could use the code i.e. methods and properties). Using external only allows contracts methods and properties to be used externally and no child types could access those as was in internal.

A contract in Solidity is defined by a contract keyword and the name of our choice to the contract. This is very much like writing a class in any programming language. A contract after been defined can have methods and variables. One of the important things to remember is that we can have multiple return types in methods in Solidity.

Truffle and Test RPC

Truffle helps us in development of the contract and its testing. The Truffle toolset also acts as an Ethereum development pipeline. Truffle has an inbuilt compiler to build our solution. It supports automated testing and makes it very easy to deploy the contract via deployment locations that are configurable in the solution. Truffle could be used in console mode and we can directly interact with our deployed contracts.

Developing a Smart Contract

Let’s start developing our first smart contract of “hello world”. We’ll start with executing Test RPC and create a project with the help of Truffle and then create our hello world contract.

 

  1. Create a new folder in your windows with the name helloworld.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  2. Once done with folder creation, open a new instance of PowerShell in administrator mode as shown below.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  3. Now, using cd command go to the folder we just created i.e. helloworld as shown in the following image.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  4. Now, we’ll use truffle to kick-start our solution. This will get the framework and simple project created for us in the helloworld directory that will help us to start quickly. So, type command “truffle init” and press enter in the power shell window.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    As you see in the above image, the command runs, downloads necessary packages and sets up our development environment. You can go back to the helloworld folder to check the folders and files created for our development environment.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  5. Now you can launch Visual Studio code and open the folder for our source code or you can follow a simpler method by just typing “code .” in the power shell console window. This will open up the folder for us in our IDE (Integrated Development Environment) i.e. Visual Studio code.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  6. Once VS Code is launched, you can see the files and folders loaded in the solution. We see that it has automatically created some test contracts for us. Let’s leave it as it is for now and move to next step.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  7. Time to create a new contract. Right-click on contracts and add a new file.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    Add a new file with the name of your choice. In my case, I have given it a name helloworld.sol as shown below.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  8. Let’s write some code now. Before we proceed to write our method, we will set pragma as shown in the following image (first line of code) to 0.4.22 that means it works with any version of solidity about 0.4.22. In this way, we would be confident that our code works exactly as expected with the set version.

    Next, define a contract with the name helloworld followed with opening and curly braces just like we do while defining a class, and inside those brackets will be our methods, properties, and variables. Define a function called PrintHelloWorld () that returns a string in the way as shown in the following image and return a hard-coded string saying “Hello World !”.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    Our code looks like as follows,

    pragma solidity ^0.4.22; contract helloWorld {  function PrintHelloWorld () public pure returns (string)   {    return "Hello World !";   } }
  9. Now, save the file by using ctrl+s. The next step is to deploy the contract.

Deploying Smart Contract

  1. Under the migrations folder, we find the file that tells truffle that which files need to be deployed to the blockchain. In that file, create a deployer for helloworld as well by creating a variable named HelloWorld requiring the file helloworld.sol and in the module.exports write deployer.deploy(HelloWorld) as shown in below image.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    The code looks like as follows,

    var Migrations = artifacts.require("./Migrations.sol"); var HelloWorld = artifacts.require("./helloworld.sol"); module.exports = function(deployer) {   deployer.deploy(Migrations);   deployer.deploy(HelloWorld); };
  2. Now we need to run the Test RPC server. To do that, open a fresh new instance on windows PowerShell and leave the already opened instance as it is.

    Type the command testrpc as shown in the following image to start the server. We could see as described by me earlier, as soon as it starts it creates test accounts and private keys for us and the very first account is used as a default account. Some of the features may need access from admin to get started. So, in case a window pops up asking for access, please allow.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    We can see that by default the server runs at the port 8545. Now since our server is up and running, leave this window opened as it is and go back to the prior PowerShell window that we were working on.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  3. It’s time to compile our solution now. Use the command truffle compile to compile the solution. Once compiled as shown in the following image, it will write artifacts to the build/contracts folder.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  4. Now we are good to deploy the contract as it is successfully compiled. We can do the deployment via truffle migrate command as shown below. Type the command press enter.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    Yes, we get an error.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    Image credit: https://pixabay.com

    The error says that it could not determine the current network. So, there is some preparation we need to do to get that working. You can skip steps 5 to 7 if you do not get an error as it may have configured on your version. But for the one who gets this error please follow steps 5 to 7 as well as described below.

  5. Go back to VS Code where the solution is opened and we see a file there named truffle.js that should contain the server configurations.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    By default, everything in that file is commented out and we can define our custom configurations. So, replace the complete text in that file with the code below:

    module.exports = {   networks: {      development: {      host: "localhost",      port: 8545,      network_id: "*" // Match any network id    }  } };

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  6. Now add a new migrations file under migrations node as shown in the following image and call it 2_deploy_contracts.js and move the deploy code from 1_initial_migration.js to this newly created file.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    So, the file contains the code as below.

    var HelloWorld = artifacts.require("./helloworld.sol"); module.exports = function(deployer) {   deployer.deploy(HelloWorld); };
  7. Now again go to the PowerShell window where we got an error and again compile the code by typing the command truffle compile and press enter. Once you press enter, the code will again be compiled for the latest changes we made in VS Code. Now again run the command truffle migrate for deployment.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    This time our migrations run fine as they find the current running server. See the image above as it successfully deploys our contract. We can also see the address it got while uploading.

  8. Now, you can go ahead to create a user interface to test the contract we just deployed, alternatively Truffle also provides a mechanism to interact with the contracts. We can do this via Truffle console. To start the truffle in console mode, run the command truffle console as shown below.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    This opens console listener for Truffle. In this mode, we can directly write JavaScript code for our contract. Let’s do it step by step.

Test Smart Contract

  1. In the truffle console mode, define a variable named helloW or any of your choices with the var keyword. And press enter. We’ll try to access our contract with this variable. After pressing enter we get undefined and that is obvious because the variable is still not defined with any content. Since the communication with contracts should be async, we write an asyn code to access the contract now. Since in our code the contract was referenced using the deployed keyword, so we’ll also access it via helloWorld.deployed(), thereafter a then keyword is used to create an async method that maps our deployed contract with the variable that we created earlier i.e. helloW. The command would be helloworld.deployed().then(function(deployed){helloW=deployed}); See the image below with all the commands to understand in detail.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

  2. Now, access and test the contract with the variable we mapped it to in our last step. Use the method call() to the helloworld contract method to invoke the contract as helloW.PrintHelloWorld.call() as shown in following image.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

    Here we get the string that we were returning from that method and so our method and contract is tested running on internal private Blockchain. Was really a fun to implement and test our smart contract.

    Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and  Test-RPC

Conclusion

In this article, we learned about smart contracts, the language used to develop smart contracts on Ethereum, Truffle and Test RPC. This article serves as a primer to those who are beginners in blockchain development and new to Ethereum and smart contracts. This article gives a foundation on how to start and proceed with smart contract development. I hope you enjoyed creating your own smart contract, deploying and testing it.

Here is a list of articles that will help you getting good insights about Azure, Blockchain, Ethereum and Smart Contracts development using Solidity.

1. Creating Virtual Machine (VM) on Microsoft Azure[^]
2. Setting up Ethereum Blockchain on Azure[^
3. Blockchain Development (Part 1): Development Environment Setup for Smart Contracts[^
4. Blockchain Development (Part 2): Programming Smart Contracts using Solidity, Truffle and Test-RPC[^]

Happy Coding!

References