Categories
2. Execute Solidity Smart Contract using Remix IDE

Solidity – While, Do-While, and For Loop

Loops are used when we have to perform an action over and over again. While writing a contract there may be a situation when we have to do some action repeatedly, In this situation, loops are implemented to reduce the number of lines of the statements. Solidity supports following loops too ease down the programming pressure.

While Loop

This is the most basic loop in solidity, Its purpose is to execute a statement or block of statements repeatedly as far as the condition is true and once the condition becomes false the loop terminates. 

Syntax:

while (condition) {
    statement or block of code to be executed if the condition is True
}

Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop.

// Solidity program to
// demonstrate the use
// of 'While loop'
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring a dynamic array
	uint[] data;
	
	// Declaring state variable
	uint8 j = 0;
	
	// Defining a function to
	// demonstrate While loop'
	function loop(
	) public returns(uint[] memory){
	while(j < 5) {
		j++;
		data.push(j);
	}
	return data;
	}
}

Output : 
 

While Loop Output

Do-While Loop

This loop is very similar to while loop except that there is a condition check which happens at the end of loop i.e. the loop will always execute at least one time even if the condition is false. 

Syntax:

do 
{
   block of statements to be executed
} while (condition);

Example: In the below example, the contract Types demonstrate the execution of a do-while loop and how an array can be initialized using the do-while loop.

// Solidity program to
// demonstrate the use of
// 'Do-While loop'
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring a dynamic array
	uint[] data;
	
	// Declaring state variable
	uint8 j = 0;

	// Defining function to demonstrate
	// 'Do-While loop'
	function loop(
	) public returns(uint[] memory){
	do{
		j++;
		data.push(j);
	}while(j < 5) ;
	return data;
	}
}

Output : 
 

Do-While Loop Output

For Loop

This is the most compact way of looping. It takes three arguments separated by a semi-colon to run. The first one is ‘loop initialization’ where the iterator is initialized with starting value, this statement is executed before the loop starts. Second is ‘test statement’ which checks whether the condition is true or not, if the condition is true the loop executes else terminates. The third one is the ‘iteration statement’ where the iterator is increased or decreased. Below is the syntax of for loop :

Syntax:

for (initialization; test condition; iteration statement) {
       statement or block of code to be executed if the condition is True
}

Example: In the below example, the contract Types demonstrate the execution of a while loop and how an array can be initialized using the while loop.

// Solidity program to
// demonstrate the use
// of 'For loop'
pragma solidity ^0.5.0;

// Creating a contract
contract Types {
	
	// Declaring a dynamic array
	uint[] data;

	// Defining a function
	// to demonstrate 'For loop'
	function loop(
	) public returns(uint[] memory){
	for(uint i=0; i<5; i++){
		data.push(i);
	}
	return data;
	}
}

Output :  

For Loop Output
Categories
2. Execute Solidity Smart Contract using Remix IDE

Solidity – Constructors

A constructor is a special method in any object-oriented programming language which gets called whenever an object of a class is initialized. It is totally different in case of Solidity, Solidity provides a constructor declaration inside the smart contract and it invokes only once when the contract is deployed and is used to initialize the contract state. A default constructor is created by the compiler if there is no explicitly defined constructor.

Creating a constructor

A Constructor is defined using a constructor keyword without any function name followed by an access modifier. It’s an optional function which initializes state variables of the contract. A constructor can be either internal or public, an internal constructor marks contract as abstract. 

Syntax:

constructor() <Access Modifier> {          
} 

Example: In the below example, in the contract constructorExample, a constructor is created to initialize the state variable str. 

  • Solidity
// Solidity program to demonstrate
// creating a constructor
pragma solidity ^0.5.0;		
		
// Creating a contract
contract constructorExample {		
		
	// Declaring state variable
	string str;		
			
	// Creating a constructor
	// to set value of 'str'
	constructor() public {				
		str = "GeeksForGeeks";		
	}		
	
	// Defining function to
	// return the value of 'str'
	function getValue(
	) public view returns (
	string memory) {		
		return str;		
	}	
}

Output : 

Creating Constructor

Constructor in Inheritance

In case if a constructor is not defined then the default constructor is called, but if the constructor is defined in a parent contract and having some arguments then the child contract should also provide the required parameters to the constructor. If the child contract is not passing any parameter to the parent’s constructor the child contract will become an abstract contract. There are two ways of calling a parent contract’s constructor: 

1. Direct Initialization: In the below example, the direct initialization method is used to initialize the constructor of the parent class.

// Solidity program to demonstrate
// Constructor in Inheritance
pragma solidity ^0.5.0;

// Creating a contract
contract Base {

// Declaring variable
uint data;

// Defining a constructor
constructor(uint _data) public {
	data = _data;
}

// Defining function
function Print(
) public returns(string memory){
	return "Direct Initialization";
}

}

// Child contract inheriting
// the parent contract 'Base'
contract Derived is Base(2){

	// Defining a constructor
	constructor() public {}

// Defining function to access
// variable of parent contract
function getData(
) external returns(uint){
	uint result = data ** 2;
	return result;
}
}

// Caller contract
contract caller{

// Creating an object of child contract
	Derived c = new Derived();

// Accessing functions of parent
// and child contract using
// object of child contract
	function getResult() public returns(uint){
		c.Print();
		return c.getData();
	}
}

Output : 
 

Direct Initialization

2. Indirect Initialization: In the below example, the indirect initialization using Base(string(abi.encodePacked(_info, _info))) is done to initialize the constructor of the base class.

// Solidity program to demonstrate
// Indirect Initialization
pragma solidity ^0.5.0;

// Creating a contract
contract Base {

// Declaring state variable
string str;

// Defining a constructor
constructor(
	string memory _str) public {
	str = _str;
}

// Defining a function
function Print(
) public returns(string memory){
	return "Indirect Initialization";
}
}

// Child contract inheriting
// parent contract 'Base'
contract Derived is Base {

// Defining a constructor
constructor(
	string memory _info) Base(
	string(abi.encodePacked(
	_info, _info))) public {}

// Defining function to
// return value of parent
// contract variable 'str'
function getStr(
) public view returns(string memory){
	return str;
}
}

// Caller contract
contract caller {

	// Creating an object of
	// child contract
	Derived c
	= new Derived("GeeksForGeeks");

	//Defining a function to access
	// functions of the parent
	//contract and child contract
	function getResult() public view{
		c.Print();
		c.getStr();
	}
}

Output : 

Indirect Initialization

Need of Constructors

Constructors are very useful in a smart contract, a parameter value can be defined at the run time and can also restrict the method call. Constructor overloading is not supported in Solidity, it only allows one constructor at a time.

Example: In the below example, the contract constructorExample consists of a constructor to demonstrate the need for the constructor.

// Solidity program to demonstrate
// Need of constructors
pragma solidity ^0.5.0;		
		
// Creating a contract
contract constructorExample {		
		
	// Declaring state variable
	string str;		
	address private owner
	= 0x62Ab98A0efB752C48bd82836D0b4335018B9B97e;

	// Defining constructor
	constructor(string memory strIn) public {				
		if(msg.sender == owner){	
			str = strIn;	
		}		
	}		
	
	// Defining function to
	// return value of 'str'
	function getValue() public view returns (
	string memory) {		
		return str;		
	}	
}

Output : 

Need for Constructors
Categories
2. Execute Solidity Smart Contract using Remix IDE

Steps to Execute Solidity Smart Contract using Remix IDE

Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract. 
 

Step 1: Open Remix IDE on any of your browsers, select on the New File and click on Solidity to choose the environment. 

Step 2: Write the Smart contract in the code section, and click the Compile button under the Compiler window to compile the contract. 

Compile Code

Step 3: To execute the code, click on the Deploy button under Deploy and Run Transactions window. 

Deploy Code

Step 4: After deploying the code click on the method calls under the drop-down of deployed contracts to run the program, and for output, check to click on the drop-down on the console.

Output Window

Step 5: For debugging click on the Debug button corresponding to the method call in the console. Here you can check each function call and variable assignments. 

Debugging Code
Categories
2. Execute Solidity Smart Contract using Remix IDE

Develop Smart Contracts for the Ethereum Blockchain

Remix is a Solidity IDE that’s used to write, compile and debug Solidity code. Solidity is a high-level, contract-oriented programming language for writing smart contracts. It was influenced by popular languages such as C++, Python and JavaScript.

IDE stands for Integrated Development Environment and is an application with a set of tools designed to help programmers execute different tasks related to software development such as writing, compiling, executing and debugging code.

Before you begin using Remix to develop smart contracts, make sure you’re familiar with some basic concepts. In particular, give these articles about blockchain and Ethereum a read.

What’s a Smart Contract/Dapp?

A smart contract is a trust-less agreement between two parties that makes use of blockchain technology, to enforce the parties to adhere to the terms, rather than relying on the traditional ways such as trusting a middleman or using laws to handle disputes.

Using the Ethereum blockchain, you can create smart contracts with the Solidity language (among others). Ethereum is not the only platform that can be used to create smart contacts, but it’s the most popular choice, as it was designed from the start to support building them.

Dapp stands for decentralized application and is a web3 application that can have a front-end written in traditional languages such as JavaScript, HTML, CSS and a smart contract (as back-end code) which runs on the blockchain. So you can simply think of a Dapp as the front end plus the associated blockchain smart contract(s).

Unlike the smart contract deployed on the blockchain itself, the front end of a Dapp can be either hosted on a centralized server like a CDN or on decentralized storage like Swarm.

Accessing the Remix IDE

You can access the Remix IDE in different ways: online, via a web browser like Chrome, from a locally installed copy, or from Mist (the Ethereum Dapp browser).

Using the In-Browser Remix IDE

You can access the Remix IDE from your web browser without any special installation. Visit https://remix.ethereum.org/ and you’ll be presented with a complete IDE with a code editor and various panels for compiling, running and debugging your smart contracts. You’ll have a default example Ballot contract that you can play with.

Remix IDE

Starting Remix IDE from Mist

You can start the Remix IDE from Mist by clicking on Develop, then Open Remix IDE. Remix will be opened in a new window. If this is your first time running the IDE, you’ll be presented with a simple example Ballot contract.

Running your Own Copy of Remix IDE

You can also run your own copy of Remix IDE by executing the following commands:

npm install remix-ide -g
remix-ide

You need to have Node.js and npm installed.

Remix Panels

After seeing how to open the Remix IDE, let’s now see the various panels composing the IDE.

File Explorer

The file explorer provides a view with the created files stored in the browser’s storage. You can rename or delete any file by right-clicking on it, then choosing the right operation from the context menu.

context menu options

Please note that the file explorer uses the browser’s local storage by default, which means you can lose all your files if you clear or the operating system automatically clears the storage. For advanced work, it’s recommended to use Remixd — a Node.js tool (available from npm npm install -g remixd) which allows the Remix IDE to access your computer’s file system.

Now let’s see the different actions that you can perform using the buttons at the top of the explorer.

Remix buttons

Creating/Opening Files in Remix

You can create a new file in the browser local storage using the first button with the + icon on the top left. You can then provide a name in the opened dialog and press OK.

Using the second button from top left, you can open an existing Solidity file from your computer file system into the Remix IDE. The file will also be stored in the browser’s local storage.

Publishing Explorer Files as GitHub Gists

Using the third and fourth buttons from top left, you can publish files from the IDE as a public GitHub gist.

Copying Files to Another Instance of Remix IDE

Using the fifth button from top left, you can copy files from the local storage to another instance of Remix by providing the URL of the instance.

Connecting to the Local File System

The last button can be used to connect the Remix IDE to your local file system if you’re running the Remixd tool.

Solidity Code Editor

The Solidity code editor provides the interface where you can write your code with many features such as syntax highlighting, auto-recompling, auto-saving etc. You can open multiple tabs and also increase/decrease the font size using the +/- button in the top-left corner.

Solidity Code Editor

Terminal

The terminal window below the editor integrates a JavaScript interpreter and the web3 object. You can execute JavaScript code in the current context, visualize the actions performed from the IDE, visualize all network transactions or transactions created from the Remix IDE etc. You can also search for data in the terminal and clear the logs.

Remix terminal

Tabs Panel

The Tabs panel provides many tabs for working with the IDE:

  • the Compile tab: used for compiling a smart contract and publishing on Swarm
  • the Run tab: used for sending transactions to the configured environment
  • the Settings tab: used for updating settings like the compiler version and many general settings for the editor
  • the Debugger tab: used for debugging transactions
  • the Analysis tab: used for getting information about the latest compilation
  • the Support tab: used for connecting with the Remix community.
Remix tabs

Remix Execution Environments

The Remix IDE provides many environments for executing the transactions:

  • JavaScript VM: a sandbox blockchain implemented with JavaScript in the browser to emulate a real blockchain.
  • Injected Web3: a provider that injects web3 such as Mist and Metamask, connecting you to your private blockchain.
  • Web3 Provider: a remote node with geth, parity or any Ethereum client. Can be used to connect to the real network, or to your private blockchain directly without MetaMask in the middle.
Remix Execution Environments

Using Remix IDE to Compile and Deploy a Smart Contract

For the sake of demonstrating what we can achieve using Remix IDE, we’ll use an example contract and we’ll see how we can:

  • compile the contract in Remix IDE
  • see some warnings emitted by the compiler when best practices aren’t followed
  • deploy the contract on the JavaScript EVM (Ethereum Virtual Machine)
  • make transactions on the deployed contract
  • see example reads and writes in the terminal IDE.

We’ll use the following example contract from this tutorial which implements a blockchain raffle:

pragma solidity ^0.4.20;

contract Blocksplit {

    address[] public players;
    mapping (address => bool) public uniquePlayers;
    address[] public winners;

    address public charity = 0xc39eA9DB33F510407D2C77b06157c3Ae57247c2A;

    function() external payable {
        play(msg.sender);
    }

    function play(address _participant) payable public {
        require (msg.value >= 1000000000000000 && msg.value <= 100000000000000000);
        require (uniquePlayers[_participant] == false);

        players.push(_participant);
        uniquePlayers[_participant] = true;
    }

}

The contract declares some variables, such as:

  • The players array variable, which holds the addresses of the raffle participants.
  • The uniquePlayers mapping, which is used to save unique players so players don’t participate multiple times from the same address. (An address will be mapped to a boolean, true or false, value indicating if the participant has already participated or not.)
  • The winners array variable, which will hold the addresses of the winners.
  • The charity variable, which holds a hardcoded address of a charity where profits will go.

It also declares:

  • A fallback function marked as payable, which enables the smart contract to accept payments.
  • play() function that enables participants to enter the raffle by providing an address.

You can read more details about this contract from this tutorial where all the code is explained in detail.

Now, go ahead and open the Remix IDE from remix.ethereum.org.

Next, create a new file by clicking on the button with the + icon.

Creating a new file

A new dialog will pop up Enter a name for your file (blocksplit.sol), then press OK:

Naming the file

A new tab will be opened in the code editor where you can start writing your contract. So just copy and paste the previous contract code in there.

First start by compiling the contract. From the Compile tab click Start to compile button.

We’re getting a message box with two warnings raised by Static Analysis of the code.

Two warnings

If you click on the message box you’ll be taken to the Analysis tab, which provides more information about the warnings:

warning info

The first warning is raised if the gas requirements of functions are too high, and the second one is raised if the require() or assert() functions are not used appropriately.

You can also use the checkboxes in the Analysis tab to determine when you want the compiler to emit warnings.

determine when you want the compiler to emit warnings

Next, let’s deploy the contract with our JavaScript VM. Switch to the Run tab, and select JavaScript VM from the dropdown menu.

Selecting the JavaScript VM

Next, click the Deploy button below the contract name.

The Deploy button

Once the contract is deployed successfully on the JavaScript VM, a box will be opened on the bottom of the Run tab.

Run tab box

Under the name and address of the deployed contract, we have some buttons with red and blue colors. Red buttons refer to actions that cause a write to the blockchain (in our case the fallback and play functions) and need a transaction, where blue buttons refer to reading from blockchain (charity, players, uniquePlayers and winners public variables we defined in the contract’s code).

You’ll also see a similar message to the following screenshot in the IDE terminal.

Terminal message

For now, the only variable that holds a value is the charity variable, because the address is hardcoded in the code so if you click on the corresponding button you’ll get the value of that address.

address value

The contract is built to allow a participant to enter the raffle by just sending ether to the address (using a payable callback function) or also call the play() function with the address of the participant.

The JavaScript VM provides five fake accounts with 100 ether each, which we can use to test the contract. You can select a current account from the dropdown menu with the name Account below the Environment dropdown.

Select a current account

Now, to send money to the contract, we first set the Value variable (between 0.001 and 0.1) and the unit (ether) from the dropdown menu. Then we call the fallback function by simply clicking on its corresponding red button.

Calling the fallback function

That’s it. We’ve sent money to the contract. The address of the selected account should be added to the players array. To check that, simply click on the blue players button.

Clicking on the blue Players button

You can add other participants by selecting a new account and repeat the previous process (to check if an account is added to the array simply enter the index, from 0 to 4, for that account in the text-box next to players button).

If you add an account that has already participated, you should get a warning in the terminal and the transaction will fail with a message like the following:

Failure message

Remix Alternatives

There are many alternatives for easy development and deployment of smart contracts, such as:

  • Truffle: advertised as the Ethereum Swiss army knife and claims to be the most popular development framework for Ethereum with a mission to make your life a whole lot easier. We’ll be working with Truffle a lot in upcoming tutorials.
  • Embark: a framework that allows you to easily develop and deploy Decentralized Applications (DApps).
  • MetaMask: a bridge that allows you to visit the distributed web of tomorrow in your browser today. It allows you to run Ethereum DApps right in your browser without running a full Ethereum node. For how to develop with MetaMask, check this faq.
  • Dapp: Dapp is a simple command line tool for smart contract development.
  • different plugins for adding Solidity support to popular IDEs such as this Visual Code plugin and this Atom plugin etc.
Categories
2. Execute Solidity Smart Contract using Remix IDE

How to Install Solidity in Windows?

To install solidity on windows ensure that you are using windows 10, as only windows 10 provides built-in Linux Subsystem. With the help of this feature, we can run the Ubuntu terminal on the Windows machine. Below are the steps to setup Solidity on windows:

Step 1: Open control panel on your system and toggle to Windows Subsystem for Linux under Control Panel>Programs>Programs and Features>Turn Windows features on or off.

Step 2: After your system restarts install “Ubuntu LTS 18.04” from Microsoft store and after installation set it up.

Step 3: After setting up Bash install and check necessary dependencies like cURL, Node version manager(NVM), NodeJS and Node Packet Manager(NPM) using the following commands:

Installing cURL :

sudo apt-get install curl
curl --version 

2: Installing NVM:

curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash
nvm --version

3: Installing NodeJS and NPM:

nvm install node
node --version
npm --version

4: After installing the dependencies, install and check solidity compiler solc by using following code:

npm install -g solc
solcjs --version