Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Blockchain Quick Start Guide

You're reading from  Blockchain Quick Start Guide

Product type Book
Published in Dec 2018
Publisher Packt
ISBN-13 9781789807974
Pages 222 pages
Edition 1st Edition
Languages
Concepts
Authors (2):
Xun (Brian) Wu Xun (Brian) Wu
Profile icon Xun (Brian) Wu
Weimin Sun Weimin Sun
Profile icon Weimin Sun
View More author details

Table of Contents (14) Chapters

Chapter 3. Overview of Solidity Programming

Solidity is a smart contract programming language. It was developed by Gavin Wood, Christian Reitwiessner, Alex Beregszaszi, and several Ethereum core contributors. It is a JavaScript-like, general-purpose language designed to target the Ethereum virtual machine (EVM). Solidity is one of four languages in the Ethereum protocol at the same level of abstraction, the others being Serpent (similar to Python), LLL (Lisp-like language), Vyper (experimental), and Mutan (deprecated). The community has slowly converged on solidity. Usually, if anyone today talks about smart contracts in Ethereum, they implicitly mean solidity.

In this chapter, we will discuss the following topics: 

  • What is solidity?
  • Tools for the solidity development environment
  • Introduction to smart contracts
  • Common smart contract patterns
  • Smart contract security
  • Case study – crowdfunding campaign

What is solidity?


Solidity is a statically typed contract language that contains state variables, functions, and common data types. Developers are able to write decentralized applications (DApps) that implement business logic functions in a smart contract. The contract verifies and enforces the constraints at compile time, as opposed to runtime. Solidity is compiled to EVM executable byte code. Once compiled, the contracts are uploaded to the Ethereum network. The blockchain will assign an address to the smart contract. Any permissioned user on the blockchain network can call a contract function to execute the smart contract. 

Here is a typical flow diagram showing the process from writing contract code to deploying and running it on the Ethereum network:

Tools for solidity development environment


Smart contract development is still in its infancy. Creating such contracts and interacting with them in a convenient manner can be done in a multitude of ways.  The following powerful tools can be used to build, monitor, and deploy your smart contracts for development on the Ethereum platform.

Browser-based IDE

In this section, we will be looking at onlien browser based tools such as Remix and EthFiddle.

Remix

Remix is a powerful, open source, smart contract tool that helps you write solidity code just from the browser. It supports compile, run, analysis, testing, and debugger options. The following three types of environments are available with Remix when developing and testing:

  • JavaScript VM: Remix comes with five Ethereum accounts, and each account is deposited with 100 ethers as default. This is convenient for testing smart contracts in the development phase. Mining is not required as it is done automatically. This option is a good choice when you...

Introduction to smart contracts


Let's begin with the most basic smart contract example,  HelloWorld.sol, shown as follows:

pragma solidity ^0.4.24;

contract HelloWorld {
  string public greeting;

  constructor() public {
    greeting = 'Hello World';
  }

  function setNewGreeting (string _newGreeting) public {
    greeting = _newGreeting;
  }
}

Solidity's file extension is .sol.  It is similar to .js for JavaScript files, and .html for HTML templates.

Layout of a solidity source file

A solidity source file is typically composed of the following constructs: pragma, comments, and import.

Pragma

The first line containing the keyword pragma simply says that the source code file will not compile with a compiler earlier than version 0.4.24. Anything newer does not break functionality. The ^ symbol implies another condition—the source file will not work either on compilers beyond version 0.5.0.

Comments

Comments are used to make the source code easier for humans to understand the function of the program...

Common smart contract patterns


In this section, we will discuss some common design and programming patterns for the smart contract programming language.

Access restriction

Access restriction is a solidity security pattern.  It only allows authorized parties to access certain functions. Due to the public nature of the blockchain, all data on the blockchain is visible to anyone. It is critical to declare your contract function, state with restricted access control, and provide security against unauthorized access to smart contract functionality.

pragma solidity ^0.4.24;
contract Ownable {
 address owner;
 uint public initTime = now;
 constructor() public {
 owner = msg.sender;
 }
 //check if the caller is the owner of the contract
 modifier onlyOwner {
 require(msg.sender == owner,"Only Owner Allowed." );
 _;
 }
 //change the owner of the contract
 //@param _newOwner the address of the new owner of the contract.
 function changeOwner(address _newOwner) public onlyOwner {
 owner = _newOwner;
...

Smart contract security


Once a smart contract has been deployed on the Ethereum network, it is immutable and public to everyone. Many of the smart contract functions are account payment related; therefore, security and testing become absolutely essential for a contract before being deployed on the main network. Following are security practices that will help you better design and write flawless Ethereum smart contracts.

Keep contract simple and modular

Try to keep your smart contract small, simple, and modularized. Complicated code is difficult to read, understand, and debug, it is also error-prone.

Use well-written library tools where possible.

Limit the amount of local variables.

Move unrelated functionality to other contracts or libraries.

Use the checks-effects-interactions pattern

Be very careful when interacting with other external contracts, it should be the last step in your function. It can introduce several unexpected risks or errors. External calls may execute malicious code. These kinds...

Case study – crowdfunding campaign


In this section, we will implement and deploy the smart contract for the crowdfunding campaign use case.

The idea of crowd funding is a process of raising funds for a project or venture from the masses. Investors receive tokens that represent a share of the startup they invested. The project sets up a predefined goal and a deadline for reaching it. Once a project misses the goal, the investments are returned, which reduces the risk for investors. This decentralized fundraising model can supplant the fund need for startup, and there is no need for a centralized trusted platform. Investors will only pay the gas fees if the fund returns. Any project contributor gets a token, and they can trade, sell, or keep these tokens. In a certain stage, the token can be used in exchange for real products as the physical reward.

Define struct and events, shown as follows:

pragma solidity ^0.4.24;

contract CrowdFunding {

    Project public project;
    Contribution[] public...

Summary


In this chapter, we learned the basic features of solidity programming. We also overviewed current popular smart contract development tools. By exploring common patterns and security best practices, we learned how to write better code to avoid contract vulnerabilities. Finally, we wrote a crowd funding campaign contract, and used Remix to deploy and test our example. 

In the next chapter, we will build a Decentralize application (DApp) for crowdfunding. 

lock icon The rest of the chapter is locked
You have been reading a chapter from
Blockchain Quick Start Guide
Published in: Dec 2018 Publisher: Packt ISBN-13: 9781789807974
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}