Various IDE and Tools

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, compil

Remix

Remix is a Solidity IDE that lets you write, compile, and debug Solidity code. Solidity is a high-level, contract-oriented programming language for writing smart contracts. C++, Python, and JavaScript are the languages that empower the Solidity.

Before starting to work with Remix for developing smart contracts, it is important to learn the basic concepts related to it.

Smart Contract/Dapp

A smart contract can be understood as a trust-less agreement between two parties with blockchain technology at its core. This smart contract enforces both the involved parties to adhere to the terms of the agreement. It eliminates the traditional method of trusting a middleman or using laws to handle disputes.

Using the Ethereum blockchain, you can smart contracts with the Solidity language (among others). However, Ethereum is not the only platform to create smart contracts, although it was designed from the start to support building them.

Dapp or decentralized application is a web3 application having its front-end written in traditional languages such as JavaScript, HTML, CSS, and a smart contract running on blockchain at the back-end.

The only difference between a smart contract and Dapp is that unlike a smart contract, Dapp has not to be deployed on the blockchain itself. Dapp can be hosted on a centralized server or on decentralized storage like Swarm.

Working With Remix IDE

Starting with accessing the Remix IDE in any of the following ways:

  • Online

  • Via a web browser such as Chrome

  • From a locally installed copy

  • From Mist (Ethereum Dapp browser)

    Using Remix on Browser

    It is quite easy to access the Remix IDE from your web browser without any prerequisite installation. Visit https://remix.ethereum.org/ and you’ll see a complete IDE consisting of the code editor and various panels to compile, run, and debug your smart contracts. A Ballot contract features as an example to help you start with.

    remix

Accessing Remix IDE from Mist

mist

You can learn more about Mist here.

Accessing Remix through your own copy

To do so, execute the following commands after installing Node.js and npm:

  1. npm install remix-ide -g

  2. remix-ide

Remix Panels

Lets us explore the various panels in the Remix IDE

File Explorer

You can view the created files stored in the browser’s storage from here. You can also rename or delete any file by right-clicking on it.

fileexplorer

Note: The file explorer uses the local memory of the browser to store all your files. Hence, there is a risk that you may lose all your files if you clear it or the operating system automatically clears the storage.

Remixd is a tool available to perform advanced work. It is a Node.js tool and enables the Remix IDE to access your computer’s file system.

Buttons available to perform different actions

button

Create/Open Files in Remix

+ icon on the top left lets you create a new file in the local storage of the browser. Enter the file name in the pop-up window, click OK.

The second button from top left lets you open an existing Solidity file from your computer file system into the Remix IDE.

Publishing Explorer Files as GitHub Gists

The third and fourth button lets you publish files from IDE as a public GitHub gist.

Copy Files

The fifth button from top left lets you copy files from local storage to another instance of Remix.

Connect to the local file system

The sixth and last button lets you connect the Remix IDE to your local file system, provided you are running the Remixd tool.

Solidity Code Editor

The code editor is an interface to let you write the code including a variety of features such as syntax highlighting, auto-recompiling, auto-saving etc. It is easy to adjust the font size using +/- button and even open multiple tabs.

button

Terminal

Located just below the editor, the terminal window integrates a JavaScript interpreter and a web3 object. Various tasks that a terminal help you to accomplish are:

  • Execute JavaScript code in the current context

  • Visualize the actions performed from the Remix IDE

  • Visualize all network transactions

  • Visualize transactions created from the Remix IDE

  • Search for data in it and clear the logs

terminal

Tabs

  • 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

terminal

Various Execution Environments

One notable feature of Remix IDE is that it 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. It helps you to connect to a real network, or directly to your pirate blockchain without the need of MetaMask

terminal

Compiling and Deploying a Smart Contract

Here’s an example of blockchain raffle to demonstrate Remix IDE at work. We will show you how to:

  • Compile a smart contract in Remix IDE

  • Errors and warnings in case of any mistakes

  • Deploy the contract on the JavaScript EVM

  • Make Transactions on the deployed contract

  • See examples reads and writes in the terminal IDE

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

Now, on breaking down the above example, we get: Some variables that the contract declares:

  • players array variable - holds the address of the raffle participants;

  • uniquePlayers mapping - mapped to a boolean, true or false, saves unique players so that they don’t participate multiple times from same address

  • winners array variable - holds the addresses of the winners

  • charity variable - holds a hardcoded address of a charity where the profits will go

It also declares:

  • payable - a fallback function that enables smart contracts to accept payments

  • play () - a function that enables participants to enter the raffle by providing an address

Learn about this contract in detail here

Let’s get started with the contract, open https://remix.ethereum.org/

Follow the below steps:

  1. Create a new file by clicking on the + icon

  2. Enter the filename in the dialog box, click OK

  3. A new tab to write contract gets opened, copy and paste the previous contract code here

  4. Start compiling the contract by clicking Start to compile button under the Compile tab

If there is anything wrong, you will get a warning about it.

warning

If you want the compiler to emit any warning, you can do so by ticking the checkboxes in the Analysis tab

warning

Now, we will deploy our contract with our JavaScript VM. Switch to Run tab, select JavaScript VM from the dropdown menu.

warning

Click Deploy below the contract name

warning

Once the contract is successfully deployed on the Javascript VM, a box opens at the bottom of the Run tab

warning

The red buttons denote the actions that cause a write to the blockchain and need a transaction. Like fallback and play functions in the above image. The blue buttons denote the reading from blockchain. Like charity, players, uniquePlayers, winners public variables defined in the contract’s code.

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

warning

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.

To test the contract, JavaScript VM provides five fake accounts with 100 ether each.

Select a current account from the dropdown menu with the name Account below the Environment dropdown.

warning

Set the value variable (between 0.001 and 0.1 ) and the unit (ether) to send money to the contract.

warning

Done. The money is sent to the contract. By clicking on the players button, you can check the addresses of the added accounts.

warning

Repeat the previous process to add participants by selecting a new account. If you try to add an account that has already participated, you will get a warning as well as the transaction will fail. Here’s how it will look:

warning

Some Alternatives for Remix:

For easy development and deployment of smart contracts, you have many alternatives such as:

  • Truffle

  • Embark

  • MetaMask

  • Dapp

Wrapping Up

We have provided a crisp understanding of using Remix IDE to develop smart contracts for the Ethereum blockchain. Get started on your own. Experiment with the codes, explore and learn.

Web3JS

web3.js is a collection of libraries which allow you to interact with a local or remote ethereum node, using a HTTP or IPC connection. It helps you to develop websites or clients that reads and writes data from the Ethereum blockchain with smart contracts. Performing actions like sending ether from one account to another, reading and writing data from smart contracts, creating smart contracts, and many more are possible with web3.JS.

Web3.JS interacts with The Ethereum Blockchain through JSON RPC, that is “Remote Procedure Call” protocol.

Dependencies

Node Package Manager

First thing we need is a Node Package Manager or NPM.

$ node -v

Web3.JS library

Install the web3.JS library with NPM in your terminal

$ npm install web3

Infura RPC URL

Accessing an Ethereum node in order to connect it to the JSON RPC on the Mainnet could be a time-consuming task if not for Infura. The benefit of Infura is that it provides access to the Ethereum node without having to run one on your own. In simple words, it provides a remote Ethereum node for free in just 3 steps.

  1. Sign up

  2. Obtain an API key

  3. Obtain the RPC URL network you want to connect to

Once done, it’ll look like this: https://mainnet.infura.io/YOUR_INFURA_API_KEY

Balance Check

All your dependencies installed, you can start developing with Web3.JS.

  1. Start Node console in your terminal

    $ node
  2. Fulfill the requirement of Web3.JS

    const Web3 = require('web3')
  3. Assign Infura URL to access a variable const rpcURL = "https://mainnet.infura.io/YOUR_INFURA_API_KEY"

  4. Replace YOUR_INFURA_API_KEY with your actual API key, once done,your Web3 connection will look like this const web3 = new Web3(rpcURL)

When the web3 connection is live, you can now interact with an Ethereum mainnet. Now, you can check the ether balance for any account with web3.eth.getBalance().

Follow these steps to check:

  1. Assign the address of the account you want to check the balance for to a variable

  2. Run the below code to check the account balance

    web3.eth.getBalance(address, (err, wei) => {
    balance = web3.utils.fromWei(wei, 'ether')
    })

As you can see, we first call the web3.eth.getBalance() to assign the task. This callback function has two arguments that it can return with, an error or the balance itself. Initially Ethereum expresses balances in Wei, the smallest subdivision of Ether, similar to cents. Using web3.utils.fromWei(wei, 'ether') we can convert the balance into Ether for our understanding.

GitHub has all the code examples available for downloading for your convenience.

Smart Contracts With Web3.JS

Here we will demonstrate how to comprehend the smart contract data from the Ethereum Blockchain.

Below are the prerequisites to get started with:

  1. The Smart contract in its JavaScript form using web3.eth.Contract() function.

  2. While reading the data, different ways to call the functions on the smart contract

The web3.eth.Contract() function expects two arguments: one for the smart contract ABI (Abstract Binary Interface) and the other for the smart contract address.

ABI is a JSON array depicting the way a specific smart contract works. An ABI can be an extremely long, unbroken array.

Let us proceed by taking the ABI for OmiseGo token, working on the ERC-20 token standard.

  1. Store the address to the OMG token from the Ethereum main net const address = "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07"

  2. Once the values are assigned, create a complete JavaScript representation of the OMG token smart contract const contract = new web3.eth.Contract(abi, address)

3) Now, we will start calling functions to read data from the smart contract Since, we have taken the example of smart contract on the ERC-20 token standard, it implements several functions such as: totalSupply(), name(), symbol(), and balanceOf(), so we have to individually read each of those values, in the following manner:

  1. Total supply of all OMG tokens

    contract.methods.totalSupply().call((err, result) => { console.log(result) })
  2. Name of OMG token

    contract.methods.name().call((err, result) => { console.log(result) })
  3. Symbol of OMG token

    contract.methods.symbol().call((err, result) => { console.log(result) })
  4. Check the balance of the account

    contract.methods.balanceOf('0xd26114cd6EE289AccF82350c8d8487fedB8A0C07').call((err, result) => { console.log(result) })

Done. You have now learnt how to read data from smart contracts with Web3.JS.

Ethereum Transactions With Web3.JS

Here you’ll learn how to create transactions on the Ethereum Blockchain with Web3.JS and all the fundamentals about its working on the Ethereum Blockchain. Also, we’ll show what happens when an Ethereum transaction is created and how to broadcast a transaction manually to the network with web3.JS.

Signing the transactions is the first step to broadcast transactions to the network. Here we’ll be using an additional JavaScript library, called ethereumjs-tx. Use the below commandline to install it:

$ npm install ethereumjs-tx

For security purposes, we are using this library as we want to sign all the transactions locally as we will be using a remote node hosted by Infura. By using this library we will be able to manage all our transactions locally rather than providing the private keys to the remote node.

Let’s get started with creating a transaction, signing it, sending and then broadcasting it to the network.

  1. Create app.js file to run the code

  2. Get access to the newly installed library

    var Tx = require('ethereumjs-tx')

  3. Set up a Web3 connection

    const Web3 = require('web3')

    const web3 = new Web3('https://ropsten.infura.io/YOUR_INFURA_API_KEY')

As we are working on the Ropsten test network to refrain from spending any money. Since all transactions cost gas in the form of Ether, we can use fake Ether on the Ropsten test net by obtaining them from the faucet. You can get them from:

http://faucet.ropsten.be:3001/

https://faucet.metamask.io/

Now, we will send fake Ether from one account to another. For this we’ll be needing two accounts and their private keys.

  1. Create new accounts with Web3.JS

    web3.eth.accounts.create()
    // > {
    // address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
    // privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709 ",
    // signTransaction: function(tx){...},
    // sign: function(data){...},
    // encrypt: function(password){...}
    // }
  2. After this, load both the accounts with fake Ether from a faucet

  3. Now, we’ll assign them to variables in our script. In your case, you’ll be using the accounts you generated.

    const account1 = '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01'
    const account2 = '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa02'
  4. Save the private keys to the environment

    export PRIVATE_KEY_1='your private key 1 here'
    export PRIVATE_KEY_1='your private key 2 here'
  5. Now, we’ll read private keys from our environment and store them to variables

    const privateKey1 = process.env.PRIVATE_KEY_1
    const privateKey2 = process.env.PRIVATE_KEY_2
  6. Convert them to a string of binary data with a Buffer to sign transactions with the private keys

    const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1)
    const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_2)\

Now, we’ve all the variables set up and from here we will: 1. Build a transaction object 2. Sign the transaction 3. Broadcast the transaction to the network

Building the transaction object

const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}

To generate a transaction, we have all the values needed such as nonce, to, value, gasLimit, and **gasPrice. Here’s what they mean:

nonce: Previous transaction count for the given account. Assign a value of this variable and convert it to hexadecimal using Web3.js utility web3.utils.toHex() to: Account we’re sending Ether to

Value: Amount of Ether to be sent. Value is expressed in Wei and converted to hexadecimal. gasLimit: Maximum amount of gas consumed by the transaction. In general it is 21000 units of gas. gasPrice: Amount we want to pay for each unit of gas.

As from field is not mentioned here, it is to be inferred that we sign this transaction with account1’s private key.

1) Assign the value for nonce variable

web3.eth.getTransactionCount(account1, (err, txCount) => {
const txObject = {
nonce: web3.utils.toHex(txCount),
to: account2,
value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
}
})

2) Use etheremjs-tx library to create a new Tx object and then sign the transaction with privateKey1

const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTx = tx.serialize()
const raw = '0x' + serializedTx.toString('hex')

3) Serialize the transaction and convert it to a hexadecimal string to pass it to Web3 as shown the code above 4) Send the signed serialized transaction to the test network

web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
})

Done. With that final step, you have sent the transaction and broadcast it to the network.

Deploying Smart Contracts with Web3.JS

Let’s get started with the deployment process. We will be using the same app.js file and the below code for tutorial:

var Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/YOUR_INFURA_API_KEY')
const account1 = '' // Your account address 1
const privateKey1 = Buffer.from('YOUR_PRIVATE_KEY_1', 'hex')

Few steps that are similar to the previous lesson will be followed here too:

  1. Build a transaction object

  2. Sign the transaction

  3. Send the transaction

Building the transaction object:

const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000), // Raise the gas limit to a much higher amount
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
data: data
}

While nonce, gasLimit, gasPrice are the same fields as the object from the previous lesson, there are some key differences as well: nonce: Same as the previous lesson gasLimit: Maximum amount of gas consumed by the transaction. As deploying smart contracts require more gas, the limit will be higher than the previous lesson gasPrice: Amount we pay for each unit of gas. Same as previous lesson value: this field is absent as we are not sending any Ether to: Similarly, this field is also absent as we’re not sending Ether to any particular account but we’re sending it to an entire network, i.e. deploying a smart contract data: It’s the bytecode of the smart contract we want to deploy To assign a value to the data parameter, which is a compiled bytecode representation of the smart contract in hexadecimal, we first need a smart contract and then we have to compile it. Once you’ve compiled the contract, you can assign the data value to a variable. Now, follow the steps: 1. Assign the nonce value by getting the transaction count

web3.eth.getTransactionCount(account1, (err, txCount) => {
const data = '' // Your data value goes here...
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
data: data
}
})

2. Sign the transaction and send it And, you’re done with the deployment of a smart contract with Web3.JS.

Calling Smart Contract Functions

Here you will learn how to write data to smart contracts with Web3.JS. Let’s get started. 1. Same basic setup with an app.js just like previous lessons

const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/YOUR_INFURA_API_KEY')
const account1 = '' // Your account address 1
const account2 = '' // Your account address 2
const privateKey1 = Buffer.from('YOUR_PRIVATE_KEY_1', 'hex')
const privateKey2 = Buffer.from('YOUR_PRIVATE_KEY_2', 'hex')

2. Build a transaction object

const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(800000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
to: contractAddress,
data: data
}

Apart from the to and data fields, every other field is the same as the previous lessons.

to: Address of the deployed contract. Obtain and assign the value momentarily. data: The hexadecimal representation of the function we want to call on the smart contract. Obtain and assign the value momentarily.

  1. Once done, we can create a JavaScript representation of the smart contract with Web3.JS

  2. Now, we can fill out the data field of the transaction

    const data = contract.methods.transfer(account2, 1000).encodeABI()

Done, We have now successfully encoded this function call for the transaction. After this, we can now sign and send the transaction. After this, we can log the values of the account balances to see that the smart contract function was called and that the token transfers were complete.

Smart Contract Events

Here you will learn how to examine smart contract events on the Ethereum Blockchain with Web3.JS.

As Ethereum smart contracts have the ability to emit events that indicate that something happened with the code execution, consumers can subscribe to these events with the functionality of Web3.JS. We’ll use ERC-20 token standard that emit a Transfer event anytime an ERC-20 token is transferred.Here, we have the OmiseGO ERC-20 token to subscribe to the Transfer event

Starting just like the previous lessons, we will:

  1. Set up the app.js file

  2. Connect to the Ethereum Main net

  3. Paste OmiseGo smart contract ABI and address obtained from Etherscan

  4. Create a JavaScript representation of the smart contract with web3.js

After this, we can look at the past events for this smart contract with getPastEvents() function. Firstly, we’ll get all the events emitted by the contract.

contract.getPastEvents(
'AllEvents',
{
fromBlock: 0,
toBlock: 'latest'
},
(err, events) => { console.log(events) }
)

Here we have two arguments: the event name and a set of filtering parameters. For successful execution we will limit the number of blocks we want to check from.

contract.getPastEvents(
'AllEvents',
{
fromBlock: 5854000,
toBlock: 'latest'
},
(err, events) => { console.log(events) }
)
Now, we can specify the Transfer event
contract.getPastEvents(
'Transfer',
{
fromBlock: 5854000,
toBlock: 'latest'
},
(err, events) => { console.log(events) }
)

And it’s done. You can now see all of the recent transfer events for the OmiseGo ERC-20 token. This code may prove to be helpful if you want to build a transaction history for the OMG token in the crypto wallet.

Inspecting Blocks

Here you will learn how to inspect blocks with Web3.JS. As it is useful in analyzing history, we will show how the web3.js functionality helps us to do that.

Let’s get started with inspection of blocks.

  1. Set up an app.js file

  2. Connect to main net to inspect blocks

    const Web3 = require('web3')
    const web3 = new Web3('https://mainnet.infura.io/YOUR_INFURA_API_KEY')
  3. At first, get the latest block number web3.eth.getBlockNumber().then(console.log)

  4. Then acquire all the data for the latest block web3.eth.getBlock('latest').then(console.log)

Additionally if you want to build a block history feature, you can get a list of the most recent blocks in the chain. Use a for loop to fetch the most recent blocks and previous 10 blocks in the chain.

web3.eth.getBlockNumber().then((latest) => {
for (let i = 0; i < 10; i++) {
web3.eth.getBlock(latest - i).then(console.log)
}
})

With Web3.JS, you can also inspect transactions contained within a specific block. const hash = '0x66b3fd79a49dafe44507763e9b6739aa0810de2c15590ac22b5e2f0a3f502073' web3.eth.getTransactionFromBlock(hash, 2).then(console.log) And it’s done. You can now successfully inspect blocks with Web3.JS. ### Web3.JS Utilities Here you will learn about the utilities included with web3.JS, their use and some additional tips and tricks. Let’s get started with our bonus information. 1. Set up an **app.js** 2. Connect to the Ethereum Main net

const Web3 = require('web3')
const web3 = new Web3('https://mainnet.infura.io/YOUR_INFURA_API_KEY')

Now, let’s explore the tips and tricks. 1. You can get the average gas price currently for the network

web3.eth.getGasPrice().then((result) => {
console.log(web3.utils.fromWei(result, 'ether')
})
  1. You can get direct access to hashing functions and use them console.log(web3.utils.sha3('Dapp University'))

  2. You can handle (pseudo) randomness by generating a 32 byte random hex console.log(web3.utils.randomHex(32))

  3. You can also get access to external library when in need

const _ = web3.utils._ _.each({ key1: 'value1', key2: 'value2' }, (value, key) => { console.log(key) })

That’s all. These are some of the bonus tips and tricks you can use with Web3.JS.