Introduction
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 those would be needed for development. In this article, we’ll explore Solidity and develop our first smart contract of “Hello World”.
Image credit: https://pixabay.com
Smart Contracts and Solidity
Developing smart contracts is just 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 being 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 e.g. “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 none 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 hell world contract.
- Create a new folder in your windows with the name helloworld.
- Once done with folder creation, open a new instance of PowerShell in administrator mode as shown below.
- Now, using cd command go to the folder we just created i.e. helloworld as shown in the following image.
- 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.
As you see in the above image, the command runs, downloads necessary packages and sets up or development environment. You can go back to the helloworld folder to check the folders and files created for our development environment.
- 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.
- 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.
- Time to create a new Right click on contracts and add a new file.
Add a new file with the name of your choice. In my case, I have given it a name helloworld.sol as shown below.
- 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 will 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 !”.
Our code looks like as follows,
- pragma solidity ^ 0.4 .22;
- contract helloWorld {
- function PrintHelloWorld() public pure returns(string) {
- return "Hello World !";
- }
- }
- Now, save the file by using ctrl+s. Next step is to deploy the contract.
Deploying Smart Contract
- Under the migrations folder, we find the file that tells Truffle 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 deploy (HelloWorld) as shown in below image.
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);
- };
- Now, we need to run the Test RPC server. To do that, open a fresh new instance ow 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.
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.
- It’s time to compile our solution now. Use the command truffle compile to compile as shown in the following image, it will write artifacts to the build\contracts folder.
- Now we are good to deploy the contract as it is successfully compiled. We can do the deployment via the truffle migrate command as shown below. Type the command and press enter.
Yes, we get an error.
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 ones who get this error please follow steps 5 to 7 as well as described below.
- 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.
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: "*"
- }
- }
- };
- 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.
So, the file contains the code as below.
- var HelloWorld = artifacts.require("./helloworld.sol");
- module.exports = function(deployer) {
- deployer.deploy(HelloWorld);
- };
- 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.
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.
- 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.
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
- In the truffle console mode, define a variable named helloW or any of your choices with the var 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 async 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.
- 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 PrintHelloWorld.call() as shown in following image.
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. It was really a fun to implement and test our smart contract.
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.
Happy Coding!
References