Commit 7d3ac8e9 by Nicolás Venturo

Merge tag 'v2.5.0'

2.5.0
parents 5b73464d 58a33682
......@@ -6,15 +6,7 @@ version: 2
aliases:
- &defaults
docker:
- image: circleci/node:8
- &npm_install_if_necessary
run:
name: Install npm dependencies
command: |
if [ ! -d node_modules ]; then
npm ci
fi
- image: circleci/node:10
- &cache_key_node_modules
key: v1-node_modules-{{ checksum "package-lock.json" }}
......@@ -26,7 +18,19 @@ jobs:
- checkout
- restore_cache:
<<: *cache_key_node_modules
- *npm_install_if_necessary
- run:
name: Install npm dependencies and prepare
command: |
if [ ! -d node_modules ]; then
npm ci
else
npm run prepare
fi
- persist_to_workspace:
root: .
paths:
- node_modules
- build
- save_cache:
paths:
- node_modules
......@@ -36,9 +40,8 @@ jobs:
<<: *defaults
steps:
- checkout
- restore_cache:
<<: *cache_key_node_modules
- *npm_install_if_necessary
- attach_workspace:
at: .
- run:
name: Linter
command: npm run lint
......@@ -46,20 +49,18 @@ jobs:
<<: *defaults
steps:
- checkout
- restore_cache:
<<: *cache_key_node_modules
- *npm_install_if_necessary
- attach_workspace:
at: .
- run:
name: Unit tests
command: npm run test
coverage:
docker:
- image: circleci/node:8
<<: *defaults
steps:
- checkout
- restore_cache:
<<: *cache_key_node_modules
- *npm_install_if_necessary
- attach_workspace:
at: .
- run:
name: Unit tests with coverage report
command: npm run coverage
......@@ -80,3 +81,4 @@ workflows:
- coverage:
requires:
- dependencies
version: 1
update_configs:
- package_manager: "javascript"
directory: "/"
update_schedule: "weekly"
version_requirement_updates: "increase_versions"
......@@ -25,6 +25,7 @@
"strict": ["error", "global"],
// Code style
"array-bracket-spacing": ["off"],
"camelcase": ["error", {"properties": "always"}],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": ["error", {"before": false, "after": true}],
......@@ -54,5 +55,8 @@
"promise/always-return": "off",
"promise/avoid-new": "off",
},
"parserOptions": {
"ecmaVersion": 2018
}
}
......@@ -10,6 +10,7 @@ daysUntilClose: 15
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
- on hold
- meta
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
......
......@@ -45,8 +45,10 @@ build/
# docs artifacts
docs/modules/api
openzeppelin-docs
# only used to package @openzeppelin/contracts
contracts/build/
contracts/README.md
# temporary artifact from solidity-coverage
allFiredEvents
......@@ -13,8 +13,17 @@
"compiler": {
"manager": "openzeppelin",
"compilerSettings": {
"optimizer": {}
"optimizer": {
"enabled": false,
"runs": "200"
}
},
"solcVersion": "0.5.11"
"solcVersion": "0.5.11",
"artifactsDir": "build/contracts",
"contractsDir": "contracts",
"typechain": {
"enabled": false
}
},
"telemetryOptIn": false
}
module.exports = {
norpc: true,
testCommand: 'node --max-old-space-size=4096 ../node_modules/.bin/truffle test --network coverage',
compileCommand: 'node --max-old-space-size=4096 ../node_modules/.bin/truffle compile --network coverage',
testCommand: 'npm test',
compileCommand: 'npm run compile',
skipFiles: [
'lifecycle/Migrations.sol',
'mocks'
'mocks',
]
}
......@@ -10,7 +10,7 @@ import "./Context.sol";
* @dev Base GSN recipient contract: includes the {IRelayRecipient} interface
* and enables GSN support on all contracts in the inheritance tree.
*
* TIP: This contract is abstract. The functions {acceptRelayedCall},
* TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall},
* {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be
* provided by derived contracts. See the
* xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more
......
......@@ -7,7 +7,7 @@ pragma solidity ^0.5.0;
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
contract IRelayHub {
interface IRelayHub {
// Relay management
/**
......@@ -36,7 +36,7 @@ contract IRelayHub {
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string memory url) public;
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out
......@@ -52,7 +52,7 @@ contract IRelayHub {
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) public;
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
......@@ -65,7 +65,7 @@ contract IRelayHub {
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) public;
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
......@@ -95,7 +95,7 @@ contract IRelayHub {
*
* Emits a {Deposited} event.
*/
function depositFor(address target) public payable;
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
......@@ -113,7 +113,7 @@ contract IRelayHub {
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) public;
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
......@@ -136,14 +136,14 @@ contract IRelayHub {
address relay,
address from,
address to,
bytes memory encodedFunction,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public view returns (uint256 status, bytes memory recipientContext);
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
......@@ -186,14 +186,14 @@ contract IRelayHub {
function relayCall(
address from,
address to,
bytes memory encodedFunction,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
) public;
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
......@@ -229,12 +229,12 @@ contract IRelayHub {
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) public view returns (uint256);
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256);
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
......@@ -247,12 +247,12 @@ contract IRelayHub {
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public;
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
......
......@@ -5,11 +5,11 @@ pragma solidity ^0.5.0;
*
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
*/
contract IRelayRecipient {
interface IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() public view returns (address);
function getHubAddr() external view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
......
......@@ -4,7 +4,7 @@ _Available since v2.4.0._
This set of contracts provide all the tools required to make a contract callable via the https://gsn.openzeppelin.com[Gas Station Network].
TIP: If you're new to the GSN, head over to our xref:openzeppelin::gsn/what-is-the-gsn.adoc[overview of the system] and basic guide to xref:ROOT:gsn.adoc[creating a GSN-capable contract].
TIP: If you're new to the GSN, head over to our xref:learn::sending-gasless-transactions.adoc[overview of the system] and basic guide to xref:ROOT:gsn.adoc[creating a GSN-capable contract].
The core contract a recipient must inherit from is {GSNRecipient}: it includes all necessary interfaces, as well as some helper methods to make interacting with the GSN easier.
......
......@@ -16,7 +16,7 @@ library MerkleProof {
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
......
......@@ -28,6 +28,7 @@ library Counters {
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
......
= Drafts
Contracts in this category should be considered unstable. They are as thoroughly reviewed as everything else in OpenZeppelin Contracts, but we have doubts about their API so we don't commit to backwards compatibility. This means these contracts can receive breaking changes in a minor version, so you should pay special attention to the changelog when upgrading. For anything that is outside of this category you can read more about xref:ROOT:api-stability.adoc[API Stability].
NOTE: This page is incomplete. We're working to improve it for the next release. Stay tuned!
== ERC 20
......
pragma solidity ^0.5.0;
pragma solidity ^0.5.10;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
......@@ -94,28 +94,11 @@ library ERC165Checker {
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool success, bool result)
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
account, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
(bool success, bytes memory result) = account.staticcall.gas(30000)(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
= Lifecycle
== Pausable
{{Pausable}}
pragma solidity ^0.5.0;
import "../utils/Create2.sol";
import "../token/ERC20/ERC20.sol";
contract Create2Impl {
function deploy(bytes32 salt, bytes memory code) public {
Create2.deploy(salt, code);
}
function deployERC20(bytes32 salt) public {
// solhint-disable-next-line indent
Create2.deploy(salt, type(ERC20).creationCode);
}
function computeAddress(bytes32 salt, bytes memory code) public view returns (address) {
return Create2.computeAddress(salt, code);
}
function computeAddress(bytes32 salt, bytes memory code, address deployer) public pure returns (address) {
return Create2.computeAddress(salt, code, deployer);
}
}
......@@ -30,4 +30,8 @@ contract ERC721FullMock is ERC721Full, ERC721Mintable, ERC721MetadataMintable, E
function setTokenURI(uint256 tokenId, string memory uri) public {
_setTokenURI(tokenId, uri);
}
function setBaseURI(string memory baseURI) public {
_setBaseURI(baseURI);
}
}
pragma solidity ^0.5.0;
import "../utils/EnumerableSet.sol";
contract EnumerableSetMock{
using EnumerableSet for EnumerableSet.AddressSet;
event TransactionResult(bool result);
EnumerableSet.AddressSet private set;
function contains(address value) public view returns (bool) {
return set.contains(value);
}
function add(address value) public {
bool result = set.add(value);
emit TransactionResult(result);
}
function remove(address value) public {
bool result = set.remove(value);
emit TransactionResult(result);
}
function enumerate() public view returns (address[] memory) {
return set.enumerate();
}
function length() public view returns (uint256) {
return set.length();
}
function get(uint256 index) public view returns (address) {
return set.get(index);
}
}
pragma solidity ^0.5.0;
import "../utils/SafeCast.sol";
contract SafeCastMock {
using SafeCast for uint;
function toUint128(uint a) public pure returns (uint128) {
return a.toUint128();
}
function toUint64(uint a) public pure returns (uint64) {
return a.toUint64();
}
function toUint32(uint a) public pure returns (uint32) {
return a.toUint32();
}
function toUint16(uint a) public pure returns (uint16) {
return a.toUint16();
}
function toUint8(uint a) public pure returns (uint8) {
return a.toUint8();
}
}
......@@ -2,7 +2,7 @@
Contract modules for simple authorization and access control mechanisms.
TIP: For more complex needs see xref:access.adoc.
TIP: For more complex needs see xref:access.adoc[Access].
== Contracts
......
......@@ -47,7 +47,7 @@ contract Secondary is Initializable, Context {
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(_primary);
emit PrimaryTransferred(recipient);
}
uint256[50] private ______gap;
......
......@@ -14,6 +14,10 @@ import "./escrow/Escrow.sol";
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
......
......@@ -325,7 +325,7 @@ contract ERC721 is Initializable, Context, ERC165, IERC721 {
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
......@@ -338,10 +338,29 @@ contract ERC721 is Initializable, Context, ERC165, IERC721 {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
......
......@@ -14,6 +14,9 @@ contract ERC721Metadata is Initializable, Context, ERC165, ERC721, IERC721Metada
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
......@@ -60,24 +63,60 @@ contract ERC721Metadata is Initializable, Context, ERC165, ERC721, IERC721Metada
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
......
......@@ -30,7 +30,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
......@@ -80,8 +80,8 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
}
// register interfaces
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
......@@ -134,9 +134,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
function send(address recipient, uint256 amount, bytes memory data) public {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
......@@ -148,7 +148,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
function transfer(address recipient, uint256 amount) public returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
......@@ -165,9 +165,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-burn}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes calldata data) external {
function burn(uint256 amount, bytes memory data) public {
_burn(_msgSender(), _msgSender(), amount, data, "");
}
......@@ -186,7 +186,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
function authorizeOperator(address operator) public {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
......@@ -201,7 +201,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
function revokeOperator(address operator) public {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
......@@ -223,16 +223,16 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
bytes memory data,
bytes memory operatorData
)
external
public
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(_msgSender(), sender, recipient, amount, data, operatorData, true);
......@@ -241,9 +241,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {Transfer} events.
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(_msgSender(), account, amount, data, operatorData);
}
......@@ -264,7 +264,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
function approve(address spender, uint256 value) public returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
......@@ -277,9 +277,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
function transferFrom(address holder, address recipient, uint256 amount) public returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
......@@ -304,7 +304,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {Transfer} events.
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
......@@ -352,7 +352,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
bytes memory operatorData,
bool requireReceptionAck
)
private
internal
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
......@@ -379,7 +379,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
bytes memory data,
bytes memory operatorData
)
private
internal
{
require(from != address(0), "ERC777: burn from the zero address");
......@@ -410,7 +410,7 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) private {
function _approve(address holder, address spender, uint256 value) internal {
// TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
// currently unnecessary.
//require(holder != address(0), "ERC777: approve from the zero address");
......@@ -437,9 +437,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
bytes memory userData,
bytes memory operatorData
)
private
internal
{
address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
......@@ -465,9 +465,9 @@ contract ERC777 is Initializable, Context, IERC777, IERC20 {
bytes memory operatorData,
bool requireReceptionAck
)
private
internal
{
address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
......
......@@ -7,19 +7,21 @@ library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
......@@ -27,7 +29,7 @@ library Address {
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
return (codehash != accountHash && codehash != 0x0);
}
/**
......
pragma solidity ^0.5.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*
* _Available since v2.5.0._
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}. Note that
* a contract cannot be deployed twice using the same salt.
*/
function deploy(bytes32 salt, bytes memory bytecode) internal returns (address) {
address addr;
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecode`
* or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) {
return computeAddress(salt, bytecode, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes memory bytecodeHash, address deployer) internal pure returns (address) {
bytes32 bytecodeHashHash = keccak256(bytecodeHash);
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash)
);
return address(bytes20(_data << 96));
}
}
pragma solidity ^0.5.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* As of v2.5.0, only `address` sets are supported.
*
* Include with `using EnumerableSet for EnumerableSet.AddressSet;`.
*
* _Available since v2.5.0._
*
* @author Alberto Cuesta Cañada
*/
library EnumerableSet {
struct AddressSet {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (address => uint256) index;
address[] values;
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
address lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(AddressSet storage set)
internal
view
returns (address[] memory)
{
address[] memory output = new address[](set.values.length);
for (uint256 i; i < set.values.length; i++){
output[i] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(AddressSet storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return set.values[index];
}
}
......@@ -6,6 +6,12 @@ Miscellaneous contracts containing utility functions, often related to working w
{{Address}}
{{SafeCast}}
{{Arrays}}
{{EnumerableSet}}
{{Create2}}
{{ReentrancyGuard}}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
......@@ -22,7 +22,7 @@
.{{contract.name}}
{{/unless}}
{{#each modifiers}}
* xref:#{{anchor}}[`{{name}}({{args.names}})`]
* {xref-{{slug fullName~}} }[`{{name}}({{args.names}})`]
{{/each}}
{{/each}}
......@@ -39,7 +39,7 @@
.{{contract.name}}
{{/unless}}
{{#each functions}}
* xref:#{{anchor}}[`{{name}}({{args.names}})`]
* {xref-{{slug fullName~}} }[`{{name}}({{args.names}})`]
{{/each}}
{{/each}}
......@@ -56,14 +56,14 @@
.{{contract.name}}
{{/unless}}
{{#each events}}
* xref:#{{anchor}}[`{{name}}({{args.names}})`]
* {xref-{{slug fullName~}} }[`{{name}}({{args.names}})`]
{{/each}}
{{/each}}
--
{{/if}}
{{#each modifiers}}
{{#each ownModifiers}}
[.contract-item]
[[{{anchor}}]]
==== `pass:normal[{{name}}({{> typed-variable-array args}})]` [.item-kind]#modifier#
......@@ -72,7 +72,7 @@
{{/each}}
{{#each functions}}
{{#each ownFunctions}}
[.contract-item]
[[{{anchor}}]]
==== `pass:normal[{{name}}({{> typed-variable-array args}}){{#if outputs}}{{> typed-variable-array outputs}}{{/if}}]` [.item-kind]#{{visibility}}#
......@@ -81,7 +81,7 @@
{{/each}}
{{#each events}}
{{#each ownEvents}}
[.contract-item]
[[{{anchor}}]]
==== `pass:normal[{{name}}({{> typed-variable-array args}})]` [.item-kind]#event#
......
.Overview
* xref:index.adoc[Getting Started]
* xref:index.adoc[Overview]
.Basics
* xref:access-control.adoc[Access Control]
* xref:tokens.adoc[Tokens]
** xref:erc20.adoc[ERC20]
*** xref:erc20-supply.adoc[Creating Supply]
*** xref:crowdsales.adoc[Crowdsales]
** xref:erc721.adoc[ERC721]
** xref:erc777.adoc[ERC777]
* xref:gsn.adoc[Gas Station Network]
* xref:crowdsales.adoc[Crowdsales]
** xref:gsn-strategies.adoc[Strategies]
* xref:utilities.adoc[Utilities]
.In Depth
* xref:erc20-supply.adoc[ERC20 Supply]
* xref:gsn-strategies.adoc[GSN Strategies]
.FAQ
* xref:api-stability.adoc[API Stability]
* xref:release-schedule.adoc[Release Schedule]
* xref:releases-stability.adoc[Releases & Stability]
......@@ -29,6 +29,7 @@ contract MyContract is Ownable {
By default, the xref:api:ownership.adoc#Ownable-owner--[`owner`] of an `Ownable` contract is the account that deployed it, which is usually exactly what you want.
Ownable also lets you:
* xref:api:ownership.adoc#Ownable-transferOwnership-address-[`transferOwnership`] from the owner account to a new one, and
* xref:api:ownership.adoc#Ownable-renounceOwnership--[`renounceOwnership`] for the owner to relinquish this administrative privilege, a common pattern after an initial stage with centralized administration is over.
......
= 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 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 Contracts and how to use them.
Crowdsales have a bunch of different properties, but here are some important ones:
......@@ -18,7 +18,7 @@ Crowdsales have a bunch of different properties, but here are some important one
* 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 xref:api:crowdsale.adoc#Crowdsale[`Crowdsale`] base contract that can be combined with various other functionalities to construct a bespoke crowdsale.
To manage all of the different combinations and flavors of crowdsales, Contracts provides a highly configurable xref:api:crowdsale.adoc#Crowdsale[`Crowdsale`] base contract that can be combined with various other functionalities to construct a bespoke crowdsale.
[[crowdsale-rate]]
== Crowdsale Rate
......@@ -120,7 +120,7 @@ contract MyCrowdsaleDeployer {
Crowdsale crowdsale = new MyCrowdsale(
1, // rate, still in TKNbits
msg.sender, // send Ether to the deployer
address(token) // the token
token // the token
);
// transfer the minter role from this contract (the default)
// to the crowdsale, so it can mint tokens
......@@ -203,7 +203,7 @@ There comes a time in every crowdsale's life where it must relinquish the tokens
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!
OpenZeppelin Contracts is here to make that easy!
[[postdeliverycrowdsale]]
=== PostDeliveryCrowdsale
......
= 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.
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 Contracts 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-contracts/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 standard interface implemented by tokens built on Ethereum is called ERC20, and Contracts includes a widely used implementation of it: the aptly named xref:api:token/ERC20.adoc[`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
== 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.
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 Contracts v1, you may have written code like the following:
[source,solidity]
----
......@@ -23,7 +21,7 @@ contract ERC20FixedSupply is ERC20 {
}
----
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.
Starting with Contracts 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 xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[`_mint`] function that will do exactly this:
[source,solidity]
----
......@@ -34,12 +32,12 @@ contract ERC20FixedSupply is ERC20 {
}
----
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.
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, we 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
== Rewarding Miners
The internal `_mint` function is the key building block that allows us to write ERC20 extensions that implement a supply mechanism.
The internal xref:api:token/ERC20.adoc#ERC20-_mint-address-uint256-[`_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!
......@@ -55,9 +53,9 @@ contract ERC20WithMinerReward is ERC20 {
As we can see, `_mint` makes it super easy to do this correctly.
[[modularizing-the-mechanism]]
== Modularizing the mechanism
== Modularizing the Mechanism
There is one supply mechanism already included in OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/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`.
There is one supply mechanism already included in Contracts: xref:api:token/ERC20.adoc#ERC20Mintable[`ERC20Mintable`]. This is a generic mechanism in which a set of accounts is assigned the `minter` role, granting them the permission to call a xref:api:token/ERC20.adoc#ERC20Mintable-mint-address-uint256-[`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].
......@@ -81,9 +79,9 @@ contract MinerRewardMinter {
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
== 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.
Additionally to `_mint`, `ERC20` provides other internal functions that can be used or extended, such as xref:api:token/ERC20.adoc#ERC20-_transfer-address-address-uint256-[`_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.
......@@ -104,6 +102,6 @@ contract ERC20WithAutoMinerReward is ERC20 {
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
== 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.
= ERC20
An ERC20 token contract keeps track of xref:tokens.adoc#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 Contracts 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]]
== Constructing an ERC20 Token Contract
Using Contracts, 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/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract GLDToken is ERC20, ERC20Detailed {
constructor(uint256 initialSupply) ERC20Detailed("Gold", "GLD", 18) public {
_mint(msg.sender, initialSupply);
}
}
----
Our 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[Creating ERC20 Supply].
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]]
== 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:
```solidity
transfer(recipient, 5 * 10^18);
```
= ERC721
We've discussed how you can make a _fungible_ token using xref:erc20.adoc[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 xref:tokens.adoc#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. The OpenZeppelin Contracts provide 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/contracts/token/ERC721/ERC721Full.sol";
import "@openzeppelin/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.
= ERC777
Like xref:erc20.adoc[ERC20], ERC777 is a standard for xref:tokens.adoc#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 brings 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 is *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 xref:erc20.adoc#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/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 xref:erc20.adoc#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
----
== Sending Tokens to Contracts
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!_
......@@ -8,7 +8,7 @@ Finally, we will cover how to create your own custom strategies.
If you're still learning about the basics of the Gas Station Network, you should first head over to the xref:gsn.adoc[GSN Guide].
[[gsn-strategies]]
== GSN strategies explained
== GSN Strategies Explained
A *GSN strategy* decides which relayed call gets approved and which relayed call gets rejected. Strategies are a key concept within the GSN. Dapps need a strategy to prevent malicious users from spending the dapp's funds for relayed call fees.
......@@ -20,7 +20,7 @@ A GSN recipient contract needs the following to work:
2. It needs to handle `msg.sender` and `msg.data` differently.
3. It needs to decide how to approve and reject relayed calls.
Depositing funds for the GSN recipient contract can be done via the https://gsn.openzeppelin.com/recipients[GSN Dapp tool] or programmatically with https://github.com/OpenZeppelin/openzeppelin-gsn-helpers#usage-from-code[OpenZeppelin GSN Helpers].
Depositing funds for the GSN recipient contract can be done via the https://gsn.openzeppelin.com/recipients[GSN Dapp tool] or programmatically with xref:gsn-helpers::api.adoc#javascript_interface[*OpenZeppelin GSN Helpers*].
The actual user's `msg.sender` and `msg.data` can be obtained safely via xref:api:GSN.adoc#GSNRecipient-_msgSender--[`_msgSender()`] and xref:api:GSN.adoc#GSNRecipient-_msgData--[`_msgData()`] of xref:api:GSN.adoc#GSNRecipient[`GSNRecipient`].
......@@ -28,7 +28,7 @@ Deciding how to approve and reject relayed calls is a bit more complex. Chances
The base xref:api:GSN.adoc#GSNRecipient[`GSNRecipient`] contract doesn't include a strategy, so you must either use one of the pre-built ones or write your own. We will first go over using the included strategies: xref:api:GSN.adoc#GSNRecipientSignature[`GSNRecipientSignature`] and xref:api:GSN.adoc#GSNRecipientERC20Fee[`GSNRecipientERC20Fee`].
== GSNRecipientSignature
== `GSNRecipientSignature`
xref:api:GSN.adoc#GSNRecipientSignature[`GSNRecipientSignature`] lets users relay calls via the GSN to your recipient contract (charging you for it) if they can prove that an account you trust approved them to do so. The way they do this is via a _signature_.
......@@ -43,7 +43,7 @@ Alternatively, you could charge the user off-chain (e.g. via credit card) for cr
The great thing about this setup is that *your contract doesn't need to change* if you want to change the business rules. All you are doing is changing the backend logic conditions under which users use your contract for free.
On the other hand, you need to have a backend server, microservice, or lambda function to accomplish this.
=== How does GSNRecipientSignature work?
=== How Does `GSNRecipientSignature` Work?
`GSNRecipientSignature` decides whether or not to accept the relayed call based on the included signature.
......@@ -51,7 +51,7 @@ The `acceptRelayedCall` implementation recovers the address from the signature o
If the included signature matches the trusted signer, the relayed call is approved.
On the other hand, when the included signature doesn't match the trusted signer, the relayed call gets rejected with an error code of `INVALID_SIGNER`.
=== How to use GSNRecipientSignature
=== How to Use `GSNRecipientSignature`
You will need to create an off-chain service (e.g. backend server, microservice, or lambda function) that your dapp calls to sign (or not sign, based on your business logic) the relayed call parameters with your trusted signer account. The signature is then included as the `approvalData` in the relayed call.
......@@ -69,7 +69,7 @@ contract MyContract is GSNRecipientSignature {
TIP: We wrote an in-depth guide on how to setup a signing server that works with `GSNRecipientSignature`, https://forum.openzeppelin.com/t/advanced-gsn-gsnrecipientsignature-sol/1414[check it out!]
== GSNRecipientERC20Fee
== `GSNRecipientERC20Fee`
xref:api:GSN.adoc#GSNRecipientERC20Fee[`GSNRecipientERC20Fee`] is a bit more complex (but don't worry, it has already been written for you!). Unlike `GSNRecipientSignature`, `GSNRecipientERC20Fee` doesn't require any off-chain services.
Instead of off-chain approving each relayed call, you will give special-purpose ERC20 tokens to your users. These tokens are then used as payment for relayed calls to your recipient contract.
......@@ -82,7 +82,7 @@ Then, issue tokens to users based on your business logic. For example, you could
NOTE: *Users do not need to call approve* on their tokens for your recipient contract to use them. They are a modified ERC20 variant that lets the recipient contract retrieve them.
=== How does GSNRecipientERC20Fee work?
=== How Does `GSNRecipientERC20Fee` Work?
`GSNRecipientERC20Fee` decides to approve or reject relayed calls based on the balance of the users tokens.
......@@ -100,7 +100,7 @@ NOTE: The gas cost estimation is not 100% accurate, we may tweak it further down
NOTE: Always use `_preRelayedCall` and `_postRelayedCall` functions. Internal `_preRelayedCall` and `_postRelayedCall` functions are used instead of public `preRelayedCall` and `postRelayedCall` functions, as the public functions are prevented from being called by non-RelayHub contracts.
=== How to use GSNRecipientERC20Fee
=== How to Use `GSNRecipientERC20Fee`
Your GSN recipient contract needs to inherit from `GSNRecipientERC20Fee` along with appropriate xref:access-control.adoc[access control] (for token minting), set the token details in the constructor of `GSNRecipientERC20Fee` and create a public `mint` function suitably protected by your chosen access control as per the following sample code (which uses the xref:api:access.adoc#MinterRole[MinterRole]):
......@@ -118,7 +118,7 @@ contract MyContract is GSNRecipientERC20Fee, MinterRole {
}
----
== Custom strategies
== Custom Strategies
If the included strategies don't quite fit your business needs, you can also write your own! For example, your custom strategy could use a specified token to pay for relayed calls with a custom exchange rate to ether. Alternatively you could issue users who subscribe to your dapp ERC721 tokens, and accounts holding the subscription token could use your contract for free as part of the subscription. There are lots of potential options!
......
......@@ -2,11 +2,11 @@
The https://gsn.openzeppelin.com[Gas Station Network] allows you to build apps where you pay for your users transactions, so they do not need to hold Ether to pay for gas, easing their onboarding process. In this guide, we will learn how to write smart contracts that can receive transactions from the GSN, by using OpenZeppelin Contracts.
If you're new to the GSN, you probably want to first take a look at the xref:openzeppelin::gsn/what-is-the-gsn.adoc[light overview of the system], to get a clearer picture of how gasless transactions are achieved. Otherwise, strap in!
If you're new to the GSN, you probably want to first take a look at the xref:learn::sending-gasless-transactions.adoc[overview of the system] to get a clearer picture of how gasless transactions are achieved. Otherwise, strap in!
== Receiving a relayed call
== Receiving a Relayed Call
The first step to writing a recipient is to inherit from our GSNRecipient contract. If you're also inheriting from other OpenZeppelin contracts, such as ERC20 or Crowdsale, this will work just fine: adding GSNRecipient to all of your token or crowdsale functions will make them GSN-callable.
The first step to writing a recipient is to inherit from our GSNRecipient contract. If you're also inheriting from other contracts, such as ERC20 or Crowdsale, this will work just fine: adding GSNRecipient to all of your token or crowdsale functions will make them GSN-callable.
```solidity
import "@openzeppelin/contracts/GSN/GSNRecipient.sol";
......@@ -16,19 +16,19 @@ contract MyContract is GSNRecipient, ... {
}
```
=== msg.sender and msg.data
=== `msg.sender` and `msg.data`
There's only one extra detail you need to take care of when working with GSN recipient contracts: _you must never use `msg.sender` or `msg.data` directly_. On relayed calls, `msg.sender` will be `RelayHub` instead of your user! This doesn't mean however you won't be able to retrieve your users' addresses: `GSNRecipient` provides two functions, `_msgSender()` and `_msgData()`, which are drop-in replacements for `msg.sender` and `msg.data` while taking care of the low-level details. As long as you use these two functions instead of the original getters, you're good to go!
WARNING: Third-party contracts you inherit from may not use these replacement functions, making them unsafe to use when mixed with `GSNRecipient`. If in doubt, head on over to our https://forum.openzeppelin.com/c/support[support forum].
=== Accepting and charging
=== Accepting and Charging
Unlike regular contract function calls, each relayed call has an additional number of steps it must go through, which are functions of the `IRelayRecipient` interface `RelayHub` will call on your contract. `GSNRecipient` includes this interface but no implementation: most of writing a recipient involves handling these function calls. They are designed to provide flexibility, but basic recipients can safely ignore most of them while still being secure and sound.
The OpenZeppelin Contracts provide a number of tried-and-tested approaches for you to use out of the box, but you should still have a basic idea of what's going on under the hood.
==== acceptRelayedCall
==== `acceptRelayedCall`
First, RelayHub will ask your recipient contract if it wants to receive a relayed call. Recall that you will be charged for incurred gas costs by the relayer, so you should only accept calls that you're willing to pay for!
......@@ -87,4 +87,4 @@ These functions allow you to implement, for instance, a flow where you charge yo
== Further reading
Read our xref:gsn-bouncers.adoc[guide on the payment strategies] (called _bouncers_) pre-built and shipped in OpenZeppelin Contracts, or check out xref:api:GSN.adoc[the API reference of the GSN base contracts].
Read our xref:gsn-strategies.adoc[guide on the payment strategies] pre-built and shipped in OpenZeppelin Contracts, or check out xref:api:GSN.adoc[the API reference of the GSN base contracts].
= Getting Started
= Contracts
*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.
*A library for secure smart contract development.* Build on a solid foundation of community-vetted code.
[[install]]
== Install
OpenZeppelin should be installed directly into your existing node.js project with `npm install @openzeppelin/contracts`. We will use https://truffleframework.com/truffle[Truffle], an Ethereum development environment, to get started.
Please install Truffle and initialize your project:
* Implementations of standards like xref:erc20.adoc[ERC20] and xref:erc721.adoc[ERC721].
* Flexible xref:access-control.adoc[role-based permissioning] scheme.
* Reusable xref:utilities.adoc[Solidity components] to build custom contracts and complex decentralized systems.
* First-class integration with the xref:gsn.adoc[Gas Station Network] for systems with no gas fees!
* Audited by leading security firms.
[source,sh]
----
$ mkdir myproject
$ cd myproject
$ npm init -y
$ npm install truffle
$ npx truffle init
----
== Overview
To install the OpenZeppelin library, run the following in your Solidity project root directory:
[[install]]
=== Installation
[source,sh]
----
```console
$ npm install @openzeppelin/contracts
----
```
NOTE: 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 xref:api-stability.adoc[API Stability] document.
OpenZeppelin Contracts features a xref:releases-stability.adoc#api-stability[stable API], which means your contracts won't break unexpectedly when upgrading to a newer minor version.
[[usage]]
== Usage
=== Usage
Once installed, you can start using the contracts in the library by importing them:
Once installed, you can use the contracts in the library by importing them:
[source,solidity]
----
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Mintable.sol";
contract MyContract is Ownable {
...
contract MyNFT is ERC721Full, ERC721Mintable {
constructor() ERC721Full("MyNFT", "MNFT") public {
}
}
----
Truffle and other Ethereum development toolkits will automatically detect the installed library, and compile the imported contracts.
TIP: If you're new to smart contract development, head to xref:learn::developing-smart-contracts.adoc[Developing Smart Contracts] to learn about creating a new project and compiling your contracts.
IMPORTANT: You should always use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself.
To keep your system secure, 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.
== Learn More
* xref:access-control.adoc[Learn about Access Control]
* xref:crowdsales.adoc[Learn about Crowdsales]
* xref:tokens.adoc[Learn about Tokens]
* xref:utilities.adoc[Learn about our Utilities]
The guides in the sidebar will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:
OpenZeppelin's xref:api:token/ERC20.adoc[full API] is also thoroughly documented, and serves as a great reference when developing your smart contract application.
* xref:access-control.adoc[Access Control]: decide who can perform each of the actions on your system.
* xref:tokens.adoc[Tokens]: create tradeable assets or collectives, and distribute them via xref:crowdsales.adoc[Crowdsales].
* xref:gsn.adoc[Gas Station Network]: let your users interact with your contracts without having to pay for gas themselves.
* xref:utilities.adoc[Utilities]: generic useful tools, including non-overflowing math, signature verification, and trustless paying systems.
Additionally, you can also ask for help or follow OpenZeppelin's development in the https://forum.openzeppelin.com[community forum].
The xref:api:token/ERC20.adoc[full API] is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the https://forum.openzeppelin.com[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.openzeppelin.com/guides. 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.
Finally, you may want to take a look at the https://blog.openzeppelin.com/guides/[guides on our blog], which cover several common use cases and good practices.. 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.openzeppelin.com/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.openzeppelin.com/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.openzeppelin.com/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
* https://blog.openzeppelin.com/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.openzeppelin.com/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.openzeppelin.com/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.
= Release Schedule
OpenZeppelin Contracts follows a xref:api-stability.adoc[semantic versioning scheme].
[[minor-releases]]
== Minor releases
OpenZeppelin Contracts 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-contracts/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-contracts/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.
= API Stability
= New Releases and API Stability
Developing smart contracts is hard, and a conservative approach towards dependencies is sometimes favored. However, it is also very important to stay on top of new releases: these may include bugfixes, or deprecate old patterns in favor of newer and better practices.
Here we describe when you should expect new releases to come out, and how this affects you as a user of OpenZeppelin Contracts.
[[release-schedule]]
== Release Schedule
OpenZeppelin Contracts follows a <<versioning-scheme, semantic versioning scheme>>.
[[minor-releases]]
=== Minor Releases
OpenZeppelin Contracts 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-contracts/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-contracts/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.
[[api-stability]]
== API Stability
On the https://github.com/OpenZeppelin/openzeppelin-contracts/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.
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. The exception to this rule are contracts in the xref:api:drafts.adoc[Drafts] category, which should be considered unstable.
[[versioning-scheme]]
== Versioning scheme
=== Versioning Scheme
We follow https://semver.org/[SemVer], which means API breakage may occur between major releases. Read more about the xref:release-schedule.adoc[release schedule] to know how often this happens (not very).
We follow https://semver.org/[SemVer], which means API breakage may occur between major releases (which <<release-schedule, don't happen very often>>).
[[solidity-functions]]
== 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-contracts/issues/1512[an `internal` method may be added to make it easier to retrieve information that was already available]).
[[internal]]
=== `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).
This extends not only to `external` and `public` functions, but also `internal` ones: many 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 Contracts 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
=== 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.
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
=== 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-contracts/issues/707[from 2.1 on, `ERC20` also emits `Approval` on `transferFrom` calls]).
[[gas-costs]]
== 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.
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
=== 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-contracts/pull/1543[#1543] and https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1550[#1550]).
[[solidity-compiler-version]]
== 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.
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 Contract'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.
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 Contracts. 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-contracts/issues/1498#issuecomment-449191611[here].
= Utilities
OpenZeppelin provides a ton of useful utilities that you can use in your project. Here are some of the more popular ones:
The OpenZeppelin Contracs provide a ton of useful utilities that you can use in your project. Here are some of the more popular ones.
[[cryptography]]
== Cryptography
* xref:api:cryptography.adoc#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 xref:api:cryptography.adoc#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 xref:api:cryptography.adoc#ECDSA-toEthSignedMessageHash-bytes32-[`toEthSignedMessageHash`]
=== Checking Signatures On-Chain
Use these functions in combination to verify that a user has signed some information on-chain:
xref:api:cryptography.adoc#ECDSA[`ECDSA`] provides functions for recovering and managing Ethereum account ECDSA signatures. These are often generated via https://web3js.readthedocs.io/en/v1.2.4/web3-eth.html#sign[`web3.eth.sign`], and are a 65 byte array (of type `bytes` in Solidity) arranged the follwing way: `[[v (1)], [r (32)], [s (32)]]`.
The data signer can be recovered with xref:api:cryptography.adoc#ECDSA-recover-bytes32-bytes-[`ECDSA.recover`], and its address compared to verify the signature. Most wallets will hash the data to sign and add the prefix '\x19Ethereum Signed Message:\n', so when attempting to recover the signer of an Ethereum signed message hash, you'll want to use xref:api:cryptography.adoc#ECDSA-toEthSignedMessageHash-bytes32-[`toEthSignedMessageHash`].
[source,solidity]
----
keccack256(
abi.encodePacked(
someData,
moreData
)
)
.toEthSignedMessageHash()
.recover(signature)
using ECDSA for bytes32;
function _verify(bytes32 data, address account) pure returns (bool) {
return keccack256(data)
.toEthSignedMessageHash()
.recover(signature) == account;
}
----
* xref:api:cryptography.adoc#MerkleProof[`MerkleProof`] — provides xref:api:cryptography.adoc#MerkleProof-verify-bytes32---bytes32-bytes32-[`verify`] for verifying merkle proofs.
WARNING: Getting signature verification right is not trivial: make sure you fully read and understand xref:api:cryptography.adoc#ECDSA[`ECDSA`]'s documentation.
=== Verifying Merkle Proofs
xref:api:cryptography.adoc#MerkleProof[`MerkleProof`] provides xref:api:cryptography.adoc#MerkleProof-verify-bytes32---bytes32-bytes32-[`verify`], which can prove that some value is part of a https://en.wikipedia.org/wiki/Merkle_tree[Merkle tree].
[[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:
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. Contracts provides helpers both for implementing ERC165 in your contracts and querying other contracts:
* xref:api:introspection.adoc#IERC165[`IERC165`] — this is the ERC165 interface that defines xref:api:introspection.adoc#IERC165-supportsInterface-bytes4-[`supportsInterface`]. When implementing ERC165, you'll conform to this interface.
* xref:api:introspection.adoc#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 xref:api:introspection.adoc#ERC165-_registerInterface-bytes4-[`_registerInterface(bytes4)`]: check out example usage as part of the ERC721 implementation.
......@@ -66,7 +66,7 @@ contract MyContract {
[[math]]
== Math
The most popular math related library OpenZeppelin provides is xref:api:math.adoc#SafeMath[`SafeMath`], which provides mathematical functions that protect your contract from overflows and underflows.
The most popular math related library OpenZeppelin Contracts provides is xref:api:math.adoc#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:
......@@ -83,13 +83,18 @@ Easy!
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 xref:api:payment.adoc#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 xref:api:payment.adoc#PullPayment[`PullPayment`], which offers an xref:api:payment.adoc#PullPayment-_asyncTransfer-address-uint256-[`_asyncTransfer`] function for sending money to something and requesting that they xref:api:payment.adoc#PullPayment-withdrawPayments-address-payable-[`withdrawPayments()`] it later.
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 xref:api:payment.adoc#PullPayment[`PullPayment`], which offers an xref:api:payment.adoc#PullPayment-_asyncTransfer-address-uint256-[`_asyncTransfer`] function for sending money to something and requesting that they xref:api:payment.adoc#PullPayment-withdrawPayments-address-payable-[`withdrawPayments()`] it later.
If you want to Escrow some funds, check out xref:api:payment.adoc#Escrow[`Escrow`] and xref:api:payment.adoc#ConditionalEscrow[`ConditionalEscrow`] for governing the release of some escrowed Ether.
[[collections]]
== Collections
If you need support for more powerful collections than Solidity's native arrays and mappings, take a look at xref:api:utils.adoc#EnumerableSet[`EnumerableSet`]. It is similar to a mapping in that it stores and removes elements in constant time and doesn't allow for repeated entries, but it also supports _enumeration_, which means you can easily query all elements of the set both on and off-chain.
[[misc]]
=== Misc
== Misc
Want to check if an address is a contract? Use xref:api:utils.adoc#Address[`Address`] and xref:api:utils.adoc#Address-isContract-address-[`Address.isContract()`].
Want to keep track of some numbers that increment by 1 every time you want another one? Check out xref:api:drafts.adoc#Counter[`Counter`]. This is especially useful for creating incremental ERC721 `tokenId`s like we did in the last section.
Want to keep track of some numbers that increment by 1 every time you want another one? Check out xref:api:drafts.adoc#Counter[`Counter`]. This is useful for lots of things, like creating incremental identifiers, as shown on the xref:721.adoc[ERC721 guide].
{{#links}}
:{{slug target.fullName}}: pass:normal[xref:{{path}}#{{target.anchor}}[`{{target.fullName}}`]]
:xref-{{slug target.fullName}}: xref:{{path}}#{{target.anchor}}
{{/links}}
[build]
command = "npm run docs build"
publish = "openzeppelin-docs/build/site"
command = "npm run docs"
publish = "build/site"
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "@openzeppelin/contracts-ethereum-package",
"version": "2.4.0",
"version": "2.5.0",
"description": "Secure Smart Contract library for Solidity",
"files": [
".openzeppelin",
......@@ -12,19 +12,19 @@
],
"scripts": {
"compile": "scripts/compile.sh",
"console": "truffle console",
"coverage": "scripts/coverage.sh",
"docs": "scripts/docs.sh",
"docs": "oz-docs -c docs",
"docs:watch": "npm run docs watch contracts 'docs/*.hbs'",
"prepare-docs": "scripts/prepare-docs.sh",
"lint": "npm run lint:js && npm run lint:sol",
"lint:fix": "npm run lint:js:fix",
"lint:js": "eslint .",
"lint:js:fix": "eslint . --fix",
"lint:js": "eslint --ignore-path .gitignore .",
"lint:js:fix": "eslint --ignore-path .gitignore . --fix",
"lint:sol": "solhint --max-warnings 0 \"contracts/**/*.sol\"",
"prepare": "node scripts/prepare.js",
"release": "scripts/release/release.sh",
"version": "scripts/release/version.sh",
"test": "scripts/test.sh"
"test": "mocha --exit --recursive test"
},
"repository": {
"type": "git",
......@@ -45,36 +45,35 @@
},
"homepage": "https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package",
"devDependencies": {
"@openzeppelin/cli": "2.5.0",
"@openzeppelin/gsn-helpers": "^0.1.5",
"@openzeppelin/gsn-provider": "^0.1.5",
"@openzeppelin/upgrades": "2.5.0",
"@openzeppelin/cli": "^2.5.3",
"@openzeppelin/gsn-helpers": "^0.2.3",
"@openzeppelin/gsn-provider": "^0.1.9",
"@openzeppelin/test-environment": "^0.1.2",
"@openzeppelin/test-helpers": "^0.5.4",
"chai": "^4.2.0",
"chai-bn": "^0.1.1",
"concurrently": "^4.1.0",
"eslint": "^4.19.1",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.13.0",
"eslint": "^6.5.1",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-mocha-no-only": "^1.1.0",
"eslint-plugin-node": "^5.2.1",
"eslint-plugin-promise": "^3.8.0",
"eslint-plugin-standard": "^3.1.0",
"ethereumjs-util": "^6.0.0",
"ganache-cli": "^6.4.1",
"ganache-cli-coverage": "https://github.com/frangio/ganache-cli/releases/download/v6.4.1-coverage/ganache-cli-coverage-6.4.1.tgz",
"http-server": "^0.11.1",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"ethereumjs-util": "^6.2.0",
"ganache-core-coverage": "https://github.com/OpenZeppelin/ganache-core-coverage/releases/download/2.5.3-coverage/ganache-core-coverage-2.5.3.tgz",
"lodash.startcase": "^4.4.0",
"micromatch": "^4.0.2",
"mocha": "^7.0.0",
"nodemon": "^1.19.0",
"npm-install-peers": "^1.2.1",
"openzeppelin-docs-utils": "github:OpenZeppelin/docs-utils",
"openzeppelin-docsite": "github:OpenZeppelin/openzeppelin-docsite#ee1df82d52ad3df4337b20392627975091f8d5b3",
"openzeppelin-test-helpers": "^0.4",
"solhint": "2.1.0",
"solhint": "2.3.0",
"solidity-coverage": "github:rotcivegaf/solidity-coverage#5875f5b7bc74d447f3312c9c0e9fc7814b482477",
"solidity-docgen": "^0.3.5",
"truffle": "^5.0.41"
"solidity-docgen": "^0.3.13"
},
"peerDependencies": {
"@openzeppelin/upgrades": "^2.5.0"
}
},
"dependencies": {}
}
......@@ -4,4 +4,6 @@ if [ "$SOLC_NIGHTLY" = true ]; then
docker pull ethereum/solc:nightly
fi
npx truffle compile
export OPENZEPPELIN_NON_INTERACTIVE=true
npx oz compile
......@@ -2,11 +2,23 @@
set -o errexit -o pipefail
# Executes cleanup function at script exit.
trap cleanup EXIT
cleanup() {
# Delete the symlink created to the allFiredEvents file solidity-coverage creates
rm -f allFiredEvents
}
log() {
echo "$*" >&2
}
SOLIDITY_COVERAGE=true scripts/test.sh || log "Test run failed"
# The allFiredEvents file is created inside coverageEnv, but solidity-coverage
# expects it to be at the top level. We create a symlink to fix this
ln -s coverageEnv/allFiredEvents allFiredEvents
OZ_TEST_ENV_COVERAGE=true npx solidity-coverage || log "Test run failed"
if [ "$CI" = true ]; then
curl -s https://codecov.io/bash | bash -s -- -C "$CIRCLE_SHA1"
......
#!/usr/bin/env bash
if [ "$1" != "build" -a "$1" != "start" ];then
echo "usage: npm run docs (build|start)" >&2
exit 1
fi
set -o errexit
if [ ! -d openzeppelin-docs ]; then
git clone https://github.com/frangio/openzeppelin-docs.git openzeppelin-docs
fi
git -C openzeppelin-docs pull -q
if [ "$1" = "build" ]; then
npm run prepare-docs
cd docs
env DISABLE_PREPARE_DOCS= node ../openzeppelin-docs/build-local.js
elif [ "$1" = "start" ]; then
npx concurrently \
'nodemon --delay 1 -e "*" -w contracts -w "docs/*.hbs" -x npm run prepare-docs' \
'cd docs; env DISABLE_PREPARE_DOCS= nodemon --delay 1 -e adoc,yml ../openzeppelin-docs/build-local.js' \
'http-server -c-1 openzeppelin-docs/build/site'
fi
#!/usr/bin/env bash
set -o errexit
OUTDIR=docs/modules/api/pages/
if [ ! -d node_modules ]; then
npm ci
fi
rm -rf "$OUTDIR"
solidity-docgen -t docs -o "$OUTDIR" -e contracts/mocks,contracts/examples
node scripts/gen-nav.js "$OUTDIR" > "$OUTDIR/../nav.adoc"
......@@ -7,15 +7,11 @@ const path = require('path');
const cp = require('child_process');
const match = require('micromatch');
function exec (cmd, ...args) {
cp.execFileSync(cmd, args, { stdio: 'inherit' });
}
function readJSON (path) {
return JSON.parse(fs.readFileSync(path));
}
exec('npm', 'run', 'compile');
cp.spawnSync('npm', ['run', 'compile'], { stdio: 'inherit' });
const pkgFiles = readJSON('package.json').files;
......
#!/usr/bin/env bash
# Exit script as soon as a command fails.
set -o errexit
# Executes cleanup function at script exit.
trap cleanup EXIT
cleanup() {
# Kill the ganache instance that we started (if we started one and if it's still running).
if [ -n "$ganache_pid" ] && ps -p $ganache_pid > /dev/null; then
kill -9 $ganache_pid
fi
}
if [ "$SOLIDITY_COVERAGE" = true ]; then
ganache_port=8555
else
ganache_port=8545
fi
ganache_running() {
nc -z localhost "$ganache_port"
}
relayer_running() {
nc -z localhost "$relayer_port"
}
start_ganache() {
local accounts=(
# 10 accounts with balance 1M ether, needed for high-value tests.
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501200,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501201,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501202,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501203,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501204,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501205,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501206,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501207,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501208,1000000000000000000000000"
--account="0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501209,1000000000000000000000000"
# 3 accounts to be used for GSN matters.
--account="0x956b91cb2344d7863ea89e6945b753ca32f6d74bb97a59e59e04903ded14ad00,1000000000000000000000000"
--account="0x956b91cb2344d7863ea89e6945b753ca32f6d74bb97a59e59e04903ded14ad01,1000000000000000000000000"
--account="0x956b91cb2344d7863ea89e6945b753ca32f6d74bb97a59e59e04903ded14ad02,1000000000000000000000000"
)
if [ "$SOLIDITY_COVERAGE" = true ]; then
npx ganache-cli-coverage --emitFreeLogs true --allowUnlimitedContractSize true --gasLimit 0xfffffffffffff --port "$ganache_port" "${accounts[@]}" > /dev/null &
else
npx ganache-cli --gasLimit 0xfffffffffff --port "$ganache_port" "${accounts[@]}" > /dev/null &
fi
ganache_pid=$!
echo "Waiting for ganache to launch on port "$ganache_port"..."
while ! ganache_running; do
sleep 0.1 # wait for 1/10 of the second before check again
done
echo "Ganache launched!"
}
setup_relayhub() {
npx oz-gsn deploy-relay-hub \
--ethereumNodeURL "http://localhost:$ganache_port" \
--from "0xbb49ad04422f9fa6a217f3ed82261b942f6981f7"
}
if ganache_running; then
echo "Using existing ganache instance"
else
echo "Starting our own ganache instance"
start_ganache
fi
npx truffle version
setup_relayhub
if [ "$SOLIDITY_COVERAGE" = true ]; then
npx solidity-coverage
else
npx truffle test "$@"
fi
const { GSNDevProvider } = require('@openzeppelin/gsn-provider');
module.exports = {
accounts: {
ether: 1e6,
},
contracts: {
type: 'truffle',
},
setupProvider: (baseProvider) => {
const { accounts } = require('@openzeppelin/test-environment');
return new GSNDevProvider(baseProvider, {
txfee: 70,
useGSN: false,
ownerAddress: accounts[8],
relayerAddress: accounts[9],
});
},
blockGasLimit: 17592186044415, // 0xfffffffffff
};
const { BN, expectEvent } = require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
const ContextMock = artifacts.require('ContextMock');
const { BN, expectEvent } = require('@openzeppelin/test-helpers');
const ContextMock = contract.fromArtifact('ContextMock');
function shouldBehaveLikeRegularContext (sender) {
describe('msgSender', function () {
......
require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const ContextMock = artifacts.require('ContextMock');
const ContextMockCaller = artifacts.require('ContextMockCaller');
require('@openzeppelin/test-helpers');
const ContextMock = contract.fromArtifact('ContextMock');
const ContextMockCaller = contract.fromArtifact('ContextMockCaller');
const { shouldBehaveLikeRegularContext } = require('./Context.behavior');
contract('Context', function ([_, sender]) {
describe('Context', function () {
const [ sender ] = accounts;
beforeEach(async function () {
this.context = await ContextMock.new();
this.caller = await ContextMockCaller.new();
......
const { constants, expectEvent } = require('openzeppelin-test-helpers');
const { accounts, contract, web3 } = require('@openzeppelin/test-environment');
const { constants, expectEvent } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const gsn = require('@openzeppelin/gsn-helpers');
const { fixSignature } = require('../helpers/sign');
const { utils: { toBN } } = require('web3');
const ERC721GSNRecipientMock = artifacts.require('ERC721GSNRecipientMock');
const ERC721GSNRecipientMock = contract.fromArtifact('ERC721GSNRecipientMock');
describe('ERC721GSNRecipient (integration)', function () {
const [ signer, sender ] = accounts;
contract('ERC721GSNRecipient (integration)', function ([_, signer, sender]) {
const tokenId = '42';
beforeEach(async function () {
......
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract, web3 } = require('@openzeppelin/test-environment');
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const gsn = require('@openzeppelin/gsn-helpers');
const { expect } = require('chai');
const GSNRecipientMock = artifacts.require('GSNRecipientMock');
const ContextMockCaller = artifacts.require('ContextMockCaller');
const GSNRecipientMock = contract.fromArtifact('GSNRecipientMock');
const ContextMockCaller = contract.fromArtifact('ContextMockCaller');
const { shouldBehaveLikeRegularContext } = require('./Context.behavior');
contract('GSNRecipient', function ([_, payee, sender, newRelayHub]) {
describe('GSNRecipient', function () {
const [ payee, sender, newRelayHub ] = accounts;
beforeEach(async function () {
this.recipient = await GSNRecipientMock.new();
});
......
const { ether, expectEvent } = require('openzeppelin-test-helpers');
const { accounts, contract, web3 } = require('@openzeppelin/test-environment');
const { ether, expectEvent } = require('@openzeppelin/test-helpers');
const gsn = require('@openzeppelin/gsn-helpers');
const { expect } = require('chai');
const GSNRecipientERC20FeeMock = artifacts.require('GSNRecipientERC20FeeMock');
const ERC20Detailed = artifacts.require('ERC20Detailed');
const IRelayHub = artifacts.require('IRelayHub');
const GSNRecipientERC20FeeMock = contract.fromArtifact('GSNRecipientERC20FeeMock');
const ERC20Detailed = contract.fromArtifact('ERC20Detailed');
const IRelayHub = contract.fromArtifact('IRelayHub');
describe('GSNRecipientERC20Fee', function () {
const [ sender ] = accounts;
contract('GSNRecipientERC20Fee', function ([_, sender, other]) {
const name = 'FeeToken';
const symbol = 'FTKN';
......
const { expectEvent, expectRevert, constants } = require('openzeppelin-test-helpers');
const { accounts, contract, web3 } = require('@openzeppelin/test-environment');
const { expectEvent, expectRevert, constants } = require('@openzeppelin/test-helpers');
const gsn = require('@openzeppelin/gsn-helpers');
const { fixSignature } = require('../helpers/sign');
const { utils: { toBN } } = require('web3');
const { ZERO_ADDRESS } = constants;
const GSNRecipientSignatureMock = artifacts.require('GSNRecipientSignatureMock');
const GSNRecipientSignatureMock = contract.fromArtifact('GSNRecipientSignatureMock');
describe('GSNRecipientSignature', function () {
const [ signer, other ] = accounts;
contract('GSNRecipientSignature', function ([_, signer, other]) {
beforeEach(async function () {
this.recipient = await GSNRecipientSignatureMock.new(signer);
});
......
## Testing
Unit test are critical to the OpenZeppelin framework. They help ensure code quality and mitigate against security vulnerabilities. The directory structure within the `/tests` directory corresponds to the `/contracts` directory. OpenZeppelin uses Mocha’s JavaScript testing framework and Chai’s assertion library. To learn more about how to tests are structured, please reference OpenZeppelin’s Testing Guide.
Unit test are critical to the OpenZeppelin framework. They help ensure code quality and mitigate against security vulnerabilities. The directory structure within the `/test` directory corresponds to the `/contracts` directory. OpenZeppelin uses Truffle testing framework(based on the Mocha JavaScript testing framework) and the Chai assertion library. To learn more about how tests are structured, please reference OpenZeppelin’s Testing Guide.
const { expectRevert, constants } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { expectRevert, constants } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const RolesMock = artifacts.require('RolesMock');
const RolesMock = contract.fromArtifact('RolesMock');
describe('Roles', function () {
const [ authorized, otherAuthorized, other ] = accounts;
contract('Roles', function ([_, authorized, otherAuthorized, other]) {
beforeEach(async function () {
this.roles = await RolesMock.new();
});
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const CapperRoleMock = artifacts.require('CapperRoleMock');
const CapperRoleMock = contract.fromArtifact('CapperRoleMock');
describe('CapperRole', function () {
const [ capper, otherCapper, ...otherAccounts ] = accounts;
contract('CapperRole', function ([_, capper, otherCapper, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await CapperRoleMock.new({ from: capper });
await this.contract.addCapper(otherCapper, { from: capper });
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const MinterRoleMock = artifacts.require('MinterRoleMock');
const MinterRoleMock = contract.fromArtifact('MinterRoleMock');
describe('MinterRole', function () {
const [ minter, otherMinter, ...otherAccounts ] = accounts;
contract('MinterRole', function ([_, minter, otherMinter, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await MinterRoleMock.new({ from: minter });
await this.contract.addMinter(otherMinter, { from: minter });
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const PauserRoleMock = artifacts.require('PauserRoleMock');
const PauserRoleMock = contract.fromArtifact('PauserRoleMock');
describe('PauserRole', function () {
const [ pauser, otherPauser, ...otherAccounts ] = accounts;
contract('PauserRole', function ([_, pauser, otherPauser, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await PauserRoleMock.new({ from: pauser });
await this.contract.addPauser(otherPauser, { from: pauser });
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const SignerRoleMock = artifacts.require('SignerRoleMock');
const SignerRoleMock = contract.fromArtifact('SignerRoleMock');
describe('SignerRole', function () {
const [ signer, otherSigner, ...otherAccounts ] = accounts;
contract('SignerRole', function ([_, signer, otherSigner, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await SignerRoleMock.new({ from: signer });
await this.contract.addSigner(otherSigner, { from: signer });
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const WhitelistAdminRoleMock = artifacts.require('WhitelistAdminRoleMock');
const WhitelistAdminRoleMock = contract.fromArtifact('WhitelistAdminRoleMock');
describe('WhitelistAdminRole', function () {
const [ whitelistAdmin, otherWhitelistAdmin, ...otherAccounts ] = accounts;
contract('WhitelistAdminRole', function ([_, whitelistAdmin, otherWhitelistAdmin, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await WhitelistAdminRoleMock.new({ from: whitelistAdmin });
await this.contract.addWhitelistAdmin(otherWhitelistAdmin, { from: whitelistAdmin });
......
const { accounts, contract } = require('@openzeppelin/test-environment');
const { shouldBehaveLikePublicRole } = require('../../behaviors/access/roles/PublicRole.behavior');
const WhitelistedRoleMock = artifacts.require('WhitelistedRoleMock');
const WhitelistedRoleMock = contract.fromArtifact('WhitelistedRoleMock');
describe('WhitelistedRole', function () {
const [ whitelisted, otherWhitelisted, whitelistAdmin, ...otherAccounts ] = accounts;
contract('WhitelistedRole', function ([_, whitelisted, otherWhitelisted, whitelistAdmin, ...otherAccounts]) {
beforeEach(async function () {
this.contract = await WhitelistedRoleMock.new({ from: whitelistAdmin });
await this.contract.addWhitelisted(whitelisted, { from: whitelistAdmin });
......
const { expectRevert, constants, expectEvent } = require('openzeppelin-test-helpers');
const { expectRevert, constants, expectEvent } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
......@@ -76,8 +76,8 @@ function shouldBehaveLikePublicRole (authorized, otherAuthorized, [other], rolen
});
it(`emits a ${rolename}Added event`, async function () {
const { logs } = await this.contract[`add${rolename}`](other, { from });
expectEvent.inLogs(logs, `${rolename}Added`, { account: other });
const receipt = await this.contract[`add${rolename}`](other, { from });
expectEvent(receipt, `${rolename}Added`, { account: other });
});
it('reverts when adding role to an already assigned account', async function () {
......@@ -106,8 +106,8 @@ function shouldBehaveLikePublicRole (authorized, otherAuthorized, [other], rolen
});
it(`emits a ${rolename}Removed event`, async function () {
const { logs } = await this.contract[`remove${rolename}`](authorized, { from });
expectEvent.inLogs(logs, `${rolename}Removed`, { account: authorized });
const receipt = await this.contract[`remove${rolename}`](authorized, { from });
expectEvent(receipt, `${rolename}Removed`, { account: authorized });
});
it('reverts when removing from an unassigned account', async function () {
......@@ -131,8 +131,8 @@ function shouldBehaveLikePublicRole (authorized, otherAuthorized, [other], rolen
});
it(`emits a ${rolename}Removed event`, async function () {
const { logs } = await this.contract[`renounce${rolename}`]({ from: authorized });
expectEvent.inLogs(logs, `${rolename}Removed`, { account: authorized });
const receipt = await this.contract[`renounce${rolename}`]({ from: authorized });
expectEvent(receipt, `${rolename}Removed`, { account: authorized });
});
it('reverts when renouncing unassigned role', async function () {
......
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const AllowanceCrowdsaleImpl = artifacts.require('AllowanceCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const AllowanceCrowdsaleImpl = contract.fromArtifact('AllowanceCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('AllowanceCrowdsale', function () {
const [ investor, wallet, purchaser, tokenWallet ] = accounts;
contract('AllowanceCrowdsale', function ([_, investor, wallet, purchaser, tokenWallet]) {
const rate = new BN('1');
const value = ether('0.42');
const expectedTokenAmount = rate.mul(value);
......
const { BN, ether, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const CappedCrowdsaleImpl = artifacts.require('CappedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const CappedCrowdsaleImpl = contract.fromArtifact('CappedCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('CappedCrowdsale', function () {
const [ wallet ] = accounts;
contract('CappedCrowdsale', function ([_, wallet]) {
const rate = new BN('1');
const cap = ether('100');
const lessThanCap = ether('60');
......
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { balance, BN, constants, ether, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const Crowdsale = artifacts.require('CrowdsaleMock');
const SimpleToken = artifacts.require('SimpleTokenMock');
const Crowdsale = contract.fromArtifact('CrowdsaleMock');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('Crowdsale', function () {
const [ investor, wallet, purchaser ] = accounts;
contract('Crowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BN(1);
const value = ether('42');
const tokenSupply = new BN('10').pow(new BN('22'));
......
const { BN, expectEvent, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const FinalizableCrowdsaleImpl = artifacts.require('FinalizableCrowdsaleImpl');
const ERC20 = artifacts.require('ERC20');
const { BN, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const FinalizableCrowdsaleImpl = contract.fromArtifact('FinalizableCrowdsaleImpl');
const ERC20 = contract.fromArtifact('ERC20');
describe('FinalizableCrowdsale', function () {
const [ wallet, other ] = accounts;
contract('FinalizableCrowdsale', function ([_, wallet, other]) {
const rate = new BN('1000');
before(async function () {
......
const { BN, ether, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const IncreasingPriceCrowdsaleImpl = artifacts.require('IncreasingPriceCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const IncreasingPriceCrowdsaleImpl = contract.fromArtifact('IncreasingPriceCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('IncreasingPriceCrowdsale', function () {
const [ investor, wallet, purchaser ] = accounts;
contract('IncreasingPriceCrowdsale', function ([_, investor, wallet, purchaser]) {
const value = ether('1');
const tokenSupply = new BN('10').pow(new BN('22'));
......
const { BN, ether, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const IndividuallyCappedCrowdsaleImpl = artifacts.require('IndividuallyCappedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const IndividuallyCappedCrowdsaleImpl = contract.fromArtifact('IndividuallyCappedCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
const { shouldBehaveLikePublicRole } = require('../behaviors/access/roles/PublicRole.behavior');
contract('IndividuallyCappedCrowdsale', function (
[_, capper, otherCapper, wallet, alice, bob, charlie, other, ...otherAccounts]) {
describe('IndividuallyCappedCrowdsale', function () {
const [ capper, otherCapper, wallet, alice, bob, charlie, other, ...otherAccounts ] = accounts;
const rate = new BN(1);
const capAlice = ether('10');
const capBob = ether('2');
......
const { balance, expectEvent } = require('openzeppelin-test-helpers');
const { balance, expectEvent } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
function shouldBehaveLikeMintedCrowdsale ([_, investor, wallet, purchaser], rate, value) {
function shouldBehaveLikeMintedCrowdsale ([ investor, wallet, purchaser ], rate, value) {
const expectedTokenAmount = rate.mul(value);
describe('as a minted crowdsale', function () {
......
const { BN, ether, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers');
const { shouldBehaveLikeMintedCrowdsale } = require('./MintedCrowdsale.behavior');
const { expect } = require('chai');
const MintedCrowdsaleImpl = artifacts.require('MintedCrowdsaleImpl');
const ERC20Mintable = artifacts.require('ERC20MintableMock');
const ERC20 = artifacts.require('ERC20');
const MintedCrowdsaleImpl = contract.fromArtifact('MintedCrowdsaleImpl');
const ERC20Mintable = contract.fromArtifact('ERC20MintableMock');
const ERC20 = contract.fromArtifact('ERC20');
describe('MintedCrowdsale', function () {
const [ deployer, investor, wallet, purchaser ] = accounts;
contract('MintedCrowdsale', function ([_, deployer, investor, wallet, purchaser]) {
const rate = new BN('1000');
const value = ether('5');
......@@ -24,7 +28,7 @@ contract('MintedCrowdsale', function ([_, deployer, investor, wallet, purchaser]
expect(await this.token.isMinter(this.crowdsale.address)).to.equal(true);
});
shouldBehaveLikeMintedCrowdsale([_, investor, wallet, purchaser], rate, value);
shouldBehaveLikeMintedCrowdsale([investor, wallet, purchaser], rate, value);
});
describe('using non-mintable token', function () {
......
const { BN, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const PausableCrowdsale = artifacts.require('PausableCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const { BN, expectRevert } = require('@openzeppelin/test-helpers');
const PausableCrowdsale = contract.fromArtifact('PausableCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('PausableCrowdsale', function () {
const [ pauser, wallet, other ] = accounts;
contract('PausableCrowdsale', function ([_, pauser, wallet, other]) {
const rate = new BN(1);
const value = new BN(1);
......
const { BN, ether, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const PostDeliveryCrowdsaleImpl = artifacts.require('PostDeliveryCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const PostDeliveryCrowdsaleImpl = contract.fromArtifact('PostDeliveryCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('PostDeliveryCrowdsale', function () {
const [ investor, wallet, purchaser ] = accounts;
contract('PostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BN(1);
const tokenSupply = new BN('10').pow(new BN('22'));
......
const { balance, BN, ether, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { balance, BN, ether, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const RefundableCrowdsaleImpl = artifacts.require('RefundableCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const RefundableCrowdsaleImpl = contract.fromArtifact('RefundableCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('RefundableCrowdsale', function () {
const [ wallet, investor, other ] = accounts;
contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, other]) {
const rate = new BN(1);
const goal = ether('50');
const lessThanGoal = ether('45');
......
const { BN, ether, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const RefundablePostDeliveryCrowdsaleImpl = artifacts.require('RefundablePostDeliveryCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const RefundablePostDeliveryCrowdsaleImpl = contract.fromArtifact('RefundablePostDeliveryCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('RefundablePostDeliveryCrowdsale', function () {
const [ investor, wallet, purchaser ] = accounts;
contract('RefundablePostDeliveryCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BN(1);
const tokenSupply = new BN('10').pow(new BN('22'));
const goal = ether('100');
......
const { BN, ether, expectEvent, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, ether, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const TimedCrowdsaleImpl = artifacts.require('TimedCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const TimedCrowdsaleImpl = contract.fromArtifact('TimedCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('TimedCrowdsale', function () {
const [ investor, wallet, purchaser ] = accounts;
contract('TimedCrowdsale', function ([_, investor, wallet, purchaser]) {
const rate = new BN(1);
const value = ether('42');
const tokenSupply = new BN('10').pow(new BN('22'));
......
const { BN, ether, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const WhitelistCrowdsale = artifacts.require('WhitelistCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleTokenMock');
const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers');
const WhitelistCrowdsale = contract.fromArtifact('WhitelistCrowdsaleImpl');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('WhitelistCrowdsale', function () {
const [ wallet, whitelister, whitelisted, otherWhitelisted, other ] = accounts;
contract('WhitelistCrowdsale', function ([_, wallet, whitelister, whitelisted, otherWhitelisted, other]) {
const rate = new BN(1);
const value = ether('42');
const tokenSupply = new BN('10').pow(new BN('22'));
......
const { constants, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract, web3 } = require('@openzeppelin/test-environment');
const { constants, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { toEthSignedMessageHash, fixSignature } = require('../helpers/sign');
const { expect } = require('chai');
const ECDSAMock = artifacts.require('ECDSAMock');
const ECDSAMock = contract.fromArtifact('ECDSAMock');
const TEST_MESSAGE = web3.utils.sha3('OpenZeppelin');
const WRONG_MESSAGE = web3.utils.sha3('Nope');
contract('ECDSA', function ([_, other]) {
describe('ECDSA', function () {
const [ other ] = accounts;
beforeEach(async function () {
this.ecdsa = await ECDSAMock.new();
});
......@@ -142,7 +146,7 @@ contract('ECDSA', function ([_, other]) {
context('toEthSignedMessage', function () {
it('should prefix hashes correctly', async function () {
(await this.ecdsa.toEthSignedMessageHash(TEST_MESSAGE)).should.equal(toEthSignedMessageHash(TEST_MESSAGE));
expect(await this.ecdsa.toEthSignedMessageHash(TEST_MESSAGE)).to.equal(toEthSignedMessageHash(TEST_MESSAGE));
expect(await this.ecdsa.toEthSignedMessageHash(TEST_MESSAGE)).to.equal(toEthSignedMessageHash(TEST_MESSAGE));
});
});
......
require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
require('@openzeppelin/test-helpers');
const { MerkleTree } = require('../helpers/merkleTree.js');
const { keccak256, bufferToHex } = require('ethereumjs-util');
const { expect } = require('chai');
const MerkleProofWrapper = artifacts.require('MerkleProofWrapper');
const MerkleProofWrapper = contract.fromArtifact('MerkleProofWrapper');
contract('MerkleProof', function () {
describe('MerkleProof', function () {
beforeEach(async function () {
this.merkleProof = await MerkleProofWrapper.new();
});
......
const { expectRevert } = require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
const { expectRevert } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const CountersImpl = artifacts.require('CountersImpl');
const CountersImpl = contract.fromArtifact('CountersImpl');
contract('Counters', function () {
describe('Counters', function () {
beforeEach(async function () {
this.counter = await CountersImpl.new();
});
......
require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
require('@openzeppelin/test-helpers');
const ERC20MetadataMock = artifacts.require('ERC20MetadataMock');
const ERC20MetadataMock = contract.fromArtifact('ERC20MetadataMock');
const { expect } = require('chai');
......
const { BN, constants, expectRevert } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const ERC20Mock = artifacts.require('ERC20Mock');
const ERC20Mintable = artifacts.require('ERC20MintableMock');
const ERC20Migrator = artifacts.require('ERC20MigratorMock');
const ERC20Mock = contract.fromArtifact('ERC20Mock');
const ERC20Mintable = contract.fromArtifact('ERC20MintableMock');
const ERC20Migrator = contract.fromArtifact('ERC20MigratorMock');
describe('ERC20Migrator', function () {
const [ owner ] = accounts;
contract('ERC20Migrator', function ([_, owner, recipient, anotherAccount]) {
const totalSupply = new BN('200');
it('reverts with a null legacy token address', async function () {
......
const { BN, expectEvent, expectRevert } = require('openzeppelin-test-helpers');
const ERC20SnapshotMock = artifacts.require('ERC20SnapshotMock');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const ERC20SnapshotMock = contract.fromArtifact('ERC20SnapshotMock');
const { expect } = require('chai');
contract('ERC20Snapshot', function ([_, initialHolder, recipient, other]) {
describe('ERC20Snapshot', function () {
const [ initialHolder, recipient, other ] = accounts;
const initialSupply = new BN(100);
beforeEach(async function () {
......
const { BN, constants, expectRevert } = require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
const { BN, constants, expectRevert } = require('@openzeppelin/test-helpers');
const { MAX_INT256, MIN_INT256 } = constants;
const { expect } = require('chai');
const SignedSafeMathMock = artifacts.require('SignedSafeMathMock');
const SignedSafeMathMock = contract.fromArtifact('SignedSafeMathMock');
contract('SignedSafeMath', function () {
describe('SignedSafeMath', function () {
beforeEach(async function () {
this.safeMath = await SignedSafeMathMock.new();
});
......
const { constants } = require('openzeppelin-test-helpers');
const { contract } = require('@openzeppelin/test-environment');
const { constants } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const StringsMock = artifacts.require('StringsMock');
const StringsMock = contract.fromArtifact('StringsMock');
contract('Strings', function () {
describe('Strings', function () {
beforeEach(async function () {
this.strings = await StringsMock.new();
});
......
const { BN, constants, expectEvent, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const ERC20Mintable = artifacts.require('ERC20MintableMock');
const TokenVesting = artifacts.require('TokenVestingMock');
const ERC20Mintable = contract.fromArtifact('ERC20MintableMock');
const TokenVesting = contract.fromArtifact('TokenVestingMock');
describe('TokenVesting', function () {
const [ owner, beneficiary ] = accounts;
contract('TokenVesting', function ([_, owner, beneficiary]) {
const amount = new BN('1000');
beforeEach(async function () {
......
const { BN, balance, ether, expectRevert, time } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { BN, balance, ether, expectRevert, time } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const SampleCrowdsale = artifacts.require('SampleCrowdsaleMock');
const SampleCrowdsaleToken = artifacts.require('SampleCrowdsaleTokenMock');
const SampleCrowdsale = contract.fromArtifact('SampleCrowdsaleMock');
const SampleCrowdsaleToken = contract.fromArtifact('SampleCrowdsaleTokenMock');
describe('SampleCrowdsale', function () {
const [ deployer, owner, wallet, investor ] = accounts;
contract('SampleCrowdsale', function ([_, deployer, owner, wallet, investor]) {
const RATE = new BN(10);
const GOAL = ether('10');
const CAP = ether('20');
......
const { constants, expectEvent } = require('openzeppelin-test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const { constants, expectEvent } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect } = require('chai');
const SimpleToken = artifacts.require('SimpleTokenMock');
const SimpleToken = contract.fromArtifact('SimpleTokenMock');
describe('SimpleToken', function () {
const [ creator ] = accounts;
contract('SimpleToken', function ([_, creator]) {
beforeEach(async function () {
this.token = await SimpleToken.new({ from: creator });
});
......
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment