* 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.

(cherry picked from commit 852e11c2db)
pull/2057/head
Francisco Giordano 6 years ago
parent 5fd011d93e
commit aa878d8b69
  1. 6
      contracts/token/ERC20/ERC20Pausable.sol
  2. 13
      contracts/token/ERC20/README.md
  3. 11
      contracts/token/ERC20/TokenTimelock.sol
  4. 19
      contracts/token/ERC721/README.md
  5. 2
      contracts/token/ERC777/README.md
  6. 105
      docs/access-control.md
  7. 42
      docs/api-stability.md
  8. 102
      docs/erc20-supply.md
  9. 46
      docs/get-started.md
  10. 18
      docs/release-schedule.md
  11. 9
      docs/sidebar.json
  12. 257
      docs/tokens.md

@ -5,7 +5,11 @@ import "../../lifecycle/Pausable.sol";
/**
* @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 {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {

@ -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).
*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:
- designation of addresses that can create token supply (`ERC20Mintable`), with an optional maximum cap (`ERC20Capped`),
- destruction of own tokens (`ERC20Burnable`),
Additionally there are multiple custom extensions, including:
- designation of addresses that can create token supply (`ERC20Mintable`), with an optional maximum cap (`ERC20Capped`)
- destruction of own tokens (`ERC20Burnable`)
- 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.

@ -3,9 +3,14 @@ pragma solidity ^0.5.0;
import "./SafeERC20.sol";
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time.
* @dev A token holder contract that will allow a 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 {
using SafeERC20 for IERC20;

@ -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).*
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. 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
desired subset through inheritance. The fully featured token implementing all
three interfaces is prepackaged as `ERC721Full`.
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.
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
desired subset through inheritance.
The fully featured token implementing all 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!

@ -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).
*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`.
Additionally there are interfaces used to develop contracts that react to token movements: `IERC777Sender`, `IERC777Recipient`.

@ -2,103 +2,106 @@
id: access-control
title: Access Control
---
Access control—that is, "who is allowed to do this thing"—is incredibly important in the world of smart contracts. The access control of your contract may govern who can mint tokens, vote on proposals, freeze transfers, and many others. It is therefore critical to understand how you implement it, lest someone else [steals your whole system](https://blog.zeppelin.solutions/on-the-parity-wallet-multisig-hack-405a8c12e8f7).
Access control—that is, "who is allowed to do this thing"—is incredibly important in the world of smart contracts. The access control of your contract governs who can mint tokens, who can vote on proposals, who can [`selfdestruct()`](https://blog.zeppelin.solutions/on-the-parity-wallet-multisig-hack-405a8c12e8f7) the contract, and more, so it's very important to understand how you implement it.
## Ownership and `Ownable`
## Ownership & Ownable.sol
The most common and basic form of access control is the concept of _ownership_: there's one account that is the `owner` and can do administrative tasks on contracts. This approach is perfectly reasonable for contracts that only have a single administrative user.
The most common and basic form of access control is the concept of _ownership_: there's an account that is the `owner` of a contract and can do administrative tasks on it. This approach is perfectly reasonable for contracts that have a single administrative user.
OpenZeppelin provides [`Ownable`](api/ownership#ownable) for implementing ownership in your contracts.
```solidity
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract MyContract is Ownable {
function normalThing()
public
{
function normalThing() public {
// anyone can call this normalThing()
}
function specialThing()
public
onlyOwner
{
function specialThing() public onlyOwner {
// only the owner can call specialThing()!
}
}
```
By default, the [`owner`](api/ownership#Ownable.owner()) of an `Ownable` contract is the `msg.sender` of the contract creation transaction, which is usually exactly what you want.
By default, the [`owner`](api/ownership#Ownable.owner()) of an `Ownable` contract is the account that deployed it, which is usually exactly what you want.
Ownable also lets you:
+ [`transferOwnership`](api/ownership#Ownable.transferOwnership(address)) to transfer ownership from one account to another
+ [`renounceOwnership`](api/ownership#Ownable.renounceOwnership()) to remove the owner altogether, useful for decentralizing control of your contract. **⚠ Warning!** Removing the owner altogether will mean that administrative tasks that are protected by `onlyOwner` will no longer be callable!
Note that any contract that supports sending transactions can also be the owner of a contract; the only requirement is that the owner has an Ethereum address, so it could be a Gnosis Multisig or Gnosis Safe, an Aragon DAO, an ERC725/uPort identity contract, or a totally custom contract that _you_ create.
- [`transferOwnership`](api/ownership#Ownable.transferOwnership(address)) from the owner account to a new one
- [`renounceOwnership`](api/ownership#Ownable.renounceOwnership()) for the owner to lose this administrative privilege, a common pattern after an initial stage with centralized administration is over
- **⚠ Warning! ⚠** Removing the owner altogether will mean that administrative tasks that are protected by `onlyOwner` will no longer be callable!
In this way you can use _composability_ to add additional layers of access control complexity to your contracts. Instead of having a single Ethereum Off-Chain Account (EOA) as the owner, you can replace them with a 2/3 multisig run by your project leads, for example.
Note that **a contract can also be the owner of another one**! This opens the door to using, for example, a [Gnosis Multisig](https://github.com/gnosis/MultiSigWallet) or [Gnosis Safe](https://safe.gnosis.io), an [Aragon DAO](https://aragon.org), an [ERC725/uPort](https://www.uport.me) identity contract, or a totally custom contract that _you_ create.
### Examples in OpenZeppelin
In this way you can use _composability_ to add additional layers of access control complexity to your contracts. Instead of having a single regular Ethereum account (Externally Owned Account, or EOA) as the owner, you could use a 2-of-3 multisig run by your project leads, for example. Prominent projects in the space, such as [MakerDAO](https://makerdao.com), use systems similar to this one.
You'll notice that none of the OpenZeppelin contracts use `Ownable`, though! This is because there are more flexible ways of providing access control that are more in-line with our reusable contract philosophy. For most contracts, We'll use `Roles` to govern who can do what. There are some cases, though—like with [`Escrow`](localhost:3000/api/payment#escrow)—where there's a direct relationship between contracts. In those cases, we'll use [`Secondary`](api/ownership#secondary) to create a "secondary" contract that allows a "primary" contract to manage it.
## Role-Based Access Control
Let's learn about Role-Based Access Control!
While the simplicity of _ownership_ can be useful for simple systems or quick prototyping, different levels of authorization are often needed. An account may be able to ban users from a system, but not create new tokens. _Role-Based Access Control (RBAC)_ offers flexibility in this regard.
## Roles & Role-Based Access Control
In essence, we will be defining multiple _roles_, each allowed to perform different sets of actions. Instead of `onlyOwner` everywhere you will use, for example, `onlyAdminRole` in some places, and `onlyModeratorRole` in others. Separately you will be able to define rules for how accounts can be assignned a role, transfer it, and more.
An alternative to single-concern `Ownable` is role based access control (RBAC), which, instead of keeping track of a single entity with "admin" level privileges, keeps track of multiple different entities with a variety of roles that inform the contract about what they can do.
Most of software development uses access control systems that are role-based: some users are regular users, some may be supervisors or managers, and a few will often have administrative privileges.
For example, a [`MintableToken`](api/token/ERC20#erc20mintable) could have a `minter` role that decides who can mint tokens (which could be assigned to a [`Crowdsale`](api/crowdsale#crowdsale)). It could also have a `namer` role that allows changing the name or symbol of the token (for whatever reason). RBAC gives you much more flexibility over who can do what and is generally recommended for applications that need more configurability. If you're experienced with web development, the vast majority of access control systems are role-based: some users are normal users, some are moderators, and some can be company employee admins.
### Using `Roles`
OpenZeppelin provides [`Roles`](api/access#roles) for implementing role-based access control.
OpenZeppelin provides [`Roles`](api/access#roles) for implementing role-based access control. Its usage is straightforward: for each role that you want to define, you'll store a variable of type `Role`, which will hold the list of accounts with that role.
Here's an example of using `Roles` in our token example above, we'll use it to implement a token that can be minted by `Minters` and renamed by `Namers`:
Here's an simple example of using `Roles` in an [`ERC20` token](tokens#erc20): we'll define two roles, `namers` and `minters`, that will be able to change the name of the token contract, and mint new tokens, respectively.
```solidity
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/access/Roles.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
contract MyToken is DetailedERC20, StandardToken {
contract MyToken is ERC20, ERC20Detailed {
using Roles for Roles.Role;
Roles.Role private minters;
Roles.Role private namers;
constructor(
string name,
string symbol,
uint8 decimals,
address[] minters,
address[] namers,
)
DetailedERC20(name, symbol, decimals)
Standardtoken()
Roles.Role private _minters;
Roles.Role private _namers;
constructor(address[] memory minters, address[] memory namers)
DetailedERC20("MyToken", "MTKN", 18)
public
{
namers.addMany(namers);
minters.addMany(minters);
for (uint256 i = 0; i < minters.length; ++i) {
_minters.add(minters[i]);
}
for (uint256 i = 0; i < namers.length; ++i) {
_namers.add(namers[i]);
}
}
function mint(address to, uint256 amount)
public
{
// only allow minters to mint
function mint(address to, uint256 amount) public {
// Only minters can mint
require(minters.has(msg.sender), "DOES_NOT_HAVE_MINTER_ROLE");
_mint(to, amount);
}
function rename(string name, string symbol)
public
{
// only allow namers to name
function rename(string memory name, string memory symbol) public {
// Only namers can change the name and symbol
require(namers.has(msg.sender), "DOES_NOT_HAVE_NAMER_ROLE");
name = name;
symbol = symbol;
}
}
```
So clean! You'll notice that the role associations are always the last arguments in the constructor; this is a good pattern to follow to keep your code more organized.
So clean! By splitting concerns this way, we can define more granular levels of permission, which was lacking in the _ownership_ approach to access control. Note that an account may have more than one role, if desired.
OpenZeppelin uses `Roles` extensively with predefined contracts that encode rules for each specific role. A few examples are: [`ERC20Mintable`](api/token/ERC20#erc20mintable) which uses the [`MinterRole`](api/access#minterrole) to determine who can mint tokens, and [`WhitelistCrowdsale`](api/crowdsale#whitelistcrowdsale) which uses both [`WhitelistAdminRole`](api/access#whitelistadminrole) and [`WhitelistedRole`](api/access#whitelistedrole) to create a set of accounts that can purchase tokens.
This flexibility allows for interesting setups: for example, a [`MintedCrowdsale`](api/crowdsale#mintedcrowdsale) expects to be given the `MinterRole` of an `ERC20Mintable` in order to work, but the token contract could also extend [`ERC20Pausable`](api/token/ERC20#erc20pausable) and assign the [`PauserRole`](api/access#pauserrole) to a DAO that serves as a contingency mechanism in case a vulnerability is discovered in the contract code. Limiting what each component of a system is able to do is known as the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), and is a good security practice.
## Usage in OpenZeppelin
You'll notice that none of the OpenZeppelin contracts use `Ownable`. `Roles` is a prefferred solution, because it provides the user of the library with enough flexibility to adapt the provided contracts to their needs.
There are some cases, though, where there's a direct relationship between contracts. For example, [`RefundableCrowdsale`](api/crowdsale#refundablecrowdsale) deploys a [`RefundEscrow`](api/payment#refundescrow) on construction, to hold its funds. For those cases, we'll use [`Secondary`](api/ownership#secondary) to create a _secondary_ contract that allows a _primary_ contract to manage it. You could also think of these as _auxiliary_ contracts.

@ -0,0 +1,42 @@
---
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).

@ -0,0 +1,102 @@
---
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.

@ -1,27 +1,39 @@
---
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:
```sh
$ mkdir myproject
$ cd myproject
$ npm init -y
$ npm install truffle
$ npx truffle init
```
To install the OpenZeppelin library, run the following in your Solidity project root directory:
```sh
$ 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';
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
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)
- [Learn About Crowdsales](crowdsales)
- [Learn About Tokens](tokens)
- [Learn About Utilities](utilities)
OpenZeppelin's [full API](api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application.
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

@ -0,0 +1,18 @@
---
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 @@
"Overview": [
"get-started"
],
"Guides": [
"Basics": [
"access-control",
"crowdsales",
"tokens",
"utilities"
],
"In Depth": [
"erc20-supply"
],
"API Reference": [
{
"type": "directory",
"directory": "api"
}
],
"FAQ": [
"api-stability",
"release-schedule"
]
}

@ -3,136 +3,235 @@ id: tokens
title: Tokens
---
Ah, the "token": the world's most powerful and most misused tool. In this section we'll learn to harness the power of native units of account for good and world peace!
Ah, the "token": the world's most powerful and most misunderstood tool.
## But First, ~~Coffee~~ a Primer on Tokens
A token is a _representation of something in the blockchain_. This something can be money, time, services, shares in a company, a virtual pet, anything. By representing things as tokens, we can allow smart contracts to interact with them, exchange them, create or destroy them.
Simply put, a token _isn't anything special_. In Ethereum, pretty much _everything_ is a contract, and that includes what we call tokens. "Sending a token" is the same as "calling a method on a smart contract that someone wrote and deployed". And, at the end of the day, a token is just a mapping of addresses to balances and some nice methods to add and subtract from those balances.
## But First, ~~Coffee~~ a Primer on Token Contracts
That's it! These balances could be considered money, or they could be voting rights or they could be experience points in your game.
Much of the confusion surrounding tokens comes from two concepts getting mixed up: _token contracts_ and the actual _tokens_.
A _token contract_ is simply an Ethereum smart contract. "Sending tokens" actually means "calling a method on a smart contract that someone wrote and deployed". At the end of the day, a token contract is not much more a mapping of addresses to balances, plus some methods to add and subtract from those balances.
It is these balances that represent the _tokens_ themselves. Someone "has tokens" when their balance in the token contract is non-zero. That's it! These balances could be considered money, experience points in a game, deeds of ownership, or voting rights, and each of these tokens would be stored in different token contracts.
### Different kinds of tokens
Note that there's a big difference between having two voting rights and two deeds of ownership: each vote is equal to all others, but houses usually are not! This is called [fungibility](https://en.wikipedia.org/wiki/Fungibility). _Fungible goods_ are equivalent and interchangeable, like Ether, fiat currencies, and voting rights. _Non-fungible_ goods are unique and distinct, like deeds of ownership, or collectibles.
In a nutshell, when dealing with non-fungibles (like your house) you care about _which ones_ you have, while in fungible assets (like your bank account statement) what matters is _how much_ you have.
### Standards
Even though the concept of a token is simple, they have a variety of complexities in the implementation. Because everything in Ethereum is just a smart contract, and there are no rules about what smart contracts have to do, the community has developed a variety of **standards** (called EIPs or ERCs) for documenting how a contract can interoperate with other contracts.
You've probably heard of the **ERC20** standard, and that's why you're here.
You've probably heard of the [ERC20](#erc20) or [ERC721](#erc721) token standards, and that's why you're here.
## ERC20
An ERC20 token is a contract that keeps track of a `mapping(address => uint256)` that represents a user's balance. These tokens are _fungible_ in that any one token is exactly equal to any other token; no tokens have special rights or behavior associated with them. This makes ERC20 useful for things like a medium of exchange currency, general voting rights, staking, and more.
An ERC20 token contract keeps track of [_fungible_ tokens](#different-kinds-of-tokens): any one token is exactly equal to any other token; no tokens have special rights or behavior associated with them. This makes ERC20 tokens useful for things like a **medium of exchange currency**, **voting rights**, **staking**, and more.
OpenZeppelin provides a few different ERC20-related contracts. Here are the core contracts you'll almost definitely be using:
OpenZeppelin provides many ERC20-related contracts. On the [`API reference`](api/token/ERC20) you'll find detailed information on their properties and usage.
- [`IERC20`](api/token/ERC20#ierc20) — defines the interface that all ERC20 token implementations should conform to
- [`ERC20`](api/token/ERC20#erc20) — the base implementation of the ERC20 interface
- [`ERC20Detailed`](api/token/ERC20#erc20detailed) — the [`name()`](api/token/ERC20#ERC20Detailed.name()), [`symbol()`](api/token/ERC20#ERC20Detailed.symbol()), and [`decimals()`](api/token/ERC20#ERC20Detailed.decimals()) getters are optional in the original standard, so `ERC20Detailed` adds that information to your token.
### Constructing an ERC20 Token Contract
Using OpenZeppelin, we can easily create our own ERC20 token contract, which will be used to track _Gold_ (GLD), an internal currency in a hypothetical game.
After that, OpenZeppelin provides a few extra properties that you may want depending on your use-case:
Here's what our GLD token might look like.
- [`ERC20Mintable`](api/token/ERC20#erc20mintable) — `ERC20Mintable` allows users with the [`MinterRole`](access-control) to call the [`mint()`](api/token/ERC20#ERC20Mintable.mint(address,uint256)) function and mint tokens to users.
- [`ERC20Burnable`](api/token/ERC20#erc20burnable) — if your token can be burned (aka, it can be destroyed), include this one.
- [`ERC20Capped`](api/token/ERC20#erc20capped) — `ERC20Capped` is a type of `ERC20Mintable` that enforces a maximum cap on tokens; this is really useful if you want to ensure network participants that there will always be a maximum number of tokens, and is useful for making sure that multiple different minting methods don't accidentally create more tokens than you expected.
- [`ERC20Pausable`](api/token/ERC20#erc20pausable) — `ERC20Pausable` allows anyone with the Pauser role to pause the token, freezing transfers to and from users. This is useful if you want to stop trades until the end of a crowdsale, or if you want to have an emergency switch for freezing your tokens in the event of a large bug. Note that there are inherent decentralization tradeoffs when using a pausable token; users may not expect that their unstoppable money can be frozen by a single address!
```solidity
pragma solidity ^0.5.0;
Finally, if you're working with ERC20 tokens, OpenZeppelin provides some utility contracts:
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
- [`SafeERC20`](api/token/ERC20#safeerc20) — provides [`safeTransfer`](api/token/ERC20#SafeERC20.safeTransfer(contract%20IERC20,address,uint256)), [`safeTransferFrom`](api/token/ERC20#SafeERC20.safeTransferFrom(contract%20IERC20,address,address,uint256)), and [`safeApprove`](api/token/ERC20#SafeERC20.safeApprove(contract%20IERC20,address,uint256)) that are helpful wrappers around the normal ERC20 functions. Using `SafeERC20` forces transfers and approvals to succeed, or the entire transaction is reverted.
- [`TokenTimelock`](api/token/ERC20#tokentimelock) — is an escrow contract for ERC20 tokens that will release some tokens after a specified timeout. This is useful for simple vesting schedules like "advisors get all of their tokens after 1 year". For a better vesting schedule, though, see [`TokenVesting`](api/drafts#tokenvesting)
contract GLDToken is ERC20, ERC20Detailed {
constructor(uint256 initialSupply) ERC20Detailed("Gold", "GLD", 18) public {
_mint(msg.sender, initialSupply);
}
}
```
OpenZeppelin contracts are often used via [inheritance](https://solidity.readthedocs.io/en/latest/contracts.html#inheritance), and here we're reusing [`ERC20`](api/token/ERC20#erc20) for the basic standard implementation and [`ERC20Detailed`](api/token/ERC20#erc20detailed) to get the [`name`](api/token/ERC20#ERC20Detailed.name()), [`symbol`](api/token/ERC20#ERC20Detailed.symbol()), and [`decimals`](api/token/ERC20#ERC20Detailed.decimals()) properties. Additionally, we're creating an `initialSupply` of tokens, which will be assigned to the address that deploys the contract.
_For a more complete discussion of ERC20 supply mechanisms, see [our advanced guide](erc20-supply)_.
That's it! Once deployed, we will be able to query the deployer's balance:
```javascript
> GLDToken.balanceOf(deployerAddress)
1000
```
We can also [transfer](api/token/ERC20#IERC20.transfer(address,uint256)) these tokens to other accounts:
```javascript
> GLDToken.transfer(otherAddress, 300)
> GLDToken.balanceOf(otherAddress)
300
> GLDToken.balanceOf(deployerAddress)
700
```
### Constructing a Nice ERC20 Token
### A note on `decimals`
Now that we know what all of the contracts do (you should read the code! It's open source!), we can make our ERC20 token that will revolutionize dogsitting by reducing human beings to organic machines that act entirely based on rational monetary incentives, fueled by the DOGGO token.
Often, you'll want to be able to divide your tokens into arbitrary amounts: say, if you own `5 GLD`, you may want to send `1.5 GLD` to a friend, and keep `3.5 GLD` to yourself. Unfortunately, Solidity and the EVM do not support this behavior: only integer (whole) numbers can be used, which poses an issue. You may send `1` or `2` tokens, but not `1.5`.
Here's what a good DOGGO token might look like.
To work around this, [`ERC20Detailed`](api/token/ERC20#erc20detailed) provides a [`decimals`](api/token/ERC20#ERC20Detailed.decimals()) field, which is used to specify how many decimal places a token has. To be able to transfer `1.5 GLD`, `decimals` must be at least `1`, since that number has a single decimal place.
How can this be achieved? It's actually very simple: a token contract can use larger integer values, so that a balance of `50` will represent `5 GLD`, a transfer of `15` will correspond to `1.5 GLD` being sent, and so on.
It is important to understand that `decimals` is _only used for display purposes_. All arithmetic inside the contract is still performed on integers, and it is the different user interfaces (wallets, exchanges, etc.) that must adjust the displayed values according to `decimals`. The total token supply and balance of each account are not specified in `GLD`: you need to divide by `10**decimals` to get the actual `GLD` amount.
You'll probably want to use a `decimals` value of `18`, just like Ether and most ERC20 token contracts in use, unless you have a very special reason not to. When minting tokens or transferring them around, you will be actually sending the number `num GLD * 10**decimals`. So if you want to send `5` tokens using a token contract with 18 decimals, the the method to call will actually be `transfer(recipient, 5 * 10**18)`.
## ERC721
We've discussed how you can make a _fungible_ token using [ERC20](#erc20), but what if not all tokens are alike? This comes up in situations like **real estate** or **collectibles**, where some items are valued more than others, due to their usefulness, rarity, etc. ERC721 is a standard for representing ownership of [_non-fungible_ tokens](#different-kinds-of-tokens), that is, where each token is unique.
ERC721 is a more complex standard than ERC20, with multiple optional extensions, and is split accross a number of contracts. OpenZeppelin provides flexibility regarding how these are combined, along with custom useful extensions. Check out the [`API reference`](api/token/ERC721) to learn more about these.
### Constructing an ERC721 Token Contract
We'll use ERC721 to track items in our game, which will each have their own unique attributes. Whenever one is to be awarded to a player, it will be minted and sent to them. Players are free to keep their token or trade it with other people as they see fit, as they would any other asset on the blockchain!
Here's what a contract for tokenized items might look like:
```solidity
contract DoggoToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable {
pragma solidity ^0.5.0;
constructor(
string memory name,
string memory symbol,
uint8 decimals
)
ERC20Burnable()
ERC20Mintable()
ERC20Detailed(name, symbol, decimals)
ERC20()
public
{}
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import "openzeppelin-solidity/contracts/drafts/Counters.sol";
contract GameItem is ERC721Full {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721Full("GameItem", "ITM") public {
}
function awardItem(address player, string memory tokenURI) public returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(player, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
}
```
`ERC20Mintable` allows to add minters via `addMinter(addr)`, so they (like the DOGGO Network multisig) can mint tokens to the dogsitters in exchange for watching the nice doggos while their owners leave for vacation. The token is `ERC20Burnable` we want to have the ability to stake DOGGO tokens on our reputation—if the dogsitter does a bad job, their tokens get burned!
The [`ERC721Full`](api/token/ERC721#erc721full) contract includes all standard extensions, and is probably the one you want to use. In particular, it includes [`ERC721Metadata`](api/token/ERC721#erc721metadata), which provides the [`_setTokenURI`](api/token/ERC721#ERC721Metadata._setTokenURI(uint256,string)) method we use to store an item's metadata.
### A Note on `decimals`
Also note that, unlike ERC20, ERC721 lacks a `decimals` field, since each token is distinct and cannot be partitioned.
You might remember from the previous chapter about crowdsales about how math is performed in financial situations: **all currency math is done in the smallest unit of that currency**.
New items can be created:
That means that the `totalSupply` of a token is actually in what we call `TKNbits`, not what you see as `TKN`. So if my total supply is `1` and we have `5` decimals in the token, that's actually `1 TKNbit` and will be displayed as `0.00001 TKN`.
```javascript
> gameItem.awardItem(playerAddress, "https://game.example/item-id-8u5h2m.json")
7
```
You probably want to use a decimals of `18`, just like Ether, unless you have a special reason not to, so when you're minting tokens to people or transferring them around, you're actually sending the number `numTKN * 10^(decimals)`. So if I'm sending you `5` tokens using a token contract with 18 decimals, the method I'm executing actually looks like `transfer(yourAddress, 5 * 10^18)`.
And the owner and metadata of each item queried:
```javascript
> gameItem.ownerOf(7)
playerAddress
> gameItem.tokenURI(7)
"https://game.example/item-id-8u5h2m.json"
```
## ERC721
This `tokenURI` should resolve to a JSON document that might look something like:
```json
{
"name": "Thor's hammer",
"description": "Mjölnir, the legendary hammer of the Norse god of thunder.",
"image": "https://game.example/item-id-8u5h2m.png",
"strength": 20
}
```
For more information about the `tokenURI` metadata JSON Schema, check out the [ERC721 specification](https://eips.ethereum.org/EIPS/eip-721).
_Note: you'll notice that the item's information is included in the metadata, but that information isn't on-chain! So a game developer could change the underlying metadata, changing the rules of the game! If you'd like to put all item information on-chain, you can extend ERC721 to do so (though it will be rather costly). You could also leverage IPFS to store the tokenURI information, but these techniques are out of the scope of this overview guide._
# Advanced standards
[ERC20](#erc20) and [ERC721](#erc721) (fungible and non-fungible assets, respectively) are the first two token contract standards to enjoy widespread use and adoption, but over time, multiple weak points of these standards were identified, as more advanced use cases came up.
As a result, a multitude of new token standards were and are still being developed, with different tradeoffs between complexity, compatibility and ease of use. We'll explore some of those here.
We've discussed how you can make a _fungible_ token using ERC20, but what if not all tokens are alike? This comes up in situations like company stock; some stock is common stock and some stock is investor shares, etc. It also comes up in a bunch of other places like in-game items, time, property, and so on.
## ERC777
[ERC721](https://eips.ethereum.org/EIPS/eip-721) is a standard for representing ownership that is **non-fungible** aka, each token has unique properties.
Like ERC20, ERC777 is a standard for [_fungible_ tokens](#different-kinds-of-tokens), and is focused around allowing more complex interactions when trading tokens. More generally, it brings tokens and Ether closer together by providing the equivalent of a `msg.value` field, but for tokens.
Let's see what contracts OpenZeppelin provides for helping us work with ERC721:
The standard also bring multiple quality-of-life improvements, such as getting rid of the confusion around `decimals`, minting and burning with proper events, among others, but its killer feature are **receive hooks**. A hook is simply a function in a contract that is called when tokens are sent to it, meaning **accounts and contracts can react to receiving tokens**.
- The [`IERC721`](api/token/ERC721#ierc721), [`IERC721Metadata`](api/token/ERC721#ierc721metadata), [`IERC721Enumerable`](api/token/ERC721#ierc721enumerable) contracts document the interfaces.
- [`ERC721`](api/token/ERC721#erc721) — is the full implementation of ERC721, and the contract you'll most likely be inheriting from.
- [`IERC721Receiver`](api/token/ERC721#ierc721receiver) — in some cases, it's beneficial to be 100% certain that a contract knows how to handle ERC721 tokens (imagine sending an in-game item to an exchange address that can't send it back!). When using [`safeTransferFrom()`](api/token/ERC721#ERC721.safeTransferFrom(address,address,uint256)), the 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 accepts ERC721 tokens, you'll want to implement this interface.
- [`ERC721Mintable`](api/token/ERC721#erc721mintable) — like the ERC20 version, `ERC721Mintable` allows addresses with the `Minter` role to mint tokens.
- [`ERC721Pausable`](api/token/ERC721#erc721pausable) — like the ERC20 version, `ERC721Pausable` allows addresses with the `Pauser` role to freeze transfers of tokens.
This enables a lot of interesting use cases, including atomic purchases using tokens (no need to do `approve` and `transferFrom` in two separate transactions), rejecting reception of tokens (by reverting on the hook call), redirecting the received tokens to other addresses (similarly to how [`PaymentSplitter`](api/payment#paymentsplitter) does it), among many others.
Furthermore, since contracts are required to implement these hooks in order to receive tokens, _no tokens can get stuck in a contract that is unaware of the ERC777 protocol_, as has happened countless times when using ERC20s.
We'll use these contracts to tokenize the time of our dogsitters: when a dogsitter wants to sell an hour of their time to watch a dog, they can mint an ERC721 token that represents that hour slot and then sell this token on an exchange. Then they'll go to the owner's house at the right time to watch their doggos.
### What if I already use ERC20?
The standard has you covered! The ERC777 standard is **backwards compatible with ERC20**, meaning you can interact with these tokens as if they were ERC20, using the standard functions, while still getting all of the niceties, including send hooks. See the [EIP's Backwards Compatibility section](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility) to learn more.
Here's what tokenized dogsitter timeframes might look like:
### Constructing an ERC777 Token Contract
We will replicate the `GLD` example of the [ERC20 guide](#constructing-an-erc20-token-contract), this time using ERC777. As always, check out the [`API reference`](api/token/ERC777) to learn more about the details of each function.
```solidity
contract DoggoTime is ERC721Full {
using Counters for Counters.Counter;
Counters.Counter private tokenId;
pragma solidity ^0.5.0;
constructor(
string memory name,
string memory symbol
)
ERC721Full(name, symbol)
public
{}
import "openzeppelin-solidity/contracts/token/ERC777/ERC777.sol";
function createDoggoTimeframe(
string memory tokenURI
contract GLDToken is ERC777 {
constructor(
uint256 initialSupply,
address[] memory defaultOperators
)
ERC777("Gold", "GLD", defaultOperators)
public
returns (bool)
{
tokenId.increment();
uint256 doggoTokenId = tokenId.current();
_mint(msg.sender, doggoTokenId);
_setTokenURI(doggoTokenId, tokenURI);
return true;
_mint(msg.sender, msg.sender, initialSupply, "", "");
}
}```
Now anyone who wants to sell their time in exchange for DOGGO tokens can call:
In this case, we'll be extending from the [`ERC777`](api/token/ERC777#erc777) contract, which provides an implementation with compatibility support for ERC20. The API is quite similar to that of [`ERC777`](api/token/ERC777#erc777), and we'll once again make use of [`_mint`](api/token/ERC777#ERC777._mint(address,address,uint256,bytes,bytes)) to assign the `initialSupply` to the deployer account. Unlike [ERC20's `_mint`](api/token/ERC20#ERC20._mint(address,uint256)), this one includes some extra parameters, but you can safely ignore those for now.
```solidity
DoggoTime(doggoTimeAddress).createDoggoTimeframe("https://example.com/doggo.json")
You'll notice both [`name`](api/token/ERC777#IERC777.name()) and [`symbol`](api/token/ERC777#IERC777.symbol()) are assigned, but not [`decimals`](api/token/ERC777#ERC777.decimals()). The ERC777 specification makes it mandatory to include support for these functions (unlike ERC20, where it is optional and we had to include [`ERC20Detailed`](api/token/ERC20#erc20detailed)), but also mandates that `decimals` always returns a fixed value of `18`, so there's no need to set it ourselves. For a review of `decimals`'s role and importance, refer back to our [ERC20 guide](tokens#a-note-on-decimals).
Finally, we'll need to set the [`defaultOperators`](api/token/ERC777#IERC777.defaultOperators()): special accounts (usually other smart contracts) that will be able to transfer tokens on behalf of their holders. If you're not planning on using operators in your token, you can simply pass an empty array. _Stay tuned for an upcoming in-depth guide on ERC777 operators!_
That's it for a basic token contract! We can now deploy it, and use the same [`balanceOf`](api/token/ERC777#IERC777.balanceOf(address)) method to query the deployer's balance:
```javascript
> GLDToken.balanceOf(deployerAddress)
1000
```
where the tokenURI should resolve to a json document that might look something like:
To move tokens from one account to another, we can use both [`ERC20`'s `transfer`](api/token/ERC777#ERC777.transfer(address,uint256)) method, or the new [`ERC777`'s `send`](api/token/ERC777#ERC777.send(address,uint256,bytes)), which fulfills a very similar role, but adds an optional `data` field:
```json
{
"name": "Alex's DOGGO Dogsitting Time — 1 Hour on Thursday the 5th at 6pm",
"description": "Alex agrees to dog sit for 1 hour of her time on Thursday the 5th at 6pm.",
"image": "https://example.com/doggo-network.png"
}
```javascript
> GLDToken.transfer(otherAddress, 300)
> GLDToken.send(otherAddress, 300, "")
> GLDToken.balanceOf(otherAddress)
600
> GLDToken.balanceOf(deployerAddress)
400
```
### Contract recipients
A key difference when using [`send`](api/token/ERC777#ERC777.send(address,uint256,bytes)) is that token transfers to other contracts may revert with the following message:
```text
ERC777: token recipient contract has no implementer for ERC777TokensRecipient
```
For more information about tokenURI metadata, check out the [finalized ERC721 spec](https://eips.ethereum.org/EIPS/eip-721).
This is a good thing! It means that the recipient contract has not registered itself as aware of the ERC777 protocol, so transfers to it are disabled to **prevent tokens from being locked forever**. As an example, [the Golem contract currently holds over 350k `GNT` tokens](https://etherscan.io/token/0xa74476443119A942dE498590Fe1f2454d7D4aC0d?a=0xa74476443119A942dE498590Fe1f2454d7D4aC0d), worth multiple tens of thousands of dollars, and lacks methods to get them out of there. This has happened to virtually every ERC20-backed project, usually due to user error.
_Note: you'll also notice that the date information is included in the metadata, but that information isn't on-chain! So Alex the dogsitter could change the time and scam some people out of their money! If you'd like to put the dates of the dogsitting hours on-chain, you can extend ERC721 to do so. You could also leverage IPFS to pin the tokenURI information, which lets viewers know if Alex has changed the metadata associated with her tokens, but these techniques are out of the scope of this overview guide._
_An upcoming guide will cover how a contract can register itself as a recipient, send and receive hooks, and other advanced features of ERC777!_

Loading…
Cancel
Save