Compare commits

...

499 Commits

Author SHA1 Message Date
8d7a871609 4.3.3 2021-11-11 13:04:38 -03:00
c9acfb3c23 Fix ERC1155 supply tracking (#2956)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit 4088540aef)
2021-11-08 19:22:25 -03:00
0c4de6721d 4.3.2 2021-09-14 18:06:39 -03:00
024cc50df4 Restrict upgrade to proxy context in UUPSUpgradeable
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit 6241995ad3)
2021-09-14 18:06:00 -03:00
6edb6dd1ca 4.3.1 2021-08-26 17:59:03 -03:00
0ec7f4c25d Add additional isOperationReady check in TimelockController
(cherry picked from commit cec4f2ef57)
2021-08-24 16:23:37 -03:00
1d2e15fbd7 4.3.0 2021-08-17 12:35:02 -03:00
e3cbfcd44b Improve Governor documentation
(cherry picked from commit 4ac1070cd3)
2021-08-17 11:20:50 -03:00
bb2b687b46 Remove duplicate lines from changelog
(cherry picked from commit 38c1dd098c)
2021-08-16 16:55:23 -03:00
494cc6d3a5 Fix typo casted -> cast
(cherry picked from commit b174f067df)
2021-08-13 18:45:15 -03:00
7072b623af Fix typo casted -> cast
(cherry picked from commit 9253c614d2)
2021-08-13 18:17:22 -03:00
4a6d82acb9 add workflow to trigger transpilation to upgradeable contracts
(cherry picked from commit 049ff9a3c7)
2021-08-13 18:17:21 -03:00
635e36ff08 4.3.0-rc.0 2021-08-06 16:08:58 +02:00
6618f9f184 Fix documentation of functions in interfaces directory 2021-08-06 11:06:30 -03:00
7fcacb549b Fix name of interfaces directory in changelog 2021-08-06 11:04:40 -03:00
541e82144f Optimize EOA signature verification (#2661)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-08-06 10:47:52 -03:00
18668870fd Add an interface folder that lists common interfaces (#2517)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-08-06 10:36:34 -03:00
694f169832 Remove changelog entry for test changes 2021-08-06 10:14:00 -03:00
7279273ebb Fix inconsistencies in contract/test hierachy (#2814)
* Fix inconsistencies in contract/test hierachy

* changelog entry
2021-08-06 13:43:23 +02:00
d89f2a4ac6 Update ERC721.behavior.js (#2801) 2021-08-05 19:44:13 +02:00
48375aa908 Read optional compiler version from args/envvars (#2810) 2021-08-05 16:03:50 +02:00
29957d4a47 Add Governor guide (#2811) 2021-08-04 19:08:44 -03:00
4b152bd8ce Improve Governor (#2794)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-08-04 18:29:13 -03:00
f782943099 Move variable declaration to top of test file (#2806)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-08-03 14:19:21 +00:00
3da0cf698f Uncomment assertion in ERC2771Context.test.js (#2796) 2021-08-03 11:06:24 -03:00
e1c0f3eaef Update tests for RFC 2606 (#2802) 2021-08-02 23:41:13 +00:00
8bcf0ad7ab Use Hardhat recommended Mocha configuration (#2805) 2021-08-02 20:35:12 -03:00
56b3b7a487 Remove mention of 2.0.0 audit in docs 2021-08-02 20:06:30 -03:00
bbd68b721d Update security policy regarding past major releases 2021-08-02 19:57:04 -03:00
2d1e82c901 remove duplicated 'private-vars-leading-underscore' solhint rule (#2800) 2021-08-02 18:02:40 +02:00
9a385dcb45 fix typo 2021-08-02 12:14:20 +02:00
3dadd40034 Avoid safe math in BitMap (#2797) 2021-07-30 09:48:45 +02:00
566a774222 Update lockfile (#2774)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-07-20 10:49:34 -03:00
865dc9365c Update codecov/codecov-action action to v2 (#2779)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-07-20 13:48:26 +00:00
0500c9e53e Use "OpenZeppelin Contracts" where appropriate (#2778) 2021-07-20 10:35:58 -03:00
d3c5bdf4de Fix yellowpaper reference (#2775) 2021-07-19 09:45:04 -03:00
7e41bf2259 Remove ERC20FlashMint from drafts section in docs 2021-07-16 19:44:40 -03:00
6c1a634053 Add Governor contracts (#2672)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-07-16 12:44:01 -03:00
f88e555234 Add values() functions to EnumerableSets (#2768)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-07-16 12:06:47 -03:00
87826f807a Update lockfile 2021-07-16 11:58:22 -03:00
b8fdc620aa Downgrade yargs to v16 2021-07-16 11:49:12 -03:00
466cf05912 Deprecate openzeppelin-solidity on every release 2021-07-16 11:22:47 -03:00
8467143f2a Update lockfile (#2763)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-07-14 16:14:51 -03:00
c346c09b01 Clarify zero address usage in proposer and executor roles in Timelock (#2765)
* Clarify zero address usage in proposer and executor roles in access control

* Address zero only applies to executor

* Fix incorrect role
2021-07-14 16:39:08 +02:00
3935b907d4 Fix NatSpec comment syntax 2021-07-13 17:10:54 -03:00
4e2641a915 Simplify selector access (#2766) 2021-07-13 01:23:14 +02:00
973b0f883a fix typo in erc20 docs (#2764) 2021-07-12 16:45:39 +02:00
6d97f09195 Gas optimization on average function of Math.sol (#2757)
* change implementation to save gas

* add average test with two max uni256 number
2021-07-10 21:28:12 +02:00
1c1ebd765d Remove defer tag for Wizard embed script 2021-07-09 16:38:44 -03:00
9eba3ef29a fix two minor typos (#2755) 2021-07-08 17:23:13 +02:00
e4696f7315 Update lockfile (#2752)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-07-06 19:23:06 -03:00
23b3807ea7 Use private instead of immutable in ERC2771Context (#2754) 2021-07-06 14:41:03 -03:00
15b92e4097 Add missing "await" in tests (#2749)
* add missing await in tests

* fix test description
2021-07-06 17:20:08 +02:00
922058dbc8 Change comma to decimal point in comment (#2742) 2021-07-05 12:20:27 -03:00
b9e2c7896d Merge branch 'release-v4.2' 2021-06-30 14:31:57 -03:00
9fbc1d71c0 4.2.0 2021-06-30 14:29:37 -03:00
3ae911b442 Update lockfile (#2732)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-06-29 17:46:11 -03:00
eea376911b Reorder AccessControl event to emit after assignment (#2738) 2021-06-24 10:38:02 -03:00
1db3037808 Fix misleading comments (#2737)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-24 10:37:20 -03:00
556e366ce5 4.2.0-rc.0 2021-06-23 09:54:29 -03:00
6842518b1b Wrapper extension for ERC20 token (#2633)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-22 19:27:33 -03:00
8a775cd8d4 Emit DelegateVotesChanged events after Transfer (#2733) 2021-06-22 19:14:40 -03:00
4d0f8c1da8 Check inheritance tree consistency (#2727)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-18 15:08:13 +00:00
27e09007cc Reorder state changes and event emission for consistency (#2719)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-18 14:58:50 +00:00
00128bd260 Fix function ordering in ERC1967Upgrades (#2722) 2021-06-14 18:54:19 -03:00
f710bafae8 Fix typos (#2723) 2021-06-14 18:51:56 -03:00
788d338c9b Improve naming of internal variables (#2721) 2021-06-14 18:51:37 -03:00
6f50f6e1ef Remove repeated code from ERC1967Upgrade (#2720) 2021-06-14 18:50:51 -03:00
fd111df16d Remove unecessary code from Context (#2718) 2021-06-14 18:44:00 -03:00
17958adaca Uninstall unused mocha dependency 2021-06-14 17:41:34 -03:00
0a05f6fa45 Add a recover(bytes32,bytes32,bytes32) that follows EIP2098 (#2713) 2021-06-14 15:12:08 -03:00
78103f3137 Update lockfile (#2717)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-06-14 18:55:46 +02:00
f7da53cebd Add a BitMap struct (#2710)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-11 15:24:00 -03:00
75f6dbb86c Add import statements and GitHub link in API docs (#2714) 2021-06-11 15:09:32 -03:00
9d5f77db9d Update lockfile (#2702)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-06-07 19:45:26 +02:00
b0cf6fbb7a Add Prettier for linting and fix Solhint config (#2697)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-07 12:33:03 -03:00
e3661abe84 Split ERC20Votes and ERC20VotesComp (#2706)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-06-04 12:52:19 -03:00
1488d4f678 Improve ECDSA tests and docs (#2619) 2021-06-01 17:59:24 -03:00
adc50d465c Tweak ERC20Votes revert reasons and documentation (#2696)
* adapt revert reason convention

* add whitespace

* tweak documentation

* fix tests
2021-05-27 18:16:37 +02:00
f6efd8aced Add totalSupply checkpoints to ER20Votes (#2695)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-05-27 15:13:18 +00:00
ad3c18eb5f Fix the ERC721 link in the ERC1155 doc (#2694) 2021-05-26 19:11:08 +00:00
eabec630b9 Update lockfile (#2690)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-26 15:27:55 -03:00
406c83649b Introduce ERC1155 totalSupply() and exists() functions (#2593)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-05-20 21:46:21 +00:00
5f50b9f6e0 Update lockfile (#2675)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-20 11:45:43 -03:00
1b37c21da5 reserve unchecked for when guarded by explicit require (#2685) 2021-05-20 16:40:18 +02:00
7144ec8db4 Fix whitespace in ERC777 (#2667) 2021-05-20 11:01:20 -03:00
f31bb101ad Move ERC20Votes and ERC20FlashMint out of draft (#2673)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-05-20 11:00:22 -03:00
7c754d0665 Add ceiling division operation to the Math.sol library (#2681)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-05-20 13:53:31 +00:00
5f7eda1f98 Tokens: wrap safe substractions in uchecked block (#2669)
* Tokens: wrap definitely safe subs in unchecked

* Add change in changelog

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-05-20 10:33:28 +02:00
f8f6d56c58 Update README intro with link to Wizard 2021-05-19 20:58:29 -03:00
8ad458e955 Explain how baseURI is used for building the tokenURI (#2679) 2021-05-19 16:07:56 -03:00
8ea06b75aa Add a Counter.reset function (#2678) 2021-05-19 15:52:43 -03:00
c3ae4790c7 Fix Changelog structure 2021-05-14 15:42:18 +02:00
5cd86f740d Update lockfile (#2666)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-12 16:14:31 +00:00
aa06c9fbc1 Use Node 12 in CI 2021-05-12 13:06:07 -03:00
100ca0b8a2 ERC20 extension for governance tokens (vote delegation and snapshots) (#2632)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-05-12 10:13:59 -03:00
8669481309 Fix typo in comment (#2660) 2021-05-05 10:41:46 -03:00
1dc4a319ab Use shorter syntax for Escrow addition (#2646) 2021-05-04 20:04:51 +00:00
08ba72afa2 Fix ERC721._beforeTokenTransfer docs (#2653) 2021-05-04 11:10:24 -03:00
0a905d674b Fix typo in tokens.adoc (#2654) 2021-05-03 16:56:50 -03:00
319afebdc0 Fix typo in ERC20._mint docs (#2648) 2021-05-03 16:54:23 -03:00
f1e92dd184 Fix code comments (#2658) 2021-05-03 16:50:07 -03:00
9048e565d7 Update dependency yargs to v17 (#2655)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-03 16:43:57 -03:00
95dec684ad Update lockfile (#2656)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-03 16:42:54 -03:00
0d40f705a7 Add link to full list of upgrades resources 2021-04-29 22:58:59 -03:00
df8a0fe8dc Complete documentation of UUPSUpgradeable 2021-04-29 22:43:39 -03:00
50a9b4d1e7 Fix package-lock.json 2021-04-29 18:14:13 -03:00
2e30b9f382 Merge branch 'release-v4.1' 2021-04-29 18:06:52 -03:00
23869e5b2a 4.1.0 2021-04-29 18:04:21 -03:00
3ba2a1354f Update solidity-docgen 2021-04-27 09:40:20 -03:00
903df56837 Review structure of Proxies API docs (#2645)
(cherry picked from commit 4a53ee5a13)
2021-04-27 09:29:52 -03:00
4a53ee5a13 Review structure of Proxies API docs (#2645) 2021-04-27 09:29:13 -03:00
cfd6e7eab9 Fix documentation typos
(cherry picked from commit a98814b930)
2021-04-26 15:41:36 -03:00
a98814b930 Fix documentation typos 2021-04-26 15:41:17 -03:00
10c763da6f Fix whitespace in doc comments
(cherry picked from commit a020a55f9d)
2021-04-26 15:37:22 -03:00
a020a55f9d Fix whitespace in doc comments 2021-04-26 15:37:04 -03:00
6552adafb2 Merge ERC1967Storage into ERC1967Upgrade (#2644)
(cherry picked from commit 5756e31999)
2021-04-26 15:16:44 -03:00
5756e31999 Merge ERC1967Storage into ERC1967Upgrade (#2644) 2021-04-26 15:16:19 -03:00
8ae9f0914b Update lockfile (#2643)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-26 10:56:01 -03:00
3c4a18f0df Update Stability document with current practices 2021-04-22 11:51:17 -03:00
165e6f1948 EnumerableSet: Remove Boundary Check in _at (#2606)
* remove boundary check

* fix tests for EnumerableSet "index out of bound"

* Changelog

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-04-20 19:51:26 +00:00
750a17653d Optimize removal in EnumerableSet (#2605)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-20 18:08:34 +00:00
07b48484ff Fix ERC721 guide for 4.x 2021-04-20 12:37:15 -03:00
a664fb1e45 Improve code comments in ERC1967._upgradeToAndCallSecure
(cherry picked from commit 2e6ef74593)
2021-04-19 19:37:19 -03:00
2e6ef74593 Improve code comments in ERC1967._upgradeToAndCallSecure 2021-04-19 19:36:14 -03:00
440b65bf77 Refactor ERC1155 transfers to use internal functions (#2636)
* Refactor ERC1155 transfers to use internal functions #2622

* apply length check to all internal calls

Co-authored-by: Robert Kaiser <kairo@kairo.at>
2021-04-19 22:13:15 +02:00
df7996b671 add Available since 4.1 comments
(cherry picked from commit 9a698e6b7b)
2021-04-19 20:55:39 +02:00
9a698e6b7b add Available since 4.1 comments 2021-04-19 20:55:16 +02:00
915109b2c4 Move UUPSUpgradeable to proxy/utils
(cherry picked from commit b9125001f0)
2021-04-19 20:46:58 +02:00
2fa86736dd typo: remove duplicate word (#2631)
(cherry picked from commit f17624194b)
2021-04-19 20:46:55 +02:00
b9125001f0 Move UUPSUpgradeable to proxy/utils 2021-04-19 20:44:10 +02:00
f17624194b typo: remove duplicate word (#2631) 2021-04-16 20:07:09 -03:00
7360a2532d Add missing changelog entry
(cherry picked from commit 72eb905c58)
2021-04-16 20:38:45 +02:00
72eb905c58 Add missing changelog entry 2021-04-16 20:37:54 +02:00
ad90dbdaff 4.1.0-rc.0 2021-04-16 18:14:24 +02:00
e0a2b195e4 Add modifier & internal function with standard revert message in AccessControl (#2609)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-16 12:15:09 -03:00
1c676ac0ec Implement UUPS proxy (ERC1822) (#2542)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-16 11:41:47 -03:00
538b6d21b1 Update ERC721 guide for 4.0 (#2630) 2021-04-15 23:49:53 -03:00
3157aff844 Update docs for setting ERC20 decimals (#2629) 2021-04-14 16:00:22 +00:00
f4898a2e3a Update lockfile (#2627)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-12 19:17:28 -03:00
555be63c90 Add support for EIP2098 "short signatures" in the ECDSA library (#2582)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-09 22:58:03 +00:00
057efbfe95 Update lockfile (#2604)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-09 17:33:14 -03:00
585db1f667 Improve Hardhat config (#2612)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-09 11:09:16 -03:00
7f6a1666fa Add Multicall module (#2608) 2021-04-07 17:26:40 +00:00
0c621246d3 Add tooling to verify signatures with support for ERC1271 (#2532)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-07 13:09:17 +00:00
5bd798c6e1 Add ERC3156 extension of ERC20 (flash minting and lending) (#2543)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-04-06 03:13:10 +00:00
5ecd2b850c Add Contracts Wizard docs page (#2624) 2021-04-05 17:46:57 -03:00
243adff49c fix typo in ERC20's documentation 2021-03-26 14:06:58 +01:00
378531b709 Fix merge issue in CHANGELOG.md 2021-03-23 16:28:01 +01:00
9584c23594 Update package-lock.json 2021-03-23 12:19:17 -03:00
64f20ec624 Fix release.sh for npm 7 2021-03-23 12:15:21 -03:00
783e928ae8 Merge branch 'release-v4.0' 2021-03-23 12:13:57 -03:00
a673994de5 4.0.0 2021-03-23 12:06:54 -03:00
9b0e27c98c add missing rewrite rule in scripts/migrate-imports.js
(cherry picked from commit a3712a3288)
2021-03-22 18:08:36 +01:00
a3712a3288 add missing rewrite rule in scripts/migrate-imports.js 2021-03-22 18:07:02 +01:00
74e03de760 removes unused dependency (#2603) 2021-03-21 19:22:45 +01:00
09e302384a Update lockfile (#2592)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-16 16:07:24 -03:00
3dc374ddcf Make overide of ERC721.isApprovedForAll affect the ERC721 logic (#2597) 2021-03-16 15:32:22 -03:00
90a72f9acd Fix ERC721URIStorage in documentation
(cherry picked from commit 7c1625b0e0)
2021-03-15 16:48:43 -03:00
7c1625b0e0 Fix ERC721URIStorage in documentation 2021-03-15 16:47:39 -03:00
cd443f0d5b Add tests to extend code coverage (#2586) 2021-03-15 13:01:47 -03:00
d5194725b7 Add optimization for EnumerableSet (#2588)
Co-authored-by: Reason <Reason@Lee.com>
2021-03-13 10:19:29 +01:00
82e3ec3afe Fix MerkleProof generation in tests and add some documentation (#2585) 2021-03-12 21:41:54 +00:00
682def9f89 Typo in ERC20 constructor docstring (#2581) 2021-03-11 17:28:26 +01:00
96aece07f3 Fix docs formatting in IERC20Permit (#2579)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-03-10 19:48:22 -03:00
508a879ef0 Remove merkleTree.js in favor of merkletreejs dependency (#2578) 2021-03-10 18:30:16 +01:00
5171e46c47 Add an internal _useNonce(address) function in ERC20Permit (#2565) 2021-03-10 12:24:12 -03:00
1ee939e7c4 4.0.0-rc.0 2021-03-09 15:38:49 +01:00
59f33c1cc1 remove extra changelog entry 2021-03-09 15:32:54 +01:00
fb95a8b34b move changelog entry to the appropriate section 2021-03-09 15:31:34 +01:00
d104ced953 fix changelog format
(cherry picked from commit 2658e01baa)
2021-03-09 15:25:22 +01:00
1fd54698ff Update lockfile (#2573)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
(cherry picked from commit 9612b891c9)
2021-03-09 15:23:05 +01:00
2658e01baa fix changelog format 2021-03-09 15:21:58 +01:00
9612b891c9 Update lockfile (#2573)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-08 22:11:26 -03:00
27fc833550 Make ERC1155.uri public (#2576)
(cherry picked from commit 5dbbda5435)
2021-03-08 17:37:25 -03:00
0b3e0d74b0 Further reorganisation of the repo (#2575)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit f076ff5dbd)
2021-03-08 17:37:03 -03:00
d75b4cf613 Update changelog to list beta bugfix separately
(cherry picked from commit 5aab6ff81b)
2021-03-08 17:37:00 -03:00
5aab6ff81b Update changelog to list beta bugfix separately 2021-03-08 17:33:04 -03:00
f076ff5dbd Further reorganisation of the repo (#2575)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-03-08 17:06:54 -03:00
b8ab763581 Add IERC20Metadata with name, symbol and decimals (#2561)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-03-08 19:53:01 +00:00
78a9821129 Mint ERC777 without reception ack (#2552) 2021-03-08 19:44:31 +00:00
5dbbda5435 Make ERC1155.uri public (#2576) 2021-03-08 15:42:34 -03:00
b1e0aa487d Fix AccessControlEnumerable not tracking renounceRole (#2572)
* Fix AccessControlEnumerable not tracking renounceRole

* Updated changelog

(cherry picked from commit 7adf0d88a0)
2021-03-08 14:32:21 +01:00
6505e28c40 removes invalid character in comments (#2571)
(cherry picked from commit fc004c0ad2)
2021-03-08 14:32:09 +01:00
7adf0d88a0 Fix AccessControlEnumerable not tracking renounceRole (#2572)
* Fix AccessControlEnumerable not tracking renounceRole

* Updated changelog
2021-03-08 13:44:20 +01:00
fc004c0ad2 removes invalid character in comments (#2571) 2021-03-08 13:42:35 +01:00
f07c39be8a Add ERC165 interface detection to AccessControl (#2562)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
(cherry picked from commit 29ffe6f426)
2021-03-04 18:50:49 -03:00
29ffe6f426 Add ERC165 interface detection to AccessControl (#2562)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-03-04 18:50:12 -03:00
ec63c604ab Fix prepack script 2021-03-03 17:06:05 +01:00
69ca2ad676 Fix name of ERC721URIStorage contract in changelog
(cherry picked from commit 3d587f3043)
2021-03-03 12:50:05 -03:00
3d587f3043 Fix name of ERC721URIStorage contract in changelog 2021-03-03 12:49:22 -03:00
ae1e384a9a Fix prepack script
(cherry picked from commit 10c52439dd5118d4b671e12d691bfde42c987fb9)
2021-03-03 16:32:22 +01:00
954f6110d6 4.0.0-beta.1 2021-03-03 16:23:38 +01:00
4390b8df12 Add ERC721URIStorage extension (#2555)
(cherry picked from commit 1705067e65)
2021-03-03 16:15:51 +01:00
cb88e15b33 Enable optimizations when publishing package (#2557)
(cherry picked from commit 618a735816)
2021-03-03 16:15:26 +01:00
1705067e65 Add ERC721URIStorage extension (#2555) 2021-03-03 12:13:09 -03:00
618a735816 Enable optimizations when publishing package (#2557) 2021-03-03 12:01:54 -03:00
136de91049 Rename variable master to implementation #2 (#2553)
(cherry picked from commit 103ff8e23d)
2021-03-03 12:33:03 +01:00
103ff8e23d Rename variable master to implementation #2 (#2553) 2021-03-03 12:31:33 +01:00
e2bf45f262 Rename variable master to implementation
(cherry picked from commit cdb929aada)
2021-03-02 21:30:26 -03:00
cdb929aada Rename variable master to implementation 2021-03-02 21:25:56 -03:00
93d990c653 Optimize constructor of ERC777 (#2551)
(cherry picked from commit 62af16b9f2)
2021-03-02 21:31:07 +01:00
62af16b9f2 Optimize constructor of ERC777 (#2551) 2021-03-02 21:29:05 +01:00
3dfd02b4b4 Fix link to TimelockController
(cherry picked from commit ba1d773176)
2021-03-02 21:14:33 +01:00
7a7bd8f6d7 Fix typo Controler -> Controller
(cherry picked from commit 583146f9d6)
2021-03-02 21:14:26 +01:00
16312fcfb9 Rename UpgradeableProxy to ERC1967Proxy (#2547)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit c789941d76)
2021-03-02 21:14:08 +01:00
a81a88cca0 Fix mentions of buidler (#2548)
(cherry picked from commit 232c355b3a)
2021-03-02 21:14:00 +01:00
5acedf5027 Change title of meta transactions page in docs sidebar
(cherry picked from commit 773c7265e8)
2021-03-02 21:13:51 +01:00
566c601d41 Update lockfile (#2546)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
(cherry picked from commit 742c436d28)
2021-03-02 21:13:39 +01:00
ba1d773176 Fix link to TimelockController 2021-03-02 15:53:03 -03:00
583146f9d6 Fix typo Controler -> Controller 2021-03-02 15:32:10 -03:00
c789941d76 Rename UpgradeableProxy to ERC1967Proxy (#2547)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-03-02 11:20:59 -03:00
232c355b3a Fix mentions of buidler (#2548) 2021-03-02 09:24:37 +01:00
773c7265e8 Change title of meta transactions page in docs sidebar 2021-03-01 14:38:12 -03:00
742c436d28 Update lockfile (#2546)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-01 14:02:18 -03:00
15214a53ce Optimize implementation of ERC20Capped (#2524)
(cherry picked from commit 36b855972b)
2021-03-01 12:09:21 -03:00
36b855972b Optimize implementation of ERC20Capped (#2524) 2021-02-24 22:07:03 +00:00
d5f4862405 Fix package.json files field
(cherry picked from commit 735c03fcf3)
2021-02-24 00:36:08 -03:00
735c03fcf3 Fix package.json files field 2021-02-24 00:35:47 -03:00
4a1985f870 Fix migrate-imports.js test for upgradeable paths
(cherry picked from commit 4519c237c5)
2021-02-24 00:20:07 -03:00
4519c237c5 Fix migrate-imports.js test for upgradeable paths 2021-02-23 23:50:40 -03:00
ac8279a0a5 Update Antora component version 2021-02-23 23:31:48 -03:00
7cab19a2e4 Check upgradeable paths in migrate-imports test
(cherry picked from commit 4ee9fd77fd)
2021-02-23 23:31:34 -03:00
4ee9fd77fd Check upgradeable paths in migrate-imports test 2021-02-23 23:29:43 -03:00
556cdf5f1a 4.0.0-beta.0 2021-02-22 17:44:21 -03:00
c760fe9a2e Update package-lock.json 2021-02-22 17:44:02 -03:00
24a0bc23cf Reorganize the repo structure (#2503)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-22 16:44:16 +00:00
c3178ff942 Add message to caution that SafeMath.sol is for Solidity 0.8 2021-02-19 18:17:42 -03:00
f8cc8b844a Minimal support for ERC2771 (GSNv2) (#2508)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-19 15:36:48 -03:00
e341bdc1b7 Remove enumerable from AccessControl and add AccessControlEnumerable extension (#2512)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-19 17:36:56 +00:00
09734e8028 Remove enumerable from ERC721 and add an ERC721Enumerable extension (#2511)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-19 13:24:39 -03:00
7d20d0e2d2 Use immutable variables where possible (#2528)
Co-authored-by: rotciv <victorfage@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-02-19 11:11:54 -03:00
0059b17dfc Remove _isConstructor() check in initializer modifier (#2531)
* Remove _isConstructor() check in initializer modifier

* add changelog entry
2021-02-18 20:53:00 -03:00
e733b24dfe Refactor ERC165 to use function overriding instead of storage (#2505)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-18 19:02:28 +00:00
f7c8252611 Remove GSNv1 contracts (#2521)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-18 15:27:18 +00:00
e66e3ca523 Improve gas efficiency of EnumerableMap (#2518)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-18 15:19:57 +00:00
24660c3e48 Fix keccak256 typo (#2525) 2021-02-17 13:34:39 +01:00
ee6348a7a0 change CHANGELOG indentation for consistency 2021-02-09 17:25:41 +01:00
a44303c373 Remove double sload when doing math checks in tokens (#2506)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-09 12:58:23 -03:00
f49e9ee41b Update lockfile (#2493)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-09 11:59:35 -03:00
1ba03b164a Add support for eth-gas-reporter (#2501)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-09 00:42:35 +00:00
9c1e703990 Add a Strings.toHexString function (#2504)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-08 20:55:56 +00:00
f2112be4d8 Add revert string to Counter decrement overflow (#2500) 2021-02-04 20:28:13 +00:00
c82895fb65 Fix codecov reports 2021-02-04 17:15:32 -03:00
b840341a77 Remove the storage associated with decimals (#2502)
* Removing the storage associated with decimals

* changelog entry

* changelog link to new issue number

* Update contracts/token/ERC20/ERC20.sol

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

* Update contracts/token/ERC20/ERC20.sol

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

* Update CHANGELOG.md

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-02-04 20:06:00 +01:00
ed7623273a Fix prepare-docs-solc.js for Hardhat 2021-02-04 14:22:19 -03:00
9425a7e0ab Merge branch 'solc-0.8'
Conflicts:
	CHANGELOG.md
	package-lock.json
	test/math/SafeMath.test.js
2021-02-02 22:13:28 +01:00
93438eca0b Merge 3.4 master into solc-0.8 (#2499)
* 3.4.0-rc.0

* Allow manual dispatch of Test CI job

* Update lockfile (#2481)

Co-authored-by: Renovate Bot <bot@renovateapp.com>

* Add "available since" comments in documentation

* Add "available since" comments in documentation

(cherry picked from commit 63a0343dda)

* Remove SafeMathMock compilation warnings (#2497)

* Remove SafeMathMock compilation warnings (#2497)

(cherry picked from commit f4e57fd529)

* 3.4.0

* fix safemath test to use renamed function from the mock

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-02 22:07:56 +01:00
e28615628b Merge branch 'release-v3.4' 2021-02-02 16:16:16 -03:00
fa64a1ced0 3.4.0 2021-02-02 16:15:12 -03:00
0f553e7f9e Remove SafeMathMock compilation warnings (#2497)
(cherry picked from commit f4e57fd529)
2021-02-02 12:03:02 -03:00
f4e57fd529 Remove SafeMathMock compilation warnings (#2497) 2021-02-02 11:46:23 -03:00
a0e2bca79a Add "available since" comments in documentation
(cherry picked from commit 63a0343dda)
2021-02-01 21:45:27 -03:00
63a0343dda Add "available since" comments in documentation 2021-02-01 21:44:58 -03:00
5db7413827 re-enabling safemath revert reasons in ERC20, ERC777 and ERC1155 (#2491)
* re-enabling safemath revert reasons in ERC20 and ERC1155

* adding revert messages to ERC777

* removing uncheck block
2021-02-01 11:00:16 +01:00
d163aeb80d Update lockfile (#2481)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-01-29 19:41:00 -03:00
60205944bb Adopt new Solidity features interfaceId, try/catch, keccak constants (#2487)
* Clean code

-  using type().interfaceId to improve readeability of ERC165 registration
- hardcoding some keccak256 that are otherwise computed at construction.

* hardcode keccak256 result

* Improve code readeability using try/catch

* Remove hardcoded hash 

tests show that solc 0.8.0 does the optimization as expected

* Use try/catch to improve readability

* ERC165Checker: Do not revert when returndata is empty + new test

* Address PR comments

* improve testing of ERC721Receiver errors

* put back comment about invalid interface id

* coverage does not support 0.8.1. Reverting back to 0.8.0

* bubble all data with length > 0 if onERC721Receive fails.

* Fix test: revert without message trigger is bubble with the default message

* using enum object to improve readability
2021-01-29 22:20:49 +01:00
03832c130c Make Context._msgData return "bytes calldata" (#2492) 2021-01-29 12:51:51 -03:00
9f93e25b88 Merge branch 'solc-0.7' into 'solc-0.8' 2021-01-27 18:36:46 -03:00
afaebc3869 Disable solhint until Solidity 0.8 supported 2021-01-27 18:17:13 -03:00
fdf57a9788 Lint 2021-01-27 18:14:15 -03:00
5609cd4c74 Fix merge errors 2021-01-27 18:04:52 -03:00
a0323d446c Transition from buidler to hardhat 2021-01-27 11:37:18 +01:00
0db76e98f9 Merge branch 'solc-0.7' into solc-0.8 2021-01-27 11:28:23 +01:00
fa33fbce75 Allow manual dispatch of Test CI job
(cherry picked from commit bcc7192af7)
2021-01-26 18:21:49 -03:00
bcc7192af7 Allow manual dispatch of Test CI job 2021-01-26 18:20:33 -03:00
0d27b7a7ff Add package-lock.json 2021-01-26 18:18:58 -03:00
6d202894b6 Merge branch 'master' 2021-01-26 18:58:15 +01:00
ff300b10e1 3.4.0-rc.0 2021-01-26 13:31:55 -03:00
18c7efe800 Make view and pure functions virtual (#2473)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-26 13:23:23 -03:00
0931062a3f Use Address.sendValue instead of address.transfer in RefundEscrow (#2480)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-26 13:07:19 -03:00
3b4c951838 Fix ERC777 potential reentrancy issues (#2483) 2021-01-26 10:57:18 -03:00
c2c08af16d Add ERC165Checker.getSupportedInterfaces (#2469)
Co-authored-by: conspyrosy <1027439+Spyros-Stylianou@users.noreply.github.com>
Co-authored-by: kamiebisu <kamiebisu@protonmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-19 17:55:22 -03:00
9e49be41b6 Add ERC1167 library (minimal proxy) (#2449)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-19 17:54:47 -03:00
dd86c97e18 Fix scripts/prepare-docs.sh 2021-01-19 14:56:17 -03:00
5a8e6bda51 Update pull request template 2021-01-19 13:41:00 -03:00
c34211417c Refactor SafeMath to avoid memory leaks (#2462)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-18 18:06:27 -03:00
974c534210 Update contracts to support Solidity 0.8.x (#2442)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-14 19:38:53 -03:00
5a58fd2de0 Update lockfile (#2467)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-01-13 21:06:06 -03:00
faec973e09 Make non-view functions virtual (#2468) 2021-01-13 18:25:39 -03:00
65b7e515a2 Align comments (#2458) 2021-01-11 16:43:45 -03:00
318c4b44ea Move Context from GSN to utils directory (#2453)
Co-authored-by: Hadrien Croubois <hadrien@openzeppelin.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-07 13:04:13 -03:00
b6e5187973 Use Address.sendValue for PaymentSplitter (#2456)
* use Address.sendValue instead of .transfer

* changelog entry

Co-authored-by: Hadrien Croubois <hadrien@openzeppelin.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-01-07 13:03:20 -03:00
1e8cb4b4a4 Bubble revert reasons in proxy initialization (#2454)
Co-authored-by: Hadrien Croubois <hadrien@openzeppelin.com>
2021-01-07 12:45:36 -03:00
9daa0d4d2f Update lockfile (#2447)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-01-04 15:19:03 -03:00
ceb7324657 Update TimelockController.sol (#2446) 2020-12-23 20:25:01 -03:00
da00d28cb7 Rename "amount" to "value" in permit (#2445) 2020-12-23 12:09:16 -03:00
c23d5e0143 Update lockfile (#2444)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-12-22 16:31:03 -03:00
d8658dbc47 Update actions/setup-node action to v2 (#2440)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-12-22 16:06:12 -03:00
a6a4c042f5 Adjust for chainid becoming view in 0.8.0. (#2443)
Co-authored-by: Alex Beregszaszi <alex@rtfs.hu>

Co-authored-by: Daniel Kirchner <daniel@ekpyron.org>
2020-12-21 18:14:21 -03:00
6be0b410dc Use explicit conversions between addresses and numbers (#2439)
Co-authored-by: hrkrshnn <webmail.hari@gmail.com>
Co-authored-by: cameel <cameel2@gmail.com>
2020-12-17 22:51:48 -03:00
051d340171 Use bytes1 and avoid using the obsolete byte type (#2438) 2020-12-14 16:42:01 -03:00
0a4233f0f6 Update lockfile (#2435)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-12-14 13:50:33 -03:00
ecc66719bd Add ERC20 Permit (EIP-2612) (#2237)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Santiago Palladino <spalladino@gmail.com>
2020-12-11 13:34:02 -03:00
03d51c5677 Bump ini from 1.3.5 to 1.3.7 (#2430)
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.7.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.7)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-12-10 19:14:51 -03:00
268c6ab36c Edit ERC20 API index to make it clearer 2020-12-09 20:04:08 -03:00
0786f31f22 Update lockfile (#2428)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-12-09 13:32:42 -03:00
883116e4af Add ERC20 and ERC777 fixed supply presets #2377 (#2399)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-12-02 14:51:33 -03:00
5748034cd3 Add EIP 712 helpers (#2418) 2020-12-02 13:17:24 -03:00
061e7f0da7 Fix Solidity warning 2020-12-01 18:33:58 -03:00
a138dc3970 Remove stalebot 2020-12-01 12:33:09 -03:00
fa2b204535 Update TimelockController docs (#2415)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-11-30 20:14:02 -03:00
73c7af102b Configure Codecov parameters 2020-11-30 19:03:58 -03:00
18a8ae5a8a Change styling for headings in API pages 2020-11-30 18:09:32 -03:00
fa65bf89be Remove inheritance that conflicts with upgradeable transpiler 2020-11-30 16:34:07 -03:00
60c8b0e02f Update lockfile (#2416)
* Update lockfile

* fix ERC1155Pausable test

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-11-30 16:16:58 -03:00
acac4a7fca Merge branch 'release-v3.3' 2020-11-26 20:48:06 -03:00
6be5ffe54f 3.3.0 2020-11-26 20:43:43 -03:00
ba843f0ad9 Fix release script 2020-11-26 20:42:32 -03:00
4297be6ac1 Use custom ids for timelock docs section titles
(cherry picked from commit 7d02933da3)
2020-11-26 19:13:44 -03:00
7d02933da3 Use custom ids for timelock docs section titles 2020-11-26 19:12:58 -03:00
d2003a6fff Fix NatSpec comment syntax
(cherry picked from commit ef0483b4be)
2020-11-26 18:57:46 -03:00
ef0483b4be Fix NatSpec comment syntax 2020-11-26 18:56:49 -03:00
9e51b2e5df Add beacon proxy changelog entry 2020-11-26 13:10:54 -03:00
951e946e71 Add a beacon proxy contract (#2411)
Co-authored-by: Santiago Palladino <spalladino@gmail.com>
2020-11-26 13:03:01 -03:00
1fccf6fa53 3.3.0-rc.2 2020-11-24 18:51:47 -03:00
7f8fc584de Remove Address.functionDelegateCall 2020-11-24 18:47:09 -03:00
1d1d2ba661 Add mention of TimelockController in intro to access docs
(cherry picked from commit 520bf7ac61)
2020-11-24 18:15:57 -03:00
520bf7ac61 Add mention of TimelockController in intro to access docs 2020-11-24 18:14:40 -03:00
85f50d3e06 Update lockfile (#2412)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-11-24 17:06:01 -03:00
e12cb97e16 Only display own modifiers in contract docs index 2020-11-20 13:37:22 -03:00
a3a7e6fa34 Remove Context from function index in docs site 2020-11-20 13:12:15 -03:00
3881175d72 Fix TimelockController link in changelog
(cherry picked from commit ef32c04795)
2020-11-19 16:05:16 -03:00
ef32c04795 Fix TimelockController link in changelog 2020-11-19 16:04:12 -03:00
42da4d6867 Fix name of argument in docstring
Fixes #2410
2020-11-18 18:54:09 -03:00
f7bb84ce4c Add changelog entry about support for both 0.6 and 0.7
(cherry picked from commit 5bd1c0d063)
2020-11-18 16:31:41 -03:00
5bd1c0d063 Add changelog entry about support for both 0.6 and 0.7 2020-11-18 16:31:15 -03:00
c67d81bae1 3.3.0-rc.1 2020-11-17 21:39:45 -03:00
a5d1ac7ed0 Merge branch 'master' into release-v3.3 2020-11-17 21:39:07 -03:00
b8187aa529 Merge branch 'master' into solc-0.7 2020-11-17 21:37:54 -03:00
877f440331 Fix package.json version out of sync 2020-11-17 21:37:21 -03:00
58892471a3 Merge branch 'master' into solc-0.7 2020-11-17 21:34:25 -03:00
90ed1af972 Support compiling with solc 0.7 (#2408) 2020-11-17 21:29:39 -03:00
21344b91ed Lint 2020-11-17 20:26:17 -03:00
3f9673c177 Update package-lock.json 2020-11-17 19:52:43 -03:00
fce2513827 Remove date from changelog 2020-11-17 19:25:45 -03:00
3debb8820e Fix changelog versioning to include date only after final release
(cherry picked from commit d3a4e31fe2)
2020-11-17 19:24:35 -03:00
d3a4e31fe2 Fix changelog versioning to include date only after final release 2020-11-17 19:23:02 -03:00
25ac33486c 3.3.0-rc.0 2020-11-17 18:58:48 -03:00
5803e11663 Improve script to version changelog 2020-11-17 18:50:10 -03:00
b33372cc92 Fix changelog entry for Bytes32Set 2020-11-17 18:27:23 -03:00
bcb2b5d1cd Update lockfile (#2407)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-11-16 15:44:11 -03:00
3f2a2b5f62 Configure compilation with solc 0.7.4 2020-11-16 14:17:03 -03:00
4972bf4f23 Merge branch 'master' into solc-0.7 2020-11-16 14:11:46 -03:00
3d2e5c0310 Update lockfile (#2384)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-11-13 22:50:00 -03:00
f547b6ff27 Remove outdated comment in testing.md 2020-11-13 16:44:11 -03:00
5272799bdd Fix ERC1155 URI example (#2401) 2020-11-12 18:23:35 -03:00
1a230e3aa5 Rename upgrade-safe package to upgradeable 2020-11-12 16:10:01 -03:00
679b7d147c Clean Buidler cache before publishing 2020-11-11 17:47:15 -03:00
8effd1e02a Add scripts for when publishing @openzeppelin/contracts directly
(cherry picked from commit a1408a3411)
2020-11-11 16:40:23 -03:00
cb19930b83 Run tests on release branches 2020-11-11 12:49:23 -03:00
c6b07b33c5 Lint 2020-11-11 12:24:08 -03:00
47e37975c9 Remove bad SafeCast test 2020-11-11 12:22:06 -03:00
5472eedbad Add guide about OZ Contracts Upgrade Safe (#2403)
Co-authored-by: Andrew B Coathup <28278242+abcoathup@users.noreply.github.com>
2020-11-10 18:24:47 -03:00
af95fe7a93 Reorder package.json fields 2020-11-09 16:40:38 -03:00
705b0b0001 Improve GitHub Actions node_modules caching 2020-11-06 23:39:56 -03:00
35c931126b Remove old contracts/examples directory from package.json 2020-11-06 19:45:08 -03:00
6aada9d356 Update dependencies 2020-11-06 17:20:48 -03:00
da9161fc91 Migrate to GitHub Actions 2020-11-06 17:20:45 -03:00
1e78adc28c Refactor buidler config 2020-11-06 14:28:01 -03:00
fcdf8f4618 Add BytesSet (#2395)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-11-04 16:57:48 -03:00
8533499507 Lint 2020-10-29 16:42:32 -03:00
fb4659c5d7 Change convention for unreleased changelog entries 2020-10-28 17:23:54 -03:00
a1408a3411 Add scripts for when publishing @openzeppelin/contracts directly 2020-10-28 17:05:14 -03:00
f06738828b Migrate to Hardhat (#2397) 2020-10-28 17:03:05 -03:00
b6b1c0130b 3.2.2-solc-0.7 2020-10-28 16:33:23 -03:00
ea305cf32e Change convention for unreleased changelog entries 2020-10-28 16:33:08 -03:00
d41102d6c3 add changelog entry for #2396 2020-10-28 16:27:38 -03:00
0c27ecc536 configure renovate using openzeppelin shareable config 2020-10-28 14:05:14 -03:00
0f55c18595 Fix/solc 0.7.4 warnings #2391 (#2396)
* Fix unnamed return variable warning

This commit fixes warnings thrown by the solc 0.7.4 compiler:
"Warning: Unnamed return variable can remain unassigned. Add an explicit
return with value to all non-reverting code paths or name the variable."

* Fix function state mutability warning

This commit fixes warnings thrown by the solc 0.7.4 compiler:
"Warning: Function state mutability can be restricted to pure"

* Fix shadows an existing declaration warning

This commit fixes warnings thrown by the solc 0.7.4 compiler:
"Warning: This declaration shadows an existing declaration."

1. Arguments by default are not underscored.
2. If the name isn't available due to shadowing, use prefix underscore.
3. If prefix underscore isn't available due to shadowing, use suffix underscore.
2020-10-28 13:42:38 -03:00
e5fbbda9ba Add audit links to readme and doc index (#2392) 2020-10-21 15:59:43 -03:00
7650210ad6 Make contracts abstract if they had internal constructors (#2383) 2020-10-20 12:24:46 -03:00
ba125961d6 Update lockfile (#2381) 2020-10-16 12:48:30 -03:00
2bb06b1af4 Replace if (...) revert() with require(...) (#2376) 2020-10-13 18:36:47 -03:00
8108f2f9b9 Fixed comment typo (#2372) 2020-10-07 17:43:40 -03:00
08dfaab829 Add changelog entry for TimelockController 2020-10-05 16:26:41 -03:00
d1c121b599 Test ERC165 support in ERC1155Holder (#2365) 2020-09-18 19:19:29 -03:00
e98b187e64 Fix typos in ERC20 docs (#2364) 2020-09-17 19:45:12 -03:00
87326f7313 Add functionStaticCall and functionDelegateCall methods to Address library (#2333)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-09-17 16:19:11 -03:00
7f3eee750a Add TimelockController (#2354)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-09-17 16:16:05 -03:00
ace35fdeda Update all dependencies transitively (#2363) 2020-09-16 12:14:53 -03:00
bf4c9d700d Update all non-major dependencies (#2349)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-09-15 23:39:41 -03:00
c7d99531a7 Re-enable coverage analysis (#2291)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-09-15 20:59:42 -03:00
ca7ee098ca Fix whitespace in IERC721Receiver (#2359)
Slight nit on spacing to reduce # of lines // conform to other OZ function syntax
2020-09-15 19:30:09 -03:00
ec8efd52b4 3.2.1-solc-0.7 2020-09-15 18:17:10 -03:00
9a83ced46e Add changelog entry for 3.2.1-solc-0.7 2020-09-15 18:15:15 -03:00
0d7bf01ac1 Merge branch 'solc-0.7' into release-v3.2.0-solc-0.7 2020-09-15 17:48:27 -03:00
1229c28ce0 Update ERC20.sol (#2357)
Remove unused `Address` library import, references.
2020-09-14 13:35:46 -03:00
f7ca35c9c6 Configure solhint for solc 0.7 2020-09-10 20:41:40 -03:00
c08d1439dd Bump solhint to 3.2.0
(cherry picked from commit 09d437c1f9)
2020-09-10 20:39:26 -03:00
09d437c1f9 Bump solhint to 3.2.0 2020-09-10 20:37:32 -03:00
492d4ac013 Merge branch 'release-v3.2.0' into master 2020-09-10 20:27:39 -03:00
870ea2a88a Add -solc-0.7 version tag 2020-09-10 20:26:59 -03:00
29f4a38c0d Merge branch 'release-v3.2.0' into release-v3.2.0-solc-0.7 2020-09-10 20:14:37 -03:00
1ada3b633e 3.2.0 2020-09-10 20:10:42 -03:00
0ce14a078a Merge branch 'release-v3.2.0' into release-v3.2.0-solc-0.7 2020-09-09 17:43:31 -03:00
45b81c969f Add note about proxy changes in the changelog
(cherry picked from commit cfb7f80003)
2020-09-09 17:43:23 -03:00
cfb7f80003 Add note about proxy changes in the changelog 2020-09-09 17:43:00 -03:00
628dea7a08 update new contracts for solidity 0.7 2020-09-08 20:15:43 -03:00
22de765f3c Merge branch 'release-v3.2.0' into release-v3.2.0-solc-0.7 2020-09-08 20:14:42 -03:00
ae4e9845de Fix a grammatical error in a comment (#2352)
changed a comment in the isContract function to make it grammatically right.
2020-09-08 14:50:12 -03:00
95dc7525ac Bump decompress from 4.2.0 to 4.2.1 (#2347)
Bumps [decompress](https://github.com/kevva/decompress) from 4.2.0 to 4.2.1.
- [Release notes](https://github.com/kevva/decompress/releases)
- [Commits](https://github.com/kevva/decompress/compare/v4.2.0...v4.2.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-09-07 20:08:27 -03:00
f1cce7e223 Bump tree-kill from 1.2.1 to 1.2.2 (#2348)
Bumps [tree-kill](https://github.com/pkrumins/node-tree-kill) from 1.2.1 to 1.2.2.
- [Release notes](https://github.com/pkrumins/node-tree-kill/releases)
- [Commits](https://github.com/pkrumins/node-tree-kill/compare/v1.2.1...v1.2.2)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-09-07 20:08:01 -03:00
f2fb8cf23b 3.2.0-rc.0 2020-09-03 16:26:55 -03:00
9f900f6dba Add changelog entries for proxies and ERC20Snapshot 2020-09-03 14:20:42 -03:00
91f16a7e47 Adapt proxies to Contracts conventions (#2345) 2020-09-03 13:49:47 -03:00
6bc2ae3731 Add documentation for proxies (#2344) 2020-09-02 20:19:54 -03:00
885b76f66f Fix AsciiDoc missing attribute references 2020-09-01 18:48:43 -03:00
ded2b0a55c Fix minor typos and grammar in docs (#2338)
* Fix typos and formatting

* Add Solidity release dates: releases-stability
2020-09-01 15:19:17 -03:00
0f08b1d099 Update dependency mocha to v8.1.3 (#2340)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-09-01 15:10:54 -03:00
aaa5ef81cf Fix typos (#2343) 2020-09-01 14:57:40 -03:00
cb791a1b21 Add Proxies from OpenZeppelin SDK (#2335) 2020-08-27 21:02:42 -03:00
0b489f4d79 Improve test descriptions #1157 (#2334)
Co-authored-by: Paolo Dibitonto <p.dibitonto@almaviva.it>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-08-25 14:58:45 -03:00
c187517395 fix solhint func-visibility for 0.7.0 2020-08-24 18:20:50 -03:00
89e2b7424b Merge branch 'master' into solc-0.7 2020-08-24 18:14:25 -03:00
1f06fd7e66 Update all non-major dependencies (#2317)
* Update all non-major dependencies

* disable solhint reason-string rule

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-08-24 18:00:34 -03:00
e5da0986bb Fix code style parameters in Event (#2324)
* chore: fix code style parameters in Event

* chore: update code style for events
2020-08-19 11:23:36 -03:00
0fc9578fe6 Merge CODE_STYLE.md into GUIDELINES.md (#2330) 2020-08-18 20:57:49 -03:00
b1ea59e814 Improve testing for ERC20Snapshot (#2331) 2020-08-18 20:40:51 -03:00
7d48d79b53 Fixed sidebar reference in README.md (#2329) 2020-08-18 12:50:35 -03:00
6d5a73815d Fix ERC20Snapshot#_beforeTokenTransfer (#2328) 2020-08-14 11:59:20 -03:00
d1f336d8fd use svg logo for better scaling 2020-08-12 20:51:33 -03:00
48072e439d Fix function state mutability warning (#2327)
Changes state mutability of granularity function from view to pure.
2020-08-12 16:06:21 -03:00
9700e6b4bd Use beforeTokenTransfer hook in ERC20Snapshot (#2312) 2020-08-11 16:51:58 -03:00
722879b32d increase mocha timeout 2020-08-11 16:45:44 -03:00
943a663a31 Updated ERC1155 tests (#2107)
Co-authored-by: Alan Lu <alanlu1023@gmail.com>
Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-08-11 16:42:51 -03:00
2acb1abb1f 3.1.0-solc-0.7 2020-07-30 17:04:48 -03:00
4eb8d2bb10 Revert "feat: use extcodesize for isContract to reduce gas (#2311)"
This reverts commit c801c8d2bb.
2020-07-30 16:53:44 -03:00
04fc35707d Migrate contracts to Solidity 0.7 (#2319)
* Update contract pragmas to solidity 0.7

* Remove internal declaration on constructors

* Reference SafeMath explicitely

* Remove public constructor declaration from abstract contracts

* Remove public constructor declaration from non-abstract contracts
2020-07-29 18:11:32 -03:00
09014f90f9 Remove acronym from Readme 2020-07-24 12:52:40 -03:00
0c667ca32a docs: add note explaining opinionated presets (#2313)
* docs: add notes explaining presets

* fix links for mint function

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-07-21 19:04:21 -03:00
7c4a2a0a29 Fix comment reference for function hash (#2307)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-07-21 17:06:36 -03:00
c801c8d2bb feat: use extcodesize for isContract to reduce gas (#2311)
* feat: use extcodesize for isContract to reduce gas

* feat: add changelog entry
2020-07-14 17:08:41 -03:00
98e862e162 Update all non-major dependencies (#2309)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-07-13 14:39:19 -03:00
b9d72d2991 Clean up build directory when publishing 2020-07-07 21:15:26 -03:00
c6612871fb Fix remaining preset links 2020-07-01 17:37:25 -03:00
b991fca341 Fix presets link 2020-07-01 12:25:05 -03:00
ef3bbbcf40 Add readme notices with link to docs site (#2300)
* add readme notices

* remove period after url
2020-06-29 17:23:53 -03:00
32f0fe5d08 Add to ERC1155 doc and minor fixes (#2282)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-06-25 14:28:50 -03:00
6d987f1418 Merge branch 'release-v3.1.0' 2020-06-23 16:10:59 -03:00
de99bccbfd 3.1.0 2020-06-23 16:09:01 -03:00
0cc882ef9d typo fix: forwared -> forwarded (#2290) 2020-06-23 14:25:30 -03:00
3f4420527b Separate mapping keyword by whitespace (#2287)
Co-authored-by: pm_468 <oleg.kuzmenko@lindenvalley.de>
2020-06-19 11:00:05 -03:00
21d06999f6 delete dependabot config 2020-06-16 19:40:06 -03:00
f3803d3a5d Bump mocha from 7.2.0 to 8.0.1 (#2280)
Bumps [mocha](https://github.com/mochajs/mocha) from 7.2.0 to 8.0.1.
- [Release notes](https://github.com/mochajs/mocha/releases)
- [Changelog](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mochajs/mocha/compare/v7.2.0...v8.0.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-06-16 15:48:42 -03:00
c6da044dc5 Update ERC20 Supply guide (#2276)
* update for ERC20PresetMinterPauser

* fix erc20 supply guide to use hooks
2020-06-12 20:20:33 -03:00
02a6b05bde Update functionCall docs
(cherry picked from commit 242400e9ea)
2020-06-12 13:23:07 -03:00
242400e9ea Update functionCall docs 2020-06-12 13:22:52 -03:00
8c1daaab57 3.1.0-rc.0 2020-06-11 16:53:19 -03:00
7f62c8e145 Fix docs links to overloaded functions (#2275)
* fix links to overloaded functions

* fix Address xrefs

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-06-11 16:50:00 -03:00
e2876b947d Fix docs link 2020-06-11 16:49:14 -03:00
ed3a513f86 Fix broken links 2020-06-11 16:48:00 -03:00
b72088a90a Add 'available since' notices 2020-06-11 16:46:33 -03:00
8b58fc7191 feat: add wrapper function for low level calls (#2264)
* feat: add wrapper function for low level calls

* add error message parameter

* adding unit tests and required mocks

* implement error message on SafeERC20

* fixed variable name in tests

* Add missing tests

* Improve docs.

* Add functionCallWithValue

* Add functionCallWithValue

* Skip balance check on non-value functionCall variants

* Increase out of gas test timeout

* Fix compile errors

* Apply suggestions from code review

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

* Add missing tests

* Add changelog entry

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-06-11 16:25:46 -03:00
d9fa59f30a Address ERC1155 changes (#2267)
* Make holder fns public

* Add context, remove msg.sender from check

* Fix location of Holder arguments

* Add beforeTransfer hook

* Minor test improvements

* Add ERC1155Burnable and tests

* Add ERC1155Pausable

* Add ERC1155PresetMinterPauser.sol

* Add uri constructors

* Improved revert reasons

* Initial docs improvements

* Add missing docs

* Improve acceptance checks revert reasons

* Apply suggestions from code review

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

* Remove note about 1155 preset uri in mint

* Add rquirements to balanceOfBatch

* Add note about URI and uri

* Fix list in docs

* Fix lint errors

* Use natural sorting for API titles

* Fix doc references

* Escape {id} references to remove docgen warnings

* Added intro docs, fixed links

* Apply suggestions from code review

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>

* Add changelog entry

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-06-09 14:47:51 -03:00
13e2132b69 docs: minor - spelling, grammar (#2273) 2020-06-09 13:18:38 -03:00
298e1b5fdc Merge branch 'release-v3.0.0' 2020-06-08 13:14:15 -03:00
82769e54c3 Fix 721 preset docs 2020-06-05 19:26:40 -03:00
022f2bc177 Improve SignedSafeMath docs 2020-06-05 18:42:28 -03:00
ccf79ee483 Fix SafeMath docs 2020-06-05 18:42:28 -03:00
ecf0725dd1 Documentation/erc721 contracts (#2218)
* Adds / Updates documentation of ERC721 contract

* Improve ERC721Burnable documentation

* Fix typo

* Revert changes on ERC721 private functions

* Add documentation to the ERC721 contract's constructor

* Add IERC721Receiver & ERC721Holder documentations

* Add references to IERC721 functions

* Add references to IERC721Metadata/Receiver

* PR fixes

* Fixes to ERC721 documentation

* Add missing fixes

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-06-05 14:29:06 -03:00
d3ef93a9a5 Deprecate SafeERC20.safeApprove (#2268)
* Deprecate SafeERC20.safeApprove

* Add changelog entry
2020-06-05 14:13:53 -03:00
47a7a575e8 [Security] Bump websocket-extensions from 0.1.3 to 0.1.4 (#2269)
Bumps [websocket-extensions](https://github.com/faye/websocket-extensions-node) from 0.1.3 to 0.1.4. **This update includes a security fix.**
- [Release notes](https://github.com/faye/websocket-extensions-node/releases)
- [Changelog](https://github.com/faye/websocket-extensions-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/faye/websocket-extensions-node/compare/0.1.3...0.1.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-06-05 14:12:27 -03:00
ff8fe4be7e [Security] Bump acorn from 6.4.0 to 6.4.1 (#2270)
Bumps [acorn](https://github.com/acornjs/acorn) from 6.4.0 to 6.4.1. **This update includes security fixes.**
- [Release notes](https://github.com/acornjs/acorn/releases)
- [Commits](https://github.com/acornjs/acorn/compare/6.4.0...6.4.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-06-05 14:12:10 -03:00
d7a6e7be2e Feature/uint enumerable set tests #2253 (#2254)
* feature: setting sublevel test scenario for AddressSet

* feat: adding tests for EnumerableSet.UintSet

* feat: adding Behavior and AddressSet and UintSet tests
2020-06-04 14:57:35 -03:00
a81e948fc9 Add a simple catch-all implementation of the metadata URI interface (#2029)
* Initial ERC1155 implementation with some tests (#1803)

* Initial ERC1155 implementation with some tests

* Remove mocked isERC1155TokenReceiver

* Revert reason edit nit

* Remove parameters associated with isERC1155TokenReceiver call

* Add tests for approvals and single transfers

* Add tests for transferring to contracts

* Add tests for batch transfers

* Make expectEvent.inTransaction tests async

* Renamed "owner" to "account" and "holder"

* Document unspecified balanceOfBatch reversion on zero behavior

* Ensure accounts can't set their own operator status

* Specify descriptive messages for underflow errors

* Bring SafeMath.add calls in line with OZ style

* Explicitly prevent _burn on the zero account

* Implement batch minting/burning

* Refactored operator approval check into isApprovedForAll calls

* Renamed ERC1155TokenReceiver to ERC1155Receiver

* Added ERC1155Holder

* Fix lint issues

* Migrate tests to @openzeppelin/test-environment

* port ERC1155 to Solidity 0.6

* make ERC1155 constructor more similar to ERC721 one

* also migrate mock contracts to Solidity 0.6

* mark all non-view functions as virtual

* add simple catch-all implementation for the metadata URI interface

* include an internal function to set the URI so users can implement functionality to switch URIs

* add tests for ERC1155 metadata URI

* fix nits, mostly pointed out by linter

* convert ERC1155 metadata URI work to Solidity 0.6

* mark all non-view functions as virtual

* Port ERC 1155 branch to Solidity 0.6 (and current master) (#2130)

* port ERC1155 to Solidity 0.6

* make ERC1155 constructor more similar to ERC721 one

* also migrate mock contracts to Solidity 0.6

* mark all non-view functions as virtual

* Update contracts/token/ERC1155/IERC1155MetadataURI.sol

Starting on Solidity v0.6.2, interfaces can now inherit. \o/

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>

* Fix compile errors

* Remove URI event

* Merge MetadataCatchAll into ERC1155

* Improve documentation.

* Simplify tests

* Move tests into ERC1155 tests

* Update documentation

* Bump minimum compiler version for inteface inheritance

* Fix holder tests

* Improve setUri docs

* Fix docs generation

Co-authored-by: Alan Lu <alanlu1023@gmail.com>
Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-06-03 11:56:58 -03:00
ccfd370b89 Update Test Helpers to 0.5.6 (#2261)
* update test-helpers to 0.5.6-rc.0

* remove comment that no longer applies

* fix uses of expectEvent.notEmitted

* remove mocha only

* update to final version

* Update test/token/ERC777/ERC777.test.js

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-06-02 17:00:56 -03:00
91516b2318 Allow overriding of ERC1155 functions (#2263)
* Make receiver functions private

* Make external functions public
2020-06-02 15:06:34 -03:00
52f7b6e03b Remove TokenVesting reference from Timelock docs (#2262) 2020-06-02 13:32:14 -03:00
64ab594ad6 Modify token presets "mint" function as virtual to allow extending (#2257)
* Modify token presets "mint" function as virtual to allow extending in parent contracts

* Update ERC20PresetMinterPauser.sol

* Update ERC721PresetMinterPauserAutoId.sol

* Update CHANGELOG.md

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-06-01 17:17:32 -03:00
394987f365 Fix ERC777 hook docs, fixes #2256 2020-06-01 13:17:15 -03:00
df4b317fb3 Update start docs command line (#2255) 2020-06-01 11:53:04 -03:00
142f6c3f05 configure renovate to run weekly 2020-05-30 23:15:48 -03:00
414adb94f0 Update dependency ethereumjs-util to v7.0.2 (#2250)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2020-05-29 17:01:43 -03:00
7ee98cf525 Configure Renovate (#2248)
* Add renovate.json

* configure renovatebot

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-05-29 16:43:57 -03:00
d418da6b91 Decrease CREATE2 address computation gas usage from 623 to 539 (#2244)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-05-28 20:47:45 -03:00
2a0f2a8ba8 Update LICENSE (#2247)
bump to 2020 reference for (c)
2020-05-28 19:15:43 -03:00
5513dfd3cf Adding SafeCast variants for signed integers (#2243)
* feat: Adding SafeCast variants for signed integers

* Add newline at EOF

* Update CHANGELOG.md

* Update contracts/utils/SafeCast.sol

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-05-26 19:17:34 -03:00
c18ffd7c81 Bump mocha from 7.1.2 to 7.2.0 (#2245)
Bumps [mocha](https://github.com/mochajs/mocha) from 7.1.2 to 7.2.0.
- [Release notes](https://github.com/mochajs/mocha/releases)
- [Changelog](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mochajs/mocha/compare/v7.1.2...v7.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-05-26 18:09:17 -03:00
424ab2a024 Update SafeERC20.sol (#2246)
tweak intro dev comment to reflect more typical use case, wrapping an `IERC20` reference for a deposit contract using others' ERC-20 tokens. I might be mistaken ~ but typically SafeERC20 won't be used in conjunction with ERC20 for OZ token deployments?
2020-05-26 13:39:54 -03:00
e2b97d6712 Update readme to reflect docsite, fixes #2168 2020-05-19 13:54:11 -03:00
217a616fde Bump ethereumjs-util from 7.0.0 to 7.0.1 (#2238)
Bumps [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util) from 7.0.0 to 7.0.1.
- [Release notes](https://github.com/ethereumjs/ethereumjs-util/releases)
- [Changelog](https://github.com/ethereumjs/ethereumjs-util/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ethereumjs/ethereumjs-util/compare/v7.0.0...v7.0.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-05-18 15:53:38 -03:00
56de324afe Add SPX license identifier (#2235) 2020-05-14 21:58:11 -03:00
fa36244bec separate prepare and prepack scripts to fix CI 2020-05-13 17:28:13 -03:00
4fe31f8d4d Fixed typo in ERC20PresetMinterPauser (#2233)
* Fixed typo in ERC20PresetMinterPauser

* Update ERC721PresetMinterPauserAutoId.sol

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-05-13 13:26:16 -03:00
cfa9ad9943 Fix ReentrancyGuard for Proxy Pattern (#2171)
* Fix ReentrancyGuard for Proxy Pattern

* Update ReentrancyGuard.sol

* Change constant values

* Add changelog entry

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-05-12 20:23:28 -03:00
fd981ad315 fix removal of mocks from published package 2020-05-12 17:36:16 -03:00
5f9a86a8f2 Remove leftovers of TokenVesting contract 2020-05-08 17:04:22 -03:00
956d6632d9 ERC1155 feature pending tasks (#2014)
* Initial ERC1155 implementation with some tests (#1803)

* Initial ERC1155 implementation with some tests

* Remove mocked isERC1155TokenReceiver

* Revert reason edit nit

* Remove parameters associated with isERC1155TokenReceiver call

* Add tests for approvals and single transfers

* Add tests for transferring to contracts

* Add tests for batch transfers

* Make expectEvent.inTransaction tests async

* Renamed "owner" to "account" and "holder"

* Document unspecified balanceOfBatch reversion on zero behavior

* Ensure accounts can't set their own operator status

* Specify descriptive messages for underflow errors

* Bring SafeMath.add calls in line with OZ style

* Explicitly prevent _burn on the zero account

* Implement batch minting/burning

* Refactored operator approval check into isApprovedForAll calls

* Renamed ERC1155TokenReceiver to ERC1155Receiver

* Added ERC1155Holder

* Fix lint issues

* Migrate tests to @openzeppelin/test-environment

* Port ERC 1155 branch to Solidity 0.6 (and current master) (#2130)

* port ERC1155 to Solidity 0.6

* make ERC1155 constructor more similar to ERC721 one

* also migrate mock contracts to Solidity 0.6

* mark all non-view functions as virtual

Co-authored-by: Alan Lu <alanlu1023@gmail.com>
Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
Co-authored-by: Robert Kaiser <kairo@kairo.at>
2020-05-08 13:38:43 -03:00
0c7b2ec09e Make Context abstract (#2229) 2020-05-08 13:02:07 -03:00
4cbcaf35e4 Fix linter errors 2020-05-08 12:57:43 -03:00
73baf0b635 Feature/Adding RoleAdminChanged event in AccessControl (#2214)
* Emit new event RoleAdminChanged

* Adding new RoleAdminChanged event in Tests

* Update suggested comments on new Event

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>

* Adding PreviousAdminRole to event

* Update AccessControl.test.js

* Update CHANGELOG.md

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-05-06 17:21:39 -03:00
78dc37739f Making IERC721Receiver an interface (#2225)
* Making IERC721Receiver an interface

* Update IERC721Receiver.sol

Co-authored-by: Nicolás Venturo <nicolas.venturo@gmail.com>
2020-05-06 16:47:53 -03:00
ac0a4327a9 Bump solidity-docgen from 0.4.1 to 0.5.3 (#2221)
* Bump solidity-docgen from 0.4.1 to 0.5.3

Bumps solidity-docgen from 0.4.1 to 0.5.3.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

* Update prepare-docs.sh

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-05-04 17:14:12 -03:00
c20e620a06 Improve Pausable docs 2020-05-04 16:37:05 -03:00
4bc45e35c2 [Security] Bump acorn from 6.4.0 to 6.4.1 (#2224)
Bumps [acorn](https://github.com/acornjs/acorn) from 6.4.0 to 6.4.1. **This update includes security fixes.**
- [Release notes](https://github.com/acornjs/acorn/releases)
- [Commits](https://github.com/acornjs/acorn/compare/6.4.0...6.4.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-05-04 15:04:48 -03:00
b362e886ec Bump ethereumjs-util from 6.2.0 to 7.0.0 (#2222)
* Bump ethereumjs-util from 6.2.0 to 7.0.0

Bumps [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util) from 6.2.0 to 7.0.0.
- [Release notes](https://github.com/ethereumjs/ethereumjs-util/releases)
- [Changelog](https://github.com/ethereumjs/ethereumjs-util/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ethereumjs/ethereumjs-util/compare/v6.2.0...v7.0.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

* update use of ethereumjs-util

* fix use of keccak hash function

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2020-05-04 14:55:16 -03:00
ca38899ede Upgrade solhint to 3.0 (#2223) 2020-05-04 14:49:41 -03:00
61973af29f Remove misleading SafeMath comment 2020-04-28 12:46:32 -03:00
433 changed files with 55138 additions and 36723 deletions

View File

@ -1,84 +0,0 @@
version: 2
# 2.1 does not yet support local run
# unless with workaround. For simplicity just use it.
# https://github.com/CircleCI-Public/circleci-cli/issues/79
aliases:
- &defaults
docker:
- image: circleci/node:10
- &cache_key_node_modules
key: v1-node_modules-{{ checksum "package-lock.json" }}
jobs:
dependencies:
<<: *defaults
steps:
- checkout
- restore_cache:
<<: *cache_key_node_modules
- 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
<<: *cache_key_node_modules
lint:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: .
- run:
name: Linter
command: npm run lint
test:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: .
- run:
name: Unit tests
command: npm run test
coverage:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: .
- run:
name: Unit tests with coverage report
command: npm run coverage
# TODO(xinbenlv, #1839): run SOLC_NIGHTLY to be run but allow it to fail.
workflows:
version: 2
everything:
jobs:
- dependencies
- lint:
requires:
- dependencies
- test:
requires:
- dependencies
- coverage:
requires:
- dependencies

View File

@ -1,3 +1,11 @@
comment: off
github_checks:
annotations: false
coverage:
range: "100...100"
status:
patch:
default:
target: 95%
project:
default:
threshold: 1%

View File

@ -1,7 +0,0 @@
version: 1
update_configs:
- package_manager: "javascript"
directory: "/"
update_schedule: "weekly"
version_requirement_updates: "increase_versions"

View File

@ -8,7 +8,7 @@ charset = utf-8
end_of_line = lf
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
trim_trailing_whitespace = false
max_line_length = 120
[*.sol]
@ -16,3 +16,6 @@ indent_size = 4
[*.js]
indent_size = 2
[*.adoc]
max_line_length = 0

View File

@ -18,6 +18,8 @@
"contract": false,
"assert": false,
"web3": false,
"usePlugin": false,
"extendEnvironment": false,
},
"rules": {

View File

@ -10,5 +10,5 @@ about: Suggest an idea for OpenZeppelin Contracts
**📝 Details**
<!-- Please describe your feature request in detail. -->
<!-- Make sure that you have reviewed the OpenZeppelin Contributor Guidelines. -->
<!-- Make sure that you have reviewed the OpenZeppelin Contracts Contributor Guidelines. -->
<!-- https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CONTRIBUTING.md -->

View File

@ -1,22 +1,20 @@
<!-- 0. 🎉 Thank you for submitting a PR! -->
<!-- Thank you for your interest in contributing to OpenZeppelin! -->
<!-- 1. Does this close any open issues? Please list them below. -->
<!-- Consider opening an issue for discussion prior to submitting a PR. -->
<!-- New features will be merged faster if they were first discussed and designed with the team. -->
<!-- Keep in mind that new features have a better chance of being merged fast if
they were first discussed and designed with the maintainers. If there is no
corresponding issue, please consider opening one for discussion first! -->
Fixes #???? <!-- Fill in with issue number -->
Fixes #
<!-- Describe the changes introduced in this pull request. -->
<!-- Include any context necessary for understanding the PR's purpose. -->
<!-- 2. Describe the changes introduced in this pull request. -->
<!-- Include any context necessary for understanding the PR's purpose. -->
<!-- 3. Before submitting, please make sure that you have:
- reviewed the OpenZeppelin Contributor Guidelines
(https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CONTRIBUTING.md),
- added tests where applicable to test new functionality,
- made sure that your contracts are well-documented,
- run the Solidity linter (`npm run lint:sol`) and fixed any issues,
- run the JS linter and fixed any issues (`npm run lint:fix`), and
- updated the changelog, if applicable.
-->
#### PR Checklist
<!-- Before merging the pull request all of the following must be complete. -->
<!-- Feel free to submit a PR or Draft PR even if some items are pending. -->
<!-- Some of the items may not apply. -->
- [ ] Tests
- [ ] Documentation
- [ ] Changelog entry

67
.github/stale.yml vendored
View File

@ -1,67 +0,0 @@
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 15
# Number of days of inactivity before an Issue or Pull Request with the stale label is closed.
# Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale.
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
# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: false
# Set to true to ignore issues with an assignee (defaults to false)
exemptAssignees: false
# Label to use when marking as stale
staleLabel: stale
# Comment to post when marking as stale. Set to `false` to disable
markComment: >
Hi all!
This Pull Request has not had any recent activity, is it still relevant? If so, what is blocking it?
Is there anything we can do to help move it forward?
Thanks!
# Comment to post when removing the stale label.
# unmarkComment: >
# Your comment here.
# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
Hi folks!
This Pull Request is being closed as there was no response to the previous prompt.
However, please leave a comment whenever you're ready to resume, so it can be reopened.
Thanks again!
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30
# Limit to only `issues` or `pulls`
only: pulls
# Optionally, specify configuration settings that are specific to just 'issues' or 'pulls':
# pulls:
# daysUntilStale: 30
# markComment: >
# This pull request has been automatically marked as stale because it has not had
# recent activity. It will be closed if no further activity occurs. Thank you
# for your contributions.
# issues:
# exemptLabels:
# - confirmed

56
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,56 @@
name: Test
on:
push:
branches:
- master
- release-v*
pull_request: {}
workflow_dispatch: {}
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12.x
- uses: actions/cache@v2
id: cache
with:
path: '**/node_modules'
key: npm-v2-${{ hashFiles('**/package-lock.json') }}
restore-keys: npm-v2-
- run: npm ci
if: steps.cache.outputs.cache-hit != 'true'
- run: npm run lint
- run: npm run test
env:
FORCE_COLOR: 1
ENABLE_GAS_REPORT: true
- run: npm run test:inheritance
- name: Print gas report
run: cat gas-report.txt
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 2
- uses: actions/setup-node@v2
with:
node-version: 12.x
- uses: actions/cache@v2
id: cache
with:
path: '**/node_modules'
key: npm-v2-${{ hashFiles('**/package-lock.json') }}
restore-keys: npm-v2-
- run: npm ci
if: steps.cache.outputs.cache-hit != 'true'
- run: npm run coverage
env:
NODE_OPTIONS: --max_old_space_size=4096
- uses: codecov/codecov-action@v2

23
.github/workflows/upgradeable.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: Upgradeable Trigger
on:
push:
branches:
- master
- release-v*
jobs:
trigger:
runs-on: ubuntu-latest
steps:
- id: app
uses: getsentry/action-github-app-token@v1
with:
app_id: ${{ secrets.UPGRADEABLE_APP_ID }}
private_key: ${{ secrets.UPGRADEABLE_APP_PK }}
- run: |
curl -X POST \
https://api.github.com/repos/OpenZeppelin/openzeppelin-contracts-upgradeable/dispatches \
-H 'Accept: application/vnd.github.v3+json' \
-H 'Authorization: token ${{ steps.app.outputs.token }}' \
-d '{ "event_type": "Update", "client_payload": { "ref": "${{ github.ref }}" } }'

7
.gitignore vendored
View File

@ -50,3 +50,10 @@ contracts/README.md
# temporary artifact from solidity-coverage
allFiredEvents
.coverage_artifacts
.coverage_cache
.coverage_contracts
# hardhat
cache
artifacts

4
.mocharc.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
require: 'hardhat/register',
timeout: 4000,
};

11
.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 120,
"explicitTypes": "always"
}
}
]
}

View File

@ -4,5 +4,12 @@ module.exports = {
compileCommand: 'npm run compile',
skipFiles: [
'mocks',
]
],
providerOptions: {
default_balance_ether: '10000000000000000000000000',
},
mocha: {
fgrep: '[skip-on-coverage]',
invert: true,
},
}

View File

@ -1,10 +1,14 @@
{
"extends": "solhint:recommended",
"rules": {
"func-order": "off",
"mark-callable-contracts": "off",
"no-empty-blocks": "off",
"compiler-version": ["error", "^0.6.0"],
"private-vars-leading-underscore": "error"
"no-unused-vars": "error",
"const-name-snakecase": "error",
"contract-name-camelcase": "error",
"event-name-camelcase": "error",
"func-name-mixedcase": "error",
"func-param-name-mixedcase": "error",
"modifier-name-mixedcase": "error",
"private-vars-leading-underscore": "error",
"var-name-mixedcase": "error",
"imports-on-top": "error"
}
}

View File

@ -1,5 +1,186 @@
# Changelog
## 4.3.3 (2021-11-11)
* `ERC1155Supply`: Handle `totalSupply` changes by hooking into `_beforeTokenTransfer` to ensure consistency of balances and supply during `IERC1155Receiver.onERC1155Received` calls.
## 4.3.2 (2021-09-14)
* `UUPSUpgradeable`: Add modifiers to prevent `upgradeTo` and `upgradeToAndCall` being executed on any contract that is not the active ERC1967 proxy. This prevents these functions being called on implementation contracts or minimal ERC1167 clones, in particular.
## 4.3.1 (2021-08-26)
* `TimelockController`: Add additional isOperationReady check.
## 4.3.0 (2021-08-17)
* `ERC2771Context`: use private variable from storage to store the forwarder address. Fixes issues where `_msgSender()` was not callable from constructors. ([#2754](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2754))
* `EnumerableSet`: add `values()` functions that returns an array containing all values in a single call. ([#2768](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2768))
* `Governor`: added a modular system of `Governor` contracts based on `GovernorAlpha` and `GovernorBravo`. ([#2672](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2672))
* Add an `interfaces` folder containing solidity interfaces to final ERCs. ([#2517](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2517))
* `ECDSA`: add `tryRecover` functions that will not throw if the signature is invalid, and will return an error flag instead. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661))
* `SignatureChecker`: Reduce gas usage of the `isValidSignatureNow` function for the "signature by EOA" case. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661))
## 4.2.0 (2021-06-30)
* `ERC20Votes`: add a new extension of the `ERC20` token with support for voting snapshots and delegation. ([#2632](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2632))
* `ERC20VotesComp`: Variant of `ERC20Votes` that is compatible with Compound's `Comp` token interface but restricts supply to `uint96`. ([#2706](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2706))
* `ERC20Wrapper`: add a new extension of the `ERC20` token which wraps an underlying token. Deposit and withdraw guarantee that the total supply is backed by a corresponding amount of underlying token. ([#2633](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2633))
* Enumerables: Improve gas cost of removal in `EnumerableSet` and `EnumerableMap`.
* Enumerables: Improve gas cost of lookup in `EnumerableSet` and `EnumerableMap`.
* `Counter`: add a reset method. ([#2678](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2678))
* Tokens: Wrap definitely safe subtractions in `unchecked` blocks.
* `Math`: Add a `ceilDiv` method for performing ceiling division.
* `ERC1155Supply`: add a new `ERC1155` extension that keeps track of the totalSupply of each tokenId. ([#2593](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2593))
* `BitMaps`: add a new `BitMaps` library that provides a storage efficient datastructure for `uint256` to `bool` mapping with contiguous keys. ([#2710](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2710))
### Breaking Changes
* `ERC20FlashMint` is no longer a Draft ERC. ([#2673](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2673)))
**How to update:** Change your import paths by removing the `draft-` prefix from `@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20FlashMint.sol`.
> See [Releases and Stability: Drafts](https://docs.openzeppelin.com/contracts/4.x/releases-stability#drafts).
## 4.1.0 (2021-04-29)
* `IERC20Metadata`: add a new extended interface that includes the optional `name()`, `symbol()` and `decimals()` functions. ([#2561](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2561))
* `ERC777`: make reception acquirement optional in `_mint`. ([#2552](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2552))
* `ERC20Permit`: add a `_useNonce` to enable further usage of ERC712 signatures. ([#2565](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2565))
* `ERC20FlashMint`: add an implementation of the ERC3156 extension for flash-minting ERC20 tokens. ([#2543](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2543))
* `SignatureChecker`: add a signature verification library that supports both EOA and ERC1271 compliant contracts as signers. ([#2532](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2532))
* `Multicall`: add abstract contract with `multicall(bytes[] calldata data)` function to bundle multiple calls together ([#2608](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2608))
* `ECDSA`: add support for ERC2098 short-signatures. ([#2582](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2582))
* `AccessControl`: add a `onlyRole` modifier to restrict specific function to callers bearing a specific role. ([#2609](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2609))
* `StorageSlot`: add a library for reading and writing primitive types to specific storage slots. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542))
* UUPS Proxies: add `UUPSUpgradeable` to implement the UUPS proxy pattern together with `EIP1967Proxy`. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542))
### Breaking changes
This release includes two small breaking changes in `TimelockController`.
1. The `onlyRole` modifier in this contract was designed to let anyone through if the role was granted to `address(0)`,
allowing the possibility to to make a role "open", which can be used for `EXECUTOR_ROLE`. This modifier is now
replaced by `AccessControl.onlyRole`, which does not have this ability. The previous behavior was moved to the
modifier `TimelockController.onlyRoleOrOpenRole`.
2. It was possible to make `PROPOSER_ROLE` an open role (as described in the previous item) if it was granted to
`address(0)`. This would affect the `schedule`, `scheduleBatch`, and `cancel` operations in `TimelockController`.
This ability was removed as it does not make sense to open up the `PROPOSER_ROLE` in the same way that it does for
`EXECUTOR_ROLE`.
## 4.0.0 (2021-03-23)
* Now targeting the 0.8.x line of Solidity compilers. For 0.6.x (resp 0.7.x) support, use version 3.4.0 (resp 3.4.0-solc-0.7) of OpenZeppelin.
* `Context`: making `_msgData` return `bytes calldata` instead of `bytes memory` ([#2492](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2492))
* `ERC20`: removed the `_setDecimals` function and the storage slot associated to decimals. ([#2502](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2502))
* `Strings`: addition of a `toHexString` function. ([#2504](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2504))
* `EnumerableMap`: change implementation to optimize for `key → value` lookups instead of enumeration. ([#2518](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2518))
* `GSN`: deprecate GSNv1 support in favor of upcoming support for GSNv2. ([#2521](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2521))
* `ERC165`: remove uses of storage in the base ERC165 implementation. ERC165 based contracts now use storage-less virtual functions. Old behavior remains available in the `ERC165Storage` extension. ([#2505](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2505))
* `Initializable`: make initializer check stricter during construction. ([#2531](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2531))
* `ERC721`: remove enumerability of tokens from the base implementation. This feature is now provided separately through the `ERC721Enumerable` extension. ([#2511](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2511))
* `AccessControl`: removed enumerability by default for a more lightweight contract. It is now opt-in through `AccessControlEnumerable`. ([#2512](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2512))
* Meta Transactions: add `ERC2771Context` and a `MinimalForwarder` for meta-transactions. ([#2508](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2508))
* Overall reorganization of the contract folder to improve clarity and discoverability. ([#2503](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2503))
* `ERC20Capped`: optimize gas usage by enforcing the check directly in `_mint`. ([#2524](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2524))
* Rename `UpgradeableProxy` to `ERC1967Proxy`. ([#2547](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2547))
* `ERC777`: optimize the gas costs of the constructor. ([#2551](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2551))
* `ERC721URIStorage`: add a new extension that implements the `_setTokenURI` behavior as it was available in 3.4.0. ([#2555](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2555))
* `AccessControl`: added ERC165 interface detection. ([#2562](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2562))
* `ERC1155`: make `uri` public so overloading function can call it using super. ([#2576](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2576))
### Bug fixes for beta releases
* `AccessControlEnumerable`: Fixed `renounceRole` not updating enumerable set of addresses for a role. ([#2572](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2572))
### How to upgrade from 3.x
Since this version has moved a few contracts to different directories, users upgrading from a previous version will need to adjust their import statements. To make this easier, the package includes a script that will migrate import statements automatically. After upgrading to the latest version of the package, run:
```
npx openzeppelin-contracts-migrate-imports
```
Make sure you're using git or another version control system to be able to recover from any potential error in our script.
### How to upgrade from 4.0-beta.x
Some further changes have been done between the different beta iterations. Transitions made during this period are configured in the `migrate-imports` script. Consequently, you can upgrade from any previous 4.0-beta.x version using the same script as described in the *How to upgrade from 3.x* section.
## 3.4.0 (2021-02-02)
* `BeaconProxy`: added new kind of proxy that allows simultaneous atomic upgrades. ([#2411](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2411))
* `EIP712`: added helpers to verify EIP712 typed data signatures on chain. ([#2418](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2418))
* `ERC20Permit`: added an implementation of the ERC20 permit extension for gasless token approvals. ([#2237](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237))
* Presets: added token presets with preminted fixed supply `ERC20PresetFixedSupply` and `ERC777PresetFixedSupply`. ([#2399](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2399))
* `Address`: added `functionDelegateCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333))
* `Clones`: added a library for deploying EIP 1167 minimal proxies. ([#2449](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2449))
* `Context`: moved from `contracts/GSN` to `contracts/utils`. ([#2453](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2453))
* `PaymentSplitter`: replace usage of `.transfer()` with `Address.sendValue` for improved compatibility with smart wallets. ([#2455](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2455))
* `UpgradeableProxy`: bubble revert reasons from initialization calls. ([#2454](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2454))
* `SafeMath`: fix a memory allocation issue by adding new `SafeMath.tryOp(uint,uint)→(bool,uint)` functions. `SafeMath.op(uint,uint,string)→uint` are now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462))
* `EnumerableMap`: fix a memory allocation issue by adding new `EnumerableMap.tryGet(uint)→(bool,address)` functions. `EnumerableMap.get(uint)→string` is now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462))
* `ERC165Checker`: added batch `getSupportedInterfaces`. ([#2469](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2469))
* `RefundEscrow`: `beneficiaryWithdraw` will forward all available gas to the beneficiary. ([#2480](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2480))
* Many view and pure functions have been made virtual to customize them via overrides. In many cases this will not imply that other functions in the contract will automatically adapt to the overridden definitions. People who wish to override should consult the source code to understand the impact and if they need to override any additional functions to achieve the desired behavior.
### Security Fixes
* `ERC777`: fix potential reentrancy issues for custom extensions to `ERC777`. ([#2483](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483))
If you're using our implementation of ERC777 from version 3.3.0 or earlier, and you define a custom `_beforeTokenTransfer` function that writes to a storage variable, you may be vulnerable to a reentrancy attack. If you're affected and would like assistance please write to security@openzeppelin.com. [Read more in the pull request.](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483)
## 3.3.0 (2020-11-26)
* Now supports both Solidity 0.6 and 0.7. Compiling with solc 0.7 will result in warnings. Install the `solc-0.7` tag to compile without warnings.
* `Address`: added `functionStaticCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333))
* `TimelockController`: added a contract to augment access control schemes with a delay. ([#2354](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2354))
* `EnumerableSet`: added `Bytes32Set`, for sets of `bytes32`. ([#2395](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2395))
## 3.2.2-solc-0.7 (2020-10-28)
* Resolve warnings introduced by Solidity 0.7.4. ([#2396](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2396))
## 3.2.1-solc-0.7 (2020-09-15)
* `ERC777`: Remove a warning about function state visibility in Solidity 0.7. ([#2327](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2327))
## 3.2.0 (2020-09-10)
### New features
* Proxies: added the proxy contracts from OpenZeppelin SDK. ([#2335](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2335))
#### Proxy changes with respect to OpenZeppelin SDK
Aside from upgrading them from Solidity 0.5 to 0.6, we've changed a few minor things from the proxy contracts as they were found in OpenZeppelin SDK.
- `UpgradeabilityProxy` was renamed to `UpgradeableProxy`.
- `AdminUpgradeabilityProxy` was renamed to `TransparentUpgradeableProxy`.
- `Proxy._willFallback` was renamed to `Proxy._beforeFallback`.
- `UpgradeabilityProxy._setImplementation` and `AdminUpgradeabilityProxy._setAdmin` were made private.
### Improvements
* `Address.isContract`: switched from `extcodehash` to `extcodesize` for less gas usage. ([#2311](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2311))
### Breaking changes
* `ERC20Snapshot`: switched to using `_beforeTokenTransfer` hook instead of overriding ERC20 operations. ([#2312](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2312))
This small change in the way we implemented `ERC20Snapshot` may affect users who are combining this contract with
other ERC20 flavors, since it no longer overrides `_transfer`, `_mint`, and `_burn`. This can result in having to remove Solidity `override(...)` specifiers in derived contracts for these functions, and to instead have to add it for `_beforeTokenTransfer`. See [Using Hooks](https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks) in the documentation.
## 3.1.0 (2020-06-23)
### New features
* `SafeCast`: added functions to downcast signed integers (e.g. `toInt32`), improving usability of `SignedSafeMath`. ([#2243](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2243))
* `functionCall`: new helpers that replicate Solidity's function call semantics, reducing the need to rely on `call`. ([#2264](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2264))
* `ERC1155`: added support for a base implementation, non-standard extensions and a preset contract. ([#2014](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2014), [#2230](https://github.com/OpenZeppelin/openzeppelin-contracts/issues/2230))
### Improvements
* `ReentrancyGuard`: reduced overhead of using the `nonReentrant` modifier. ([#2171](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2171))
* `AccessControl`: added a `RoleAdminChanged` event to `_setAdminRole`. ([#2214](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2214))
* Made all `public` functions in the token preset contracts `virtual`. ([#2257](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2257))
### Deprecations
* `SafeERC20`: deprecated `safeApprove`. ([#2268](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2268))
## 3.0.2 (2020-06-08)
### Improvements

View File

@ -1,69 +0,0 @@
# Code Style
We value clean code and consistency, and those are prerequisites for us to
include new code in the repository. Before proposing a change, please read this
document and take some time to familiarize yourself with the style of the
existing codebase.
## Solidity code
In order to be consistent with all the other Solidity projects, we follow the
[official recommendations documented in the Solidity style guide](http://solidity.readthedocs.io/en/latest/style-guide.html).
Any exception or additions specific to our project are documented below.
### Naming
* Try to avoid acronyms and abbreviations.
* All state variables should be private.
* Private state variables should have an underscore prefix.
```
contract TestContract {
uint256 private _privateVar;
uint256 internal _internalVar;
}
```
* Parameters must not be prefixed with an underscore.
```
function test(uint256 testParameter1, uint256 testParameter2) {
...
}
```
* Internal and private functions should have an underscore prefix.
```
function _testInternal() internal {
...
}
```
```
function _testPrivate() private {
...
}
```
* Events should be emitted immediately after the state change that they
represent, and consequently they should be named in past tense.
```
function _burn(address _who, uint256 _value) internal {
super._burn(_who, _value);
emit TokensBurned(_who, _value);
}
```
Some standards (e.g. ERC20) use present tense, and in those cases the
standard specification prevails.
* Interface names should have a capital I prefix.
```
interface IERC777 {
```

View File

@ -44,21 +44,14 @@ npm test
npm run lint
```
or you can simply run CircleCI locally
```bash
circleci local execute --job build
circleci local execute --job test
```
*Note*: requires installing CircleCI and docker locally on your machine.
5) Go to [github.com/OpenZeppelin/openzeppelin-contracts](https://github.com/OpenZeppelin/openzeppelin-contracts) in your web browser and issue a new pull request.
*IMPORTANT* Read the PR template very carefully and make sure to follow all the instructions. These instructions
refer to some very important conditions that your PR must meet in order to be accepted, such as making sure that all tests pass, JS linting tests pass, Solidity linting tests pass, etc.
6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin.
6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin Contracts.
*IMPORTANT* Please pay attention to the maintainer's feedback, since its a necessary step to keep up with the standards OpenZeppelin attains to.
*IMPORTANT* Please pay attention to the maintainer's feedback, since its a necessary step to keep up with the standards OpenZeppelin Contracts attains to.
## All set!

View File

@ -10,7 +10,7 @@ program that extracts the API Reference from source code.
The [`docs.openzeppelin.com`](https://github.com/OpenZeppelin/docs.openzeppelin.com)
repository hosts the configuration for the entire site, which includes
documetation for all of the OpenZeppelin projects.
documentation for all of the OpenZeppelin projects.
To run the docs locally you should run `npm run docs start` on this
To run the docs locally you should run `npm run docs:watch` on this
repository.

View File

@ -1,7 +1,7 @@
Design Guidelines
=======
These are some global design goals in OpenZeppelin.
These are some global design goals in OpenZeppelin Contracts.
#### D0 - Security in Depth
We strive to provide secure, tested, audited code. To achieve this, we need to match intention with function. Thus, documentation, code clarity, community review and security discussions are fundamental.
@ -28,37 +28,78 @@ Consistency on the way classes are used is paramount to an easier understanding
#### D6 - Regular Audits
Following good programming practices is a way to reduce the risk of vulnerabilities, but professional code audits are still needed. We will perform regular code audits on major releases, and hire security professionals to provide independent review.
## Style Guidelines
# Style Guidelines
The design guidelines have quite a high abstraction level. These style guidelines are more concrete and easier to apply, and also more opinionated.
The design guidelines have quite a high abstraction level. These style guidelines are more concrete and easier to apply, and also more opinionated. We value clean code and consistency, and those are prerequisites for us to include new code in the repository. Before proposing a change, please read these guidelines and take some time to familiarize yourself with the style of the existing codebase.
### General
## Solidity code
#### G0 - Default to Solidity's official style guide.
In order to be consistent with all the other Solidity projects, we follow the
[official recommendations documented in the Solidity style guide](http://solidity.readthedocs.io/en/latest/style-guide.html).
Follow the official Solidity style guide: https://solidity.readthedocs.io/en/latest/style-guide.html
Any exception or additions specific to our project are documented below.
#### G1 - No Magic Constants
* Try to avoid acronyms and abbreviations.
Avoid constants in the code as much as possible. Magic strings are also magic constants.
* All state variables should be private.
#### G2 - Code that Fails Early
* Private state variables should have an underscore prefix.
We ask our code to fail as soon as possible when an unexpected input was provided or unexpected state was found.
```
contract TestContract {
uint256 private _privateVar;
uint256 internal _internalVar;
}
```
#### G3 - Internal Amounts Must be Signed Integers and Represent the Smallest Units.
* Parameters must not be prefixed with an underscore.
Avoid representation errors by always dealing with weis when handling ether. GUIs can convert to more human-friendly representations. Use Signed Integers (int) to prevent underflow problems.
```
function test(uint256 testParameter1, uint256 testParameter2) {
...
}
```
* Internal and private functions should have an underscore prefix.
```
function _testInternal() internal {
...
}
```
```
function _testPrivate() private {
...
}
```
* Events should be emitted immediately after the state change that they
represent, and consequently they should be named in past tense.
```
function _burn(address who, uint256 value) internal {
super._burn(who, value);
emit TokensBurned(who, value);
}
```
Some standards (e.g. ERC20) use present tense, and in those cases the
standard specification prevails.
* Interface names should have a capital I prefix.
```
interface IERC777 {
```
### Testing
## Tests
#### T1 - Tests Must be Written Elegantly
* Tests Must be Written Elegantly
Style guidelines are not relaxed for tests. Tests are a good way to show how to use the library, and maintaining them is extremely necessary.
Tests are a good way to show how to use the library, and maintaining them is extremely necessary. Don't write long tests, write helper functions to make them be as short and concise as possible (they should take just a few lines each), and use good variable names.
Don't write long tests, write helper functions to make them be as short and concise as possible (they should take just a few lines each), and use good variable names.
* Tests Must not be Random
#### T2 - Tests Must not be Random
Inputs for tests should not be generated randomly. Accounts used to create test contracts are an exception, those can be random. Also, the type and structure of outputs should be checked.
Inputs for tests should not be generated randomly. Accounts used to create test contracts are an exception, those can be random. Also, the type and structure of outputs should be checked.

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Copyright (c) 2016-2020 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@ -1,8 +1,7 @@
# <img src="logo.png" alt="OpenZeppelin" height="40px">
# <img src="logo.svg" alt="OpenZeppelin" height="40px">
[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts)
[![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts)
[![Build Status](https://circleci.com/gh/OpenZeppelin/openzeppelin-contracts.svg?style=shield)](https://circleci.com/gh/OpenZeppelin/openzeppelin-contracts)
[![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts)
**A library for secure smart contract development.** Build on a solid foundation of community-vetted code.
@ -10,8 +9,8 @@
* Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721).
* Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme.
* Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems.
* First-class integration with the [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn) for systems with no gas fees!
* Audited by leading security firms (_last full audit on v2.0.0_).
:mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator.
## Overview
@ -28,13 +27,12 @@ OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/con
Once installed, you can use the contracts in the library by importing them:
```solidity
pragma solidity ^0.5.0;
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Mintable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract MyNFT is ERC721Full, ERC721Mintable {
constructor() ERC721Full("MyNFT", "MNFT") public {
contract MyCollectible is ERC721 {
constructor() ERC721("MyCollectible", "MCO") {
}
}
```
@ -45,7 +43,7 @@ To keep your system secure, you should **always** use the installed code as-is,
## Learn More
The guides in the sidebar will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:
The guides in the [docs site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:
* [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system.
* [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectives, and distribute them via [Crowdsales](https://docs.openzeppelin.com/contracts/crowdsales).
@ -62,18 +60,20 @@ Finally, you may want to take a look at the [guides on our blog](https://blog.op
## Security
This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience.
This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin Contracts is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience.
The core development principles and strategies that OpenZeppelin is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits.
The core development principles and strategies that OpenZeppelin Contracts is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits.
The latest audit was done on October 2018 on version 2.0.0.
Please report any security issues you find to security@openzeppelin.org.
Critical bug fixes will be backported to past major releases.
## Contribute
OpenZeppelin exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)!
OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)!
## License
OpenZeppelin is released under the [MIT License](LICENSE).
OpenZeppelin Contracts is released under the [MIT License](LICENSE).

View File

@ -10,10 +10,10 @@ Publish a release candidate with `npm run release rc`.
Publish the final release with `npm run release final`.
Follow the general [OpenZeppelin release checklist].
Follow the general [OpenZeppelin Contracts release checklist].
[details about release schedule]: https://docs.openzeppelin.com/contracts/releases-stability
[OpenZeppelin release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md
[OpenZeppelin Contracts release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md
## Merging the release branch

18
SECURITY.md Normal file
View File

@ -0,0 +1,18 @@
# Security Policy
## Supported Versions
The recommendation is to use the latest version available.
| Version | Supported |
| ------- | ------------------------------------ |
| 4.x | :white_check_mark::white_check_mark: |
| 3.4 | :white_check_mark: |
| 2.5 | :white_check_mark: |
| < 2.0 | :x: |
## Reporting a Vulnerability
Please report any security issues you find to security@openzeppelin.org.
Critical bug fixes will be backported to past major releases.

View File

@ -1,5 +1,7 @@
# OpenZeppelin Audit
NOTE ON 2021-07-19: This report makes reference to Zeppelin, OpenZeppelin, OpenZeppelin [C]ontracts, the OpenZeppelin team, and OpenZeppelin library. Many of these things have since been renamed and know that this audit applies to what is currently called the OpenZeppelin Contracts which are maintained by the OpenZeppelin Conracts Community.
March, 2017
Authored by Dennis Peterson and Peter Vessenes

View File

@ -1,230 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IRelayRecipient.sol";
import "./IRelayHub.sol";
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 {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
* information on how to use the pre-built {GSNRecipientSignature} and
* {GSNRecipientERC20Fee}, or how to write your own.
*/
abstract contract GSNRecipient is IRelayRecipient, Context {
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
uint256 constant private _RELAYED_CALL_ACCEPTED = 0;
uint256 constant private _RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal _POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view override returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal virtual {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal virtual {
IRelayHub(_relayHub).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view virtual override returns (address payable) {
if (msg.sender != _relayHub) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view virtual override returns (bytes memory) {
if (msg.sender != _relayHub) {
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes memory context) public virtual override returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal virtual returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal virtual;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (_RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (_RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}

View File

@ -1,152 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./GSNRecipient.sol";
import "../math/SafeMath.sol";
import "../access/Ownable.sol";
import "../token/ERC20/SafeERC20.sol";
import "../token/ERC20/ERC20.sol";
/**
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that charges transaction fees in a special purpose ERC20
* token, which we refer to as the gas payment token. The amount charged is exactly the amount of Ether charged to the
* recipient. This means that the token is essentially pegged to the value of Ether.
*
* The distribution strategy of the gas payment token to users is not defined by this contract. It's a mintable token
* whose only minter is the recipient, so the strategy must be implemented in a derived contract, making use of the
* internal {_mint} function.
*/
contract GSNRecipientERC20Fee is GSNRecipient {
using SafeERC20 for __unstable__ERC20Owned;
using SafeMath for uint256;
enum GSNRecipientERC20FeeErrorCodes {
INSUFFICIENT_BALANCE
}
__unstable__ERC20Owned private _token;
/**
* @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
*/
constructor(string memory name, string memory symbol) public {
_token = new __unstable__ERC20Owned(name, symbol);
}
/**
* @dev Returns the gas payment token.
*/
function token() public view returns (IERC20) {
return IERC20(_token);
}
/**
* @dev Internal function that mints the gas payment token. Derived contracts should expose this function in their public API, with proper access control mechanisms.
*/
function _mint(address account, uint256 amount) internal virtual {
_token.mint(account, amount);
}
/**
* @dev Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN.
*/
function acceptRelayedCall(
address,
address from,
bytes memory,
uint256 transactionFee,
uint256 gasPrice,
uint256,
uint256,
bytes memory,
uint256 maxPossibleCharge
)
public
view
virtual
override
returns (uint256, bytes memory)
{
if (_token.balanceOf(from) < maxPossibleCharge) {
return _rejectRelayedCall(uint256(GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE));
}
return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice));
}
/**
* @dev Implements the precharge to the user. The maximum possible charge (depending on gas limit, gas price, and
* fee) will be deducted from the user balance of gas payment token. Note that this is an overestimation of the
* actual charge, necessary because we cannot predict how much gas the execution will actually need. The remainder
* is returned to the user in {_postRelayedCall}.
*/
function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) {
(address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256));
// The maximum token charge is pre-charged from the user
_token.safeTransferFrom(from, address(this), maxPossibleCharge);
}
/**
* @dev Returns to the user the extra amount that was previously charged, once the actual execution cost is known.
*/
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal virtual override {
(address from, uint256 maxPossibleCharge, uint256 transactionFee, uint256 gasPrice) =
abi.decode(context, (address, uint256, uint256, uint256));
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
// ERC20 transfer.
uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
// After the relayed call has been executed and the actual charge estimated, the excess pre-charge is returned
_token.safeTransfer(from, maxPossibleCharge.sub(actualCharge));
}
}
/**
* @title __unstable__ERC20Owned
* @dev An ERC20 token owned by another contract, which has minting permissions and can use transferFrom to receive
* anyone's tokens. This contract is an internal helper for GSNRecipientERC20Fee, and should not be used
* outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__ERC20Owned is ERC20, Ownable {
uint256 private constant _UINT256_MAX = 2**256 - 1;
constructor(string memory name, string memory symbol) public ERC20(name, symbol) { }
// The owner (GSNRecipientERC20Fee) can mint tokens
function mint(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
// The owner has 'infinite' allowance for all token holders
function allowance(address tokenOwner, address spender) public view override returns (uint256) {
if (spender == owner()) {
return _UINT256_MAX;
} else {
return super.allowance(tokenOwner, spender);
}
}
// Allowance for the owner cannot be changed (it is always 'infinite')
function _approve(address tokenOwner, address spender, uint256 value) internal override {
if (spender == owner()) {
return;
} else {
super._approve(tokenOwner, spender, value);
}
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
if (recipient == owner()) {
_transfer(sender, recipient, amount);
return true;
} else {
return super.transferFrom(sender, recipient, amount);
}
}
}

View File

@ -1,72 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./GSNRecipient.sol";
import "../cryptography/ECDSA.sol";
/**
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that allows relayed transactions through when they are
* accompanied by the signature of a trusted signer. The intent is for this signature to be generated by a server that
* performs validations off-chain. Note that nothing is charged to the user in this scheme. Thus, the server should make
* sure to account for this in their economic and threat model.
*/
contract GSNRecipientSignature is GSNRecipient {
using ECDSA for bytes32;
address private _trustedSigner;
enum GSNRecipientSignatureErrorCodes {
INVALID_SIGNER
}
/**
* @dev Sets the trusted signer that is going to be producing signatures to approve relayed calls.
*/
constructor(address trustedSigner) public {
require(trustedSigner != address(0), "GSNRecipientSignature: trusted signer is the zero address");
_trustedSigner = trustedSigner;
}
/**
* @dev Ensures that only transactions with a trusted signature can be relayed through the GSN.
*/
function acceptRelayedCall(
address relay,
address from,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory approvalData,
uint256
)
public
view
virtual
override
returns (uint256, bytes memory)
{
bytes memory blob = abi.encodePacked(
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce, // Prevents replays on RelayHub
getHubAddr(), // Prevents replays in multiple RelayHubs
address(this) // Prevents replays in multiple recipients
);
if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _trustedSigner) {
return _approveRelayedCall();
} else {
return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER));
}
}
function _preRelayedCall(bytes memory) internal virtual override returns (bytes32) { }
function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal virtual override { }
}

View File

@ -1,269 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* 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.
*/
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
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
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
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 {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @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) 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) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
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 calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}

View File

@ -1,76 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Base interface for a contract that will be called via the GSN from {IRelayHub}.
*
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
*/
interface IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
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
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. ``relay``'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}

View File

@ -1,28 +0,0 @@
= Gas Station Network (GSN)
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: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.
Utilities to make writing xref:ROOT:gsn-strategies.adoc[GSN strategies] easy are available in {GSNRecipient}, or you can simply use one of our pre-made strategies:
* {GSNRecipientERC20Fee} charges the end user for gas costs in an application-specific xref:ROOT:tokens.adoc#ERC20[ERC20 token]
* {GSNRecipientSignature} accepts all relayed calls that have been signed by a trusted third party (e.g. a private key in a backend)
You can also take a look at the two contract interfaces that make up the GSN protocol: {IRelayRecipient} and {IRelayHub}, but you won't need to use those directly.
== Recipient
{{GSNRecipient}}
== Strategies
{{GSNRecipientSignature}}
{{GSNRecipientERC20Fee}}
== Protocol
{{IRelayRecipient}}
{{IRelayHub}}

View File

@ -1,14 +1,18 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
@ -41,65 +45,65 @@ import "../GSN/Context.sol";
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
EnumerableSet.AddressSet members;
mapping(address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
* @dev See {IERC165-supportsInterface}.
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
* @dev Revert with a standard message if `account` is missing `role`.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
* The format of the revert reason is given by the following regular expression:
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
@ -108,7 +112,7 @@ abstract contract AccessControl is Context {
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
@ -122,9 +126,7 @@ abstract contract AccessControl is Context {
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
@ -137,9 +139,7 @@ abstract contract AccessControl is Context {
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
@ -157,7 +157,7 @@ abstract contract AccessControl is Context {
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
@ -185,19 +185,25 @@ abstract contract AccessControl is Context {
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}

View File

@ -0,0 +1,79 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}

View File

@ -0,0 +1,87 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}

View File

@ -0,0 +1,30 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

View File

@ -1,8 +1,9 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
@ -15,7 +16,7 @@ import "../GSN/Context.sol";
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
@ -23,16 +24,14 @@ contract Ownable is Context {
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
function owner() public view virtual returns (address) {
return _owner;
}
@ -40,7 +39,7 @@ contract Ownable is Context {
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
@ -52,8 +51,7 @@ contract Ownable is Context {
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
_setOwner(address(0));
}
/**
@ -62,7 +60,12 @@ contract Ownable is Context {
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}

View File

@ -1,9 +1,21 @@
= Access
= Access Control
Contract modules for authorization and access control mechanisms.
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/access
== Contracts
This directory provides ways to restrict who can access the functions of a contract or when they can do it.
- {AccessControl} provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts.
- {Ownable} is a simpler mechanism with a single owner "role" that can be assigned to a single account. This simpler mechanism can be useful for quick tests but projects with production concerns are likely to outgrow it.
== Authorization
{{Ownable}}
{{IAccessControl}}
{{AccessControl}}
{{IAccessControlEnumerable}}
{{AccessControlEnumerable}}

View File

@ -1,83 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}

View File

@ -1,9 +0,0 @@
= Cryptography
This collection of libraries provides simple and safe ways to use different cryptographic primitives.
== Libraries
{{ECDSA}}
{{MerkleProof}}

View File

@ -1,174 +0,0 @@
pragma solidity ^0.6.0;
import "../token/ERC20/SafeERC20.sol";
import "../access/Ownable.sol";
import "../math/SafeMath.sol";
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public {
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
// solhint-disable-next-line max-line-length
require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration");
require(duration > 0, "TokenVesting: duration is 0");
// solhint-disable-next-line max-line-length
require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time");
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() public view returns (uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() public view returns (uint256) {
return _duration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenVesting: cannot revoke");
require(!_revoked[address(token)], "TokenVesting: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
}
}
}

View File

@ -1,9 +1,10 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../GSN/Context.sol";
import "../math/SafeMath.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/math/SafeMath.sol";
/**
* @title PaymentSplitter
@ -19,8 +20,6 @@ import "../math/SafeMath.sol";
* function.
*/
contract PaymentSplitter is Context {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
@ -39,13 +38,12 @@ contract PaymentSplitter is Context {
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor (address[] memory payees, uint256[] memory shares) public payable {
// solhint-disable-next-line max-line-length
require(payees.length == shares.length, "PaymentSplitter: payees and shares length mismatch");
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares[i]);
_addPayee(payees[i], shares_[i]);
}
}
@ -58,7 +56,7 @@ contract PaymentSplitter is Context {
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive () external payable virtual {
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
@ -104,15 +102,15 @@ contract PaymentSplitter is Context {
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]);
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account].add(payment);
_totalReleased = _totalReleased.add(payment);
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
account.transfer(payment);
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
@ -128,7 +126,7 @@ contract PaymentSplitter is Context {
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}

View File

@ -0,0 +1,10 @@
= Finance
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/finance
This directory includes primitives for financial systems. We currently only offer the {PaymentSplitter} contract, but we want to grow this directory so we welcome ideas.
== PaymentSplitter
{{PaymentSplitter}}

View File

@ -0,0 +1,337 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSA.sol";
import "../utils/cryptography/draft-EIP712.sol";
import "../utils/introspection/ERC165.sol";
import "../utils/math/SafeCast.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/Timers.sol";
import "./IGovernor.sol";
/**
* @dev Core of the governance system, designed to be extended though various modules.
*
* This contract is abstract and requires several function to be implemented in various modules:
*
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
* sure this modifier is consistant with the execution model.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore memory proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (proposal.voteStart.isPending()) {
return ProposalState.Pending;
} else if (proposal.voteEnd.isPending()) {
return ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
return
_quorumReached(proposalId) && _voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}

View File

@ -0,0 +1,214 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165.sol";
/**
* @dev Interface of the {Governor} core.
*
* _Available since v4.3._
*/
abstract contract IGovernor is IERC165 {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId) public view virtual returns (ProposalState);
/**
* @notice module:core
* @dev block number used to retrieve user's votes and quorum.
*/
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:core
* @dev timestamp at which votes close.
*/
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of blocks, between the vote start and vote ends.
*
* Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
/**
* @dev Cast a with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
}

View File

@ -0,0 +1,164 @@
= Governance
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance
This directory includes primitives for on-chain governance.
== Governor
This modular system of Governor contracts allows the deployment on-chain voting protocols similar to https://compound.finance/docs/governance[Compound's Governor Alpha & Bravo] and beyond, through the ability to easily customize multiple aspects of the protocol.
[TIP]
====
For a guided experience, set up your Governor contract using https://wizard.openzeppelin.com/#governor[Contracts Wizard].
For a written walkthrough, check out our guide on xref:ROOT:governance.adoc[How to set up on-chain governance].
====
* {Governor}: The core contract that contains all the logic and primitives. It is abstract and requires choosing one of each of the modules below, or custom ones.
Votes modules determine the source of voting power, and sometimes quorum number.
* {GovernorVotes}: Extracts voting weight from an {ERC20Votes} token.
* {GovernorVotesComp}: Extracts voting weight from a COMP-like or {ERC20VotesComp} token.
* {GovernorVotesQuorumFraction}: Combines with `GovernorVotes` to set the quorum as a fraction of the total token supply.
Counting modules determine valid voting options.
* {GovernorCountingSimple}: Simple voting mechanism with 3 voting options: Against, For and Abstain.
Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a `queue` step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed.
* {GovernorTimelockControl}: Connects with an instance of {TimelockController}. Allows multiple proposers and executors, in addition to the Governor itself.
* {GovernorTimelockCompound}: Connects with an instance of Compound's https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[`Timelock`] contract.
Other extensions can customize the behavior or interface in multiple ways.
* {GovernorCompatibilityBravo}: Extends the interface to be fully `GovernorBravo`-compatible. Note that events are compatible regardless of whether this extension is included or not.
* {GovernorProposalThreshold}: Restricts proposals to delegates with a minimum voting power.
In addition to modules and extensions, the core contract requires a few virtual functions to be implemented to your particular specifications:
* <<Governor-votingDelay-,`votingDelay()`>>: Delay (in number of blocks) since the proposal is submitted until voting power is fixed and voting starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, or delegate their votes.
* <<Governor-votingPeriod-,`votingPeriod()`>>: Delay (in number of blocks) since the proposal starts until voting ends.
* <<Governor-quorum-uint256-,`quorum(uint256 blockNumber)`>>: Quorum required for a proposal to be successful. This function includes a `blockNumber` argument so the quorum can adapt through time, for example, to follow a token's `totalSupply`.
NOTE: Functions of the `Governor` contract do not include access control. If you want to restrict access, you should add these checks by overloading the particular functions. Among these, {Governor-_cancel} is internal by default, and you will have to expose it (which the right access control mechanism) yourself if this function is needed.
=== Core
{{IGovernor}}
{{Governor}}
=== Modules
{{GovernorCountingSimple}}
{{GovernorVotes}}
{{GovernorVotesQuorumFraction}}
{{GovernorVotesComp}}
=== Extensions
{{GovernorTimelockControl}}
{{GovernorTimelockCompound}}
{{GovernorProposalThreshold}}
{{GovernorCompatibilityBravo}}
== Timelock
In a governance system, the {TimelockController} contract is in carge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}.
{{TimelockController}}
[[timelock-terminology]]
==== Terminology
* *Operation:* A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see xref:access-control.adoc#operation_lifecycle[operation lifecycle]). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content.
* *Operation status:*
** *Unset:* An operation that is not part of the timelock mechanism.
** *Pending:* An operation that has been scheduled, before the timer expires.
** *Ready:* An operation that has been scheduled, after the timer expires.
** *Done:* An operation that has been executed.
* *Predecessor*: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations.
* *Role*:
** *Admin:* An address (smart contract or EOA) that is in charge of granting the roles of Proposer and Executor.
** *Proposer:* An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations.
** *Executor:* An address (smart contract or EOA) that is in charge of executing operations once the timelock has expired. This role can be given to the zero address to allow anyone to execute operations.
[[timelock-operation]]
==== Operation structure
Operation executed by the xref:api:governance.adoc#TimelockController[`TimelockController`] can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations.
Both operations contain:
* *Target*, the address of the smart contract that the timelock should operate on.
* *Value*, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction.
* *Data*, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role `ROLE` to `ACCOUNT` can be encode using web3js as follows:
```javascript
const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI()
```
* *Predecessor*, that specifies a dependency between operations. This dependency is optional. Use `bytes32(0)` if the operation does not have any dependency.
* *Salt*, used to disambiguate two otherwise identical operations. This can be any random value.
In the case of batched operations, `target`, `value` and `data` are specified as arrays, which must be of the same length.
[[timelock-operation-lifecycle]]
==== Operation lifecycle
Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle:
`Unset` -> `Pending` -> `Pending` + `Ready` -> `Done`
* By calling xref:api:governance.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:governance.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:governance.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method.
* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed.
* By calling xref:api:governance.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:governance.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed.
* xref:api:governance.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.
Operations status can be queried using the functions:
* xref:api:governance.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`]
* xref:api:governance.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`]
* xref:api:governance.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`]
[[timelock-roles]]
==== Roles
[[timelock-admin]]
===== Admin
The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, both the timelock and the deployer have this role. After further configuration and testing, the deployer can renounce this role such that all further maintenance operations have to go through the timelock process.
This role is identified by the *TIMELOCK_ADMIN_ROLE* value: `0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5`
[[timelock-proposer]]
===== Proposer
The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.
WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.
This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1`
[[timelock-executor]]
===== Executor
The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executors can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers. Alternatively, it is possible to allow _any_ address to execute a proposal once the timelock has expired by granting the executor role to the zero address.
This role is identified by the *EXECUTOR_ROLE* value: `0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63`
WARNING: A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the {AccessControl} documentation to learn more about role management.

View File

@ -0,0 +1,352 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControl.sol";
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}

View File

@ -0,0 +1,301 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/Counters.sol";
import "../../utils/math/SafeCast.sol";
import "../extensions/IGovernorTimelock.sol";
import "../extensions/GovernorProposalThreshold.sol";
import "../Governor.sol";
import "./IGovernorCompatibilityBravo.sol";
/**
* @dev Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
*
* This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added
* through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
*
* _Available since v4.3._
*/
abstract contract GovernorCompatibilityBravo is
IGovernorTimelock,
IGovernorCompatibilityBravo,
Governor,
GovernorProposalThreshold
{
using Counters for Counters.Counter;
using Timers for Timers.BlockNumber;
enum VoteType {
Against,
For,
Abstain
}
struct ProposalDetails {
address proposer;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
mapping(address => Receipt) receipts;
bytes32 descriptionHash;
}
mapping(uint256 => ProposalDetails) private _proposalDetails;
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual override returns (string memory) {
return "support=bravo&quorum=bravo";
}
// ============================================== Proposal lifecycle ==============================================
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override(IGovernor, Governor, GovernorProposalThreshold) returns (uint256) {
_storeProposal(_msgSender(), targets, values, new string[](calldatas.length), calldatas, description);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev See {IGovernorCompatibilityBravo-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
_storeProposal(_msgSender(), targets, values, signatures, calldatas, description);
return propose(targets, values, _encodeCalldata(signatures, calldatas), description);
}
/**
* @dev See {IGovernorCompatibilityBravo-queue}.
*/
function queue(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
queue(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev See {IGovernorCompatibilityBravo-execute}.
*/
function execute(uint256 proposalId) public payable virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
execute(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
function cancel(uint256 proposalId) public virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
require(
_msgSender() == details.proposer || getVotes(details.proposer, block.number - 1) < proposalThreshold(),
"GovernorBravo: proposer above threshold"
);
_cancel(
details.targets,
details.values,
_encodeCalldata(details.signatures, details.calldatas),
details.descriptionHash
);
}
/**
* @dev Encodes calldatas with optional function signature.
*/
function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
private
pure
returns (bytes[] memory)
{
bytes[] memory fullcalldatas = new bytes[](calldatas.length);
for (uint256 i = 0; i < signatures.length; ++i) {
fullcalldatas[i] = bytes(signatures[i]).length == 0
? calldatas[i]
: abi.encodeWithSignature(signatures[i], calldatas[i]);
}
return fullcalldatas;
}
/**
* @dev Store proposal metadata for later lookup
*/
function _storeProposal(
address proposer,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) private {
bytes32 descriptionHash = keccak256(bytes(description));
uint256 proposalId = hashProposal(targets, values, _encodeCalldata(signatures, calldatas), descriptionHash);
ProposalDetails storage details = _proposalDetails[proposalId];
if (details.descriptionHash == bytes32(0)) {
details.proposer = proposer;
details.targets = targets;
details.values = values;
details.signatures = signatures;
details.calldatas = calldatas;
details.descriptionHash = descriptionHash;
}
}
// ==================================================== Views =====================================================
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold()
public
view
virtual
override(IGovernorCompatibilityBravo, GovernorProposalThreshold)
returns (uint256);
/**
* @dev See {IGovernorCompatibilityBravo-proposals}.
*/
function proposals(uint256 proposalId)
public
view
virtual
override
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
)
{
id = proposalId;
eta = proposalEta(proposalId);
startBlock = proposalSnapshot(proposalId);
endBlock = proposalDeadline(proposalId);
ProposalDetails storage details = _proposalDetails[proposalId];
proposer = details.proposer;
forVotes = details.forVotes;
againstVotes = details.againstVotes;
abstainVotes = details.abstainVotes;
ProposalState status = state(proposalId);
canceled = status == ProposalState.Canceled;
executed = status == ProposalState.Executed;
}
/**
* @dev See {IGovernorCompatibilityBravo-getActions}.
*/
function getActions(uint256 proposalId)
public
view
virtual
override
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
ProposalDetails storage details = _proposalDetails[proposalId];
return (details.targets, details.values, details.signatures, details.calldatas);
}
/**
* @dev See {IGovernorCompatibilityBravo-getReceipt}.
*/
function getReceipt(uint256 proposalId, address voter) public view virtual override returns (Receipt memory) {
return _proposalDetails[proposalId].receipts[voter];
}
/**
* @dev See {IGovernorCompatibilityBravo-quorumVotes}.
*/
function quorumVotes() public view virtual override returns (uint256) {
return quorum(block.number - 1);
}
// ==================================================== Voting ====================================================
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return _proposalDetails[proposalId].receipts[account].hasVoted;
}
/**
* @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum.
*/
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return quorum(proposalSnapshot(proposalId)) < details.forVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
ProposalDetails storage details = _proposalDetails[proposalId];
return details.forVotes > details.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
Receipt storage receipt = details.receipts[account];
require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast");
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = SafeCast.toUint96(weight);
if (support == uint8(VoteType.Against)) {
details.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
details.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
details.abstainVotes += weight;
} else {
revert("GovernorCompatibilityBravo: invalid vote type");
}
}
}

View File

@ -0,0 +1,118 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IGovernor.sol";
/**
* @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
*
* _Available since v4.3._
*/
abstract contract IGovernorCompatibilityBravo is IGovernor {
/**
* @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as
* {{proposal}} returns a very different structure.
*/
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool executed;
mapping(address => Receipt) receipts;
}
/**
* @dev Receipt structure from Compound Governor Bravo
*/
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
/**
* @dev Part of the Governor Bravo's interface.
*/
function quorumVotes() public view virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_.
*/
function proposals(uint256)
public
view
virtual
returns (
uint256 id,
address proposer,
uint256 eta,
uint256 startBlock,
uint256 endBlock,
uint256 forVotes,
uint256 againstVotes,
uint256 abstainVotes,
bool canceled,
bool executed
);
/**
* @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_.
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256);
/**
* @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_.
*/
function queue(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_.
*/
function execute(uint256 proposalId) public payable virtual;
/**
* @dev Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
*/
function cancel(uint256 proposalId) public virtual;
/**
* @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_.
*/
function getActions(uint256 proposalId)
public
view
virtual
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
);
/**
* @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_.
*/
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}

View File

@ -0,0 +1,105 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
/**
* @dev Extension of {Governor} for simple, 3 options, vote counting.
*
* _Available since v4.3._
*/
abstract contract GovernorCountingSimple is Governor {
/**
* @dev Supported vote types. Matches Governor Bravo ordering.
*/
enum VoteType {
Against,
For,
Abstain
}
struct ProposalVote {
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
mapping(address => bool) hasVoted;
}
mapping(uint256 => ProposalVote) private _proposalVotes;
/**
* @dev See {IGovernor-COUNTING_MODE}.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual override returns (string memory) {
return "support=bravo&quorum=for,abstain";
}
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return _proposalVotes[proposalId].hasVoted[account];
}
/**
* @dev Accessor to the internal vote counts.
*/
function proposalVotes(uint256 proposalId)
public
view
virtual
returns (
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes
)
{
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return (proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes);
}
/**
* @dev See {Governor-_quorumReached}.
*/
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return proposalvote.forVotes > proposalvote.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual override {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
require(!proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast");
proposalvote.hasVoted[account] = true;
if (support == uint8(VoteType.Against)) {
proposalvote.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
proposalvote.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
proposalvote.abstainVotes += weight;
} else {
revert("GovernorVotingSimple: invalid value for enum VoteType");
}
}
}

View File

@ -0,0 +1,34 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
/**
* @dev Extension of {Governor} for proposal restriction to token holders with a minimum balance.
*
* _Available since v4.3._
*/
abstract contract GovernorProposalThreshold is Governor {
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}

View File

@ -0,0 +1,242 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../../utils/math/SafeCast.sol";
/**
* https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[Compound's timelock] interface
*/
interface ICompoundTimelock {
receive() external payable;
// solhint-disable-next-line func-name-mixedcase
function GRACE_PERIOD() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function MINIMUM_DELAY() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function MAXIMUM_DELAY() external view returns (uint256);
function admin() external view returns (address);
function pendingAdmin() external view returns (address);
function delay() external view returns (uint256);
function queuedTransactions(bytes32) external view returns (bool);
function setDelay(uint256) external;
function acceptAdmin() external;
function setPendingAdmin(address) external;
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) external payable returns (bytes memory);
}
/**
* @dev Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by
* the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be
* the admin of the timelock for any operation to be performed. A public, unrestricted,
* {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
*
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
* inaccessible.
*
* _Available since v4.3._
*/
abstract contract GovernorTimelockCompound is IGovernorTimelock, Governor {
using SafeCast for uint256;
using Timers for Timers.Timestamp;
struct ProposalTimelock {
Timers.Timestamp timer;
}
ICompoundTimelock private _timelock;
mapping(uint256 => ProposalTimelock) private _proposalTimelocks;
/**
* @dev Emitted when the timelock controller used for proposal execution is modified.
*/
event TimelockChange(address oldTimelock, address newTimelock);
/**
* @dev Set the timelock.
*/
constructor(ICompoundTimelock timelockAddress) {
_updateTimelock(timelockAddress);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Overriden version of the {Governor-state} function with added support for the `Queued` and `Expired` status.
*/
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
ProposalState status = super.state(proposalId);
if (status != ProposalState.Succeeded) {
return status;
}
uint256 eta = proposalEta(proposalId);
if (eta == 0) {
return status;
} else if (block.timestamp >= eta + _timelock.GRACE_PERIOD()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @dev Public accessor to check the address of the timelock
*/
function timelock() public view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public accessor to check the eta of a queued proposal
*/
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
return _proposalTimelocks[proposalId].timer.getDeadline();
}
/**
* @dev Function to queue a proposal to the timelock.
*/
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
uint256 eta = block.timestamp + _timelock.delay();
_proposalTimelocks[proposalId].timer.setDeadline(eta.toUint64());
for (uint256 i = 0; i < targets.length; ++i) {
require(
!_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], eta))),
"GovernorTimelockCompound: identical proposal action already queued"
);
_timelock.queueTransaction(targets[i], values[i], "", calldatas[i], eta);
}
emit ProposalQueued(proposalId, eta);
return proposalId;
}
/**
* @dev Overriden execute function that run the already queued proposal through the timelock.
*/
function _execute(
uint256 proposalId,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual override {
uint256 eta = proposalEta(proposalId);
require(eta > 0, "GovernorTimelockCompound: proposal not yet queued");
for (uint256 i = 0; i < targets.length; ++i) {
_timelock.executeTransaction{value: values[i]}(targets[i], values[i], "", calldatas[i], eta);
}
}
/**
* @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
* been queued.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override returns (uint256) {
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
uint256 eta = proposalEta(proposalId);
if (eta > 0) {
for (uint256 i = 0; i < targets.length; ++i) {
_timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta);
}
_proposalTimelocks[proposalId].timer.reset();
}
return proposalId;
}
/**
* @dev Address through which the governor executes action. In this case, the timelock.
*/
function _executor() internal view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Accept admin right over the timelock.
*/
// solhint-disable-next-line private-vars-leading-underscore
function __acceptAdmin() public {
_timelock.acceptAdmin();
}
/**
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
* must be proposed, scheduled and executed using the {Governor} workflow.
*
* For security reason, the timelock must be handed over to another admin before setting up a new one. The two
* operations (hand over the timelock) and do the update can be batched in a single proposal.
*
* Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the
* timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of
* governance.
*/
function updateTimelock(ICompoundTimelock newTimelock) external virtual onlyGovernance {
_updateTimelock(newTimelock);
}
function _updateTimelock(ICompoundTimelock newTimelock) private {
emit TimelockChange(address(_timelock), address(newTimelock));
_timelock = newTimelock;
}
}

View File

@ -0,0 +1,153 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IGovernorTimelock.sol";
import "../Governor.sol";
import "../TimelockController.sol";
/**
* @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
* delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
* {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly.
*
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
* inaccessible.
*
* _Available since v4.3._
*/
abstract contract GovernorTimelockControl is IGovernorTimelock, Governor {
TimelockController private _timelock;
mapping(uint256 => bytes32) private _timelockIds;
/**
* @dev Emitted when the timelock controller used for proposal execution is modified.
*/
event TimelockChange(address oldTimelock, address newTimelock);
/**
* @dev Set the timelock.
*/
constructor(TimelockController timelockAddress) {
_updateTimelock(timelockAddress);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Overriden version of the {Governor-state} function with added support for the `Queued` status.
*/
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
ProposalState status = super.state(proposalId);
if (status != ProposalState.Succeeded) {
return status;
}
// core tracks execution, so we just have to check if successful proposal have been queued.
bytes32 queueid = _timelockIds[proposalId];
if (queueid == bytes32(0)) {
return status;
} else if (_timelock.isOperationDone(queueid)) {
return ProposalState.Executed;
} else {
return ProposalState.Queued;
}
}
/**
* @dev Public accessor to check the address of the timelock
*/
function timelock() public view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public accessor to check the eta of a queued proposal
*/
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);
return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
}
/**
* @dev Function to queue a proposal to the timelock.
*/
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
uint256 delay = _timelock.getMinDelay();
_timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
_timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);
emit ProposalQueued(proposalId, block.timestamp + delay);
return proposalId;
}
/**
* @dev Overriden execute function that run the already queued proposal through the timelock.
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override {
_timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
}
/**
* @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
* been queued.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual override returns (uint256) {
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
if (_timelockIds[proposalId] != 0) {
_timelock.cancel(_timelockIds[proposalId]);
delete _timelockIds[proposalId];
}
return proposalId;
}
/**
* @dev Address through which the governor executes action. In this case, the timelock.
*/
function _executor() internal view virtual override returns (address) {
return address(_timelock);
}
/**
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
* must be proposed, scheduled and executed using the {Governor} workflow.
*/
function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
_updateTimelock(newTimelock);
}
function _updateTimelock(TimelockController newTimelock) private {
emit TimelockChange(address(_timelock), address(newTimelock));
_timelock = newTimelock;
}
}

View File

@ -0,0 +1,27 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../../token/ERC20/extensions/ERC20Votes.sol";
import "../../utils/math/Math.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotes is Governor {
ERC20Votes public immutable token;
constructor(ERC20Votes tokenAddress) {
token = tokenAddress;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPastVotes(account, blockNumber);
}
}

View File

@ -0,0 +1,26 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../../token/ERC20/extensions/ERC20VotesComp.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from a Comp token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotesComp is Governor {
ERC20VotesComp public immutable token;
constructor(ERC20VotesComp token_) {
token = token_;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPriorVotes(account, blockNumber);
}
}

View File

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./GovernorVotes.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a
* fraction of the total supply.
*
* _Available since v4.3._
*/
abstract contract GovernorVotesQuorumFraction is GovernorVotes {
uint256 private _quorumNumerator;
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator);
constructor(uint256 quorumNumeratorValue) {
_updateQuorumNumerator(quorumNumeratorValue);
}
function quorumNumerator() public view virtual returns (uint256) {
return _quorumNumerator;
}
function quorumDenominator() public view virtual returns (uint256) {
return 100;
}
function quorum(uint256 blockNumber) public view virtual override returns (uint256) {
return (token.getPastTotalSupply(blockNumber) * quorumNumerator()) / quorumDenominator();
}
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
_updateQuorumNumerator(newQuorumNumerator);
}
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual {
require(
newQuorumNumerator <= quorumDenominator(),
"GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator"
);
uint256 oldQuorumNumerator = _quorumNumerator;
_quorumNumerator = newQuorumNumerator;
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
}
}

View File

@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IGovernor.sol";
/**
* @dev Extension of the {IGovernor} for timelock supporting modules.
*
* _Available since v4.3._
*/
abstract contract IGovernorTimelock is IGovernor {
event ProposalQueued(uint256 proposalId, uint256 eta);
function timelock() public view virtual returns (address);
function proposalEta(uint256 proposalId) public view virtual returns (uint256);
function queue(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public virtual returns (uint256 proposalId);
}

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/IERC1155.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/extensions/IERC1155MetadataURI.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/IERC1155Receiver.sol";

View File

@ -0,0 +1,18 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

View File

@ -0,0 +1,94 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./IERC165.sol";
interface IERC1363 is IERC165, IERC20 {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(
address to,
uint256 value,
bytes memory data
) external returns (bool);
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value
) external returns (bool);
/**
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(
address from,
address to,
uint256 value,
bytes memory data
) external returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(
address spender,
uint256 value,
bytes memory data
) external returns (bool);
}

View File

@ -0,0 +1,31 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(
address operator,
address from,
uint256 value,
bytes memory data
) external returns (bytes4);
}

View File

@ -0,0 +1,29 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(
address owner,
uint256 value,
bytes memory data
) external returns (bytes4);
}

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC1820Implementer.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC1820Registry.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/IERC20Metadata.sol";

View File

@ -0,0 +1,22 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}

View File

@ -0,0 +1,6 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
import "./IERC3156FlashLender.sol";

View File

@ -0,0 +1,28 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}

View File

@ -0,0 +1,42 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
/**
* @dev Interface of the ERC3156 FlashLender, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/IERC721Enumerable.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/IERC721Metadata.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721Receiver.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC777/IERC777.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC777/IERC777Recipient.sol";

View File

@ -0,0 +1,5 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC777/IERC777Sender.sol";

View File

@ -0,0 +1,50 @@
= Interfaces
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/interfaces
== List of standardized interfaces
These interfaces are available as `.sol` files, and also as compiler `.json` ABI files (through the npm package). These
are usefull to interract with third party contracts that implement them.
- {IERC20}
- {IERC20Metadata}
- {IERC165}
- {IERC721}
- {IERC721Receiver}
- {IERC721Enumerable}
- {IERC721Metadata}
- {IERC777}
- {IERC777Recipient}
- {IERC777Sender}
- {IERC1155}
- {IERC1155Receiver}
- {IERC1155MetadataURI}
- {IERC1271}
- {IERC1363}
- {IERC1820Implementer}
- {IERC1820Registry}
- {IERC2612}
- {IERC2981}
- {IERC3156FlashLender}
- {IERC3156FlashBorrower}
== Detailed ABI
{{IERC1271}}
{{IERC1363}}
{{IERC1363Receiver}}
{{IERC1820Implementer}}
{{IERC1820Registry}}
{{IERC2612}}
{{IERC2981}}
{{IERC3156FlashLender}}
{{IERC3156FlashBorrower}}

View File

@ -0,0 +1,7 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/draft-IERC20Permit.sol";
interface IERC2612 is IERC20Permit {}

View File

@ -1,28 +0,0 @@
= Introspection
This set of interfaces and contracts deal with https://en.wikipedia.org/wiki/Type_introspection[type introspection] of contracts, that is, examining which functions can be called on them. This is usually referred to as a contract's _interface_.
Ethereum contracts have no native concept of an interface, so applications must usually simply trust they are not making an incorrect call. For trusted setups this is a non-issue, but often unknown and untrusted third-party addresses need to be interacted with. There may even not be any direct calls to them! (e.g. `ERC20` tokens may be sent to a contract that lacks a way to transfer them out of it, locking them forever). In these cases, a contract _declaring_ its interface can be very helpful in preventing errors.
There are two main ways to approach this.
* Locally, where a contract implements `IERC165` and declares an interface, and a second one queries it directly via `ERC165Checker`.
* Globally, where a global and unique registry (`IERC1820Registry`) is used to register implementers of a certain interface (`IERC1820Implementer`). It is then the registry that is queried, which allows for more complex setups, like contracts implementing interfaces for externally-owned accounts.
Note that, in all cases, accounts simply _declare_ their interfaces, but they are not required to actually implement them. This mechanism can therefore be used to both prevent errors and allow for complex interactions (see `ERC777`), but it must not be relied on for security.
== Local
{{IERC165}}
{{ERC165}}
{{ERC165Checker}}
== Global
{{IERC1820Registry}}
{{IERC1820Implementer}}
{{ERC1820Implementer}}

View File

@ -1,11 +0,0 @@
= Math
These are math-related utilities.
== Libraries
{{SafeMath}}
{{SignedSafeMath}}
{{Math}}

View File

@ -1,152 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when 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.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}

View File

@ -1,62 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}

View File

@ -0,0 +1,39 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771Context is Context {
address private _trustedForwarder;
constructor(address trustedForwarder) {
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == _trustedForwarder;
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
}

View File

@ -0,0 +1,58 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSA.sol";
import "../utils/cryptography/draft-EIP712.sol";
/**
* @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
*/
contract MinimalForwarder is EIP712 {
using ECDSA for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
bytes32 private constant _TYPEHASH =
keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
mapping(address => uint256) private _nonces;
constructor() EIP712("MinimalForwarder", "0.0.1") {}
function getNonce(address from) public view returns (uint256) {
return _nonces[from];
}
function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(
keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
function execute(ForwardRequest calldata req, bytes calldata signature)
public
payable
returns (bool, bytes memory)
{
require(verify(req, signature), "MinimalForwarder: signature does not match request");
_nonces[req.from] = req.nonce + 1;
(bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(
abi.encodePacked(req.data, req.from)
);
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.gas / 63);
return (success, returndata);
}
}

View File

@ -0,0 +1,12 @@
= Meta Transactions
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/metatx
== Core
{{ERC2771Context}}
== Utils
{{MinimalForwarder}}

View File

@ -0,0 +1,17 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControlEnumerable.sol";
contract AccessControlEnumerableMock is AccessControlEnumerable {
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public {
_setRoleAdmin(roleId, adminRoleId);
}
function senderProtected(bytes32 roleId) public onlyRole(roleId) {}
}

View File

@ -1,15 +1,17 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../access/AccessControl.sol";
contract AccessControlMock is AccessControl {
constructor() public {
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public {
_setRoleAdmin(roleId, adminRoleId);
}
function senderProtected(bytes32 roleId) public onlyRole(roleId) {}
}

View File

@ -1,10 +1,14 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../utils/Address.sol";
contract AddressImpl {
string public sharedAnswer;
event CallReturnValue(string data);
function isContract(address account) external view returns (bool) {
return Address.isContract(account);
}
@ -13,6 +17,30 @@ contract AddressImpl {
Address.sendValue(receiver, amount);
}
function functionCall(address target, bytes calldata data) external {
bytes memory returnData = Address.functionCall(target, data);
emit CallReturnValue(abi.decode(returnData, (string)));
}
function functionCallWithValue(
address target,
bytes calldata data,
uint256 value
) external payable {
bytes memory returnData = Address.functionCallWithValue(target, data, value);
emit CallReturnValue(abi.decode(returnData, (string)));
}
function functionStaticCall(address target, bytes calldata data) external {
bytes memory returnData = Address.functionStaticCall(target, data);
emit CallReturnValue(abi.decode(returnData, (string)));
}
function functionDelegateCall(address target, bytes calldata data) external {
bytes memory returnData = Address.functionDelegateCall(target, data);
emit CallReturnValue(abi.decode(returnData, (string)));
}
// sendValue's tests require the contract to hold Ether
receive () external payable { }
receive() external payable {}
}

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../utils/Arrays.sol";
@ -9,7 +9,7 @@ contract ArraysImpl {
uint256[] private _array;
constructor (uint256[] memory array) public {
constructor(uint256[] memory array) {
_array = array;
}

View File

@ -0,0 +1,11 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract BadBeaconNoImpl {}
contract BadBeaconNotContract {
function implementation() external pure returns (address) {
return address(0x1);
}
}

View File

@ -0,0 +1,27 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/structs/BitMaps.sol";
contract BitMapMock {
using BitMaps for BitMaps.BitMap;
BitMaps.BitMap private _bitmap;
function get(uint256 index) public view returns (bool) {
return _bitmap.get(index);
}
function setTo(uint256 index, bool value) public {
_bitmap.setTo(index, value);
}
function set(uint256 index) public {
_bitmap.set(index);
}
function unset(uint256 index) public {
_bitmap.unset(index);
}
}

View File

@ -0,0 +1,50 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CallReceiverMock {
string public sharedAnswer;
event MockFunctionCalled();
uint256[] private _array;
function mockFunction() public payable returns (string memory) {
emit MockFunctionCalled();
return "0x1234";
}
function mockFunctionNonPayable() public returns (string memory) {
emit MockFunctionCalled();
return "0x1234";
}
function mockStaticFunction() public pure returns (string memory) {
return "0x1234";
}
function mockFunctionRevertsNoReason() public payable {
revert();
}
function mockFunctionRevertsReason() public payable {
revert("CallReceiverMock: reverting");
}
function mockFunctionThrows() public payable {
assert(false);
}
function mockFunctionOutOfGas() public payable {
for (uint256 i = 0; ; ++i) {
_array.push(i);
}
}
function mockFunctionWritesStorage() public returns (string memory) {
sharedAnswer = "42";
return "0x1234";
}
}

View File

@ -0,0 +1,18 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Implementation contract with an admin() function made to clash with
* @dev TransparentUpgradeableProxy's to test correct functioning of the
* @dev Transparent Proxy feature.
*/
contract ClashingImplementation {
function admin() external pure returns (address) {
return 0x0000000000000000000000000000000011111142;
}
function delegatedFunction() external pure returns (bool) {
return true;
}
}

View File

@ -0,0 +1,36 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/Clones.sol";
import "../utils/Address.sol";
contract ClonesMock {
using Address for address;
using Clones for address;
event NewInstance(address instance);
function clone(address implementation, bytes calldata initdata) public payable {
_initAndEmit(implementation.clone(), initdata);
}
function cloneDeterministic(
address implementation,
bytes32 salt,
bytes calldata initdata
) public payable {
_initAndEmit(implementation.cloneDeterministic(salt), initdata);
}
function predictDeterministicAddress(address implementation, bytes32 salt) public view returns (address predicted) {
return implementation.predictDeterministicAddress(salt);
}
function _initAndEmit(address instance, bytes memory initdata) private {
if (initdata.length > 0) {
instance.functionCallWithValue(initdata, msg.value);
}
emit NewInstance(instance);
}
}

View File

@ -1,8 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../payment/escrow/ConditionalEscrow.sol";
import "../utils/escrow/ConditionalEscrow.sol";
// mock class using ConditionalEscrow
contract ConditionalEscrowMock is ConditionalEscrow {

View File

@ -1,8 +1,8 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../GSN/Context.sol";
import "../utils/Context.sol";
contract ContextMock is Context {
event Sender(address sender);
@ -23,7 +23,11 @@ contract ContextMockCaller {
context.msgSender();
}
function callData(ContextMock context, uint256 integerValue, string memory stringValue) public {
function callData(
ContextMock context,
uint256 integerValue,
string memory stringValue
) public {
context.msgData(integerValue, stringValue);
}
}

View File

@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma solidity ^0.8.0;
import "../utils/Counters.sol";
@ -20,4 +20,8 @@ contract CountersImpl {
function decrement() public {
_counter.decrement();
}
function reset() public {
_counter.reset();
}
}

Some files were not shown because too many files have changed in this diff Show More