Writing Ethereum Smart Contracts with Solidity


Writing Ethereum Smart Contracts with Solidity

Recipe ID: hsts-r22


Self-paced training

We offer blockchain introduction, Hyperledger for system admin, Ethereum, Solidity, Corda R3, Hyperledger for developers, blockchain cybersecurity and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced blockchain training, visit our Complete Blockchain Development Training page.


Recipe Overview

For those who are not familiar with Hyperledger project Intro to Hyperledger Family and Hyperledger Blockchain Ecosystem and Hyperledger Design Philosophy and Framework Architecture articles are strongly recommended.

To better follow and understand this recipe, it is advisable to read Essential Hyperledger Sawtooth Features for Enterprise Blockchain Developers, Blockchain Developer Guide- How to Install and work with Hyperledger Sawtooth , Configuring Hyperledger Sawtooth Validator and REST API and Blockchain Developer Guide- How to Install Hyperledger Seth and Docker on AWS articles in advance.

In our previous recipes, we reviewed i- Ethereum, Solidity and how to use Hyperledger Seth to build blockchain application with Ethereum and ii-How to install Hyperledger Burrow on AWS. In this recipe, we show you how to write smart contracts with Solidity.

Remix (https:/​/​github.​com/​ethereum/​remix) and Truffle (https:/​/​truffleframework.com) are popular Ethereum development frameworks. You can use either of these to write smart contracts with Solidity for Burrow. For this recipe, we will use the online version of Remix to write a sample smart contract with Solidity, since this version is simple and easy to use. You can access it here: https:/​/​remix.​ethereum.​org.

Smart Contract Project Overview

In this smart contract, we will perform transactions to deposit coins, withdraw coins, and query the account balance. The smart contract looks as follows:

Ethereum and solidity

 

Build Smart Contract

Follow these steps to create your first smart contract using Remix:

1. Create the new smart contract in the Remix browser.

This BasicContract.sol sample contract will keep the balance of an account, and the contract owner will be able to put deposits into and withdraw from the contract. Its code is as follows:

pragma solidity >=0.0.0;

contract BasicContract {

int s_amount;

address s_owner;

constructor() public {

s_owner = msg.sender;

s_amount = 0;

}

modifier onlyOwner() {

require(msg.sender == s_owner);

_;

}

function deposit(int v) public {

require(v >= 0);

s_amount = s_amount + v;

}

function withdraw(int v) public onlyOwner { require(v >= 0);

require(s_amount >= v);

s_amount = s_amount - v;

}

function getBalance() constant public returns (int retVal) { return s_amount;

}

function getAddress() constant public returns (address a) { return s_owner;

}
}

2. You can use the preceding code to create a new BasicContract contract in the Remix browser, as follows. Click on Compile to compile the contract to verify that there are no grammar or coding errors, as shown in the following screenshot:
solidity programming


3. Run and test the contract in the Remix browser. After the contract is successfully compiled, you can go to the Run tab in the browser.

4. Click Deploy to deploy the contract in Remix.

5. Select the BasicContract and click on the deposit, withdraw, and getBalance buttons to test the contract in Remix:
smart contracts in solidity


Put Things Together

We will walk through the structure and features of the Solidity language with our sample smart contract. Solidity is one of the most commonly used programming languages to write smart contracts for Ethereum blockchain, and it can also be adapted to write smart contracts that are executed on the Hyperledger Burrow blockchain network.

Using the pragma version and importing another source file
The Solidity file starts with the pragma version, which annotates the compiler version that the contract is compatible with. It is in the format of 0.x.0. The version could be specified as range, which is a comparator which specifies the versions that satisfy the condition. In the sample contract, it is any compiler after version 0.0.0:
pragma solidity >=0.0.0;

After the pragma version, the Solidity file could also define how to import symbols from other source files. For example, we can import all global symbols from another source file, as follows:
import "filename";

Similarly, we can import all global symbols from another source file into a new global symbol, whose members are all the global symbols from the file, by using the following statement:
import * as symbolname from "filename";

Using Contracts in Solidity
Contracts in Solidity are similar to classes in Java, C++, Python, and other Object-Oriented Programming languages. Solidity is contract-oriented, and contracts can contain declarations of state variables, functions, function modifiers, events, and so on. Click on https:/​/​solidity.readthedocs.​io/​en/​v0.​4.​21/​structure-​of-​a-​contract.​html#structure-​state-variables for more details. A contract is defined as follows:

contract BasicContract {

......

}

The Address type refers to the Ethereum address of a contract or account. The address is 20 bytes, and any contract could explicitly be converted into an address. The address has functions such as balance (which provides the balance of the address in the Ether unit Wei) and transfer (which transfers Ether to the address).
In the sample contract, two state variables are defined. One is the amount, with the int datatype, and the other is the address of the account that is creating the contract:
int s_amount;

address s_owner;

 

constructor() public {

s_owner = msg.sender;

s_amount = 0;

}

function functionname(params) visibility modifier returns (return values)

Functions can have the following visibilities:

Functions can also be declared with modifiers such as pure, constant, view, and payable:

Contracts can also define one unnamed function, the fallback function, which is executed if no functions in the contract match the function identifier in the message call.
The following code block contains a function that is defined in the sample contract. The require function is the guard condition or error handler in the contract. If the condition is not satisfied in calling the require function, the EVM will abort the transaction and roll back the state of the contract:

function withdraw(int v) public onlyOwner {

require(v >= 0);

require(s_amount >= v);

s_amount = s_amount - v;

}

function getBalance() constant public returns (int retVal) { return s_amount;

}

 

In our example contract, we define a function modifier to allow only the account that creates the contract to call the withdraw function:

modifier onlyOwner() {

require(msg.sender == s_owner);

_;

}

Solidity also supports events, as follows:

Solidity offers a full set of object-oriented features and supports interface, enum, struct, inheritance, and so on. In this section, we went through some basic features that we can use to write a smart contract with Solidity. Lastly, good knowledge of JavaScript programming is a must for working with Solidity.

Now that you learned how to build a Ethereum smart contract with Solidity, we can move on to the next and final step: Deploying and calling Ethereum smart contracts on Burrow.

The following recipes are excellent resources for installing other Hyperledger tools:
Blockchain Developer Guide- Overview of Hyperledger Explorer and its Development Environment
Blockchain Developer Guide- How to Install Hyperledger Fabric on AWS
Blockchain Hyperledger Composer Business Network Modeling and Environment Setup
Blockchain Developer Guide- How to Install Hyperledger Indy and Indy CLI on AWS

To conclude this recipe, we like to recommend our Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs and Blockchain Hyperledger Development in 30 hours courses to those interested in pursuing a blockchain development career. Indeed, as of this writing, Hyperledger Foundation offers the following two Hyperledger certifications: The Certified Hyperledger Fabric Administrator (CHFA) and The Certified Hyperledger Sawtooth Administrator (CHSA), both of which are highly regarded in the industry. Hyperledger Foundation is in the process of creating Hyperledger Developer certification program, which may be released in early or middle of 2020. In short, by taking our hands-on online Hyperledger class, you would be able to obtain CHFA certification.

This tutorial is written by Brian Wu who is our senior Hyperledger instructor in Washington DC. His Hyperledger Cookbook with 40+ hands-on recipes is highly recommended.

Related Training Courses

Hands-on Node.JS, MongoDB and Express.js Training
Advance JavaScript, jQuery Using JSON and Ajax
Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs
Learn Blockchain Hyperledger Development & Get Certified in 30 Hrs
Become Blockchain Certified Security Architect in 30 hours
Blockchain Certified Solution Architect in 30 hours
Introduction to Python Programming
Object Oriented Programming with UML


Private and Custom Tutoring

We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.


View Other Classes!