Note
For a comprehensive coverage of blockchain development in Ethereum or mastering Solidity programming, taking our below self paced courses is highly recommended:
- Blockchain Solidity Course for Beginners
- Ethereum Developer Course
- Blockchain Security Course for Beginners
Recap
In our previous series,
- Review of Infura for Ethereum Development
- Review of Infura Ethereum API
- How to Use Remix with Infura for Ethereum Development
- How Ethereum Client API Works
- How Ethereum IPFS Storage Works
- How to Install and Start Ethereum IPFS Storage
- How to Run Ethereum IPFS Storage
- How to Work with Ethereum Swarm Storage
- How to Install Ethereum Swarm Storage
- How to Handle Ethereum Messages with Whisper
- Review of Popular Ethereum Smart Contract Libraries
In this article series, we will move our focus to Ethereum private chains. For developers, private blockchains are set up for testing purposes. Private chains have advantages over public blockchains in testing. For example, there is no need
Recap
In our previous article (How to Handle Ethereum Messages with Whisper), we discussed how to process Ethereum messages with Whisper.
In this article, we survey the most popular libraries for Ethereum smart contract development
Popular smart contract libraries
As we have learned so far, developing a secure, reusable, and efficient smart contract is not an easy task. It takes a lot of effort, experience, and testing. Once a smart contract has been deployed to a blockchain, anyone in the blockchain can access it. So, developing a top, secure, and quality smart contract becomes a crucial task for any smart contract developer. Well-tested, reusable, and secured libraries become very important. There are many popular open source Ethereum libraries available, as follows:
- Modular Libraries: A library that’s used for utilizing EVMs
- Aragon: A DAO protocol, including the aragonOS smart contract framework for upgradeability and governance
- DateTime Library: A Solidity date and time library
OpenZeppelin is one of the most popular libraries, and we’ll discuss it in the next section. It provides many handy tokens and utility libraries.
One-to-One Live Blockchain Classes
Coding Bootcamps school offers One-to-One Live Blockchain Classes for Beginners.
Working with OpenZeppelin
OpenZeppelin is an open source framework for Solidity smart contracts. It is one of the most widely used Solidity libraries that provide reusable, secure, and modular smart contract code. All of this smart contract code is fully tested to follow the best practice security patterns. The framework is maintained by the Zeppelin company.
OpenZeppelin libraries provide many useful smart contracts, including access, crowdsale, cryptography, introspection, life cycle, math, ownership, payment, token, and utils. The following table shows all of the library project structures:
OpenZeppelin libraries | Description |
access | Provides role-based access control. |
crowdsale | Provides token-based crowdsale contract libraries. |
Cryptography | Provides different cryptographic primitives libraries. |
Introspection | Provides a set of local and global interfaces. |
Draft | The contract is currently in testing status by OpenZeppelin. |
Lifecycle | Provides life cycle management for the contract, and supports pausing and unpausing smart contracts via the pauserRole user. |
math | Provides math-related utilities. |
ownership | Provides simple authorization and access control mechanisms. |
payment | Provides payment-related utilities. |
token | Provides the most popular ERC token utilities. |
utils | Provides miscellaneous smart contract utility functions. |
Let’s explore some OpenZeppelin libraries to understand how we can use these utilities.
Setting up a dev environment
To understand more about OpenZeppelin, let’s set up a Truffle project and run a simple example to get started:
- Set up a Truffle project, create a project folder, and navigate to the project root folder. Then, issue the following Truffle command:
npm install truffle npx truffle init
- Install the OpenZeppelin library and, under the project root folder, run the following npm command:
npm install openzeppelin-solidity
This should install the OpenZeppelin library under the node_modules directory. A Truffle project can read all of these Solidity classes by using an import-related class.
Access control
In Solidity smart contracts, role-based access control is used to restrict unauthorized users from accessing certain functions. With defined access control policies, the smart contract can build the security rule around roles and privileges.
To use the OpenZeppelin Roles function, you need to import Roles.sol from the OpenZeppelin access folder. Then, you have to define the roles you want to use. In our example, we define an admin and minter role. Here is an example of how we can create an admin role and a minter role:
pragma solidity >=0.4.22 <0.6.0; import "openzeppelin-solidity/contracts/access/Roles.sol"; contract AclRole { using Roles for Roles.Role; Roles.Role private admins; Roles.Role private minters; function onlyAdminRole() view public { //only admin can use this function require(admins.has(msg.sender), "You must be admin"); } function onlyMintersRole() view public { //only minters can use this function require(minters.has(msg.sender), "You must be minter"); } function anyone() public { //anyone can use this function } }
In the preceding example, we created two role functions:
- OnlyAdminRole(): Allows the admin role to access and perform functions
- OnlyMinterRole(): Only allows the minter role to access and perform functions
Next, let’s take a look at math functions.
Math
OpenZeppelin libraries provide that SafeMath contract, which has the add, sub, mul, div, and mod methods so that developers can perform safe math operations. Here is the list of functions:
- add(uint256 a, uint256 b)
- sub(uint256 a, uint256 b)
- mul(uint256 a, uint256 b)
- div(uint256 a, uint256 b)
- mod(uint256 a, uint256 b)
The add function is equivalent to Solidity’s + operator. For example, we can add certain balance values:
balances[msg.sender] = balances[msg.sender].add(_value);
The sub function is equivalent to Solidity’s – operator. For example, we can subtract certain balance values:
balances[msg.sender] = balances[msg.sender].sub(_value);
The mul function is equivalent to Solidity’s * operator. For example, we can multiply a balance value by two:
balances[msg.sender] = balances[msg.sender].mul(2);
The div function is equivalent to Solidity’s / operator. For example, we can divide a balance value by 10:
balances[msg.sender] = balances[msg.sender].div(10);
The mod function is equivalent to Solidity’s % operator. For example, if we only charge a multiple of one ether (such as 1eth, 2eth, and so on), we can use the weiUnit mod. After the mod operation, we can find out how much of the remaining ether needs to be returned to the sender:
uint weiUnit = 1 * 10 ** 16;
uint returnAmt = msg.value.mod(weiUnit); uint payAmount = msg.value.sub(returnAmt);
Token
OpenZeppelin libraries provide a set of comprehensive token implementations for ERC20, ERC721, and ERC777. The following screenshot shows the ERC20 implemented by OpenZeppelin libraries. It makes token development much easier and safer:
Let’s review ERC20 token libraries.
An ERC20 token keeps track of user address and balance information. The IERC20 interface defines functions and events that all ERC20 tokens must implement:
- ERC20: This provides basic implementation for IERC20.
- ERC20Burable: This allows the token holder to burn a certain number of tokens.
- ERC20Mintable: This allows MonterRole to mint (create) a certain amount of new tokens when needed.
- ERC20Capped: This adds caps for the token supply.
- ERC20Detailed: This adds name, symbol, and decimal to the ERC20 token’s implementation.
- ERC20Pausable: Users with pauseRole can pause and resume or freeze and resume the token transfer.
- SafeERC20: This provides a wrapper around ERC20 token functions such as safeTransfer, safeTransferFrom, and safeApprove via the callOptionalReturn (IERC20 token and bytes memory data) function.
- TokenTimeLock: This allows the token beneficiary to extract a certain amount of tokens after a specific release time.
Let’s utilize OpenZeppelin-developed token smart contract to implement our ERC20 token. We will use ERC20 for basic ERC20 implementation. ERC20Detailed is for token detail information such as symbol, name, and decimal.
Here is our SampleToken implementation. You can see how easy it is when we use the openzeppelin token libraries. Let’s take a look at the code implementation here:
import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; contract SampleToken is ERC20, ERC20Detailed, Ownable { uint256 public initialSupply = 100000000000; constructor () public ERC20Detailed("SampleToken", "ST", 18) { _mint(msg.sender, initialSupply); } }
We can see that we just need to extend our smart contract from the openzeppelin ERC20 token implementation; you can immediately create your own token by doing this. It makes writing token smart contracts much more straightforward.
Utils
The OpenZeppelin util libraries provide address, arrays, and the ReentrancyGuard utility. Address has a function, isContract(address account), which will return true if the account is the contract. Arrays have a function, findUpperBound(uint256[] array, uint256 element), which is a sorted search array and returns the upperBound element (first index) that returns a value larger or equal to the element value. ReentrancyGuard prevents a reentrance call to a function.
Next Article
Now that we finished our forth article series, we move on to our next article series discussing how to create Ethereum private chains. Specifically, we cover the following 12 articles:
- Review of Private and Permissioned blockchain
- How to Set up a Local Private Ethereum Blockchain
- How to Run Geth on a Local Private Ethereum Blockchain
- How to Build a Local Private Ethereum Blockchain with Mining
- How to Run Geth on a Local Private Ethereum Blockchain with Mining
- How to Create an Account on a Local Private Ethereum Blockchain
- How to Use Ethereum Optional Flags with New Chains
- Review of Ethereum Options for Development and Testing
- Review of Ethereum Developer Chain Options
- Review of Ethereum API and Console Options
- Review of Ethereum Networking Options
- Review of Ethereum Transaction Pool Options
This article is written in collaboration with Brian Wu who is a leading author of “Learn Ethereum: Build your own decentralized applications with Ethereum and smart contracts” book. He has written 7 books on blockchain development.
Resources
coming soon