Commit 852e11c2 by Francisco Giordano Committed by Nicolás Venturo

New guides (#1792)

* Improved tokens guide, add ERC777.

* Fix typo.

* Add release schedule and api stability.

* Add erc20 supply guide.

* Revamp get started

* Add Solidity version to examples

* Update access control guide.

* Add small disclaimer to blog guides

* Update tokens guide.

* Update docs/access-control.md

Co-Authored-By: Francisco Giordano <frangio.1@gmail.com>

* Update docs/access-control.md

Co-Authored-By: Francisco Giordano <frangio.1@gmail.com>

* Update docs/access-control.md

Co-Authored-By: Francisco Giordano <frangio.1@gmail.com>

* Apply suggestions from code review

Co-Authored-By: Francisco Giordano <frangio.1@gmail.com>

* Apply suggestions from code review

Co-Authored-By: Francisco Giordano <frangio.1@gmail.com>

* Documentation: Typos and add npm init -y to setup instructions (#1793)

* Fix typos in GameItem ERC721 sample contract

* Add npm init -y to create package.json

* Address review comments.
parent 79346123
...@@ -5,7 +5,11 @@ import "../../lifecycle/Pausable.sol"; ...@@ -5,7 +5,11 @@ import "../../lifecycle/Pausable.sol";
/** /**
* @title Pausable token * @title Pausable token
* @dev ERC20 modified with pausable transfers. * @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to e.g. stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/ */
contract ERC20Pausable is ERC20, Pausable { contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) { function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
......
...@@ -19,13 +19,16 @@ sections: ...@@ -19,13 +19,16 @@ sections:
This set of interfaces, contracts, and utilities are all related to the [ERC20 Token Standard](https://eips.ethereum.org/EIPS/eip-20). This set of interfaces, contracts, and utilities are all related to the [ERC20 Token Standard](https://eips.ethereum.org/EIPS/eip-20).
*For a walkthrough on how to create an ERC20 token read our [ERC20 guide](../../tokens.md#constructing-a-nice-erc20-token).* *For an overview of ERC20 tokens and a walkthrough on how to create a token contract read our [ERC20 guide](../../tokens#erc20).*
There a few core contracts that implement the behavior specified in the EIP: `IERC20`, `ERC20`, `ERC20Detailed`. There a few core contracts that implement the behavior specified in the EIP:
- `IERC20`: the interface all ERC20 implementations should conform to
- `ERC20`: the base implementation of the ERC20 interface
- `ERC20Detailed`: includes the `name()`, `symbol()` and `decimals()` optional standard extension to the base interface
Additionally there are multiple extensions, including: Additionally there are multiple custom extensions, including:
- designation of addresses that can create token supply (`ERC20Mintable`), with an optional maximum cap (`ERC20Capped`), - designation of addresses that can create token supply (`ERC20Mintable`), with an optional maximum cap (`ERC20Capped`)
- destruction of own tokens (`ERC20Burnable`), - destruction of own tokens (`ERC20Burnable`)
- designation of addresses that can pause token operations for all users (`ERC20Pausable`). - designation of addresses that can pause token operations for all users (`ERC20Pausable`).
Finally, there are some utilities to interact with ERC20 contracts in various ways. Finally, there are some utilities to interact with ERC20 contracts in various ways.
......
...@@ -3,9 +3,14 @@ pragma solidity ^0.5.0; ...@@ -3,9 +3,14 @@ pragma solidity ^0.5.0;
import "./SafeERC20.sol"; import "./SafeERC20.sol";
/** /**
* @title TokenTimelock * @dev A token holder contract that will allow a beneficiary to extract the
* @dev TokenTimelock is a token holder contract that will allow a * tokens after a given release time.
* beneficiary to extract the tokens after a given release time. *
* Useful for simple vesting schedules like "advisors get all of their tokens
* after 1 year".
*
* For a more complete vesting schedule, see
* [`TokenVesting`](api/drafts#tokenvesting).
*/ */
contract TokenTimelock { contract TokenTimelock {
using SafeERC20 for IERC20; using SafeERC20 for IERC20;
......
...@@ -26,12 +26,17 @@ This set of interfaces, contracts, and utilities are all related to the [ERC721 ...@@ -26,12 +26,17 @@ This set of interfaces, contracts, and utilities are all related to the [ERC721
*For a walkthrough on how to create an ERC721 token read our [ERC721 guide](../../tokens.md#erc721).* *For a walkthrough on how to create an ERC721 token read our [ERC721 guide](../../tokens.md#erc721).*
The EIP consists of three interfaces, found here as `IERC721`, The EIP consists of three interfaces, found here as `IERC721`, `IERC721Metadata`, and `IERC721Enumerable`. Only the first one is required in a contract to be ERC721 compliant.
`IERC721Metadata`, and `IERC721Enumerable`. Only the first one is required in a
contract to be ERC721 compliant. Each interface is implemented separately in Each interface is implemented separately in `ERC721`, `ERC721Metadata`, and `ERC721Enumerable`. You can choose the subset of functionality you would like to support in your token by combining the
`ERC721`, `ERC721Metadata`, and `ERC721Enumerable`. You can choose the subset desired subset through inheritance.
of functionality you would like to support in your token by combining the
desired subset through inheritance. The fully featured token implementing all The fully featured token implementing all three interfaces is prepackaged as `ERC721Full`.
three interfaces is prepackaged as `ERC721Full`.
Additionally, `IERC721Receiver` can be used to prevent tokens from becoming forever locked in contracts. Imagine sending an in-game item to an exchange address that can't send it back!. When using `safeTransferFrom()`, the token contract checks to see that the receiver is an `IERC721Receiver`, which implies that it knows how to handle `ERC721` tokens. If you're writing a contract that needs to receive `ERC721` tokens, you'll want to include this interface.
Finally, some custom extensions are also included:
- `ERC721Mintable` — like the ERC20 version, this allows certain addresses to mint new tokens
- `ERC721Pausable` — like the ERC20 version, this allows addresses to freeze transfers of tokens
> This page is incomplete. We're working to improve it for the next release. Stay tuned! > This page is incomplete. We're working to improve it for the next release. Stay tuned!
...@@ -12,6 +12,8 @@ sections: ...@@ -12,6 +12,8 @@ sections:
This set of interfaces and contracts are all related to the [ERC777 token standard](https://eips.ethereum.org/EIPS/eip-777). This set of interfaces and contracts are all related to the [ERC777 token standard](https://eips.ethereum.org/EIPS/eip-777).
*For an overview of ERC777 tokens and a walkthrough on how to create a token contract read our [ERC777 guide](../../tokens#erc20).*
The token behavior itself is implemented in the core contracts: `IERC777`, `ERC777`. The token behavior itself is implemented in the core contracts: `IERC777`, `ERC777`.
Additionally there are interfaces used to develop contracts that react to token movements: `IERC777Sender`, `IERC777Recipient`. Additionally there are interfaces used to develop contracts that react to token movements: `IERC777Sender`, `IERC777Recipient`.
---
id: api-stability
title: API Stability
---
On the [OpenZeppelin 2.0 release](https://github.com/OpenZeppelin/openzeppelin-solidity/releases/tag/v2.0.0), we committed ourselves to keeping a stable API. We aim to more precisely define what we understand by _stable_ and _API_ here, so users of the library can understand these guarantees and be confident their project won't break unexpectedly.
In a nutshell, the API being stable means _if your project is working today, it will continue to do so_. New contracts and features will be added in minor releases, but only in a backwards compatible way.
## Versioning scheme
We follow [SemVer](https://semver.org/), which means API breakage may occur between major releases. Read more about the [release schedule](release-schedule) to know how often this happens (not very).
## Solidity functions
While the internal implementation of functions may change, their semantics and signature will remain the same. The domain of their arguments will not be less restrictive (e.g. if transferring a value of 0 is disallowed, it will remain disallowed), nor will general state restrictions be lifted (e.g. `whenPaused` modifiers).
If new functions are added to a contract, it will be in a backwards-compatible way: their usage won't be mandatory, and they won't extend functionality in ways that may foreseeable break an application (e.g. [an `internal` method may be added to make it easier to retrieve information that was already available](https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1512)).
### `internal`
This extends not only to `external` and `public` functions, but also `internal` ones: many OpenZeppelin contracts are meant to be used by inheriting them (e.g. `Pausable`, `PullPayment`, the different `Roles` contracts), and are therefore used by calling these functions. Similarly, since all OpenZeppelin state variables are `private`, they can only be accessed this way (e.g. to create new `ERC20` tokens, instead of manually modifying `totalSupply` and `balances`, `_mint` should be called).
`private` functions have no guarantees on their behavior, usage, or existence.
Finally, sometimes language limitations will force us to e.g. make `internal` a function that should be `private` in order to implement features the way we want to. These cases will be well documented, and the normal stability guarantees won't apply.
## Libraries
Some of our Solidity libraries use `struct`s to handle internal data that should not be accessed directly (e.g. `Roles`). There's an [open issue](https://github.com/ethereum/solidity/issues/4637) in the Solidity repository requesting a language feature to prevent said access, but it looks like it won't be implemented any time soon. Because of this, we will use leading underscores and mark said `struct`s to make it clear to the user that its contents and layout are _not_ part of the API.
## Events
No events will be removed, and their arguments won't be changed in any way. New events may be added in later versions, and existing events may be emitted under new, reasonable circumstances (e.g. [from 2.1 on, `ERC20` also emits `Approval` on `transferFrom` calls](https://github.com/OpenZeppelin/openzeppelin-solidity/issues/707)).
## Gas costs
While attempts will generally be made to lower the gas costs of working with OpenZeppelin contracts, there are no guarantees regarding this. In particular, users should not assume gas costs will not increase when upgrading library versions.
## Bugfixes
The API stability guarantees may need to be broken in order to fix a bug, and we will do so. This decision won't be made lightly however, and all options will be explored to make the change as non-disruptive as possible. When sufficient, contracts or functions which may result in unsafe behaviour will be deprecated instead of removed (e.g. [#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543) and [#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550)).
## Solidity compiler version
Starting on version 0.5.0, the Solidity team switched to a faster release cycle, with minor releases every few weeks (v0.5.0 was released on November 2018, and v0.5.5 on March 2019), and major, breaking-change releases every couple months (with v0.6.0 scheduled for late March 2019). Including the compiler version in OpenZeppelin's stability guarantees would therefore force the library to either stick to old compilers, or release frequent major updates simply to keep up with newer Solidity releases.
Because of this, **the minimum required Solidity compiler version is not part of the stability guarantees**, and users may be required to upgrade their compiler when using newer versions of OpenZeppelin. Bugfixes will still be backported to older library releases so that all versions currently in use receive these updates.
You can read more about the rationale behind this, the other options we considered and why we went down this path [here](https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1498#issuecomment-449191611).
---
id: erc20-supply
title: Creating ERC20 Supply
---
In this guide you will learn how to create an ERC20 token with a custom supply mechanism. We will showcase two idiomatic ways to use OpenZeppelin for this purpose that you will be able to apply to your smart contract development practice.
***
The standard interface implemented by tokens built on Ethereum is called ERC20, and OpenZeppelin includes a widely used implementation of it: the aptly named [`ERC20`](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.1.2/contracts/token/ERC20/ERC20.sol) contract. This contract, like the standard itself, is quite simple and bare-bones. In fact, if you try deploy an instance of `ERC20` as-is it will be quite literally useless... it will have no supply! What use is a token with no supply?
The way that supply is created is not defined in the ERC20 document. Every token is free to experiment with their own mechanisms, ranging from the most decentralized to the most centralized, from the most naive to the most researched, and more.
#### Fixed supply
Let's say we want a token with a fixed supply of 1000, initially allocated to the account that deploys the contract. If you've used OpenZeppelin v1, you may have written code like the following.
```solidity
contract ERC20FixedSupply is ERC20 {
constructor() public {
totalSupply += 1000;
balances[msg.sender] += 1000;
}
}
```
Starting with OpenZeppelin v2 this pattern is not only discouraged, but disallowed. The variables `totalSupply` and `balances` are now private implementation details of `ERC20`, and you can't directly write to them. Instead, there is an internal `_mint` function that will do exactly this.
```solidity
contract ERC20FixedSupply is ERC20 {
constructor() public {
_mint(msg.sender, 1000);
}
}
```
Encapsulating state like this makes it safer to extend contracts. For instance, in the first example we had to manually keep the `totalSupply` in sync with the modified balances, which is easy to forget. In fact, I omitted something else that is also easily forgotten: the `Transfer` event that is required by the standard, and which is relied on by some clients. The second example does not have this bug, because the internal `_mint` function takes care of it.
#### Rewarding miners
The internal `_mint` function is the key building block that allows us to write ERC20 extensions that implement a supply mechanism.
The mechanism we will implement is a token reward for the miners that produce Ethereum blocks. In Solidity we can access the address of the current block's miner in the global variable `block.coinbase`. We will mint a token reward to this address whenever someone calls the function `mintMinerReward()` on our token. The mechanism may sound silly, but you never know what kind of dynamic this might result in, and it's worth analyzing and experimenting with!
```solidity
contract ERC20WithMinerReward is ERC20 {
function mintMinerReward() public {
_mint(block.coinbase, 1000);
}
}
```
As we can see, `_mint` makes it super easy to do this correctly.
#### Modularizing the mechanism
There is one supply mechanism already included in OpenZeppelin: [`ERC20Mintable`](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.1.2/contracts/token/ERC20/ERC20Mintable.sol). This is a generic mechanism in which a set of accounts is assigned the `minter` role, granting them the permission to call a `mint` function, an external version of `_mint`.
This can be used for centralized minting, where an externally owned account (i.e. someone with a pair of cryptographic keys) decides how much supply to create and to whom. There are very legitimate use cases for this mechanism, such as [traditional asset-backed stablecoins](https://medium.com/reserve-currency/why-another-stablecoin-866f774afede#3aea).
The accounts with the minter role don't need to be externally owned, though, and can just as well be smart contracts that implement a trustless mechanism. We can in fact implement the same behavior as the previous section.
```solidity
contract MinerRewardMinter {
ERC20Mintable _token;
constructor(ERC20Mintable token) public {
_token = token;
}
function mintMinerReward() public {
_token.mint(block.coinbase, 1000);
}
}
```
This contract, when initialized with an `ERC20Mintable` instance, will result in exactly the same behavior implemented in the previous section. What is interesting about using `ERC20Mintable` is that we can easily combine multiple supply mechanisms by assigning the role to multiple contracts, and moreover that we can do this dynamically.
#### Automating the reward
Additionally to `_mint`, `ERC20` provides other internal functions that can be used or extended, such as `_transfer`. This function implements token transfers and is used by `ERC20`, so it can be used to trigger functionality automatically. This is something that can't be done with the `ERC20Mintable` approach.
Adding to our previous supply mechanism, we can use this to mint a miner reward for every token transfer that is included in the blockchain.
```solidity
contract ERC20WithAutoMinerReward is ERC20 {
function _mintMinerReward() internal {
_mint(block.coinbase, 1000);
}
function _transfer(address from, address to, uint256 value) internal {
_mintMinerReward();
super._transfer(from, to, value);
}
}
```
Note how we override `_transfer` to first mint the miner reward and then run the original implementation by calling `super._transfer`. This last step is very important to preserve the original semantics of ERC20 transfers.
#### Wrapping up
We've seen two ways to implement ERC20 supply mechanisms: internally through `_mint`, and externally through `ERC20Mintable`. Hopefully this has helped you understand how to use OpenZeppelin and some of the design principles behind it, and you can apply them to your own smart contracts.
--- ---
id: get-started id: get-started
title: Get Started title: Getting Started
--- ---
OpenZeppelin can be installed directly into your existing node.js project with `npm install openzeppelin-solidity`. We will use [Truffle](https://github.com/trufflesuite/truffle), an Ethereum development environment, to get started. **OpenZeppelin is a library for secure smart contract development.** It provides implementations of standards like ERC20 and ERC721 which you can deploy as-is or extend to suit your needs, as well as Solidity components to build custom contracts and more complex decentralized systems.
## Install
OpenZeppelin should be installed directly into your existing node.js project with `npm install openzeppelin-solidity`. We will use [Truffle](https://truffleframework.com/truffle), an Ethereum development environment, to get started.
Please install Truffle and initialize your project: Please install Truffle and initialize your project:
```sh ```sh
$ mkdir myproject $ mkdir myproject
$ cd myproject $ cd myproject
$ npm init -y
$ npm install truffle $ npm install truffle
$ npx truffle init $ npx truffle init
``` ```
To install the OpenZeppelin library, run the following in your Solidity project root directory: To install the OpenZeppelin library, run the following in your Solidity project root directory:
```sh ```sh
$ npm install openzeppelin-solidity $ npm install openzeppelin-solidity
``` ```
After that, you'll get all the library's contracts in the `node_modules/openzeppelin-solidity/contracts` folder. Because Truffle and other Ethereum development toolkits understand `node_modules`, you can use the contracts in the library like so: _OpenZeppelin features a stable API, which means your contracts won't break unexpectedly when upgrading to a newer minor version. You can read ṫhe details in our [API Stability](api-stability) document._
## Usage
Once installed, you can start using the contracts in the library by importing them:
```solidity
pragma solidity ^0.5.0;
```js
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
contract MyContract is Ownable { contract MyContract is Ownable {
...@@ -29,21 +41,27 @@ contract MyContract is Ownable { ...@@ -29,21 +41,27 @@ contract MyContract is Ownable {
} }
``` ```
Truffle and other Ethereum development toolkits will automatically detect the installed library, and compile the imported contracts.
>You should always use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself.
## Next Steps ## Next Steps
After installing OpenZeppelin, check out the rest of the guides in the sidebar to learn about the different contracts that OpenZeppelin provides and how to use them. Check out the the guides in the sidebar to learn about different concepts, and how to use the contracts that OpenZeppelin provides.
- [Learn about Access Control](access-control)
- [Learn about Crowdsales](crowdsales)
- [Learn about Tokens](tokens)
- [Learn about our Utilities](utilities)
- [Learn About Access Control](access-control) OpenZeppelin's [full API](api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application.
- [Learn About Crowdsales](crowdsales)
- [Learn About Tokens](tokens)
- [Learn About Utilities](utilities)
You may also want to take a look at the guides on our blog, which cover several common use cases and good practices: https://blog.zeppelin.solutions/guides/home. Additionally, you can also ask for help or follow OpenZeppelin's development in the [community forum](https://forum.zeppelin.solutions).
For example, [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment. Finally, you may want to take a look at the guides on our blog, which cover several common use cases and good practices: https://blog.zeppelin.solutions/guides/home. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve.
[A Gentle Introduction to Ethereum Programming, Part 1](https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform. * [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment
For a more in-depth dive, you may read the guide [Designing the architecture for your Ethereum application](https://blog.zeppelin.solutions/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world. * [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform
You may also ask for help or follow OpenZeppelin's progress in the community [forum](https://forum.zeppelin.solutions), or read OpenZeppelin's full API on this website. * For a more in-depth dive, you may read the guide [Designing the architecture for your Ethereum application](https://blog.zeppelin.solutions/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world
---
id: release-schedule
title: Release Schedule
---
OpenZeppelin follows a [semantic versioning scheme](api-stability).
#### Minor releases
OpenZeppelin has a **5 week release cycle**. This means that every five weeks a new release is published.
At the beginning of the release cycle we decide which issues we want to prioritize, and assign them to [a milestone on GitHub](https://github.com/OpenZeppelin/openzeppelin-solidity/milestones). During the next five weeks, they are worked on and fixed.
Once the milestone is complete, we publish a feature-frozen release candidate. The purpose of the release candidate is to have a period where the community can review the new code before the actual release. If important problems are discovered, several more release candidates may be required. After a week of no more changes to the release candidate, the new version is published.
#### Major releases
Every several months a new major release may come out. These are not scheduled, but will be based on the need to release breaking changes such as a redesign of a core feature of the library (e.g. [roles](https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1146) in 2.0). Since we value stability, we aim for these to happen infrequently (expect no less than six months between majors). However, we may be forced to release one when there are big changes to the Solidity language.
...@@ -2,16 +2,23 @@ ...@@ -2,16 +2,23 @@
"Overview": [ "Overview": [
"get-started" "get-started"
], ],
"Guides": [ "Basics": [
"access-control", "access-control",
"crowdsales", "crowdsales",
"tokens", "tokens",
"utilities" "utilities"
], ],
"In Depth": [
"erc20-supply"
],
"API Reference": [ "API Reference": [
{ {
"type": "directory", "type": "directory",
"directory": "api" "directory": "api"
} }
],
"FAQ": [
"api-stability",
"release-schedule"
] ]
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment