Best Ethereum Smart Contract Tutorial: How to Guide!


Back to New at Nirolution Solidity Tutorial Blog

Best Ethereum Smart Contract Tutorial: Learn Ethereum!

Do you want to build a smart contract, but you don´t know how to start? With our Ethereum Smart Contract tutorial you will learn step by step how to create a smart contract. We will show you how to install Solidity, what you need for a smart contract and how you can modify your smart contract.

“Ethereum Smart Contract Tutorial” – Content:

  1. Step 1: How To Install Solidity
  2. Data types of Solidity
  3. Step 2: Built your Solidity Smart Contract
  4. Step 3: Smart Contract Heredity
  5. Step 4: Smart Contract Modifier


Ethereum Smart Contract Tutorial Step 1: How To Install Solidity

Before we can built our smart contract, you first need to download the following tools:

This shouldn’t take long. Once you have successfully installed all three tools, we also need an extension for Visual Studio to run Solidity.

You can download it here.

Now we can start. So you have to create an empty folder called Truffle on your desktop. Then go to Visual Studio and open this folder via File -> Open Folder. After you need to download a test environment that we can work with.  To do this, type the following command into the terminal (Use the View > Terminal menu command):

npm install truffle -g

If you receive an error message, simply restart Visual Studio and try it again. It should work after the restart.

Ethereum Smart Contract Tutorial


So, this gives us the tools we need to create our Smart Contract with Solidity and an environment, now we can test our Smart Contracts.

Now we need Ganache. It’s a local Blockchain for developing and testing Blockchain code.

You can find the link here.

Here are 10 Ethereum accounts with 100 exemplary Ethers each which of course have no value.

Ethereum Smart Contract Tutorial


The last thing we need is MetaMask. It is a browser extension and we need it, so we can connect the Blockchain that we just downloaded with our browser. Therefore, you need to download the corresponding browser extension, depending on which browser you are using.

Optional: Highlighting code helps you a lot with programming. Thus, we need a text editor for that. It is optional and you don´t have to download it, but it can help you a lot. You can find the link here.

Data types of Solidity

Before we can jump right into building our Smart Contract, we first need to cover some basics. Solidity is a new blockchain programming language. More specifically, it is a contract programming language. Thus, it lets you create Smart Contracts, Dapps, and more.

Solidity is a statically typed language, which means that the Data types for Solidity of each variable must be specified at compile time. This also means that all classes have to be static. Before we can create our Smart Contract, here is a brief introduction to Solidity’s data types.

  • Hash: 256-bit, 32-byte data chunk, indexable in bytes and operable with bitwise operations.
  • uint: 256-bit unsigned integer that works with bitwise and unsigned arithmetic operations.
  • int: 256-bit signed integer that works with bitwise. That means values can also be negative.
  • string32: Zero terminated ASCII string with a maximum length of 32 bytes (256 bits).
  • Address: Account identifier, similar to a 160-bit hash type.
  • bool: Two-status value, True/False.
  • Structs: physical grouping of variables.

The data types of Solidity differ only slightly from those in Java. However, it is important to know these small differences because they are key for successfully learning Solidity. Now we can start to create our Smart Contract.

Ethereum Smart Contract Tutorial Step 2: Built your Solidity Smart Contract

So the next step of our Ethereum Smart Contract tutorial is to actually build one. Solidity is a contract-oriented programming language based on Ethereum. It is an interesting and exciting programming language that is becoming more and more popular. Let’s dig into it!

First, we have to open Visual Basics. So in the beginning, we have to tell Solidity that we want to use it and, of course, which version we need.
For this, we type in “pragma solidity” at the beginning and then the version we want to use.

pragma solidity ^0.4.0;

After that, we define a contract of type “Contract” and give him a name. Then we have to give our contract a name. Here you can choose any name you want. In our example, we will call our contract “MyFirstContract”.

Please note that we want to stick to the correct notations when creating variables, classes, and methods right from the start. This means we distinguish between Camel Case and Pascal Case. PascalCase means that if we give our variables names, we start each word with a capital letter. This is only true for class names (e.g. our contract) and methods. As an example, we can take our contract MyFirstContract, where each new word starts with an uppercase letter (another example would be ThatIsAnExample). With camelCase, each name starts with a small letter. However, this is only used for naming variables (e.g. uint) and arguments of methods. As example “uint aVariableDeclare”)

Name your Smart Contract

So now we have to determine what we want to include in our Smart Contract. First we have to add the name to our contract. For this, we can simply use “string name;” as in Java.

pragma solidity ^0.4.0;

contract MyFirstContract {

string name;
}

Set Datatypes

You can set this variable to private by modifying the access modifier “private”. This is not set at the beginning of the variable like in Java, but between the data type and the name of the variable. This will look like the following:

pragma solidity ^0.4.0;

contract MyFirstContract {

string private _name;
}

The convention for naming our private variables will have an underscore “_” right before the actual name, written in lowercase.

Furthermore, we need an age for our Smart Contract. For this, we used “uint private _age”. The syntax looks like this:

pragma solidity ^0.4.0;
 
contract MyFirstContract {

string private _name;
uint private _age;
}

Create a Set and Get Function

Because now all variables are private, they don’t have a real function yet. Therefore, we create a set and get function for “_name” and “_age”. Our two fields will be now called ‘property’. So this means that when we later talk about properties, we mean fields with either a set or a get- function (or natural with both). But what do we achieve now? Now with the help of a get-function we can access our variable from the outside and for example, display it on our screen.

However, this only refers to the output and not to the assignment. So now the set function comes into play. Over this we can get access to our properties. With certain plausibility checks, we can intercept impermissible values beforehand. For example our property “_age” may not be smaller than 0 or our string “_name” must contain at least x characters.

We can do this the same way as in JavaSkript. Therefore, we simply enter “function” into the console. Then the keyword “set” appears followed by the property we want to change, in our case “Name”. Now we have to declare a parameter within parentheses, just like with a method. This entered value (string) is then stored by the console. So in our case, we create another variable named “newName” of the same type as “name” (Attention: use camelCase here). This is then assigned to our private variable within our set function.

This will look like this:

pragma solidity ^0.4.0;

contract MyFirstContract {

string private _name;
uint private _age;

  function setName(string newName) {
  
  _name = newName;
  }
}

Everything we type into the console will change the name of our contract because of the function “setName”.

Now we can now display the name on the screen, we write a get-function for it. This works like the set function. Therefore we write a get „followed by“ name. The only difference here is that we only have a return, because we only want to get the value displayed.

pragma solidity ^0.4.0;

contract MyFirstContract {

string private _name;
uint private _age;

  function setName(string newName) {
  
  _name = newName;
  }

  function getName() returns (string) {
  
  return _name;
  }
}

Now we do the whole thing for the variable Age. This should look like this:

pragma solidity ^0.4.0;

contract MyFirstContract {

string private _name;
uint private _age;

  function setName(string newName) {

  _name = newName;
  }

  function getName() returns (string) {

  return _name;
  }

  function setAge(unit newAge) {

  _age= newAge;
  }

  function getAge() returns (unit) {

  return _age;
  }
}

Create a Plausibility Check

Finally, we can add a plausibility check to the two SET functions. For the age we naively say that the input have to be higher than 0. For the name we want an input with at least one character and that it should be unequal to zero.

Now we have our two methods and can easily test if our simple Smart Contract works. We just have to press “Create” and if we have done everything right, we can enter the name as well as the age. So it is important that you use quotation marks when entering strings.

You have now created your first very simple Smart Contract in Solidity.

Ethereum Smart Contract Tutorial Step 3: Smart Contract Heredity

The next step in our Smart Contract Tutorial is to use heredity. So now we want to inherit “MyFirstContract” from our first contract. This will make it the so-called upper class. So all classes or contracts inherited from it will automatically become its subclass. The subclasses inherit all methods, properties, and fields from the superclass without having to create them again.

With solidity heredity we do not have to define any additional functions in our own contract, we can simply access functions with of the superclasses.

How does it all work now?

Based on our simple Smart Contract “MyFirstContract” we now create a new contract in Solidity called “Bank”. So that our “MyFirstContract” contract can inherit the functions from “Bank”, we need the “is” function. This will look like this:

pragma solidity ^0.4.0;

contract MyFirstContract is Bank {

}

Create a Bank Account

Now we have to create our Smart Contract “Bank”. This works like our bank account. Depending on the amount of money deposited, our bank account has a certain value, a possibility to make deposits, and we should be able to withdraw the money.

First, we create the Smart Contract “Bank” with an indefinite value. For this indefinite value we create a new private field of the type “uint” and call it “_value”. We use this data type because we only want positive values and it would not make sense to deposit a negative amount. Such cases can also be intercepted with the help of a plausibility check.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;

}

Create a Deposit Function

After that, we need a function to deposit money into the account. The function now gets a parameter of type “unit” from the outside (i.e. by an input from the console), which we declare with “amount”. The following will happen: If you now want to deposit money, the function “Deposit” gets a certain value from the outside. Within this function we now perform the following calculation.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;

  function deposit(unit amount) {

  _value += amount;
  }
}

The value of the bank account is the sum of all deposits we have made. Therefore, we use “value+=amount;”.

Create a withdraw function

Now we have to be able to withdraw money. Therefore we write a “withdraw” function.

pragma solidity ^0.4.0;

contract Bank {
  
uint private _value;

  function deposit(unit amount) {

  _value += amount;
  }

  function withdraw(unit amount) {

  _value -= amount;
  }
}

This function actually works exactly like our “deposit” function, but we deduct the paid amount from our account within the function.

The value of the account is reduced by the value “amount”.

Create a balance function

Now we still need a function to be able to get our current account balance. Therefore, we create the function “Balance” which should return us an integer value. Here we do not use the data type “uint”, because with our credit card we are able to get negative values.

This function is created as follows: First we write the keyword “function”, because it is a function. Then we give the function a name, in our case “Balance”. Immediately after that, there are 2 empty round brackets. If we still had parameters, which the function would get from outside (see function “Deposit” or “Withdraw”), we would have to define them within the round brackets. Finally, there is the return of the function, which is done with the keyword “returns” and then the data type that we want to be returned.

Within the function we simply return the value “value” calculated in our above functions.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;

  function deposit(unit amount) {
  
  _value += amount;
  }

  function withdraw(unit amount) {
  
  _value -= amount;
  }

  function balance() returns(unit) {
  
  return _value;
  }
}

The function should show us the current value of our bank account.

Create a check value function

So that nobody withdraws money, which he does not have, we must create a function at the end that checks it. Therefore, we write a function “CheckValue” which should return us a “Boolean”. This data type has two states, true or false.

The function has the same structure as our “Balance” function, but this time we get a Boolean back.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;

  function deposit(unit amount) {
  
  _value += amount;
  }

  function withdraw(unit amount) {
  
  _value -= amount;
  }

  function balance() returns(unit) {
 
  return _value;
  }

  function checkValue(uint amount) returns(bool) {
 
  return _value >= amount;
  }
}

Create a plausibility check

Now we have to change our “Withdraw” function so you can only withdraw money if you have enough in your account. We create a plausibility check for this. These always work according to the same principle. Since we only want to perform a function if all checks were successful, we always write our check at the beginning of a function. With the help of an “if-Statement” we can write our function “CheckValue” in parentheses after the “if”. This function now gets the amount we want to withdraw as parameter, therefore, the value in “amount” is passed to the function. If the check is OK, a “true” is returned and we process the code within the “If-Statement”. Alternatively “CheckValue(amount) == true” would also work. However, if the function returns “false”, the calculation would not be executed and the bank account would remain untouched.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;

  function deposit(unit amount) {
  
  _value += amount;
  }

  function withdraw(unit amount) {
  
    if (checkValue(amount)) {
    
    _value -= amount;
    }
  }  

  function balance() returns(unit) {
  
  return _value;
  }

  function checkValue(uint amount) returns(bool) {
  
  return _value >= amount;
  }
}

Our contracts inherit from Bank

Our virtual bank account is now ready. We can now deposit and withdraw money. Since our Smart Contract “MyFirstContract” inherits from “Bank”, it now also has the functions “deposit”, “withdraw” and “balance”.

Ethereum Smart Contract Tutorial Step 4: Smart Contract Modifier

The next step of our Ethereum Smart Contract tutorial is creating a modifier. When you create a Smart Contract, some kind of message is sent to the Blockchain. This message allows you to access your contract. So that no one else but the creator of the Smart Contract can change anything, we create a new variable of type address called “owner”.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;
adresse private _owner;

}

With “address” we can store a 20-byte value and perform operations such as “==” (equality) or “>” (greater than). This data type also has a so-called “members”. These are additional prescribed methods like “send” or “balance”, which can be called via a modifier. But we’ll get to that later.
Smart Contract Constructor

Now we have to assign the message to the variable “_owner” in the constructor of Bank when creating the Smart Contract. Constructors basically work like normal methods or functions, but they have a few significant differences. First of all, we need to explain the construction of a constructor. They only have the keyword “function” in front of the actual name. Also, the name is not randomly selectable, because this always depends on the name of the class or in our case on the “contract” (in our example: “bank”). Unlike methods, the constructor has no return values. A class or contract can have as many constructors as you want, but they must differ in at least one parameter (the variables in the round brackets). These values have to be specified in the round brackets after “new Contract ()” when creating a new object or Smart Contracts. (Contract c = new Contract(- here -) )

The last and perhaps most important feature of a constructor is that you can call it only once when creating an object or Smart Contracts after compiling. Therefore, the constructor is usually used to set start values (default values) and to prevent unwanted entries with plausibility checks.

pragma solidity ^0.4.0;

contract Bank {
uint private _value;
adresse private _owner;

  function Bank(uint amount){

  value = amount;
  owner = msg.sender;
  }

  modifier _ownerFunc {
 
  require(owner == msg.sender);
  _;
  }
}

Create a Solidity Modifier

So to be able to use the variable “owner” now, we have to create a modifier.

pragma solidity ^0.4.0;

contract Bank {
uint private _value;
adresse private _owner;

  function Bank(uint amount){

  value = amount;
  owner = msg.sender;
  }

  modifier _ownerFunc {
  
  require(owner == msg.sender);
  _;
  }
}

For this, we use the keyword modifier and call our construct “ownerFunc”. Now we specify the requirement with “require”. The “owner” and the message of the creator must be the same. Only the address of the creator is compared with that of the sender. If this statement is “true”, the code is processed. If this statement is “false”, nothing happens. Then we set “_;” so that the function is always executed first. This will display an error if someone who is not the creator of the smart contract wants to change something. Now we just need to add “ownerFunc” to each function where we don’t want anyone other than the creator to be able to change anything.

At the end of each affected method, we add our modifier “ownerFunc” after the parameter values.

pragma solidity ^0.4.0;

contract Bank {

uint private _value;
adresse private _owner;

  modifier _ownerFunc {
  
  require(owner == msg.sender);
  _;
  }

  function deposit(unit amount) _ownerFunc {
  
  value += amount;
  }

  function withdraw(unit amount) _ownerFunc {

    if(checkValue(amount)) {
  
    value -= amount;
    }
  }
}

Now only the creators of the Smart Contract can deposit and withdraw money.

With this, you have created a simple and working Smart Contract. We hope you like our Ethereum Smart Contract tutorial.

We hope you like our Ethereum Smart Contract Tutorial. If you want to be informed about the latest updates, follow us on Facebook, Pinterest and Steemit.

Stay current on your favorite topics

Leave a Reply