1

Introduction to Javascript and Solidity-Part 2: Solidity

2 weeks ago

In the first part, we tackled JavaScript and showed you the very basics of the programming language. In part 2, we are going to be talking about Solidity and how you can use this programming language to your advantage. Before we begin with the coding part, some basics about solidity.

Introduction to Javascript and Solidity-Part 2: Solidity

Solidity – An Introduction

For anyone who wants to learn how to make DAPPs (Decentralized Applications) or get into the ICO game, learning Solidity is an absolute must. Solidity was developed by Gavin Wood, Christian Reitwiessner, Alex Beregszaszi, Yoichi Hirai and several former Ethereum core contributors to enable writing smart contracts on blockchain platforms such as Ethereum.

Solidity is meant to be a purposefully slimmed down, loosely-typed language with a syntax very similar to JavaScript. You can check out the Solidity Docs right here.

Using Solidity you will be coding smart contracts which are going to be executed in the Ethereum Virtual Machine aka EVM. Ethereum developers mention a set amount of gas which is assigned to their contracts. Each line of the contract requires some amount of gas to execute. The gas limit should be enough for the contract to execute completely.

Having said that, let’s begin coding.

Remix – IDE

We are going to execute our codes on Remix. Click here to go on the Remix website. Remix is an in-browser environment where you can execute your smart contracts on a test blockchain. This was created by the Ethereum Foundation themselves so that you can start developing contracts, as and when you please.

So, the moment you go on this website you will see this screen:

Introduction to Javascript and Solidity-Part 2: Solidity

Now, this UI can be extremely intimidating when you look at it for the first time. However, let’s break it down section by section. We will be going from the left.

Introduction to Javascript and Solidity-Part 2: Solidity

The left side of the browser has all the contracts that you are currently working on.

Up next you have this:

Introduction to Javascript and Solidity-Part 2: Solidity

This is the editor where you are actually going to code. By default, the Remix UI has the ballot smart contract which you can ignore for now. There is no need to get into this.

After that you have:

Introduction to Javascript and Solidity-Part 2: Solidity
This is the program log.

Any errors that you face while coding and all the outputs of your program will be detailed in this log.

On the right side you have:

Introduction to Javascript and Solidity-Part 2: Solidity

On the right-hand side, you have the section that’s going to do most of the work. By default, it will be on the “Compile Tab” but it is at the “Run Tab” where you are going to do most of the work.

Introduction to Javascript and Solidity-Part 2: Solidity

Environment: There are three Environments where you can execute your smart contracts which are: JavaScript VM, Injected Web3, and Web3 Provider.

Account: There are five account addresses that you can use as an owner of this contract. Each address has 100 test ether tokens attached to it.

Introduction to Javascript and Solidity-Part 2: Solidity

Gas Limit: The total gas limit that is assigned for the execution of this smart contract.

Value: How much Ether tokens you want to provide for your transactions.

This should be enough for now. Let’s get started with some simple, basic programs.

Data Types in Solidity

Firstly, let’s cover the data types that you will be using in solidity. In computer science and computer programming, a data type or simply type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data.

Is the data an integer or a string or an array?

The way the compiler makes these decisions is by looking at the data type.

So, firstly, let’s check the integer data types that you will have in solidity:

  • Normal integer declaration called “int” which goes from -128 to 127
  • Unsigned Integer “uint” which goes from 0-255 and doesn’t store any negative values

Up next, we have boolean data types which only stores “true” or “false”. To declare boolean values you do this: bool a;

After that, you have Strings and Bytes.

You can use string in solidity as this: string name. Strings are stored as an array of values in solidity.

Bytes is an array of bytes which goes from 1-32 characters. So what is the difference between Strings and Bytes?

Solidity documentation says:

As a rule of thumb, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of bytes1 to bytes32 because they are much cheaper.

Up next, we have something cool called “enum”. Enums are one way to create a user-defined type in Solidity. This is how you declare them:

enum Action {REMOVE, UPDATE}

 So, how do you use them in the program?

Action myAction = Action.UPDATE;

You create a variable of the type Action, which is the name of the enum that we have used in the example above. And then simply assign an action to them.

You can read the solidity docs to get a more in-depth knowledge on various data types.

Basic Programs

#1 Hello World

pragma solidity ^0.4.19;

//section 1

contract myfirstcontract{

   

   string public greeting;

   address public owner;

   

   event GreetingChanged(string oldGreeting, string newGreeting);



//section 2  



   function myfirstcontract(string _greeting) {

       greeting = _greeting;

       owner = msg.sender;

       

   }



 //section 3  



   function setGreeting(string _greeting) {



       require(owner == msg.sender);

       GreetingChanged(greeting, _greeting);

       greeting = _greeting;

   }

}

 

So, we have divided the smart contract into three sections. Let’s look at each of the section and see what’s going on in there.

 

Section 1

 

//section 1</b>

&nbsp;

<b>pragma solidity ^0.4.19;</b>

&nbsp;

<b>contract myfirstcontract{</b>

<b>    </b>

<b>    string public greeting;</b>

<b>    address public owner;</b>

<b>    </b>

<b>    event GreetingChanged(string oldGreeting, string newGreeting);</b>

“pragma solidity ^0.4.19” shows that we are using a the 0.4.19 version of the solidity. The “^” also makes sure that our program will execute on higher versions as well.

“contract myfirstcontract” declares our contract which we have named “myfirstcontract”.

After that we are declaring a string called “greeting” which we will use to save our message. This string is a “public” string. We are also declaring a public variable named “owner” of type address to save the address of the owner of the contract.

The advantage of using a “public” variable is that it automatically gets a “getter” function assigned to them. A getter function helps access the value of a variable while a “setter” function allows you to modify the value.

After that we have an event called “GreetingChanged”. This event makes sure that anytime there occurs any change in greeting, the change is broadcasted.

 

Section 2

 

//section 1</b>

&nbsp;

<b>pragma solidity ^0.4.19;</b>

&nbsp;

<b>contract myfirstcontract{</b>

<b>    </b>

<b>    string public greeting;</b>

<b>    address public owner;</b>

<b>    </b>

<b>    event GreetingChanged(string oldGreeting, string newGreeting);</b>

In this section we are going to declare a constructor. The constructor, as you may have noticed, shares the same name as the contract. The job of the constructor is to initialize the variables during runtime. The constructor takes “_greeting” as a parameter and uses that to initialize “greeting”. At the same time, the address of the person who is sending the parameter is saved in owner. Since the constructor executes only at the beginning of the runtime, the person whose address gets saved is the contract creator.

Section 3

//section 3  

  function setGreeting(string _greeting) {

       require(owner == msg.sender);

       GreetingChanged(greeting, _greeting);

       greeting = _greeting;

   }

In the third section we have the setter function, which will help us modify the values kept in the variables. As a parameter, this function takes in the new greeting, in case a modification is required.

So, what is happening inside the function?

We want to introduce some access control to the program. This is why, we are checking whether the one making the modification is the owner of the contract or not. As we will see later, if someone else tries to do a modification, the compiler will throw an exception and return an error.

So, if that condition is met, the GreetingChanged event is triggered and the value of “greeting” gets updated with “_greeting”.

Alright, so now let’s compile the program. Save your program and choose “myfirstcontract” here:

Introduction to Javascript and Solidity-Part 2: Solidity

After that, click on “Deploy” to execute the contract. The moment you do that, notice what happens in the log.

Introduction to Javascript and Solidity-Part 2: Solidity

You see that message?

It shows the execution was successful. Also do you see that down arrow key next to the Debug button? Click on it and it will open up the details of the transactions:

Introduction to Javascript and Solidity-Part 2: Solidity

Status: Shows that the transaction has succeeded


Transaction Hash: The unique hash of the transaction. It shows the transaction ID.


Contract Address: The address of the smart contract. Whenever a contract is successfully deployed, it gets assigned an address which sorta acts like the contracts ID.


From: The address of the owner of the contract that we have chosen


To: Shows that the constructor has generated the variables.


Gas: The upper limit of the gas that we have set beforehand


Transaction Cost: How much gas it cost to send the contract to the blockchain.


Execution Cost: How much gas it cost to execute the contract.


Hash: The hash of the transaction .


Input: This is the compiled solidity code that is actually read by the Ethereum Virtual Machine.


Decoded Input: The input given to the contract which is passed via the parameters.


Logs: Shows any events that the contract may have generated.


Value: Since the contract was given no Ether tokens by us, it shows 0 wei.

Ok, now we want you to focus on the right side of your screen. Do you see this?

Introduction to Javascript and Solidity-Part 2: Solidity

Next to the “Account” field you will see that the address has a little less than 100 Ether tokens. This shows that this much Ether was used to deploy the contract.

Click the tab under Deployed Contracts and it will reveal this:

Introduction to Javascript and Solidity-Part 2: Solidity

In this:

  • “greeting” and “owner” are getter functions which have been created by default because of the variables were declared as “public”.
  • The “setGreeting” is a setter function where you can input the data.

Since “setGreeting” takes in a string parameter, you must input the data in double quotes. Quite like this:

Introduction to Javascript and Solidity-Part 2: Solidity

 

Once you enter the data, press the “setGreeting” button:

Introduction to Javascript and Solidity-Part 2: Solidity

There are two fields that we want you to focus on:

Decoded Input: Shows the input string that we have given.

Logs: Creates an event which shows that the value of “greeting” has changed.

Alright, now let’s click on the “greeting” button on the getter function:

Introduction to Javascript and Solidity-Part 2: Solidity

It instantly gives you the value of the greeting variable.

When you check the logs you will see the following:

Introduction to Javascript and Solidity-Part 2: Solidity

See the “decoded output” field and you will see “Hello World” there.

Similarly, just click on the “owner” button:

Introduction to Javascript and Solidity-Part 2: Solidity

It shows the value of the address of the owner. Now when you check the logs:

Introduction to Javascript and Solidity-Part 2: Solidity

The decoded output shows the address of the owner of the contract.

Now, let’s do something. Let’s choose some other address in the Account field:

Introduction to Javascript and Solidity-Part 2: Solidity

When you change the address, try to get to enter a new string in the setter function, you will get the following message in the log:

Introduction to Javascript and Solidity-Part 2: Solidity

This error comes because this fails the access control we put into our code. Remember this line of code:

require(owner == msg.sender);

This makes sure that no other address apart from the owner can change the data in the contract.

#2 Name and Age

//section 1



pragma solidity ^0.4.19;



contract mysecondcontract{

   string private name;

   uint private age;

   

//section 2

  

function setname(string newName) {

       name = newName;

   }

   

   function getName() returns (string) {

       return name;

   }

   //section 3    



   function setAge(uint newAge) {

       age = newAge;

   }

   

   function getAge() returns (uint) {

       return age;

   }

}

Section 1

pragma solidity ^0.4.19;



contract mysecondcontract{

   string private name;

   uint private age;

We have declared a smart contract named “mysecondcontract”. This has two private variables. A string called “name” and a unsigned integer (a non-negative integer) called “age”.

Section 2

function setname(string newName) {

       name = newName;

   }

   

   function getName() returns (string) {

       return name;

   }

In this section, we will have the setter and getter function for the name variable. The first part is a normal setter function which takes in a parameter to initialize the name variable.

The second part is a getter function which helps the owner access the “name” variable.

Section 3

function setAge(uint newAge) {

       age = newAge;

   }

   

   function getAge() returns (uint) {

       return age;

   }

This part defines a setter and getter function for age.

Let’s execute the contract and set age as “28”. The log now looks like this:

Introduction to Javascript and Solidity-Part 2: Solidity

As you can see, the age is reflected in the “decoded input”.

Now, let’s set the name as “Max”.

Now, the decoded input field shows the name “Max”.

We can now check the getter function of the age to see the output:

Introduction to Javascript and Solidity-Part 2: Solidity

The output field shows the age.

Now, for the getter function of the name:

Introduction to Javascript and Solidity-Part 2: Solidity

Now it shows the decoded output i.e. the name.

Inheritance and Solidity

Inheritance is one of the most powerful tools in programming. In solidity, it helps you derive one smart contract from an older smart contract. The format looks like this:

contract A {

-------

}



contract B is A {

------

}

The “is” keyword implies that the contract B is inheriting value from contract A. Now, contract A can define which of its elements it wants to share with contract B via access modifiers. Solidity gives you four access modifiers:

  • Private: The element doesn’t get inherited and nor can it be accessed by external elements.
  • Public: The element can be inherited and be accessed by external elements.
  • Internal: The element can be inherited but can’t be accessed by external elements
  • External: The element can’t be inherited but it can be accessed by external elements.

Ok, now that we have mentioned all that, let’s do some inheritance on our contract. We will be modifying the mysecondcontract code.

pragma solidity ^0.4.19;



//section 1



interface regulator {

   function checkValue(uint amount) returns (bool);

   function loan() returns (bool);

   

}



#section 2



contract Bank is regulator {

   uint private value;

   

   function Bank(uint amount) {

       value = amount;

   }

   function deposit(uint amount) {

       value += amount;

   }

   

   function withdraw(uint amount) {

       if (checkValue(amount)) {

           value -= amount;

       }

   }

   

   function balance() returns (uint) {

       return value;

   }

   

   function checkValue(uint amount) returns (bool) {

       return value >= amount;

   }

   

   function loan() returns (bool) {

       return value > 0;

   }

}

//section 3

contract mysecondcontract is Bank{

   string private name;

   uint private age;

   

   function setname(string newName) {

       name = newName;

   }

   

   function getName() returns (string) {

       return name;

   }

   

   function setAge(uint newAge) {

       age = newAge;

   }

   

   function getAge() returns (uint) {

       return age;

   }

}



Section 1



Lets look at the code in question:



interface regulator {

   function checkValue(uint amount) returns (bool);

   function loan() returns (bool);

   }

 

Let’s look at the code in question:

 

interface regulator {

   function checkValue(uint amount) returns (bool);

   function loan() returns (bool);

   }

 

The first thing that we have declared is an interface. The interface helps you define the functions without actually revealing how they are going to be working internally. Their internal mechanisms are to be revealed in the other contracts.

Section 2

 

contract Bank is regulator {

   uint private value;

   

   function Bank(uint amount) {

       value = amount;

   }

   function deposit(uint amount) {

       value += amount;

   }

   

   function withdraw(uint amount) {

       if (checkValue(amount)) {

           value -= amount;

       }

   }

   

   function balance() returns (uint) {

       return value;

   }

   

   function checkValue(uint amount) returns (bool) {

       return value >= amount;

   }

   

   function loan() returns (bool) {

       return value > 0;

   }

}

So, we have declared a contract called bank which is inheriting its values from the interface. The first thing that we are doing is declaring a constructor which will initialize the variable value.

After that we have a couple of setter functions called “withdraw” and “deposit” which helps the contract withdraw and deposit from the user’s account.

Look at the withdraw function in particular.

function withdraw(uint amount) {

       if (checkValue(amount)) {

           value -= amount;

       }

Before we can withdraw, the function calls the checkValue function that it has inherited from the interface to make sure whether the user has enough value in their account to withdraw the money or not.

After the setter functions, we have the getter functions which returns, in order:

  • The balance in the user’s account
  • Whether the user has enough money for a withdrawal or not.
  • If the user is open for a loan or not. For this we are just checking if the user’s balance is > 0  or not.

Section 3

 

contract mysecondcontract is Bank{

   string private name;

   uint private age;

   

   function setname(string newName) {

       name = newName;

   }

   

   function getName() returns (string) {

       return name;

   }

   

   function setAge(uint newAge) {

       age = newAge;

   }

   

   function getAge() returns (uint) {

       return age;

   }

}

This section of the contract is the same as before. The only difference being that it is inheriting properties from the Bank contract.

Solidity Imports and Libraries

Up next we have to important solidity functionalities that you should be comfortable with, imports and libraries. For this, we are going to create two separate contract files which we are going to call “library.sol” and “testLibrary.sol”.

Our library.sol program looks like this:

pragma solidity ^0.4.19;



contract Libraries {

   function test() {}

}

And testLibrary looks like this:



pragma solidity ^0.4.19;



import "browser/library.sol";



contract testLibrary is Libraries {

   

}

The testLibrary program is simply importing the Libraries file which is stored in the location: browser/library.sol. All solidity programs, by default, are stored in browser folder.

Access Modifiers and Fallback Functions

Access modifiers and Fallback Functions are fun little tools that you can use to spice up your contracts. Let’s begin with fallback functions. Check out the following code:

 

pragma solidity ^0.4.19;



contract testTransaction {

   

   event SenderLogger(address);

   event ValueLogger(uint);

   function () payable {

       SenderLogger(msg.sender);

       ValueLogger(msg.value);

   }

   

}

 

This is a simple smart contract which lets you extract the details of a transaction. Basically, if someone sends Ether to this contract, then this contract will extract:

  • The address of the sender
  • The amount of Ether that they are sending.

The fallback function is right here:

 function () payable {

       SenderLogger(msg.sender);

       ValueLogger(msg.value);

   }

As you can see, the function has no name and you can only put in one fallback function in each contract. The idea is to enable anyone to get in touch with the contract and send Ether tokens to it.

So, let’s execute the program and see some data. We are going to deploy the contract. Put 1 Ether in the “value” field and press the “fallback” button.

Introduction to Javascript and Solidity-Part 2: Solidity

So, now let’s check the logs.

Introduction to Javascript and Solidity-Part 2: Solidity

The last field in the table in the value field which shows the amount of Ether in wei that has been sent to the contract.

Alright, so now let’s put some modifiers in the program and change things around.

 

pragma solidity ^0.4.19;



contract Transaction {

   

   event SenderLogger(address);

   event ValueLogger(uint);

   

   address private owner;

   

   modifier isOwner {

       require(owner == msg.sender);

       _;

   }

   

   modifier validValue {

       assert(msg.value >= 1 ether);

       _;

   }

   

   function Transaction() {

       owner = msg.sender;

   }

   

   function () payable isOwner validValue {

       SenderLogger(msg.sender);

       ValueLogger(msg.value);

   }

   

}

Ok, so this contract is the same as the previous one. We still want to extract transaction details. However, we have added the following two conditions:

  • Only the owner of the contract can send the transaction
  • The transaction should be at least 1 Ether

So, let’s look at a modifier and see how we are executing it:

modifier isOwner {

       require(owner == msg.sender);

       _;

   }

So, what exactly are we doing here?

We have declared a modifier, which is basically a custom access control function, which runs a “require” function to make sure that only the owner can use the contract.

Do you also notice the “_;”?

This indicates that after the access modifier is executed, the function whose entrance it is protecting needs to run as well.

Let’s check our next modifier:

modifier validValue {

       assert(msg.value >= 1 ether);

       _;

   }

This is again a straightforward modifier which is checking whether the value passed into the contract is greater than 1 ether or not.

Ok, so now that we have defined these modifiers, how exactly are we going to utilize them in the function? Well, let’s check it out:

function () payable isOwner validValue {

       SenderLogger(msg.sender);

       ValueLogger(msg.value);

   }

See our fallback function now? We have added the access modifiers to the function header to restrict access to it. Now, let’s run the contract through Remix and see what we get here.

Let’s add an ether to the value field and see what we get.

Introduction to Javascript and Solidity-Part 2: Solidity

The log shows:

  • The address of the sender
  • The value of Ether put inside the contract

Now, what happens if we:

  • Send less than 1 ether
  • Send ether from a different address

Less Than 1 Ether

We sent 0.2 Ether in the value field and the program immediately gave an error:

Introduction to Javascript and Solidity-Part 2: Solidity

From A Different Address

We sent 1 Ether from a different address. Once again we get an error:

Introduction to Javascript and Solidity-Part 2: Solidity

Structures and Mapping In Solidity

Before we end this guide, we want to familiarize you with two more concepts that you are going to run into while coding.

  • Structures
  • Mapping

Structures are objects which lack methods. They only define the variables.

Mapping in solidity is sorta like a hash table which initialized virtually so that each potential key exists. Mapping can be declared like this:

mapping (A => B).

A = Can be of any type apart from mapping, array, enum, contract, and struct.

B = Can be of any type (including mapping).

Let’s execute a program which includes both of these features:

 

pragma solidity ^0.4.19;



contract showmap {

   

//Section 1

  

 struct Account {

       uint balance;

   }

   

   Account myAccount;

   

   function structFunc() {

       myAccount.balance = 100;

   }

   

//section 2

   

mapping (address => Account) _accounts;

   

   function () payable {

       _accounts[msg.sender].balance += msg.value;

   }

   

   function getBalance() returns (uint) {

       return _accounts[msg.sender].balance;

   }

}

Section 1

So, we have declared a structure named Account which has a uint datatype named “balance”. We then initialized a variable named myAccount of type Account and then used the structFunc() function to assign a value of 100 to the myAccount.balance.

Section 2

By using the mapping keyword, we are mapping addresses to our Account structure and calling it “_accounts”.

We then have a fallback function to add the ether given to it by the user into their balance. The getBalance() function then returns the value of the updated balance to the user.

Let’s look at this in action.

We are going to send 10 Ether to the smart contract.

So, using the fallback function, we sent 10 Ether to the account which you can see in the log here:

Introduction to Javascript and Solidity-Part 2: Solidity

So, if we getBalance right now, this is what we will get:

Introduction to Javascript and Solidity-Part 2: Solidity

Note the “decoded output” field and notice how the balance is reflected as 10 Ether.

Introduction to Javascript and Solidity-Part 2: Solidity

Now, let’s send 10 more Ether to the contract via the fallback function and let’s check the balance again via getBalance().

If you see the getBalance() field then you will notice that the balance reflects 20 Ether.

Conclusion

There is a lot more to solidity than what we have covered here. In the near future, we are going to show you how you can create your own cryptocurrency using solidity.

However, for now, if you want to educate yourself even more, then enroll for our solidity courses. We have extremely well-trained teachers who are going to guide you through your journey as a developer.

You can also check out these series of videos by “What’s Solidity”. They have superb videos and majority of the code used here have been taken from their gitHub page.

The purpose of these two articles was to give you an introduction on both JavaScript and Solidity. We hope that you have your basics clear now to take on more challenging programs/contracts.

Like what you read? Give us one like or share it to your friends

6
1

Related Guides

Join Blockgeeks

Create an account to access our exclusive point system, get instant notifications for new courses, workshops, free webinars and start interacting with our enthusiastic blockchain community. Don’t miss out and join right now!

Already have an account? Sign In

Comments

    The Code displayed when explaining “Section 1,” “Section 2” and “Section 3” have HTML tags embedding in them (which I don’t thinks was intended). Also,the code display in the “Section 2” explanation is a duplicate of the “Section 1” code sample.