migrate content to format for new docs site
Squashed commit of the following:
commit fcf35eb806100de300bd9803ce3150dde1ecc424
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 17 17:16:04 2019 -0300
remove all docsite dependency
commit eeaee9a9d43d70704f6ab17b5126ddbd52b93a50
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 17 17:15:23 2019 -0300
update solidity-docgen
commit f021ff951829ea0c155186749819403c6b76e803
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 17 17:05:06 2019 -0300
update docsite script for new setup
commit ff887699d381cfbbe3acf1f1c0de8e22b58480f3
Merge: c938aa1d 84f85a41
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 17 16:46:46 2019 -0300
Merge branch 'master' into antora
commit c938aa1d9ed05ac83a34e2cebd8353f8331ad6d6
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jul 16 18:24:29 2019 -0300
make component name shorter
commit 5bbd6931e02cbbd8864c82655ad0f390ceead5f3
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 20:16:17 2019 -0300
add all info to docs templates
commit 39682c4515d7cf0f0368ed557f50d2709174208a
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 20:13:49 2019 -0300
fix npm docsite script
commit 7ae46bd4a0437abf66150d54d05adf46e3de2cab
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 18:48:05 2019 -0300
convert inline docs to asciidoc
commit cfdfd3dee4b4bf582fde22c8cb6e17a603d6e0c8
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 17:34:52 2019 -0300
add missing contract names in readmes
commit 15b6a2f9bfb546cf1d3bf4f104278b118bf1b3f4
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 17:16:47 2019 -0300
fix script path
commit 80d82b909f9460d1450d401f00b3f309da506b29
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 17:13:53 2019 -0300
update version of solidity-docgen
commit a870b6c607b9c2d0012f8a60a4ed1a1c8b7e8ebd
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 17:03:53 2019 -0300
add nav generation of api ref
commit 069cff4a25b83752650b54b86d85608c2f547e5e
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Wed Jul 10 16:32:14 2019 -0300
initial migration to asciidoc and new docgen version
commit 55216eed0a6551da913c8d1da4b2a0d0d3faa1a8
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 20:39:35 2019 -0300
add basic api doc example
commit 0cbe50ce2173b6d1d9a698329d91220f58822a53
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 19:31:31 2019 -0300
add sidebars
commit 256fc942845307258ac9dc25aace48117fa10f79
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 15:22:38 2019 -0300
add page titles
commit f4d0effa70e1fc0662729863e8ee72a8821bc458
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 15:19:41 2019 -0300
add contracts index file
commit b73b06359979f7d933df7f2b283c50cb1c31b2a0
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 15:14:52 2019 -0300
fix header levels
commit fb57d9b820f09a1b7c04eed1a205be0e45866cac
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 15:11:47 2019 -0300
switch format to preferred asciidoctor format
commit 032181d8804137332c71534753929d080a31a71f
Author: Francisco Giordano <frangio.1@gmail.com>
Date: Tue Jun 25 15:05:38 2019 -0300
initialize antora component and convert docs to asciidoc
This commit is contained in:
15
docs/modules/ROOT/nav.adoc
Normal file
15
docs/modules/ROOT/nav.adoc
Normal file
@ -0,0 +1,15 @@
|
||||
.Overview
|
||||
* xref:index.adoc[Getting Started]
|
||||
|
||||
.Basics
|
||||
* xref:access-control.adoc[Access Control]
|
||||
* xref:tokens.adoc[Tokens]
|
||||
* xref:crowdsales.adoc[Crowdsales]
|
||||
* xref:utilities.adoc[Utilities]
|
||||
|
||||
.In Depth
|
||||
* xref:erc20-supply.adoc[ERC20 Supply]
|
||||
|
||||
.FAQ
|
||||
* xref:api-stability.adoc[API Stability]
|
||||
* xref:release-schedule.adoc[Release Schedule]
|
||||
108
docs/modules/ROOT/pages/access-control.adoc
Normal file
108
docs/modules/ROOT/pages/access-control.adoc
Normal file
@ -0,0 +1,108 @@
|
||||
= 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 https://blog.zeppelin.solutions/on-the-parity-wallet-multisig-hack-405a8c12e8f7[steals your whole system].
|
||||
|
||||
[[ownership-and-ownable]]
|
||||
== Ownership and `Ownable`
|
||||
|
||||
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 link:api/ownership#ownable[`Ownable`] for implementing ownership in your contracts.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
|
||||
|
||||
contract MyContract is Ownable {
|
||||
function normalThing() public {
|
||||
// anyone can call this normalThing()
|
||||
}
|
||||
|
||||
function specialThing() public onlyOwner {
|
||||
// only the owner can call specialThing()!
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
By default, the link:api/ownership#Ownable.owner()[`owner`] of an `Ownable` contract is the account that deployed it, which is usually exactly what you want.
|
||||
|
||||
Ownable also lets you: - link:api/ownership#Ownable.transferOwnership(address)[`transferOwnership`] from the owner account to a new one - link:api/ownership#Ownable.renounceOwnership()[`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!
|
||||
|
||||
Note that *a contract can also be the owner of another one*! This opens the door to using, for example, a https://github.com/gnosis/MultiSigWallet[Gnosis Multisig] or https://safe.gnosis.io[Gnosis Safe], an https://aragon.org[Aragon DAO], an https://www.uport.me[ERC725/uPort] identity contract, or a totally custom contract that _you_ create.
|
||||
|
||||
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 https://makerdao.com[MakerDAO], use systems similar to this one.
|
||||
|
||||
[[role-based-access-control]]
|
||||
== 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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
[[using-roles]]
|
||||
=== Using `Roles`
|
||||
|
||||
OpenZeppelin provides link:api/access#roles[`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 simple example of using `Roles` in an link:tokens#erc20[`ERC20` token]: 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.
|
||||
|
||||
[source,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 ERC20, ERC20Detailed {
|
||||
using Roles for Roles.Role;
|
||||
|
||||
Roles.Role private _minters;
|
||||
Roles.Role private _namers;
|
||||
|
||||
constructor(address[] memory minters, address[] memory namers)
|
||||
DetailedERC20("MyToken", "MTKN", 18)
|
||||
public
|
||||
{
|
||||
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 minters can mint
|
||||
require(minters.has(msg.sender), "DOES_NOT_HAVE_MINTER_ROLE");
|
||||
|
||||
_mint(to, amount);
|
||||
}
|
||||
|
||||
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! 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: link:api/token/ERC20#erc20mintable[`ERC20Mintable`] which uses the link:api/access#minterrole[`MinterRole`] to determine who can mint tokens, and link:api/crowdsale#whitelistcrowdsale[`WhitelistCrowdsale`] which uses both link:api/access#whitelistadminrole[`WhitelistAdminRole`] and link:api/access#whitelistedrole[`WhitelistedRole`] to create a set of accounts that can purchase tokens.
|
||||
|
||||
This flexibility allows for interesting setups: for example, a link:api/crowdsale#mintedcrowdsale[`MintedCrowdsale`] expects to be given the `MinterRole` of an `ERC20Mintable` in order to work, but the token contract could also extend link:api/token/ERC20#erc20pausable[`ERC20Pausable`] and assign the link:api/access#pauserrole[`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 https://en.wikipedia.org/wiki/Principle_of_least_privilege[principle of least privilege], and is a good security practice.
|
||||
|
||||
[[usage-in-openzeppelin]]
|
||||
== 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, link:api/crowdsale#refundablecrowdsale[`RefundableCrowdsale`] deploys a link:api/payment#refundescrow[`RefundEscrow`] on construction, to hold its funds. For those cases, we'll use link:api/ownership#secondary[`Secondary`] to create a _secondary_ contract that allows a _primary_ contract to manage it. You could also think of these as _auxiliary_ contracts.
|
||||
55
docs/modules/ROOT/pages/api-stability.adoc
Normal file
55
docs/modules/ROOT/pages/api-stability.adoc
Normal file
@ -0,0 +1,55 @@
|
||||
= API Stability
|
||||
|
||||
On the https://github.com/OpenZeppelin/openzeppelin-solidity/releases/tag/v2.0.0[OpenZeppelin 2.0 release], 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]]
|
||||
== Versioning scheme
|
||||
|
||||
We follow https://semver.org/[SemVer], which means API breakage may occur between major releases. Read more about the link:release-schedule[release schedule] to know how often this happens (not very).
|
||||
|
||||
[[solidity-functions]]
|
||||
== 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. https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1512[an `internal` method may be added to make it easier to retrieve information that was already available]).
|
||||
|
||||
[[internal]]
|
||||
=== `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]]
|
||||
== 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 https://github.com/ethereum/solidity/issues/4637[open issue] 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]]
|
||||
== 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. https://github.com/OpenZeppelin/openzeppelin-solidity/issues/707[from 2.1 on, `ERC20` also emits `Approval` on `transferFrom` calls]).
|
||||
|
||||
[[gas-costs]]
|
||||
== 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]]
|
||||
== 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. https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543[#1543] and https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550[#1550]).
|
||||
|
||||
[[solidity-compiler-version]]
|
||||
== 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 https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1498#issuecomment-449191611[here].
|
||||
244
docs/modules/ROOT/pages/crowdsales.adoc
Normal file
244
docs/modules/ROOT/pages/crowdsales.adoc
Normal file
@ -0,0 +1,244 @@
|
||||
= Crowdsales
|
||||
|
||||
Crowdsales are a popular use for Ethereum; they let you allocate tokens to network participants in various ways, mostly in exchange for Ether. They come in a variety of shapes and flavors, so let's go over the various types available in OpenZeppelin and how to use them.
|
||||
|
||||
Crowdsales have a bunch of different properties, but here are some important ones: - Price & Rate Configuration - Does your crowdsale sell tokens at a fixed price? - Does the price change over time or as a function of demand? - Emission - How is this token actually sent to participants? - Validation — Who is allowed to purchase tokens? - Are there KYC / AML checks? - Is there a max cap on tokens? - What if that cap is per-participant? - Is there a starting and ending time frame? - Distribution - Does distribution of funds happen in real-time or after the crowdsale? - Can participants receive a refund if the goal is not met?
|
||||
|
||||
To manage all of the different combinations and flavors of crowdsales, OpenZeppelin provides a highly configurable link:api/crowdsale#crowdsale[`Crowdsale`] base contract that can be combined with various other functionalities to construct a bespoke crowdsale.
|
||||
|
||||
[[crowdsale-rate]]
|
||||
== Crowdsale Rate
|
||||
|
||||
Understanding the rate of a crowdsale is super important, and mistakes here are a common source of bugs.
|
||||
|
||||
✨ *HOLD UP FAM THIS IS IMPORTANT* ✨
|
||||
|
||||
Firstly, *all currency math is done in the smallest unit of that currency and converted to the correct decimal places when _displaying_ the currency*.
|
||||
|
||||
This means that when you do math in your smart contracts, you need to understand that you're adding, dividing, and multiplying the smallest amount of a currency (like wei), _not_ the commonly-used displayed value of the currency (Ether).
|
||||
|
||||
In Ether, the smallest unit of the currency is wei, and `1 ETH === 10^18 wei`. In tokens, the process is _very similar_: `1 TKN === 10^(decimals) TKNbits`.
|
||||
|
||||
* The smallest unit of a token is "bits" or `TKNbits`.
|
||||
* The display value of a token is `TKN`, which is `TKNbits * 10^(decimals)`
|
||||
|
||||
What people usually call "one token" is actually a bunch of TKNbits, displayed to look like `1 TKN`. This is the same relationship that Ether and wei have. And what you're _always_ doing calculations in is *TKNbits and wei*.
|
||||
|
||||
So, if you want to issue someone "one token for every 2 wei" and your decimals are 18, your rate is `0.5e18`. Then, when I send you `2 wei`, your crowdsale issues me `2 * 0.5e18 TKNbits`, which is exactly equal to `10^18 TKNbits` and is displayed as `1 TKN`.
|
||||
|
||||
If you want to issue someone "`1 TKN` for every `1 ETH`", and your decimals are 18, your rate is `1`. This is because what's actually happening with the math is that the contract sees a user send `10^18 wei`, not `1 ETH`. Then it uses your rate of 1 to calculate `TKNbits = rate * wei`, or `1 * 10^18`, which is still `10^18`. And because your decimals are 18, this is displayed as `1 TKN`.
|
||||
|
||||
One more for practice: if I want to issue "1 TKN for every dollar (USD) in Ether", we would calculate it as follows:
|
||||
|
||||
* assume 1 ETH == $400
|
||||
* therefore, 10^18 wei = $400
|
||||
* therefore, 1 USD is `10^18 / 400`, or `2.5 * 10^15 wei`
|
||||
* we have a decimals of 18, so we'll use `10 ^ 18 TKNbits` instead of `1 TKN`
|
||||
* therefore, if the participant sends the crowdsale `2.5 * 10^15 wei` we should give them `10 ^ 18 TKNbits`
|
||||
* therefore the rate is `2.5 * 10^15 wei === 10^18 TKNbits`, or `1 wei = 400 TKNbits`
|
||||
* therefore, our rate is `400`
|
||||
|
||||
(this process is pretty straightforward when you keep 18 decimals, the same as Ether/wei)
|
||||
|
||||
[[token-emission]]
|
||||
== Token Emission
|
||||
|
||||
One of the first decisions you have to make is "how do I get these tokens to users?". This is usually done in one of three ways:
|
||||
|
||||
* (default) — The `Crowdsale` contract owns tokens and simply transfers tokens from its own ownership to users that purchase them.
|
||||
* link:api/crowdsale#mintedcrowdsale[`MintedCrowdsale`] — The `Crowdsale` mints tokens when a purchase is made.
|
||||
* link:api/crowdsale#allowancecrowdsale[`AllowanceCrowdsale`] — The `Crowdsale` is granted an allowance to another wallet (like a Multisig) that already owns the tokens to be sold in the crowdsale.
|
||||
|
||||
[[default-emission]]
|
||||
=== Default Emission
|
||||
|
||||
In the default scenario, your crowdsale must own the tokens that are sold. You can send the crowdsale tokens through a variety of methods, but here's what it looks like in Solidity:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
IERC20(tokenAddress).transfer(CROWDSALE_ADDRESS, SOME_TOKEN_AMOUNT);
|
||||
----
|
||||
|
||||
Then when you deploy your crowdsale, simply tell it about the token
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
new Crowdsale(
|
||||
1, // rate in TKNbits
|
||||
MY_WALLET, // address where Ether is sent
|
||||
TOKEN_ADDRESS // the token contract address
|
||||
);
|
||||
----
|
||||
|
||||
[[minted-crowdsale]]
|
||||
=== Minted Crowdsale
|
||||
|
||||
To use a link:api/crowdsale#mintedcrowdsale[`MintedCrowdsale`], your token must also be a link:api/token/ERC20#erc20mintable[`ERC20Mintable`] token that the crowdsale has permission to mint from. This can look like:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyToken is ERC20, ERC20Mintable {
|
||||
// ... see "Tokens" for more info
|
||||
}
|
||||
|
||||
contract MyCrowdsale is Crowdsale, MintedCrowdsale {
|
||||
constructor(
|
||||
uint256 rate, // rate in TKNbits
|
||||
address payable wallet,
|
||||
IERC20 token
|
||||
)
|
||||
MintedCrowdsale()
|
||||
Crowdsale(rate, wallet, token)
|
||||
public
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
contract MyCrowdsaleDeployer {
|
||||
constructor()
|
||||
public
|
||||
{
|
||||
// create a mintable token
|
||||
ERC20Mintable token = new MyToken();
|
||||
|
||||
// create the crowdsale and tell it about the token
|
||||
Crowdsale crowdsale = new MyCrowdsale(
|
||||
1, // rate, still in TKNbits
|
||||
msg.sender, // send Ether to the deployer
|
||||
address(token) // the token
|
||||
);
|
||||
// transfer the minter role from this contract (the default)
|
||||
// to the crowdsale, so it can mint tokens
|
||||
token.addMinter(address(crowdsale));
|
||||
token.renounceMinter();
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
[[allowancecrowdsale]]
|
||||
=== AllowanceCrowdsale
|
||||
|
||||
Use an link:api/crowdsale#allowancecrowdsale[`AllowanceCrowdsale`] to send tokens from another wallet to the participants of the crowdsale. In order for this to work, the source wallet must give the crowdsale an allowance via the ERC20 link:api/token/ERC20#IERC20.approve(address,uint256)[`approve`] method.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyCrowdsale is Crowdsale, AllowanceCrowdsale {
|
||||
constructor(
|
||||
uint256 rate,
|
||||
address payable wallet,
|
||||
IERC20 token,
|
||||
address tokenWallet // <- new argument
|
||||
)
|
||||
AllowanceCrowdsale(tokenWallet) // <- used here
|
||||
Crowdsale(rate, wallet, token)
|
||||
public
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
Then after the crowdsale is created, don't forget to approve it to use your tokens!
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
IERC20(tokenAddress).approve(CROWDSALE_ADDRESS, SOME_TOKEN_AMOUNT);
|
||||
----
|
||||
|
||||
[[validation]]
|
||||
== Validation
|
||||
|
||||
There are a bunch of different validation requirements that your crowdsale might be a part of:
|
||||
|
||||
* link:api/crowdsale#cappedcrowdsale[`CappedCrowdsale`] — adds a cap to your crowdsale, invalidating any purchases that would exceed that cap
|
||||
* link:api/crowdsale#individuallycappedcrowdsale[`IndividuallyCappedCrowdsale`] — caps an individual's contributions.
|
||||
* link:api/crowdsale#whitelistcrowdsale[`WhitelistCrowdsale`] — only allow whitelisted participants to purchase tokens. this is useful for putting your KYC / AML whitelist on-chain!
|
||||
* link:api/crowdsale#timedcrowdsale[`TimedCrowdsale`] — adds an link:api/crowdsale#TimedCrowdsale.openingTime()[`openingTime`] and link:api/crowdsale#TimedCrowdsale.closingTime()[`closingTime`] to your crowdsale
|
||||
|
||||
Simply mix and match these crowdsale flavors to your heart's content:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyCrowdsale is Crowdsale, CappedCrowdsale, TimedCrowdsale {
|
||||
|
||||
constructor(
|
||||
uint256 rate, // rate, in TKNbits
|
||||
address payable wallet, // wallet to send Ether
|
||||
IERC20 token, // the token
|
||||
uint256 cap, // total cap, in wei
|
||||
uint256 openingTime, // opening time in unix epoch seconds
|
||||
uint256 closingTime // closing time in unix epoch seconds
|
||||
)
|
||||
CappedCrowdsale(cap)
|
||||
TimedCrowdsale(openingTime, closingTime)
|
||||
Crowdsale(rate, wallet, token)
|
||||
public
|
||||
{
|
||||
// nice, we just created a crowdsale that's only open
|
||||
// for a certain amount of time
|
||||
// and stops accepting contributions once it reaches `cap`
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
[[distribution]]
|
||||
== Distribution
|
||||
|
||||
There comes a time in every crowdsale's life where it must relinquish the tokens it's been entrusted with. It's your decision as to when that happens!
|
||||
|
||||
The default behavior is to release tokens as participants purchase them, but sometimes that may not be desirable. For example, what if we want to give users a refund if we don't hit a minimum raised in the sale? Or, maybe we want to wait until after the sale is over before users can claim their tokens and start trading them, perhaps for compliance reasons?
|
||||
|
||||
OpenZeppelin is here to make that easy!
|
||||
|
||||
[[postdeliverycrowdsale]]
|
||||
=== PostDeliveryCrowdsale
|
||||
|
||||
The link:api/crowdsale#postdeliverycrowdsale[`PostDeliveryCrowdsale`], as its name implies, distributes tokens after the crowdsale has finished, letting users call link:api/crowdsale#PostDeliveryCrowdsale.withdrawTokens(address)[`withdrawTokens`] in order to claim the tokens they've purchased.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyCrowdsale is Crowdsale, TimedCrowdsale, PostDeliveryCrowdsale {
|
||||
|
||||
constructor(
|
||||
uint256 rate, // rate, in TKNbits
|
||||
address payable wallet, // wallet to send Ether
|
||||
IERC20 token, // the token
|
||||
uint256 openingTime, // opening time in unix epoch seconds
|
||||
uint256 closingTime // closing time in unix epoch seconds
|
||||
)
|
||||
PostDeliveryCrowdsale()
|
||||
TimedCrowdsale(openingTime, closingTime)
|
||||
Crowdsale(rate, wallet, token)
|
||||
public
|
||||
{
|
||||
// nice! this Crowdsale will keep all of the tokens until the end of the crowdsale
|
||||
// and then users can `withdrawTokens()` to get the tokens they're owed
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
[[refundablecrowdsale]]
|
||||
=== RefundableCrowdsale
|
||||
|
||||
The link:api/crowdsale#refundablecrowdsale[`RefundableCrowdsale`] offers to refund users if a minimum goal is not reached. If the goal is not reached, the users can link:api/crowdsale#RefundableCrowdsale.claimRefund(address%20payable)[`claimRefund`] to get their Ether back.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyCrowdsale is Crowdsale, RefundableCrowdsale {
|
||||
|
||||
constructor(
|
||||
uint256 rate, // rate, in TKNbits
|
||||
address payable wallet, // wallet to send Ether
|
||||
IERC20 token, // the token
|
||||
uint256 goal // the minimum goal, in wei
|
||||
)
|
||||
RefundableCrowdsale(goal)
|
||||
Crowdsale(rate, wallet, token)
|
||||
public
|
||||
{
|
||||
// nice! this crowdsale will, if it doesn't hit `goal`, allow everyone to get their money back
|
||||
// by calling claimRefund(...)
|
||||
}
|
||||
}
|
||||
----
|
||||
109
docs/modules/ROOT/pages/erc20-supply.adoc
Normal file
109
docs/modules/ROOT/pages/erc20-supply.adoc
Normal file
@ -0,0 +1,109 @@
|
||||
= 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 https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.1.2/contracts/token/ERC20/ERC20.sol[`ERC20`] 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]]
|
||||
== 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.
|
||||
|
||||
[source,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.
|
||||
|
||||
[source,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]]
|
||||
== 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!
|
||||
|
||||
[source,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]]
|
||||
== Modularizing the mechanism
|
||||
|
||||
There is one supply mechanism already included in OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.1.2/contracts/token/ERC20/ERC20Mintable.sol[`ERC20Mintable`]. 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 https://medium.com/reserve-currency/why-another-stablecoin-866f774afede#3aea[traditional asset-backed stablecoins].
|
||||
|
||||
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.
|
||||
|
||||
[source,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]]
|
||||
== 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.
|
||||
|
||||
[source,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]]
|
||||
== 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.
|
||||
70
docs/modules/ROOT/pages/index.adoc
Normal file
70
docs/modules/ROOT/pages/index.adoc
Normal file
@ -0,0 +1,70 @@
|
||||
= Getting 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]]
|
||||
== Install
|
||||
|
||||
OpenZeppelin should be installed directly into your existing node.js project with `npm install openzeppelin-solidity`. We will use https://truffleframework.com/truffle[Truffle], an Ethereum development environment, to get started.
|
||||
|
||||
Please install Truffle and initialize your project:
|
||||
|
||||
[source,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:
|
||||
|
||||
[source,sh]
|
||||
----
|
||||
$ npm install openzeppelin-solidity
|
||||
----
|
||||
|
||||
_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 link:api-stability[API Stability] document._
|
||||
|
||||
[[usage]]
|
||||
== Usage
|
||||
|
||||
Once installed, you can start using the contracts in the library by importing them:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
|
||||
|
||||
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
|
||||
|
||||
Check out the the guides in the sidebar to learn about different concepts, and how to use the contracts that OpenZeppelin provides.
|
||||
|
||||
* link:access-control[Learn about Access Control]
|
||||
* link:crowdsales[Learn about Crowdsales]
|
||||
* link:tokens[Learn about Tokens]
|
||||
* link:utilities[Learn about our Utilities]
|
||||
|
||||
OpenZeppelin's link:api/token/ERC20[full API] is also thoroughly documented, and serves as a great reference when developing your smart contract application.
|
||||
|
||||
Additionally, you can also ask for help or follow OpenZeppelin's development in the https://forum.zeppelin.solutions[community forum].
|
||||
|
||||
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.
|
||||
|
||||
* https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05[The Hitchhiker’s Guide to Smart Contracts in Ethereum] will help you get an overview of the various tools available for smart contract development, and help you set up your environment
|
||||
* https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094[A Gentle Introduction to Ethereum Programming, Part 1] provides very useful information on an introductory level, including many basic concepts from the Ethereum platform
|
||||
* For a more in-depth dive, you may read the guide https://blog.zeppelin.solutions/designing-the-architecture-for-your-ethereum-application-9cec086f8317[Designing the architecture for your Ethereum application], which discusses how to better structure your application and its relationship to the real world
|
||||
17
docs/modules/ROOT/pages/release-schedule.adoc
Normal file
17
docs/modules/ROOT/pages/release-schedule.adoc
Normal file
@ -0,0 +1,17 @@
|
||||
= Release Schedule
|
||||
|
||||
OpenZeppelin follows a link:api-stability[semantic versioning scheme].
|
||||
|
||||
[[minor-releases]]
|
||||
== 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 https://github.com/OpenZeppelin/openzeppelin-solidity/milestones[a milestone on GitHub]. 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]]
|
||||
== 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. https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1146[roles] 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.
|
||||
247
docs/modules/ROOT/pages/tokens.adoc
Normal file
247
docs/modules/ROOT/pages/tokens.adoc
Normal file
@ -0,0 +1,247 @@
|
||||
= Tokens
|
||||
|
||||
Ah, the "token": the world's most powerful and most misunderstood tool.
|
||||
|
||||
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.
|
||||
|
||||
== But First, [line-through]*Coffee* a Primer on Token Contracts
|
||||
|
||||
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 https://en.wikipedia.org/wiki/Fungibility[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>> or <<ERC721>> token standards, and that's why you're here.
|
||||
|
||||
[[ERC20]]
|
||||
== ERC20
|
||||
|
||||
An ERC20 token contract keeps track of link:#different-kinds-of-tokens[_fungible_ 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 many ERC20-related contracts. On the xref:api:token/ERC20.adoc[`API reference`] you'll find detailed information on their properties and usage.
|
||||
|
||||
=== 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.
|
||||
|
||||
Here's what our GLD token might look like.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
|
||||
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
|
||||
|
||||
contract GLDToken is ERC20, ERC20Detailed {
|
||||
constructor(uint256 initialSupply) ERC20Detailed("Gold", "GLD", 18) public {
|
||||
_mint(msg.sender, initialSupply);
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
OpenZeppelin contracts are often used via https://solidity.readthedocs.io/en/latest/contracts.html#inheritance[inheritance], and here we're reusing xref:api:token/ERC20.adoc#erc20[`ERC20`] for the basic standard implementation and xref:api:token/ERC20.adoc#ERC20Detailed[`ERC20Detailed`] to get the xref:api:token/ERC20.adoc#ERC20Detailed-name[`name`], xref:api:token/ERC20.adoc#ERC20Detailed-symbol[`symbol`], and xref:api:token/ERC20.adoc#ERC20Detailed-decimals[`decimals`] properties. Additionally, we're creating an `initialSupply` of tokens, which will be assigned to the address that deploys the contract.
|
||||
|
||||
TIP: For a more complete discussion of ERC20 supply mechanisms, see xref:erc20-supply.adoc[our advanced guide].
|
||||
|
||||
That's it! Once deployed, we will be able to query the deployer's balance:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> GLDToken.balanceOf(deployerAddress)
|
||||
1000
|
||||
----
|
||||
|
||||
We can also xref:api:token/ERC20.adoc#IERC20-transfer-address-uint256[transfer] these tokens to other accounts:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> GLDToken.transfer(otherAddress, 300)
|
||||
> GLDToken.balanceOf(otherAddress)
|
||||
300
|
||||
> GLDToken.balanceOf(deployerAddress)
|
||||
700
|
||||
----
|
||||
|
||||
=== A note on `decimals`
|
||||
|
||||
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`.
|
||||
|
||||
To work around this, xref:api:token/ERC20.adoc#erc20detailed[`ERC20Detailed`] provides a xref:api:token/ERC20.adoc#ERC20Detailed.decimals()[`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]]
|
||||
== ERC721
|
||||
|
||||
We've discussed how you can make a _fungible_ token using link:#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 link:#different-kinds-of-tokens[_non-fungible_ 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 xref:api:token/ERC721.adoc[`API reference`] 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:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
The xref:api:token/ERC721.adoc#erc721full[`ERC721Full`] contract includes all standard extensions, and is probably the one you want to use. In particular, it includes xref:api:token/ERC721.adoc#erc721metadata[`ERC721Metadata`], which provides the xref:api:token/ERC721.adoc#ERC721Metadata._setTokenURI(uint256,string)[`_setTokenURI`] method we use to store an item's metadata.
|
||||
|
||||
Also note that, unlike ERC20, ERC721 lacks a `decimals` field, since each token is distinct and cannot be partitioned.
|
||||
|
||||
New items can be created:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> gameItem.awardItem(playerAddress, "https://game.example/item-id-8u5h2m.json")
|
||||
7
|
||||
----
|
||||
|
||||
And the owner and metadata of each item queried:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> gameItem.ownerOf(7)
|
||||
playerAddress
|
||||
> gameItem.tokenURI(7)
|
||||
"https://game.example/item-id-8u5h2m.json"
|
||||
----
|
||||
|
||||
This `tokenURI` should resolve to a JSON document that might look something like:
|
||||
|
||||
[source,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 https://eips.ethereum.org/EIPS/eip-721[ERC721 specification].
|
||||
|
||||
_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
|
||||
|
||||
link:#erc20[ERC20] and link:#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.
|
||||
|
||||
[[ERC777]]
|
||||
== ERC777
|
||||
|
||||
Like ERC20, ERC777 is a standard for link:#different-kinds-of-tokens[_fungible_ 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.
|
||||
|
||||
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*.
|
||||
|
||||
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 xref:api:payment#paymentsplitter[`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.
|
||||
|
||||
=== 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 https://eips.ethereum.org/EIPS/eip-777#backward-compatibility[EIP's Backwards Compatibility section] to learn more.
|
||||
|
||||
=== Constructing an ERC777 Token Contract
|
||||
|
||||
We will replicate the `GLD` example of the link:#constructing-an-erc20-token-contract[ERC20 guide], this time using ERC777. As always, check out the xref:api:token/ERC777.adoc[`API reference`] to learn more about the details of each function.
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
pragma solidity ^0.5.0;
|
||||
|
||||
import "openzeppelin-solidity/contracts/token/ERC777/ERC777.sol";
|
||||
|
||||
contract GLDToken is ERC777 {
|
||||
constructor(
|
||||
uint256 initialSupply,
|
||||
address[] memory defaultOperators
|
||||
)
|
||||
ERC777("Gold", "GLD", defaultOperators)
|
||||
public
|
||||
{
|
||||
_mint(msg.sender, msg.sender, initialSupply, "", "");
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
In this case, we'll be extending from the xref:api:token/ERC777.adoc#erc777[`ERC777`] contract, which provides an implementation with compatibility support for ERC20. The API is quite similar to that of xref:api:token/ERC777.adoc#erc777[`ERC777`], and we'll once again make use of xref:api:token/ERC777.adoc#ERC777._mint(address,address,uint256,bytes,bytes)[`_mint`] to assign the `initialSupply` to the deployer account. Unlike xref:api:token/ERC20.adoc#ERC20._mint(address,uint256)[ERC20's `_mint`], this one includes some extra parameters, but you can safely ignore those for now.
|
||||
|
||||
You'll notice both xref:api:token/ERC777.adoc#IERC777.name()[`name`] and xref:api:token/ERC777.adoc#IERC777.symbol()[`symbol`] are assigned, but not xref:api:token/ERC777.adoc#ERC777.decimals()[`decimals`]. The ERC777 specification makes it mandatory to include support for these functions (unlike ERC20, where it is optional and we had to include xref:api:token/ERC20.adoc#erc20detailed[`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 link:tokens#a-note-on-decimals[ERC20 guide].
|
||||
|
||||
Finally, we'll need to set the xref:api:token/ERC777.adoc#IERC777.defaultOperators()[`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 xref:api:token/ERC777.adoc#IERC777.balanceOf(address)[`balanceOf`] method to query the deployer's balance:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> GLDToken.balanceOf(deployerAddress)
|
||||
1000
|
||||
----
|
||||
|
||||
To move tokens from one account to another, we can use both xref:api:token/ERC777.adoc#ERC777.transfer(address,uint256)[`ERC20`'s `transfer`] method, or the new xref:api:token/ERC777.adoc#ERC777.send(address,uint256,bytes)[`ERC777`'s `send`], which fulfills a very similar role, but adds an optional `data` field:
|
||||
|
||||
[source,javascript]
|
||||
----
|
||||
> GLDToken.transfer(otherAddress, 300)
|
||||
> GLDToken.send(otherAddress, 300, "")
|
||||
> GLDToken.balanceOf(otherAddress)
|
||||
600
|
||||
> GLDToken.balanceOf(deployerAddress)
|
||||
400
|
||||
----
|
||||
|
||||
=== Contract recipients
|
||||
|
||||
A key difference when using xref:api:token/ERC777.adoc#ERC777.send(address,uint256,bytes)[`send`] is that token transfers to other contracts may revert with the following message:
|
||||
|
||||
[source,text]
|
||||
----
|
||||
ERC777: token recipient contract has no implementer for ERC777TokensRecipient
|
||||
----
|
||||
|
||||
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, https://etherscan.io/token/0xa74476443119A942dE498590Fe1f2454d7D4aC0d?a=0xa74476443119A942dE498590Fe1f2454d7D4aC0d[the Golem contract currently holds over 350k `GNT` tokens], 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.
|
||||
|
||||
_An upcoming guide will cover how a contract can register itself as a recipient, send and receive hooks, and other advanced features of ERC777!_
|
||||
95
docs/modules/ROOT/pages/utilities.adoc
Normal file
95
docs/modules/ROOT/pages/utilities.adoc
Normal file
@ -0,0 +1,95 @@
|
||||
= Utilities
|
||||
|
||||
OpenZeppelin provides a ton of useful utilities that you can use in your project. Here are some of the more popular ones:
|
||||
|
||||
[[cryptography]]
|
||||
== Cryptography
|
||||
|
||||
* link:api/cryptography#ecdsa[`ECDSA`] — provides functions for recovering and managing Ethereum account ECDSA signatures:
|
||||
* to use it, declare: `using ECDSA for bytes32;`
|
||||
* signatures are tightly packed, 65 byte `bytes` that look like `{v (1)} {r (32)} {s (32)}`
|
||||
** this is the default from `web3.eth.sign` so you probably don't need to worry about this format
|
||||
* recover the signer using link:api/cryptography#ECDSA.recover(bytes32,bytes)[`myDataHash.recover(signature)`]
|
||||
* if you are using `eth_personalSign`, the signer will hash your data and then add the prefix `\x19Ethereum Signed Message:\n`, so if you're attempting to recover the signer of an Ethereum signed message hash, you'll want to use link:api/cryptography#ECDSA.toEthSignedMessageHash(bytes32)[`toEthSignedMessageHash`]
|
||||
|
||||
Use these functions in combination to verify that a user has signed some information on-chain:
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
keccack256(
|
||||
abi.encodePacked(
|
||||
someData,
|
||||
moreData
|
||||
)
|
||||
)
|
||||
.toEthSignedMessageHash()
|
||||
.recover(signature)
|
||||
----
|
||||
|
||||
* link:api/cryptography#merkleproof[`MerkleProof`] — provides link:api/cryptography#MerkleProof.verify(bytes32%5B%5D,bytes32,bytes32)[`verify`] for verifying merkle proofs.
|
||||
|
||||
[[introspection]]
|
||||
== Introspection
|
||||
|
||||
In Solidity, it's frequently helpful to know whether or not a contract supports an interface you'd like to use. ERC165 is a standard that helps do runtime interface detection. OpenZeppelin provides some helpers, both for implementing ERC165 in your contracts and querying other contracts:
|
||||
|
||||
* link:api/introspection#ierc165[`IERC165`] — this is the ERC165 interface that defines link:api/introspection#IERC165.supportsInterface(bytes4)[`supportsInterface`]. When implementing ERC165, you'll conform to this interface.
|
||||
* link:api/introspection#erc165[`ERC165`] — inherit this contract if you'd like to support interface detection using a lookup table in contract storage. You can register interfaces using link:api/introspection#ERC165._registerInterface(bytes4)[`_registerInterface(bytes4)`]: check out example usage as part of the ERC721 implementation.
|
||||
* link:api/introspection#erc165checker[`ERC165Checker`] — ERC165Checker simplifies the process of checking whether or not a contract supports an interface you care about.
|
||||
* include with `using ERC165Checker for address;`
|
||||
* link:api/introspection#ERC165Checker._supportsInterface(address,bytes4)[`myAddress._supportsInterface(bytes4)`]
|
||||
* link:api/introspection#ERC165Checker._supportsAllInterfaces(address,bytes4%5B%5D)[`myAddress._supportsAllInterfaces(bytes4[])`]
|
||||
|
||||
[source,solidity]
|
||||
----
|
||||
contract MyContract {
|
||||
using ERC165Checker for address;
|
||||
|
||||
bytes4 private InterfaceId_ERC721 = 0x80ac58cd;
|
||||
|
||||
/**
|
||||
* @dev transfer an ERC721 token from this contract to someone else
|
||||
*/
|
||||
function transferERC721(
|
||||
address token,
|
||||
address to,
|
||||
uint256 tokenId
|
||||
)
|
||||
public
|
||||
{
|
||||
require(token.supportsInterface(InterfaceId_ERC721), "IS_NOT_721_TOKEN");
|
||||
IERC721(token).transferFrom(address(this), to, tokenId);
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
[[math]]
|
||||
== Math
|
||||
|
||||
The most popular math related library OpenZeppelin provides is link:api/math#safemath[`SafeMath`], which provides mathematical functions that protect your contract from overflows and underflows.
|
||||
|
||||
Include the contract with `using SafeMath for uint256;` and then call the functions:
|
||||
|
||||
* `myNumber.add(otherNumber)`
|
||||
* `myNumber.sub(otherNumber)`
|
||||
* `myNumber.div(otherNumber)`
|
||||
* `myNumber.mul(otherNumber)`
|
||||
* `myNumber.mod(otherNumber)`
|
||||
|
||||
Easy!
|
||||
|
||||
[[payment]]
|
||||
== Payment
|
||||
|
||||
Want to split some payments between multiple people? Maybe you have an app that sends 30% of art purchases to the original creator and 70% of the profits to the current owner; you can build that with link:api/payment#paymentsplitter[`PaymentSplitter`]!
|
||||
|
||||
In solidity, there are some security concerns with blindly sending money to accounts, since it allows them to execute arbitrary code. You can read up on these security concerns in the https://consensys.github.io/smart-contract-best-practices/[Ethereum Smart Contract Best Practices] website. One of the ways to fix reentrancy and stalling problems is, instead of immediately sending Ether to accounts that need it, you can use link:api/payment#pullpayment[`PullPayment`], which offers an link:api/payment#PullPayment._asyncTransfer(address,uint256)[`_asyncTransfer`] function for sending money to something and requesting that they link:api/payment#PullPayment.withdrawPayments(address%20payable)[`withdrawPayments()`] it later.
|
||||
|
||||
If you want to Escrow some funds, check out link:api/payment#escrow[`Escrow`] and link:api/payment#conditionalescrow[`ConditionalEscrow`] for governing the release of some escrowed Ether.
|
||||
|
||||
[[misc]]
|
||||
=== Misc
|
||||
|
||||
Want to check if an address is a contract? Use link:api/utils#address[`Address`] and link:api/utils#Address.isContract(address)[`Address.isContract()`].
|
||||
|
||||
Want to keep track of some numbers that increment by 1 every time you want another one? Check out link:api/drafts#counter[`Counter`]. This is especially useful for creating incremental ERC721 `tokenId`s like we did in the last section.
|
||||
Reference in New Issue
Block a user