Smart Contract Libraries

Smart Contract Libraries#

There are two smart contract libraries that we will use to start the development of our ERC-20 tokens, both recommended by the OpenZeppelin team: SafeMath and Context. SafeMath will ensure that there are no errors when doing math in Solidity contracts (e.g. adding, subtracting, multiplying and division), and Context will be used to track some metadata for the token smart contract we deploy.

SafeMath Library#

Let's start off by writing the SafeMath library. To start writing the library, create a folder in the contracts folder called libraries. In that folder, create a file called SafeMath.sol. Now open this library file and start by specifying the version of Solidity that we will be using.

The SafeMath library that we will create will be simple, with methods add, sub and mul. Since token smart contracts interact with large numbers, this library will ensure that we don't have any overflows in the numbers we are adding, subtracting, or multiplying. This is because numbers in Solidity are capped by the uint256 variable (uint256 has a maximum value of (2**256)-1).

Identify the library in Solidity like this:

This library has been vetted by OpenZeppelin and another organization called DappHub. Each method we add to the library will be responsible for interacting with two uint256 numbers. The methods will all be internal, pure, and return a uint256 value to the method caller.

Now that we have the placeholders for our add, sub and mul functions, let's write the code to ensure that when we work with large numbers in our ERC-20 tokens we don't run into any overflow errors.

Normally, to add two numbers together we can simply write x + y. If we combine that with a require statement then we can do the addition that we require (with the proper checks in place) in one line. When the two numbers are added together, we have to make sure that the sum that we get from x and y is greater than one of the values. Add the following code between the {} for the add function:

 

This page is a preview of Creating an ERC20 Token on Ethereum

No discussions yet