Compare commits

...

614 Commits

Author SHA1 Message Date
fd81a96f01 Release v4.9.3 (#4482)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-07-28 18:11:15 -03:00
70dea74ac7 Add changeset PR numbers 2023-07-28 18:01:28 -03:00
e4435eed75 Adjust ERC2771Context._msgData for msg.data.length < 20 (#4484)
(cherry picked from commit 9445f96223)
2023-07-27 17:31:02 -03:00
7ec712baa5 Make ERC2771Context return original sender address if msg.data.length <= 20 (#4481)
(cherry picked from commit 28d9ac2bdb)
2023-07-25 19:39:49 -03:00
d26025b410 Fix error when running hardhat test with parameters (#4265)
(cherry picked from commit dfef6a68ee)
2023-07-01 01:51:28 -03:00
a54f6398e5 Update docs for SafeERC20.forceApprove (#4231)
(cherry picked from commit 06861dce54)
2023-07-01 01:36:26 -03:00
e50c24f583 Release v4.9.2 (#4364)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-06-16 17:42:01 -03:00
4d2383e171 Merge pull request from GHSA-wprv-93r4-jj2p 2023-06-16 17:17:41 -03:00
f03420b5c7 Remove automatic conflict resolution for merge from release branch (#4362)
(cherry picked from commit 002a7c8812)
2023-06-16 15:43:14 -03:00
ded8c9eedb Update index.adoc (#4336)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
(cherry picked from commit d6c7cee321)
2023-06-13 17:32:52 -03:00
281550b71c Release v4.9.1 (#4321)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Francisco <fg@frang.io>
2023-06-06 22:40:02 -03:00
33ff9b086d Merge pull request from GHSA-5h3x-9wvq-w4m2
Co-authored-by: Francisco <fg@frang.io>
Co-authored-by: Ernesto García <ernestognw@gmail.com>
(cherry picked from commit d9474327a4)
2023-06-06 21:33:16 -03:00
fa3a30a580 Fix typo in crosschain.adoc 2023-06-02 11:33:28 -03:00
4e6deb3c56 Fix import substitution for docs examples 2023-06-01 17:56:57 -03:00
819820517d Fix doc MyGovernor example doesn't compile (#4282)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-06-01 15:00:49 -03:00
a6e2671690 Fix release merge script (#4273)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
(cherry picked from commit 7e814a3074)
2023-05-23 18:21:33 -03:00
54b3f14346 Release v4.9.0 (#4272)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Francisco <fg@frang.io>
2023-05-23 15:17:15 -03:00
813cc2b79d Exit release candidate 2023-05-23 17:42:48 +00:00
4f7047ceec Release v4.9.0 (rc) (#4243)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-05-16 23:45:09 -03:00
a43069e841 Reduce frequency of version comment updates (#4244)
(cherry picked from commit 1642b6639b)
2023-05-12 14:26:07 -03:00
e0fe936729 Fix bug allowing anyone to cancel an admin renounce (#4238)
Co-authored-by: Francisco Giordano <fg@frang.io>
(cherry picked from commit 3ec4307c8a)
2023-05-11 16:36:51 -03:00
652ae921e1 Prevent attempt to publish to npm (#4239)
(cherry picked from commit f355bd3a2a)
2023-05-11 16:36:51 -03:00
9673c56eba Clean up pending admin schedule on renounce in DefaultAdminRules (#4230)
(cherry picked from commit 3e1b25a5cf)
2023-05-11 16:36:51 -03:00
46d5a87c00 Fix spelling error in CHANGELOG.md (#4232)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-05-10 16:11:06 -03:00
f214e476e6 Disable code size warnings on exposed contracts
(cherry picked from commit d095542fa4)
2023-05-09 17:39:44 -03:00
17cf519425 Release v4.9.0 (rc) (#4228)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-05-09 17:00:00 -03:00
43eb8d1265 Specify changeset PRs manually
(cherry picked from commit dff520afae)
2023-05-09 16:55:02 -03:00
2d2c5f348d Start release candidate 2023-05-09 19:41:46 +00:00
df3f1fc4db Specify changeset commit manually 2023-05-09 16:37:25 -03:00
0ee84342b7 Add PDF report for v4.9 audit (#4227) 2023-05-09 16:09:52 -03:00
51294b7480 Make transpilation setup local to this repo (#4041)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-05-09 15:52:23 -03:00
34d926dd7e Implement extra suggestions from audit review of 4.9 (#4224) 2023-05-09 13:19:35 -03:00
832c352c7d Update lockfile (#4203)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-09 00:04:41 -03:00
908f78d07b Enable more Slither detectors (#4219) 2023-05-08 18:00:49 -03:00
692d8c85a4 Fix lookup documentation in ERC20Votes and Checkpoints (#4218)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-05-05 17:25:23 -03:00
72ed4ca67a Ensure AccessControlDefaultAdminRules's initialDefaultAdmin is non-zero (#4220)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-05-05 16:31:23 -03:00
dcba9f995f Add AccessControlDefaultAdminRules FV (#4180)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <fg@frang.io>
2023-05-05 16:27:43 -03:00
8b2ed0f570 Fix early reporting of FV prover's output (#4213)
Co-authored-by: Francisco <fg@frang.io>
2023-05-04 13:54:22 -03:00
9e8b74a0e2 Add more test cases for EIP712 (#4212) 2023-05-04 10:33:57 -03:00
a7ee03565b Move certora helpers to a dedicated folder (#4211) 2023-05-03 14:34:14 +00:00
10022da83d Disable automatic formal verification workflow on push (#4208) 2023-05-03 16:13:42 +02:00
538655c3c0 Add reentrancy test cases for ERC4626 (#4197)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-05-03 09:35:48 +02:00
0a2a33be30 Add formal verification specs for EnumerableSet & EnumerableMap (#4167)
Co-authored-by: Francisco <fg@frang.io>
2023-05-03 02:54:23 +00:00
ab2604ac5b Add reentrancy test cases for TimelockController (#4200)
Co-authored-by: Francisco <fg@frang.io>
2023-05-02 11:36:56 +02:00
6ff415de6b Downgrade Node for Slither (#4202) 2023-04-28 17:15:15 -03:00
d23f818a59 Fix AccessControlDefaultAdminRules admin consistency (#4177)
Co-authored-by: Francisco <fg@frang.io>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-04-28 15:09:58 +02:00
44d6053b43 Only run FV on new or updated specs (#4195) 2023-04-28 14:01:41 +02:00
f959d7e4e6 Fix release note in IERC1967 (#4183) 2023-04-25 12:57:50 -03:00
8f14d52b73 Fix Checkpoints fuzz overflow (#4184)
Co-authored-by: Francisco <fg@frang.io>
2023-04-25 12:57:16 -03:00
1a079d258b Improve Address tests (#4191) 2023-04-25 08:31:01 -03:00
6aac66d065 Merge release-v4.8 (#4188)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Benjamin <benjaminxh+github@gmail.com>
Co-authored-by: Owen <omurovec@yahoo.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: JulissaDantes <julissadcj@gmail.com>
Co-authored-by: Ernesto García <ernestognw@gmail.com>
Co-authored-by: Yamen Merhi <yamennmerhi@gmail.com>
Co-authored-by: Pascal Marco Caversaccio <pcaversaccio@users.noreply.github.com>
Co-authored-by: alpharush <0xalpharush@protonmail.com>
Co-authored-by: Paul Razvan Berg <paul.razvan.berg@gmail.com>
2023-04-24 09:18:27 -03:00
91df66c4a9 Implement suggestions from audit of 4.9 (#4176)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-04-21 08:35:07 -03:00
8d633cb7d1 Merge pull request from GHSA-93hq-5wgc-jc82
Co-authored-by: Francisco <fg@frang.io>
2023-04-13 15:47:51 -03:00
3b117992e1 Improve docs for transparent proxy (#4181)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-04-13 11:04:04 -03:00
dd1265cb1d Improve ERC4626 test coverage (#4134)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
2023-04-12 17:33:50 -03:00
788d6a129a Add fuzz tests for ShortString (#4175) 2023-04-12 17:09:30 +02:00
86f6eb2c9c Add FV specification for ERC721 (#4104)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-04-12 00:29:36 -03:00
661343f74c Add DoubleEndedQueue FV (#4147)
Co-authored-by: Francisco <fg@frang.io>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-04-11 23:17:10 -03:00
473d0b6884 Add Codecov token 2023-04-11 20:36:58 -03:00
f2346b6749 Add fuzz tests for the Checkpoints library (#4146)
Co-authored-by: Francisco <fg@frang.io>
2023-04-11 11:21:53 +02:00
cf86fd9962 Merge changesets for transparency improvements (#4165) 2023-04-05 22:20:34 +02:00
31723ed608 Reenable skipped TransparentUpgradeableProxy test (#4161)
Co-authored-by: Francisco <fg@frang.io>
2023-04-05 18:47:18 +00:00
5523c1482b Fix TransparentUpgradeableProxy's transparency (#4154)
Co-authored-by: Francisco <fg@frang.io>
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-04-05 16:57:08 +02:00
ead3bcaccb Fix spurious CI check failures (#4160) 2023-04-04 23:05:39 -03:00
7e7060e00e Update IERC3156FlashBorrower.sol (#4145) 2023-03-30 20:57:09 +02:00
ca822213f2 Make AccessControlDefaultAdminRules delay configurable (#4079)
Co-authored-by: Francisco <fg@frang.io>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-03-26 14:23:13 -03:00
3f610ebc25 Fix typo in README (#4129) 2023-03-21 11:33:16 -03:00
1a60b061d5 Add Pausable FV (#4117)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-03-16 16:08:28 -03:00
4f4b6ab403 Update certora/README.md (#4114)
Co-authored-by: Francisco <fg@frang.io>
2023-03-15 11:06:25 -03:00
1c8df659b9 Clarify Governor Bravo compatibility scope (#4090)
Co-authored-by: Francisco <fg@frang.io>
2023-03-14 19:14:01 -03:00
75ef7b8b27 Add FV specs for TimelockController (#4098)
Co-authored-by: Francisco <fg@frang.io>
2023-03-14 10:27:37 -03:00
ea2d5ad2e7 Update lockfile (#4080)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-13 21:09:01 -03:00
e69248e551 Limit concurrency of formal-verification runs 2023-03-13 21:05:22 -03:00
e739144cb0 Update dependency certora-cli to v3.6.4 (#4110)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Francisco <fg@frang.io>
2023-03-13 18:31:24 -03:00
6794c9460b Run formal verification when label is added (#4112) 2023-03-13 12:45:58 -03:00
f8e3c375d1 Credit YieldBox for virtual offset (#4103) 2023-03-09 17:55:52 -03:00
58a62916de Bump and pin Forge Std submodule (#4102) 2023-03-09 17:41:08 +00:00
3214f6c256 Add FV specification for ERC20Wrapper (#4100)
Co-authored-by: Francisco <fg@frang.io>
2023-03-08 22:12:37 +00:00
5f7f660c6e Add FV specs for Initializable (#4095)
Co-authored-by: Francisco <fg@frang.io>
2023-03-08 22:17:35 +01:00
b952a82d29 Throw error when requested specs are not found (#4101) 2023-03-08 22:16:37 +01:00
a55013e742 Add effect checks on the accesscontrol specs (#4099) 2023-03-08 19:31:46 +01:00
aaad1f4a4f Add FV specs for Ownable and Ownable2Steps (#4094)
Co-authored-by: Santiago Palladino <spalladino@gmail.com>
Co-authored-by: Francisco <fg@frang.io>
2023-03-08 19:30:07 +01:00
4fb6833e32 Formal verification using Certora (#4084)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-03-06 21:31:48 +00:00
de520fe25a Add byteLengthWithFallback to ShortStrings (#4089)
Co-authored-by: Francisco <fg@frang.io>
2023-03-06 20:44:58 +00:00
7f028d6959 Fix empty short string encoding (#4088)
Co-authored-by: Francisco <fg@frang.io>
2023-03-03 22:45:52 +01:00
eedca5d873 Merge release-v4.8 branch 2023-03-02 21:13:25 -03:00
e58c6d8ff4 Fix linter error 2023-03-02 19:47:41 -03:00
8ba26f388f Merge pull request from GHSA-878m-3g6q-594q
* Test batch minting of 1

* Fix balance tracking

* fix lint

* add changeset

* rename UNSAFE -> unsafe

* fix docs

* fix changeset

* grammar

* add explanation of preserved invariant

* add fuzz tests

* rename variable

* improve property definition

* add burn

* add test ownership multiple batches

* refactor fuzz tests

* change ownership test for better probability

* typo

* reorder comment

* update changelog notes

* edit changelog

* lint

* Update CHANGELOG.md

---------

Co-authored-by: Francisco Giordano <fg@frang.io>
2023-03-02 19:41:28 -03:00
0ebc6e3529 Fix grammar in docs (#4085) 2023-03-02 10:40:36 +01:00
e1a77ab15f Fix an upgrade replay bug in Governor.propose (#4082) 2023-03-01 15:35:15 -03:00
dad73159df Add AccessControlDefaultAdminRules (#4009)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <fg@frang.io>
2023-02-24 21:48:08 +00:00
2c69f9f9f5 Fix comment on ERC777._beforeTokenTransfer (#3982) 2023-02-24 18:31:54 -03:00
3f3774c5df Improve ERC1363 documentation (#3993)
Co-authored-by: Francisco <fg@frang.io>
2023-02-24 18:28:37 -03:00
8b47e96af1 Add SafeERC20.forceApprove() (#4067) 2023-02-24 20:29:49 +00:00
0fbd039554 Update lockfile (#4018)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-24 17:14:21 -03:00
2c6ef8c875 Fix ERC1363 interfaceId (#4074) 2023-02-24 16:14:49 -03:00
eb38c059d8 Add comment on unchecked arithmetic (division by zero) in Math.sol (#4050)
Co-authored-by: Francisco <fg@frang.io>
2023-02-24 18:34:03 +00:00
8a43ebac28 Document "duplicate" proposal storing in GovernorCompatibilityBravo (#4073)
Co-authored-by: Francisco <fg@frang.io>
2023-02-24 13:48:55 -03:00
b4d765b130 Allow return data length >= 32 in SignatureChecker (#4038)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-02-24 15:05:46 +00:00
d5581531de Add a "fees" section to the ERC4626 guide (#4054)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-02-24 11:49:10 -03:00
62dbb1b06a Document clock modes for token and governor (#4058)
Co-authored-by: Francisco <fg@frang.io>
2023-02-24 11:48:30 -03:00
6e88df28cb Mark ERC777 and ERC1820 as deprecated (#4066) 2023-02-23 20:06:22 -03:00
a6b8366980 Improve ERC4626 event coverage (#4072) 2023-02-23 17:06:47 -03:00
9d06a1b64b Remove unused Solhint overrides (#4069) 2023-02-23 12:52:10 +01:00
7b3e7b7055 Re-enable ERC4626 property test on empty vaults (#4068) 2023-02-22 15:23:06 -03:00
53235263a3 Implement 0x00 version of EIP-191 in ECDSA Library (#4063) 2023-02-22 15:22:50 +01:00
adb861fb3b Change Governor.cancel to receive all parameters (#4056) 2023-02-22 10:00:41 +01:00
227473e88c Fix comment in ERC4626 on decimals default (#4060)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-02-21 19:27:34 -03:00
df814dd374 Update crytic/slither-action action to v0.3.0 (#4064)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-21 19:26:14 -03:00
1e245aa54b Add isValidERC1271SignatureNow to SignatureChecker library (#3932)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <fg@frang.io>
2023-02-21 15:16:44 +00:00
815bfbf383 Deprecate the timers library (#4062)
Co-authored-by: Francisco <fg@frang.io>
2023-02-21 11:18:50 -03:00
7ac4349710 Delete no longer needed .gitattributes file 2023-02-17 21:55:42 -03:00
08d085f2c9 Fix ERC4906 compliance of ERC721URIStorage (#4055)
Co-authored-by: Francisco <fg@frang.io>
2023-02-17 13:43:23 -03:00
96a2297e15 Add IERC4906 interface and use in ERC721 (#4012)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-02-17 09:26:10 +00:00
d64d7aa5d1 ERC4626 inflation attack mitigation (#3979)
Co-authored-by: Francisco <fg@frang.io>
2023-02-17 10:08:31 +01:00
d5d9d4bd3d Simplify ERC721Wrapper.depositFor to save gas (#4048) 2023-02-16 23:35:43 -03:00
5e76b26225 Add Subgraphs to docs sidebar 2023-02-16 14:34:17 -03:00
4ff538af58 Fix flaky timestamp tests (#4046) 2023-02-15 19:16:22 -03:00
4e8aa43a90 Add publishing integrity check after releasing (#4045)
Co-authored-by: Francisco <fg@frang.io>
2023-02-15 18:21:29 -03:00
6d18435098 Add RELEASING.md docs (#3981)
Co-authored-by: Francisco Giordano <fg@frang.io>
2023-02-14 20:03:37 -03:00
2c711d0b05 Restrict ERC721Wrapper wrap by direct transfer (#4043)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-02-14 17:47:07 -03:00
5a00628ed3 Update getsentry/action-github-app-token action to v2 (#4036)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-10 15:21:45 -03:00
dfcc1d16c5 Bump http-cache-semantics from 4.1.0 to 4.1.1 (#4024)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-09 18:42:08 -03:00
6259e13a0c Improve ERC721 Wrapper tests (#4039) 2023-02-09 22:36:14 +01:00
790cc5b65a Add timestamp based governor with EIP-6372 and EIP-5805 (#3934)
Co-authored-by: Francisco Giordano <fg@frang.io>
Co-authored-by: Ernesto García <ernestognw@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-02-09 22:33:55 +01:00
94cd8ef12e Add ERC721 Wrapper (#3863)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-02-09 13:43:34 -06:00
5b027e517e Add missing await in tests (#4037) 2023-02-08 21:03:27 +00:00
d625cb45ea Include EIP-5267 discovery in EIP-712 (#3969)
Co-authored-by: Francisco <frangio.1@gmail.com>
Co-authored-by: Francisco <fg@frang.io>
2023-02-08 15:53:57 +01:00
8177c4620e Improve gas efficiency in ECDSA (#3853)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Pascal Marco Caversaccio <pcaversaccio@users.noreply.github.com>
2023-02-07 22:18:33 -03:00
4d3e423443 Make ERC20Wrapper.underlying variable private (#4029)
Co-authored-by: Kimani Kelly <kimanikelly@Kimanis-MacBook-Pro.local>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-02-07 22:16:36 -03:00
95027565c4 Improve release-cycle.yml error reporting (#4034) 2023-02-07 22:15:24 -03:00
1575cc6908 Update Tally screenshots (#4030) 2023-02-06 12:20:12 -03:00
260e082ed1 Add a library for handling short strings in a gas efficient way (#4023)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-02-06 09:59:25 +01:00
3b591a48ac Add storageLayout to outputSelection 2023-02-03 21:15:59 -03:00
d13ec90f37 Add warning for supportsERC165InterfaceUnchecked edge case (#4017) 2023-02-03 16:15:41 -03:00
132e5aa97b Add IERC5313.sol (#4013)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-02-03 15:57:47 -03:00
740ce2d440 Update renovate.json 2023-02-02 21:08:41 -03:00
91e8d0ba3c Add string and bytes support to the StorageSlots library (#4008)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-02-01 18:46:05 -03:00
a70ee4e3bb Check storage layout consistency in PRs (#3967)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-01-31 17:45:24 -03:00
Mio
501a78e134 Fix typos (#4015) 2023-01-31 14:11:37 +01:00
591c12d22d Remove outdated note about virtual view functions (#4014) 2023-01-30 21:00:56 -03:00
1684c57922 Add ERC*Pausable warning for public pausing mechanism (#4007)
Co-authored-by: Francisco <fg@frang.io>
2023-01-28 20:21:07 -03:00
bc6de21fe2 Create ProposalSalt event for TimelockController (#4001)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-01-27 15:47:43 -03:00
5e28952cbd Add a public Governor.cancel function (#3983) 2023-01-26 20:46:11 +01:00
0320a718e8 Fix Governance docs reference to blocktime (#3994) 2023-01-26 14:38:34 -03:00
d6fb3d645f Add guidelines for pull requests (#4002) 2023-01-26 14:17:18 -03:00
69c8d1010e Make upgradeTo and upgradeToAndCall public (#3959)
Co-authored-by: Francisco <fg@frang.io>
2023-01-25 16:46:34 -03:00
a284569a7c Rename ERC20ReturnFalseMock copy.sol to ERC20ReturnFalseMock.sol (#4000) 2023-01-25 14:54:51 +01:00
a34dd8bb1b Add solidity language to missing code snippets (#3992) 2023-01-24 18:00:03 -03:00
b1c2c43d6a Lint should not override files (#3988) 2023-01-23 11:30:11 +01:00
c404862cba Use oz-upgrades-unsafe-allow-reachable in ERC1967Upgrade (#3971)
Co-authored-by: Francisco <fg@frang.io>
2023-01-19 22:00:53 +00:00
2a62fb4a2d Improve TransparentUpgradeableProxy's transparency (#3977)
Co-authored-by: Francisco <fg@frang.io>
2023-01-19 18:34:15 -03:00
afcdc58419 Delete tag next once latest is published (#3973)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2023-01-19 17:21:17 -03:00
dc1ffa79e7 Fix changeset action access to ref branch (#3978)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2023-01-19 16:36:54 -03:00
c8b466b7b5 Disable Foundry for slither-action
(cherry picked from commit 4072e853fe)
2023-01-18 23:31:59 -03:00
5a0863ccf0 Change job titles in release-cycle.yml (#3972) 2023-01-18 23:14:40 -03:00
0c89a8b771 Automate release process via Changesets (#3915)
Co-authored-by: Francisco <fg@frang.io>
2023-01-18 20:34:32 -03:00
f81e5f51c1 Use allow-reachable delegatecall in Multicall (#3970) 2023-01-18 18:07:13 -03:00
74b8ae9372 Annotate Multicall contract (#3961)
Co-authored-by: Francisco <fg@frang.io>
2023-01-18 19:40:35 +00:00
c9bc4f8203 Make Ownable2Step.acceptOwnership virtual (#3960) 2023-01-17 23:57:14 -03:00
88a64a802e Update guidelines and project documentation (#3966)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-01-17 23:44:56 -03:00
18691d1a6f Show if event parameter is indexed in docs (#3958)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-01-16 16:04:03 -03:00
785f65183c Fix wrong PR CHANGELOG link (#3957) 2023-01-13 17:23:05 -03:00
a5af0adce4 Ignore reentrancy inexecuteBatch and update Slither config (#3955)
Co-authored-by: Francisco <fg@frang.io>
2023-01-13 17:29:53 +00:00
d89e51ac42 Use actionlint on GitHub Actions workflows (#3953) 2023-01-13 11:05:13 -03:00
717fbc45cb Add docs on non-stability of internal function use (#3952) 2023-01-13 11:17:38 +01:00
ac30219a6a Add explicit permissions to docs workflow 2023-01-12 20:55:53 -03:00
42fab12584 Remove unnecessary CI cache 2023-01-12 17:43:54 -03:00
6b17b33430 Use a staticcall to fetch ERC20.decimals in ERC4626 (#3943)
Co-authored-by: Francisco <frangio.1@gmail.com>
2023-01-12 12:33:15 -03:00
5dbde1a5c9 Fix governance tutorial contract (#3948)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-01-12 10:43:29 -03:00
86de1e8b6c Pin Slither to 0.9.1 (#3949) 2023-01-12 09:50:06 +01:00
d59306bd06 Improve ERC20.decimals documentation (#3933) 2023-01-06 14:09:02 +01:00
a28aafdc85 Use Prettier for JS files (#3913)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2023-01-04 15:03:40 +01:00
88754d0b36 Add keys() accessor to EnumerableMaps (#3920)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2023-01-03 22:25:37 +01:00
2fc24fc8d4 Rename param to match the interface (#3917) 2023-01-03 12:30:51 -03:00
3a3c87b1a6 Fix docs for Math.log256 (#3916) 2023-01-03 11:52:53 -03:00
c1d9da4052 Use hardhat-exposed to reduce the need for mocks (#3666)
Co-authored-by: Francisco <fg@frang.io>
2023-01-03 14:38:13 +00:00
a81b0d0b21 Use unchecked in MerkleProof.processMultiProof (#3869)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
Co-authored-by: Francisco <fg@frang.io>
2023-01-02 22:04:49 -03:00
276b32a5ec Update lockfile (#3909)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-01-02 21:42:08 +00:00
4fc19ddb8d Add label to Renovate PRs 2023-01-02 18:03:24 -03:00
0892f877b8 Fix base for Renovate config 2023-01-02 17:45:42 -03:00
a4596cab05 Add warning on SELFDESTRUCT usage with isContract (#3875)
Co-authored-by: Francisco <fg@frang.io>
2022-12-30 22:00:53 +00:00
ccc175a9ed Add /out to .gitignore (#3908) 2022-12-30 16:51:22 -03:00
2336bd3e8e Simplify ESLint config (#3903) 2022-12-29 17:08:12 -03:00
cc27aed391 Improve Strings equal tests (#3902)
Co-authored-by: Francisco <fg@frang.io>
2022-12-29 19:11:15 +00:00
bc50d373e3 Rename approved parameter in IERC721 (#3900)
Co-authored-by: Francisco <fg@frang.io>
2022-12-28 23:32:50 +00:00
b0db207e4e Fix typos in testing files (#3899) 2022-12-28 20:16:56 -03:00
cafe5eb985 Update blurb on GovernorVotes compatibility (#3764) 2022-12-28 20:07:29 -03:00
8335676b0e Add Strings.toString for signed integers (#3773)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Gbolahan <89295500+GbolahanAnon@users.noreply.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-12-28 22:46:52 +00:00
96ff934ad0 Update forge-std submodule to v1.2.0 (#3885)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
2022-12-28 19:34:44 -03:00
7a6a9d1516 Add Strings.equal (#3774)
Co-authored-by: Francisco <fg@frang.io>
2022-12-28 18:23:24 -03:00
f799475d93 Fix links to Wizard (#3901) 2022-12-28 17:02:40 -03:00
446cd9f5fb Update lockfile (#3788)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-23 22:56:03 -03:00
b709eae01d Update Prettier Solidity (#3898) 2022-12-23 22:28:05 -03:00
4072e853fe Disable Foundry for slither-action 2022-12-23 17:43:10 -03:00
a3b9fac30e Update lockfileVersion to 2 (#3897) 2022-12-22 21:49:32 -03:00
3f16692dad Update dependency got to 11.8.5 [SECURITY] (#3894)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-22 21:08:26 -03:00
6b0c9f4e77 Revert "Disable Foundry for slither-action" (#3889) 2022-12-19 18:21:00 -03:00
3d7a93876a Improve documentation of Initializable getters (#3861)
Co-authored-by: Ernesto García <ernestognw@gmail.com>
2022-12-07 00:49:15 +00:00
98967feeb2 Disable Foundry for slither-action (#3860) 2022-12-06 11:55:49 -03:00
206a239448 Remove unused variables in tests (#3852) 2022-12-05 17:25:53 -03:00
93cd2ecb73 Improve readability of processMultiProof (#3854)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
2022-12-05 10:41:44 -03:00
c30fad9955 Add ERC-4626 Upgrade Note (#3849) 2022-12-02 17:10:43 -03:00
88fa71ecd5 Update dependency decode-uri-component to 0.2.1 [SECURITY] (#3845)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-02 12:51:09 -03:00
24d1bb668a Add Ownable2Step to the docs (#3836)
Co-authored-by: Francisco <fg@frang.io>
2022-12-01 10:34:58 -03:00
4e8b2fa659 Add additional conditions when testing ERC4626 roundtrip (#3839) 2022-11-30 15:44:38 -03:00
8f8fd84f1e Improve some NatSpec and revert reasons (#3809)
Co-authored-by: JulissaDantes <julissadcj@gmail.com>
2022-11-25 12:55:16 -03:00
8c9a831596 Fix whitespace in docs (#3832)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-11-23 12:48:26 -03:00
99589794db Add forgotten await to ERC1155URIStorage beforeEach block. (#3807) 2022-11-16 11:15:58 -03:00
b2970b96e5 Update lockfile 2022-11-10 23:27:54 -03:00
7c5f6bc2c8 Merge branch 'release-v4.8' 2022-11-09 19:23:01 -03:00
49c0e4370d 4.8.0 2022-11-08 11:29:29 -03:00
e0137d4cbe Fix outdated docs about timelock admin (#3806)
(cherry picked from commit 47d4ebb734)
2022-11-07 20:00:49 -03:00
e708b096cf Remove outdated note about hooks from documentation (#3789)
Co-authored-by: Francisco <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
(cherry picked from commit 634710d795)
2022-11-07 20:00:48 -03:00
47d4ebb734 Fix outdated docs about timelock admin (#3806) 2022-11-07 20:00:19 -03:00
634710d795 Remove outdated note about hooks from documentation (#3789)
Co-authored-by: Francisco <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-11-05 15:13:49 -03:00
c7315e8779 Add ERC4626 standard property tests (#3792)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-11-04 17:56:32 +01:00
0b6becd49f Remove the draft prefix to ERC20Permit (#3793)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-11-04 12:55:55 -03:00
88a3f95715 Optimize condition in _disableInitializers (#3787) 2022-11-03 20:57:56 -03:00
d5ca39e9a2 Rename _isVaultCollateralized to _isVaultHealthy for clarity (#3796) 2022-11-02 11:46:08 -03:00
16fa1834e5 Fix MerkleProof natspec
(cherry picked from commit 7d01facdb8)
2022-11-01 15:22:56 -03:00
7d01facdb8 Fix MerkleProof natspec 2022-11-01 15:22:47 -03:00
8bfcb65924 Update recommendation of JS library for merkle trees
(cherry picked from commit 8d105825e9)
2022-11-01 15:14:20 -03:00
8d105825e9 Update recommendation of JS library for merkle trees 2022-11-01 15:13:50 -03:00
36951d5838 few typo fixes (#3779) 2022-10-26 17:02:57 +02:00
f99bc4e0cf grammar fix (#3782) 2022-10-26 17:02:06 +02:00
25fe191202 Fix comment in ERC721Consecutive (#3778)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-10-25 01:46:51 +00:00
014ce9c6e6 ERC721ConsecutiveEnumerable is no longer unreachable
(cherry picked from commit a1948250ab)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-10-18 14:20:25 +02:00
a1948250ab ERC721ConsecutiveEnumerable is no longer unreachable 2022-10-18 14:13:05 +02:00
1f18fea1de 4.8.0-rc.2 2022-10-17 18:53:40 +02:00
1a41a503e0 Skip deleted file when updating release version in comments
(cherry picked from commit a71caa28e7)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-10-17 18:53:31 +02:00
a71caa28e7 Skip deleted file when updating release version in comments 2022-10-17 18:52:38 +02:00
3742c16948 Refactor consecutive transfer hooks (#3753)
(cherry picked from commit 08d5e4a9b0)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-10-17 18:42:01 +02:00
08d5e4a9b0 Refactor consecutive transfer hooks (#3753) 2022-10-17 17:09:23 +02:00
02722fcc03 Use unchecked in ERC20Votes and fix typo (#3748)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-10-17 17:00:47 +02:00
eb03304b70 Add ReentrancyGuard status getter (#3714)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-10-17 14:43:45 +02:00
c463b8a67e Fix typo in comment (#3765) 2022-10-17 14:42:18 +02:00
4e18cdc186 Update merkle multiproof docs with a caution note
(cherry picked from commit 8d908fe2c2)
2022-10-06 19:13:26 -03:00
8d908fe2c2 Update merkle multiproof docs with a caution note 2022-10-06 19:12:29 -03:00
47003aebec typo fix (#3752) 2022-10-05 17:47:39 -03:00
34e5863cd5 Reduce gas in log256 (#3745) 2022-10-05 17:19:28 -03:00
b7aff6363f Update lockfile (#3746)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-10-05 16:26:04 -03:00
9a11de924d Update crytic/slither-action action to v0.2.0 (#3751)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-10-05 16:24:21 -03:00
7201e6707f Fix typo in a comment (#3747) 2022-10-03 10:06:44 +02:00
561d1061fc Fix typos, improve wording and punctuation. (#3741) 2022-09-30 20:13:19 -03:00
50501a751e Update docs pipeline to solidity-docgen@0.6 (#3707)
(cherry picked from commit c52625018b)
2022-09-30 12:55:21 -03:00
f0de978a9e Improve handling and docs for ERC4626.decimals (#3733)
(cherry picked from commit 14f98dbb58)
2022-09-30 12:55:06 -03:00
16408a1dcf Update Arbitrum's vendored contracts to Nitro (#3692)
Co-authored-by: Francisco <frangio.1@gmail.com>
(cherry picked from commit 9938a85558)
2022-09-30 12:55:01 -03:00
0b3acb286a Recommended improvement to ERC721Consecutive (#3712)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit c22db8104e)
2022-09-30 12:54:56 -03:00
c52625018b Update docs pipeline to solidity-docgen@0.6 (#3707) 2022-09-30 12:52:45 -03:00
26dddee1c0 Fix typo (#3738) 2022-09-29 00:05:54 +02:00
14f98dbb58 Improve handling and docs for ERC4626.decimals (#3733) 2022-09-28 15:42:55 -03:00
9938a85558 Update Arbitrum's vendored contracts to Nitro (#3692)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-09-28 14:46:48 -03:00
c22db8104e Recommended improvement to ERC721Consecutive (#3712)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-09-27 16:13:15 -03:00
2a45f99fc4 Bump yargs-parser from 2.4.1 to 20.2.4 (#3726)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-27 12:08:57 -03:00
fb9345814b Remove unnecessary Address library import in SignatureChecker (#3731) 2022-09-27 10:26:17 +02:00
72bbe63ec7 Fix incorrect issue number in CHANGELOG (#3732) 2022-09-27 10:23:23 +02:00
ec88e9d6aa Add support for EOA target in Governor.relay (#3730)
(cherry picked from commit ed12acfb0a)
2022-09-26 15:28:14 -03:00
ed12acfb0a Add support for EOA target in Governor.relay (#3730) 2022-09-26 15:27:33 -03:00
5e8e8bb9f0 Fixes broken link (#3728) 2022-09-25 00:58:09 +02:00
561d0eead3 Add comments to unsafeAccess functions of Arrays library (#3718) 2022-09-23 19:23:32 -03:00
e2362ce74f Add documentation about the security of overrides (#3725) 2022-09-24 00:06:20 +02:00
c08c6e1b84 Add fuzz testing of mulDiv (#3717)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-09-23 18:45:20 -03:00
16791134c1 4.8.0-rc.1 2022-09-23 18:59:29 +02:00
76273ecd8e Change admin role allocation in TimelockControler constructor (#3722)
Co-authored-by: Francisco <frangio.1@gmail.com>
(cherry picked from commit 408055dfab)
2022-09-23 12:28:39 -03:00
d89a62e0a6 Improve ERC20FlashMint documentation (#3719)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
(cherry picked from commit aa4b901788)
2022-09-23 12:28:34 -03:00
089f9b95af Ignore specific warnings and make the rest into errors (#3695)
(cherry picked from commit 046121e080)
2022-09-23 12:28:19 -03:00
8740d8f7f3 Update ReentrancyGuard documentation (#3715)
(cherry picked from commit 06e678d6ef)
2022-09-23 12:28:14 -03:00
09369d265c Improve Initializable docstrings (#3704)
Co-authored-by: tincho <tinchoabbate@noreply.users.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
(cherry picked from commit a549ec673e)
2022-09-23 12:28:02 -03:00
1bbdf2005d Update the informational link (#3703)
(cherry picked from commit 76b538c226)
2022-09-23 12:27:56 -03:00
c8a0639afe Update dependency solidity-coverage to ^0.8.0 (#3681)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
(cherry picked from commit d6975f8e07)
2022-09-23 12:27:45 -03:00
3f6c8245aa Update lockfile (#3698)
(cherry picked from commit fac768cd2c)
2022-09-23 12:27:39 -03:00
408055dfab Change admin role allocation in TimelockControler constructor (#3722)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-09-23 16:58:56 +02:00
aa4b901788 Improve ERC20FlashMint documentation (#3719)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-09-23 11:48:39 +02:00
8f0d4d4a41 Fix fuzzing coverage (#3716) 2022-09-22 23:13:09 +02:00
046121e080 Ignore specific warnings and make the rest into errors (#3695) 2022-09-22 22:33:13 +02:00
06e678d6ef Update ReentrancyGuard documentation (#3715) 2022-09-22 21:42:52 +02:00
8d3d181207 Fix issue number in CHANGELOG (#3710)
(cherry picked from commit 8769b19860)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-09-20 11:00:49 +02:00
8769b19860 Fix issue number in CHANGELOG (#3710) 2022-09-20 11:00:13 +02:00
a615329423 Make ERC721Votes no longer a Draft (#3699)
(cherry picked from commit 7a14f6c595)
2022-09-17 13:04:59 -03:00
7a14f6c595 Make ERC721Votes no longer a Draft (#3699) 2022-09-17 18:03:03 +02:00
a549ec673e Improve Initializable docstrings (#3704)
Co-authored-by: tincho <tinchoabbate@noreply.users.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-09-16 18:16:37 +00:00
76b538c226 Update the informational link (#3703) 2022-09-15 19:41:12 -03:00
7deed7a769 Disable fuzzing on upgradeable contracts
(cherry picked from commit 9416743a10)
2022-09-13 19:20:50 -03:00
9416743a10 Disable fuzzing on upgradeable contracts 2022-09-13 19:20:29 -03:00
d6975f8e07 Update dependency solidity-coverage to ^0.8.0 (#3681)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-13 14:45:11 -03:00
fac768cd2c Update lockfile (#3698) 2022-09-13 11:43:30 -03:00
5e6fd491f3 4.8.0-rc.0 2022-09-07 18:08:32 -03:00
6a8d977d22 Skip changelog check if label is present (#3687) 2022-09-07 20:13:18 +00:00
3c552e6e03 Fix relevant warnings (#3685) 2022-09-07 15:56:18 -03:00
5d31ad0eb9 Fix: typo & grammar (#3684) 2022-09-07 20:45:09 +02:00
80ae402387 Add fuzz tests for Math.sqrt & Math.logX using Foundry (#3676)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-09-07 14:25:29 -03:00
c1d6e39aab Add log2, log10 and log256 functions (#3670) 2022-09-07 08:29:48 +00:00
d857ab5702 Fix EnumerableMap and EnumerableSet generation 2022-09-06 23:12:22 +02:00
42fe56031f Fix EnumerableMap and EnumerableSet warning format 2022-09-06 15:41:47 -03:00
171fa40bc8 ERC721 extension for efficient batch minting (#3311)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-09-05 23:09:30 +02:00
005a35b02a Optimize Math.max and SignedMath.max (#3679)
Co-authored-by: Daniel Liu <liudaniel@qq.com>
2022-09-05 11:37:43 -03:00
84fafa7832 Fix typos (#3677) 2022-09-05 09:34:42 +02:00
e09ccd1449 Optimize votes lookups for recent checkpoints (#3673) 2022-09-04 22:48:26 +02:00
a60ae0f18b Remove unused migrations directory 2022-09-02 20:48:21 -03:00
66ec91bc45 Update lockfile (#3669)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-01 17:04:36 -03:00
1c3410aa75 Fix grammar, wording, and typos in changelog (#3668) 2022-09-01 19:26:06 +02:00
1f0e7cdf04 Add Ownable2Step extension with 2-step transfer (#3620)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-09-01 15:46:44 +00:00
160bf1a6eb Optimize toString (#3573)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-08-31 23:08:35 +00:00
1eb55e2864 Remove unnecessary virtual (#3650) 2022-08-31 17:25:54 -03:00
4b8b92c8bf Make VestingWallet payable to allow funding at construction (#3665) 2022-08-31 20:18:57 +02:00
affe2456ea Search the whole checkpoint trace if offset overflows during initial exponential search. (#3662) 2022-08-30 22:59:23 +02:00
71aaca2d9d Extend Checkpoints with new sizes and lookup mechanisms (#3589) 2022-08-30 21:32:12 +02:00
4b16e88747 Improve recommendation on ERC721 transferFrom vs safeTransferFrom (#3647)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-08-29 17:40:21 -03:00
93bc3b657b Remove Codecov Patch status outside PRs 2022-08-26 14:03:47 -03:00
141130db27 Inherit asset decimals in ERC4626 (#3639) 2022-08-26 09:53:53 +02:00
e45b49eab8 Change 'caller' to 'sender' to more closely match EIP-4626 specs. (#3649) 2022-08-26 09:52:41 +02:00
62bab225c1 Fix wording and grammar in docs (#3645)
Fix wording and grammar
2022-08-25 10:52:41 -03:00
dc14c72e53 Update comment for _beforeTokenTransfer (#3586) 2022-08-24 12:07:35 -03:00
6b9bda872d Optimize Clones assembly (#3640) 2022-08-24 09:25:52 +00:00
6d8017d07e Optimize Create2.computeAddress (#3600)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-23 17:38:13 -03:00
24fc709533 Set up codespell (#3643) 2022-08-23 12:43:03 -03:00
f491e98d37 Use unchecked for ERC721 balance updates (#3524)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-23 02:48:09 +00:00
98c3a79b57 Change execution order to avoid reentry through the _beforeTokenTransfer hook (#3611)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-19 10:33:19 -03:00
17bc2dabe0 Procedurally generate EnumerableSet and EnumerableMap (#3429) 2022-08-19 14:12:18 +02:00
c797195f1d Add getter for number of releasable tokens in VestingWallet (#3580)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-19 02:05:18 +00:00
27d4293db6 Remove redundant changelog entry 2022-08-18 22:54:43 -03:00
26cf47a2be Add internal functions _getInitializedVersion and _isInitializing (#3598) 2022-08-18 20:42:31 -03:00
397c946141 Remove the draft prefix for EIP712 as it is now final (#3621)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-18 20:40:45 -03:00
2d4fb93087 Bump undici from 5.8.0 to 5.9.1 (#3632)
Bumps [undici](https://github.com/nodejs/undici) from 5.8.0 to 5.9.1.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.8.0...v5.9.1)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: indirect
...

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-18 18:47:26 -03:00
54dec0cad5 Fix typo in CHANGELOG (#3630) 2022-08-18 10:04:30 +02:00
bbb9a17872 Fix links in Utilities 2022-08-17 15:40:28 -03:00
6729fec74a Add warning about issue with Arbitrum cross-chain utilities (#3626) 2022-08-17 18:07:36 +02:00
4ae655c368 Update link to Consensys best practices (#3597)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-08-16 22:37:01 -03:00
324eda228c Remove redundant ECDSA constraint (#3591)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-08-16 18:08:07 +00:00
2dc086563f Fix misspelling in comment (#3613) 2022-08-12 10:44:20 +02:00
386848174b Fix preset links in docs 2022-08-11 11:16:41 -03:00
d693d89d99 Fix ECDSA signature malleability (#3610) 2022-08-10 15:40:03 -03:00
ff16696c9c Update ERC777 event documentation (#3594) 2022-08-10 14:21:23 +02:00
ca6f95a7da Improve documentation in UUPSUpgradeable (#3606) 2022-08-10 11:15:08 +02:00
d514cdd26e Preserve camelCase in GovernorCountingSimple (#3608) 2022-08-10 10:50:23 +02:00
85a9bed49e Remove unsued imported library "Math.sol" (#3605) 2022-08-10 10:39:47 +02:00
ec825d8999 Update lockfile (#3592)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-02 15:50:51 -03:00
ce0068c21e Fix lint error in scripts/checks/compareGasReports.js 2022-07-29 09:38:10 +02:00
bc14f8dc89 Fix contract bytecode length comparaison 2022-07-29 09:31:02 +02:00
7b5ef46371 Add a GH action that checks changelog (#3588) 2022-07-27 23:10:59 +02:00
c11acfd9d3 Fix compiler warning 2022-07-27 16:47:36 -03:00
ffb0ae76e3 Update changelog 2022-07-27 16:44:34 -03:00
dc4869eb23 Avoid returnbomb in ERC165Checker (#3587)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-27 16:41:05 +00:00
8ea1fc87c9 Keep track of historical quorum values (#3561)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-27 13:23:10 -03:00
0d91b620b7 Report changes to contract construction cost in CI (#3579) 2022-07-26 11:42:42 +02:00
81336aefb5 Fix arbitrum L1 to L2 crosschain call detection (#3578)
* Fix arbitrum L1 to L2 crosschain call detection

* fix BridgeArbitrumL2Mock

* update changelog

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-25 22:42:37 +02:00
7ddbfe181e Add access control comment for ERC721 _burn function (#3576)
* Added access control comment for ERC721 _burn function

* Update contracts/token/ERC721/ERC721.sol

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* Update contracts/token/ERC721/ERC721.sol

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

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-25 22:42:13 +02:00
48dd186870 Improve readme style (#3577)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-25 17:17:35 -03:00
fbf235661e Improve grammar in transfer error messages (#3542) 2022-07-25 17:01:14 -03:00
d1b1e17d23 Add internal overrideable _flashFee in ERC20FlashMint (#3551)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-22 14:44:58 -03:00
6e8d885ca7 Bump undici from 5.5.1 to 5.8.0 (#3569)
Bumps [undici](https://github.com/nodejs/undici) from 5.5.1 to 5.8.0.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v5.5.1...v5.8.0)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: indirect
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-21 20:01:10 -03:00
0ccfd2dbd3 Fix error in documentation and typo (#3567) 2022-07-21 12:55:10 -03:00
580b7ab816 Optimize safe casting of signed numbers (#3565) 2022-07-20 12:55:05 -03:00
d3ff81b37f Remove line length configuration for markdown files 2022-07-19 18:33:27 -03:00
1b1dd0ca2c Update link to ERC721 preset in docs (#3553)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-19 10:19:59 -03:00
e0149921b8 Update solmate repo link (#3563) 2022-07-19 10:09:02 -03:00
628a6e2866 Fix issues caused by abi.decode reverting (#3552)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-18 21:01:20 +00:00
d50e608a4f Add GitPOAP badge to display number of minted GitPOAPs for contributors (#3545) 2022-07-15 12:00:56 +00:00
6ab8d6a67e Improve spelling in ERC1155 revert reasons (#3433) 2022-07-12 14:00:12 +00:00
3210a8653b Modify ReentrancyGuard to reduce contract size (#3515)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-11 21:01:44 +00:00
96163c87e3 Implicitly clear ERC721 approval on burn (#3538) 2022-07-09 10:25:45 +02:00
3a1c020b7d Skip pull_request actions when fetching ref in gas-compare action 2022-07-09 09:49:16 +02:00
cfc9f840a0 Generate comparative gas repports on PR (#3532)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-08 19:07:39 -03:00
5e7e9acfa4 Fix broken forum URL (#3537)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-08 19:03:39 -03:00
8b778fa20d Move adds on total earlier to enable the use of unchecked (#3527)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-07-05 14:49:24 -03:00
e7397844f8 Update lockfile (#3523)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-07-04 16:47:26 -03:00
e02c378745 Implicitly clear ERC721 approval on transfers (#3481)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-07-04 15:29:15 -03:00
597654db00 Fixed typos in Math: sqrt function. (#3522) 2022-07-04 15:19:17 -03:00
5fbf494511 Use unchecked arithmetic in "_transfer", "_mint" and "_burn" (#3513) 2022-07-01 22:40:30 +02:00
7a8f269457 Fix changelog (#3519)
fix changelog
2022-06-30 12:02:59 +02:00
4a194b3a1c Fix typo in ERC4626 comments (#3518) 2022-06-30 12:01:04 +02:00
3dac7bbed7 Merge v4.7 back into master (#3516) 2022-06-29 12:34:30 +02:00
b159b3fee2 Minor wording fixes ERC4626 contract (#3510) 2022-06-28 14:56:09 +02:00
e734b42fc2 Enable using ERC165 check for one supported interface directly (#3339)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-06-27 17:51:33 -03:00
40172c22d9 Refactor address-to-hex-string conversion in _checkRole function (#3509)
Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-06-27 20:45:51 +00:00
6f88199db9 Optimize Address.functionCall removing redundant isContract check (#3469)
Co-authored-by: Francisco <frangio.1@gmail.com>
2022-06-27 17:02:33 -03:00
e8c60f92e3 Remove unused using statements in GovernorCompatibilityBravo (#3506) 2022-06-27 13:23:08 +02:00
2894059775 Support memory arrays in MerkleTree multiproof (#3493) 2022-06-27 13:15:52 +02:00
74738721dc Make ERC4626 _deposit and _withdraw internal virtual (#3504) 2022-06-24 14:55:20 -03:00
450c569d78 Add a caution note to ERC4626 about EOA access (#3503) 2022-06-24 10:22:10 +02:00
4bf9ab41f8 Clarify PaymentSplitter shares are static 2022-06-23 18:35:03 -03:00
83277ff916 Remove _setupRole docs usage in favor of _grantRole (#3489) 2022-06-17 15:27:00 -03:00
cb3f2ab900 Address.functionCall internal call stack simplification (#3468) 2022-06-16 15:17:09 +02:00
109778c17c Fix check for generated code when last updated is a release candidate 2022-06-14 15:38:04 -03:00
ed704d82b3 Output diff when test:generation fails 2022-06-14 15:31:26 -03:00
a55b7d1372 Rename ERC20TokenizedVault to ERC4626 (#3467) 2022-06-14 11:39:01 +02:00
5a0bff465d Enable the YUL IR pipeline when building with optimisations (#3279) 2022-06-13 12:16:37 -03:00
4135bf9707 Fix typos in timelock test (#3461)
fix typos
2022-06-11 09:31:30 +02:00
429b2242d8 Disable test for updated generated code on upgradeable contracts 2022-06-10 18:13:47 -03:00
c10a097fa8 Disable all checks but tests on upgradeable repository 2022-06-10 16:37:52 -03:00
cb7dbf8297 Disable coverage on upgradeable repository 2022-06-09 19:58:26 -03:00
7c75b8aa89 Add a SafeERC20:safePermit function (#3280) 2022-06-07 15:17:02 +00:00
08d109d877 Optimize Ownable and Pausable modifiers' size impact (#3347) 2022-06-07 15:21:58 +02:00
jjz
3ac4add548 Add sqrt for math (#3242) 2022-06-07 08:26:45 +02:00
3aa7ff74b0 Update lockfile (#3442)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-06 21:31:16 +00:00
994cf9b34b Clarify role of MinimalForwarder (#3399)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-06-06 18:27:56 -03:00
f6cd8032ba Fix typo in crosschain.adoc (#3453) 2022-06-06 18:20:23 -03:00
051cc9e446 Revert unwanted breaking change in the Clones library (#3456)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-06-06 20:41:48 +00:00
54ce38c2e5 Remove runtime check of ERC1967 storage slots (#3455) 2022-06-06 15:22:51 -03:00
d506e3b1a5 Simplify Initializable (#3450) 2022-06-03 19:30:50 +00:00
113443470c Reorder arguments for multiProof functions (#3447) 2022-06-03 09:36:14 +02:00
35090c1bf1 Add tests for improved coverage (#3448)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-06-02 23:01:55 +00:00
04204b8fb9 Improve GitHub Actions (#3451) 2022-06-02 19:42:49 -03:00
5e00787199 ERC4626 (#3171) 2022-06-02 10:03:03 +02:00
62f2c0531b Simplify ERC721 revert reasons (#3438) 2022-06-01 18:22:13 -03:00
4fc9fd3efe Support more efficient merkle proofs through calldata (#3200)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-06-01 20:36:42 +00:00
6d00281593 Fix typo in README.adoc (#3445)
Fix typo and link
2022-06-01 22:26:39 +02:00
2b0b0bb186 Fix merkle multiProof for single leaf tree (#3446) 2022-06-01 20:21:56 +00:00
6766b2de3b Add getters for number of unclaimed tokens in PaymentSplitter (#3350) 2022-05-31 19:26:18 +00:00
4942bd19e2 Update lockfile (#3430) 2022-05-30 17:27:50 -03:00
82a63f6389 Remove redundant require in ERC721 (#3434)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-05-26 22:22:35 -03:00
488dd562fb Improve error messages for ERC721 and 1155 (#3254)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-05-27 00:52:43 +00:00
61294a62af Restore previous behavior of initializer during construction (#3344) 2022-05-25 15:01:45 -03:00
f8157ac854 Add multiProofVerify (#3276) 2022-05-25 09:39:15 +02:00
65b45726b3 Add memory safe assembly annotations (#3384)
Co-authored-by: Nate <nate@Nates-MacBook-Pro.local>
2022-05-23 15:37:08 -03:00
c019e7c5bb Fix typo causing broken URL in ERC20Snapshot comment (#3428) 2022-05-23 14:57:57 -03:00
de74c8c62c Add bytes32 to uint enumerable map (#3416) 2022-05-23 08:02:27 +00:00
b61faf8368 Procedural SafeCast.sol generation (#3245) 2022-05-21 14:38:31 +02:00
c4f76cfa15 Add uint to uint enumerable map (#3338) 2022-05-20 13:31:53 +00:00
6339027a7a Add mention of events possibly emitted (#3421) 2022-05-19 13:35:42 -03:00
46db8a98b0 Rename return parameter (#3413) 2022-05-19 15:52:54 +02:00
c2077f0034 Add warning about use of delete (#3412) 2022-05-18 21:27:33 +02:00
ee4d8380d3 Fix minor typo in IERC1155 and IERC721 docs (#3419) 2022-05-18 15:19:41 +02:00
5772512058 Add address to string conversion (#3403)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-05-13 18:46:26 +00:00
cd2da98d4d Refactor magic constant in TimelocController test (#3397) 2022-05-12 22:23:56 +00:00
e633ee9ed3 Fix spelling and grammar in comments (#3408) 2022-05-11 18:10:00 -03:00
3bdf4bfd29 Annotate Memory-Safe Assembly (#3392) 2022-05-06 19:49:02 -03:00
3b9381dfb1 Add customizable fee receiver to ERC20FlashMint (#3327)
Co-authored-by: Mazen Khalil <mazen@immunityledger.org>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-05-06 18:46:23 -03:00
07b1b472c0 Improve wording consistency in code/doc (#3365) 2022-05-04 18:20:59 -03:00
4574ce45b6 Add a cross-chain guide for the documentation (#3325) 2022-05-04 21:19:04 +00:00
5ed20f32cf Update lockfile (#3386)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-04 18:04:52 -03:00
14ca3aeb79 Fix links in documentation (#3387) 2022-05-02 18:06:52 -03:00
1d2ab4f41c Add 4.6 upgradeability notice 2022-05-02 18:05:40 -03:00
be3cfa0f90 Add custom error to CrossChainEnabledPolygonChild (#3380) 2022-04-29 16:14:18 +02:00
fcf35e5722 Fix changelog merge issue (#3364) 2022-04-27 09:40:13 +02:00
a035b235b4 Release v4.6 (#3358)
* 4.6.0-rc.0

* Fix release script to only release @openzeppelin/contracts

(cherry picked from commit 2bd75a44bb)

* make ERC2981:royaltyInfo public (#3305)

(cherry picked from commit d2832ca7a9)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* add transpilation guards to the crosschain mocks (#3306)

(cherry picked from commit 9af5af8fff)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* Fix tests on upgradeable contracts after transpilation

(cherry picked from commit 0762479dd5)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* Remove unused constructor argument

(cherry picked from commit 69c3781043)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* Bump minimum Solidity version for Initializable.sol to 0.8.2 (#3328)

(cherry picked from commit cb14ea3c5c)

* Fix update-comment script to ignore invalid tags

(cherry picked from commit 848fef5b6c)
Signed-off-by: Hadrien Croubois <hadrien.croubois@gmail.com>

* 4.6.0

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-04-27 09:34:09 +02:00
848fef5b6c Fix update-comment script to ignore invalid tags 2022-04-26 18:48:34 +02:00
85627ffa91 Update links in docs (#3356)
* Update links in Access Control section

* Update Tally url

* Update web3 url to the freshest version
2022-04-26 11:34:51 +02:00
c12076fb7e Fix ERC777 link (#3351) 2022-04-23 16:35:04 +02:00
d4e6236b2b Fix deprecated expectEvent.inLogs #3332 (#3333) 2022-04-23 10:20:55 -03:00
5a75065659 Fix typo in CHANGELOG (#3341) 2022-04-14 02:08:36 -03:00
cb14ea3c5c Bump minimum Solidity version for Initializable.sol to 0.8.2 (#3328) 2022-04-14 00:21:52 +02:00
7392d83738 Bump minimist from 1.2.5 to 1.2.6 (#3303)
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-11 10:05:45 -03:00
28dd490726 Optimize ERC1167 proxy creation code by 1 opcode (#3329) 2022-04-08 19:27:11 -03:00
bc810db320 Use a customizable _execute function in TimelockController (#3317)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-04-08 17:05:57 -03:00
dd01889434 Remove outdated documentation in ERC2981._setTokenRoyalty 2022-04-07 20:34:04 -03:00
731e199038 Improve docs for ERC721URIStorage._burn (#3324) 2022-04-07 20:28:18 -03:00
d4d8d2ed97 Fix burn documentation (#3246)
Co-authored-by: xombxomb <dmfinn@wustl.edu>
2022-04-05 19:44:20 -03:00
f81b80fb39 Update lockfile (#3309)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-05 18:07:25 -03:00
3fb25b604b Update codecov/codecov-action action to v3 (#3320)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-05 16:56:57 -03:00
742e85be7c Change zero address revert message in the balanceOf function of ERC721 and ERC1155 (#3314) 2022-04-02 12:13:33 +02:00
69c3781043 Remove unused constructor argument 2022-04-01 00:16:32 -03:00
0762479dd5 Fix tests on upgradeable contracts after transpilation 2022-03-31 23:41:31 -03:00
049701eacd Update crytic/slither-action action to v0.1.1 (#3307)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-31 18:42:01 -03:00
f85eb5b725 Use slither action (#3278)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-31 18:28:47 -03:00
9af5af8fff add transpilation guards to the crosschain mocks (#3306) 2022-03-31 20:04:04 +02:00
d2832ca7a9 make ERC2981:royaltyInfo public (#3305) 2022-03-31 20:01:22 +02:00
2bd75a44bb Fix release script to only release @openzeppelin/contracts 2022-03-30 23:15:27 -03:00
2a4ca65404 Update release script to stop publishing old openzeppelin-solidity package 2022-03-30 22:29:53 -03:00
3f49408fb6 Move event definition at the top of IERC20, IERC777 and IERC1820 (#3228) 2022-03-30 12:36:37 -03:00
e7719ded56 Match IERC721 function order with EIP spec (#3287) 2022-03-30 12:34:17 -03:00
668a648bc6 Add utilities for CrossChain messaging (#3183)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-30 11:41:04 -03:00
02fcc75bb7 Add ERC1155URIStorage (#3210)
* Add ERC721URIStorage-like extension for ERC1155

* Add tests for ERC1155URIStorage extension

* add changelog entry for ERC721URIStorage

* Fix linting errors

* Emit URI event in ERC1155URIStorage

* Remove exists check and ERC1155Supply dependency

* Fix lint error

* Overwrite ERC1155 uri method

* Update ERC1155URIStorage specs

* Fix ERC1155URIStorageMock

* Rename _setTokenURI => _setURI in ERC1155URIStorage

* Add baseURI to ERC1155URIStorage

* Move super.uri call in ERC1155URIStorage

* Clearify ERC1155URIStorage description in change log

* reorder changelog & add documentation

* improve documentation

* fix typo

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-03-29 09:15:43 +00:00
ae270b0d89 Align data location of interface with implementation (#3295)
Co-authored-by: chriseth <chris@ethereum.org>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-28 17:48:28 -03:00
e029096ca4 Add Initialized event (#3294)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-28 15:36:30 -03:00
76eee35971 Improve revert message in Governor (#3275)
* Fixed typo

* fix testing and adding changelog

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-03-25 11:02:15 +01:00
bfff03c0d2 add missing PR link in Changelog 2022-03-25 10:36:08 +01:00
76fca3aec8 Add ERC721 and ERC1155 receiver support in Governor, Timelock (#3230)
* add ERC721 and ERC1155 receiver support in Governor, Timelock and MinimalForwarder (#3174)

* revert the nft receiver hooks from MinimalForwarder and linting updates

* add ERC165 support & simplify test

* add changelog entry

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-03-24 01:25:00 +01:00
74c9130a59 typo fixed (#3264) 2022-03-23 15:31:25 +01:00
15d5174139 Fix minor typo in CONTRIBUTING.md. (#3284) 2022-03-23 09:21:33 +01:00
05077f70f1 Update actions/cache action to v3 (#3277)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-22 18:47:06 -03:00
faf5820f03 Fix many spelling errors (#3274) 2022-03-22 18:16:20 -03:00
0eba5112c8 Allow the re-initialization of contracts (#3232)
* allow re-initialization of contracts

* fix lint

* use a private function to avoid code duplication

* use oz-retyped-from syntax

* add documentation

* rephrase

* documentation

* Update contracts/proxy/utils/Initializable.sol

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

* reinitialize test

* lint

* typos and style

* add note about relation between initializer and reinitializer

* lint

* set _initializing in the modifier

* remove unnecessary variable set

* rename _preventInitialize -> _disableInitializers

* rename preventInitialize -> disableInitializers

* test nested reinitializers in reverse order

* docs typos and style

* edit docs for consistency between initializer and reinitializer

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-22 18:06:29 +00:00
b13bdb0249 Add bytes32 to bytes32 enumerable map (#3192)
* feat(enumerablemap): add bytes32 to bytes32 map

* chore(changelog): edit CHANGELOG

* feat(enumerable map): edit struct visibility
2022-03-22 16:36:29 +01:00
c028c56965 Add changelog entry for #3259 (#3281)
* improve wrapper decimal support

* Update test/token/ERC20/extensions/ERC20Wrapper.test.js

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

* add changelog entry

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-22 16:11:20 +01:00
98716177ae Inherit ERC20Wrapper decimals from the underlying (#3259) 2022-03-22 09:55:49 +01:00
52eeebecda spelling fix 2022-03-14 12:54:08 +01:00
6a5bbfc4cb Refactor governor testing (#3194)
* starting a governor test refactor

* improve governor tests

* refactor compatibility tests using the governor helper

* improve governor helper

* improve governor helper

* refactor governor tests

* refactor testing

* fix testing (still TODO)

* fix tests

* fix tests

* fix spelling

* use different instances of GovernorHelper

* add vote with params support

* coverage

* simplify ERC165 helper

* remove unused proposal argument

* refactor setProposal

* lint

* refactor setProposal return values

* add a data default value

* improve proposal reconstruction and storage in helper

* proposal object refactoring

* lint

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-11 09:30:30 +01:00
8372b4f923 Update Hardhat to latest (#3260) 2022-03-10 18:40:50 -03:00
cc1c18098c Replace immutable with constant for _PERMIT_TYPEHASH (#3196)
* replace `immutable` with `constant` for _PERMIT_TYPEHASH

This commit is related to the following issue discussion: https://github.com/OpenZeppelin/contracts-wizard/issues/89#issuecomment-1042391318

Since Solidity version `0.6.12` the `keccak256` of string literals is treated specially and the hash is evaluated at compile time. Since the OpenZeppelin Wizard also uses `constant` for OpenZeppelin's AccessControl's roles declarations, it's good practice to make this consistent.

* Update CHANGELOG

* fix: ensure transpiler compatibility

* fix: fixing var-name-mixedcase

* prettier & lint check

Signed-off-by: Pascal Marco Caversaccio <pascal.caversaccio@hotmail.ch>

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-03-09 17:38:29 +01:00
c72281ea45 docs(erc1155): correct ERC1155Holder.sol import (#3250) 2022-03-09 09:32:46 +01:00
f2a311dc4a Make Votes._getVotingUnits view (#3225)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-08 21:39:53 +00:00
8b162e39b5 Add a canceller role to the TimelockController (#3165)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-08 18:28:20 -03:00
62eb4568be Optimize ERC721 _isApprovedOrOwner function (#3248) 2022-03-08 18:18:56 -03:00
f8bfa560e9 Use _spendAllowance in ERC20FlashMint (#3226)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-03-08 19:34:24 +00:00
212221d6ff Add mention of OpenZeppelin Defender in readme 2022-03-08 16:24:50 -03:00
Ben
c239e1af8d Fix typo (#3241)
Fix camelcase of 'lastvalue' to 'lastValue'
2022-03-04 15:36:19 -03:00
f590fcdfe9 Fix typo in Proxy.sol 2022-03-04 10:40:20 -03:00
9bded169e8 Update lockfile (#3229)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-02 16:47:58 -03:00
dc739dcbe3 Update actions/checkout action to v3 (#3234)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-01 20:02:06 -03:00
fd07cc6290 Extend Governor with parameterized votes (#3043)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-03-01 17:55:20 -03:00
f9d9279320 Update actions/setup-node action to v3 (#3220)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-01 12:54:10 -03:00
abdb20a6bd Change dependency source to work around Truffle limitation (#3218) 2022-02-25 14:49:58 +00:00
3e74681e77 Read allowance from overridable function in increase/decrease (#3213) 2022-02-23 11:28:44 -03:00
f6b614a7c5 Perform ERC1155.afterTokenTransfer hooks before acceptance check (#3215) 2022-02-22 18:24:03 -03:00
458697be32 Fix typos (#3207)
Fix misspelling in ERC20 contract comments.
2022-02-22 18:26:18 +01:00
af7ec04b78 Improve security of the onlyGovernance modifier (#3147)
* add a protection mechanism to prevent relaying transaction that are not
part of an execute operation

* more accurate relay authorization

* force reset the relay authorizations after executions

* refactor of the onlyGovernor modifier

* only whitelist when executor is not governor itself

* fix lint

* add private function for call permission management

* use deque

* fix lint

* remove unecessary dependency

* remove unecessary dependency

* comment rephrasing

* Update contracts/governance/Governor.sol

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

* cache keccak256(_msgData())

* use Context

* lint

* conditionnal clear

* add test to cover queue.clear()

* lint

* write more extended docs for onlyGovernance

* add changelog entry

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-02-18 21:03:03 +01:00
eae2384178 Add git paragraph to installation section (#3197) 2022-02-18 10:09:07 +01:00
6db2d0ea39 Update dependency yargs to v17 (#3101)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-17 23:13:19 -03:00
3fe65ef467 Fix docs navigation 2022-02-16 18:50:54 -03:00
525a672862 Add missing docs about reverts in DoubleEndedQueue 2022-02-16 16:42:33 -03:00
aace774961 Add a double ended queue (#3153)
* add vector, lifo and fifo structures

* fix lint

* need more memory for coverage

* remove Vector wrappers and gas optimization

* refactor Vector testing

* revert package.json changes

* rename to DoubleEndedQueue

* rename and refactor

* refactor tests and expand coverage

* test for custom errors

* add changelog entry

* add docs

* add sample code and note about storage vs. memory

* add available since

* lint

* use underscore for struct members

* add struct documentation

* remove SafeCast in length

* rename i -> index and improve docs

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-02-16 09:32:16 +01:00
6fec54f17f Update lockfile (#3193) 2022-02-15 23:03:33 -03:00
58f635312a Fix typo in CHANGELOG (#3191) 2022-02-15 11:27:08 +01:00
3dfc0a44f8 ERC1155 after token transfer hook (#3166)
* add Hooks _afterTokenTransfer

* avoid duplicate call to _asSingleton

* add changelog entry

* update changelog link to PR

* Update CHANGELOG.md

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

Co-authored-by: CryptoV8 <91189073+CryptoV8@users.noreply.github.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-02-14 16:55:43 +01:00
be3c5ca504 clarify _spendAllowance natspec (#3188) 2022-02-13 14:48:45 +01:00
4cb0926f11 Fix grammar typo in doc (#3186)
Add missing verb "are".
2022-02-11 15:41:22 +01:00
5b6112000c Update lockfile (#3067)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-09 18:26:27 -03:00
afb20119b3 Release v4.5 2022-02-09 18:16:53 -03:00
718d0ba2a1 Update dependency simple-get to 2.8.2 [SECURITY] (#3181)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-09 13:28:01 -03:00
591e30b7b6 Update dependency node-fetch to 2.6.7 [SECURITY] (#3176)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-09 12:38:52 -03:00
24f561a9a1 Update dependency shelljs to 0.8.5 [SECURITY] (#3177)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-09 12:38:39 -03:00
32b4eee9a3 Update dependency follow-redirects to 1.14.7 [SECURITY] (#3175)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-09 12:30:55 -03:00
c5a6cae898 Add a _spendAllowance function to ERC20 & ERC777 (#3170) 2022-02-09 12:26:53 -03:00
63b466901f Rename some ERC20 parameters to match the standard document. (#3167)
* Renames `sender` to `source`.

The naming variable was incorrect.  The source of the funds is *not* necessarily (and in most cases isn't) the sender of the transaction.  Also, this code has a `msgSender` which further adds confusion.

* Changes to `from/to` instead of `source`.

* Function documentation matches new names

* Changed other instances of sender/recipient to from/to.

Also changed `msgSender` to `owner` in the approval related methods.

* apply changes to IERC20.sol + minor renaming in ERC20.sol

Co-authored-by: Daniel Von Fange <daniel@leancoder.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-02-08 00:05:29 +01:00
defcf20042 Simplify ERC721 example (#3115) 2022-02-04 18:47:06 -03:00
b119b564df Improve wording for forum link in new issue templates 2022-02-04 12:17:36 -03:00
28986d2f2e Start tokenId at zero in docs (#3162)
- Fixes #3123
2022-02-03 11:45:06 -03:00
85566faeb2 Improve documentation of various governance aspects (#3161)
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-02-02 13:36:45 -03:00
bfd05d9646 Add "available since" on Base64.sol 2022-02-01 20:04:28 -03:00
574f3b89e1 Add proper revert message on overflow of totalSupply during burn (#3144) 2022-02-01 19:10:11 -03:00
ca755ce799 Add AddressToUintMap (#3150)
* add AddressToUintMap

* Update contracts/utils/structs/EnumerableMap.sol

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

* address comments

* lint code

* merge mocks into a single file

* add PR link to changelog entry

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-02-01 17:37:32 +01:00
fc01c51c13 Simplify inheritance to avoid overrides 2022-01-31 22:05:20 -03:00
21c5d623d6 Update Copyright notice and include contributors 2022-01-31 17:33:42 -03:00
4f8af2dceb Add test and docs describing a misuse of MerkleProof (#3090)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-31 12:10:13 -03:00
a81b07ce91 Fix typo in retrieval of onERC721Received selector (#3151) 2022-01-31 10:47:56 +01:00
f55d2716a8 Add function documentation for SignatureChecker. 2022-01-28 22:44:32 -03:00
ae54e6de1d Fix typo in CHANGELOG (#3138)
Remove repeated word "the".
2022-01-27 09:59:11 +01:00
fb950c6166 Add a virtual _checkRole(bytes32) internal function to AccessControl (#3137)
* add a virtual _onlyRole(bytes32) modifier

* _onlyRole(role) → _checkRole(role)

* update doc
2022-01-26 21:36:10 +01:00
6fb1e843cf Make royaltyInfo(uint256 _tokenId, uint256 _salePrice) virtual (#3133)
* Make royaltyInfo(uint256 _tokenId, uint256 _salePrice) virtual

Should be cherrypicked in release 4.5

* fix lint
2022-01-26 17:35:05 +01:00
78deae5a76 Fix typo in CHANGELOG (#3135)
Change `ERC2891` > `ERC2981`.
2022-01-26 09:30:53 +01:00
e298476a90 Simplification of ERC777's transfer & transferFrom by using _send (#3128)
* Update ERC777.sol

* Update ERC777.sol

* Update ERC777.sol

* Update ERC777.sol

* fix revert reasons

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-01-25 14:56:13 +01:00
a5e042cedf Fix use of ^ (xor) instead of ** (power) (#3130) 2022-01-24 18:55:12 -03:00
d57593c148 Lint 2022-01-24 00:42:17 -03:00
7c47ac7193 Add workflow to generate and update docs branches 2022-01-23 19:19:38 -03:00
8f70c8867e Fix typo in ERC721.sol (#3127) 2022-01-23 11:05:41 +01:00
b3b83b558e Add Slither reentrancy check in CI (#3047)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-21 00:15:54 +00:00
783ac759a9 upgrade solidity-coverage to 0.7.18 to support ERC165 coverage (#3117) 2022-01-18 00:05:17 -03:00
25eeb80b18 Fix broken pull request links in change log (#3114)
Co-authored-by: Han Lin Yap <codler@users.noreply.github.com>
2022-01-16 01:02:27 +01:00
3eb2d43b06 Move abs(int256) from Math to SafeMath (#3110)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-14 22:27:04 +00:00
ecae978cb5 Make more functions virtual (#3078)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-13 18:56:36 +00:00
e192fac276 Simplify UUPSUpgradeable along the lines of ERC1822 (#3021)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-13 15:46:55 -03:00
3458c1e854 Add SignedMath with math utilities for signed integers (#2686)
* add contract and tests

* avoid implicit cast

* add test cases

* fix test names

* modify avarage and add tests

* improve signed average formula

* fix lint

* better average formula

* refactor signed average testing

* add doc and changelog entry

* Update contracts/utils/math/SignedMath.sol

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

* remove ceilDiv

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-12 20:08:59 +01:00
dee772a55f Add documentation to TokenTimelock 2022-01-12 11:51:09 -03:00
1051db3802 Use abi.encodePacked instead of bytes.concat 2022-01-11 16:51:55 -03:00
a8f35b6c25 Make script executable 2022-01-11 16:41:59 -03:00
c366de3626 Fix encoding of signature+calldata in GovernorCompatibilityBravo (#3100)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-11 15:45:06 -03:00
80d8da0564 Do not reduce approval on transferFrom if current allowance is type(uint256).max (#3085)
* add feature request #3084

* Update contracts/token/ERC20/ERC20.sol

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

* Add changelog note

* add documentation

* test unlimitted allowance and add ERC777 unlimitted allowance

* reference PR in changelog

* documentation IERC20 -> ERC20

* use asciidoc note syntax

* use asciidoc note syntax

* typo

* typos

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2022-01-11 00:08:33 +01:00
fd7c4ba8f0 Update pragma in utils/Address.sol to 0.8.1 (#3098) 2022-01-10 19:47:43 -03:00
8dd744fc18 Add missing reference to PR in changelog 2022-01-09 17:50:05 +01:00
828fe365ee Normalize return variable names in IERC721Enumerable (#3079)
* Name missing return variable in IERC721Enumerable

For consistency among all functions.

* remove return variable names
2022-01-07 15:39:46 +01:00
a65c03bc0d Implement Non Fungible Token Royalty (EIP2981) (#3012)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2022-01-06 19:34:57 -03:00
1e815f3308 Restructure intro to ERC721 contract docs 2022-01-06 17:45:21 -03:00
d74605641c Fix typos (#3075)
Correct a couple of misspellings.
2022-01-05 10:13:30 +01:00
a9f994f063 Reduce ERC20 allowance before triggering transfer (#3056)
* Reduce ERC20 allowance before triggering transfer

* adapt ERC777 to reduce allowance before transfer

* fix test for ERC777

* use smaller number to reduce balance

* simplify test description

* don't use deprecated expectEvents.inLogs

* fix test

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-12-31 09:17:12 +00:00
ef0273fde1 Add Base64 library to utils (#2884)
* Add Base64 library to utils

* Fix typo on Base64 padding

* Added documentation for Base64 and references from ERC1155 and ERC721

* Updated Changelog

* Fix typo in utilities doc

* use mstore8 to improve memory accesses

* use shorter strings with encodePacked

* do not use using-for syntax, for clarity

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-29 20:41:20 +01:00
da3a9ae18b Avoid assembly in signature V and S decomposition (#3060)
* Avoid assembly in signature V and S decomposition

* Update ECDSA.sol
2021-12-29 16:22:39 +01:00
e3391cd65f Fix typo (#3058) 2021-12-28 21:52:00 -03:00
e9e177f53b Fix ERC2771ContextMock for upgradeable contracts 2021-12-27 21:26:47 -03:00
fe38eae6cd Re-enable immutable forwarder in ERC2771Context (#2917)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-27 21:21:56 -03:00
915ca181ba Add Certora's Governance verification rules (#2997)
Co-authored-by: Shelly Grossman <shelly@certora.com>
Co-authored-by: Aleksander Kryukov <58052996+RedLikeRosesss@users.noreply.github.com>
Co-authored-by: Michael M <91594326+MichaelMorami@users.noreply.github.com>
Co-authored-by: Aleksander Kryukov <firealexkryukov@gmail.com>
2021-12-27 19:11:59 -03:00
a0a8bbb57f Remove note about enabling self-delegation 2021-12-27 12:24:37 -03:00
1ffcb10bd2 Change release script to only update version comment for changed files (#3033)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-22 19:21:45 -03:00
10c8fcd3b8 Use invalid opcode to consume all gas in MinimalForwarder (#3035) 2021-12-22 19:01:24 -03:00
cafd900ad6 Fix memory leak in merkle verification (#3039) 2021-12-21 17:01:28 -03:00
e667ec9533 Add Governor Timelock Control Warning (#3032)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-20 17:00:13 -03:00
5ac4d93ae3 Add missing letter (#3034) 2021-12-17 15:46:45 +00:00
0550d13aee Add ERC721 import in tutorial 2021-12-16 18:29:31 -03:00
d95cdaae8e Replace excodesize assembly with address.code.length (https://github.com/ethereum/solidity/releases/tag/v0.8.1) (#3025) 2021-12-15 18:54:10 +01:00
4a9cc8b491 Merge branch 'release-v4.4' 2021-12-14 13:34:03 -03:00
bda61cd5e5 Fix typo (#3016) 2021-12-12 22:55:19 +01:00
b42b05311b Add ERC721Votes for NFT-based governance (#2944)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
Co-authored-by: Hadrien Croubois <hadrien@openzeppelin.com>
2021-12-10 18:58:45 -03:00
9a7e4a0112 Remove trailing whitespace 2021-12-10 13:09:46 -03:00
e141d8917a Create v4.4.1 section in changelog 2021-12-10 13:04:03 -03:00
08840b9f8c Update initializer modifier to prevent reentrancy during initialization (#3006)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-10 13:02:35 -03:00
0c858e2071 Improve revert reason in ERC721 (#2975)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-09 23:42:18 +00:00
4625192940 Fix changelog entry for GovernorPreventLateQuorum 2021-12-09 20:32:53 -03:00
2a09e50d09 Update lockfile (#2993)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-12-08 20:17:11 -03:00
04109f8bee Address: explain dangers of isContract (#2994)
Co-authored-by: Ivo Georgiev <ivo@strem.io>
2021-12-08 20:10:40 -03:00
8ef7655e7b Fix a typo in erc20-supply.adoc (#3005)
Fix a typo
2021-12-07 13:41:21 +01:00
a05312f1b7 fix changelog structure 2021-12-01 18:20:42 +01:00
abf6024faf Add a governor module to protect against late quorum (#2973)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-12-01 13:56:31 -03:00
6089f11c2f Add a relay mechanism in the governor (#2926)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-11-30 17:19:20 -03:00
3536587665 Fix typo (#2992) 2021-11-30 17:15:29 +01:00
7d17acfb2f Merge branch 'release-v4.4' 2021-11-25 16:56:07 -03:00
0859c70936 Make VestingWallet token event argument indexed (#2988) 2021-11-25 14:38:18 -03:00
6481b05e4f Add changelog entry for deprecation of presets 2021-11-25 14:23:30 -03:00
c739d1976b Update security email domain and Immunefi text 2021-11-25 11:05:11 -03:00
f6db5c1f30 A function which returns the absolute value of a signed value (#2984)
* Add a function which returns the absolute (and obviously unsigned) value of a signed value.

* add changelog entry and fix lint

Co-authored-by: Hadrien Croubois <hadrien.croubois@gmail.com>
2021-11-24 14:09:05 +01:00
2f2604d673 Deprecate presets in favor of Wizard (#2986) 2021-11-24 10:14:14 +01:00
86bd4d7389 add bug bounty info 2021-11-22 15:05:21 +01:00
52d42d6e03 Improve docs wording on constructors and proxies (#2935) 2021-11-19 15:08:56 -03:00
4c8642b70a Update lockfile (#2932)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-11-18 11:29:08 -03:00
a57e638f57 Improve GovernorTimelockControl.state() to detect direct cancel (#2977) 2021-11-18 09:53:05 -03:00
6e5bf05211 make setters in GovernorSettings virtual 2021-11-18 10:15:48 +01:00
a94cf0509f Make quorum behavior match GovernorBravo (#2974)
* Make quorum inclusive minimum in GovernorCompatibilityBravo

* add PR link
2021-11-16 13:24:22 +01:00
e63b09c9ad Fix Timelock Controller description typo (#2960) 2021-11-11 14:49:53 +01:00
57630d2a64 Fix link to #2849 in changelog 2021-11-09 15:39:58 -03:00
2b4e023180 Fix typo and reframed a sentence (#2951)
Corrected spelling for a word on line number 3 and sentence reframed on line number 309
2021-11-08 23:05:32 +01:00
b5daea6d5f Grammar correction in utilities doc (#2952)
Fix grammar in a sentence
2021-11-08 23:04:44 +01:00
4088540aef Fix ERC1155 supply tracking (#2956)
Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
2021-11-08 18:47:21 -03:00
ce51655c81 fix typos in GovernorSettings (#2957) 2021-11-08 17:23:23 +01:00
7579828180 AccessControlEnumerable: Hook into the internal function (#2946)
* AccessControlEnumerable: Hook into the internal function

* add changelog entry
2021-11-08 12:22:13 -03:00
342265d290 Update governance.adoc (#2948) 2021-11-06 22:29:51 +01:00
5cdf2a8fdf Fix markdown rendering in utilities.adoc (#2934) 2021-11-04 19:08:23 -03:00
fbfe19d6db Improve documentation around ERC1155 2021-11-03 10:35:42 -03:00
ee14987721 Improve formatting of docs for TimelockController roles 2021-11-01 17:32:00 -03:00
5a398018ee Add missing newline in docs 2021-11-01 17:26:37 -03:00
a73ad8cc8c Fix update-comment.js 2021-11-01 17:26:27 -03:00
46ce0cfa33 Update index.adoc (#2922)
Fixed typo
2021-10-28 17:44:07 -03:00
a51e181e3b Fix unbounded recursion in ERC20WithAutoMinerReward example 2021-10-28 13:14:21 -03:00
2b046d79e1 Fix changelog links 2021-10-27 18:14:06 -03:00
a56258945a Add mention of Solidity policy in our own security policy 2021-10-27 11:19:54 -03:00
599 changed files with 47697 additions and 34320 deletions

12
.changeset/config.json Normal file
View File

@ -0,0 +1,12 @@
{
"$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json",
"changelog": [
"@changesets/changelog-github",
{
"repo": "OpenZeppelin/openzeppelin-contracts"
}
],
"commit": false,
"access": "public",
"baseBranch": "master"
}

View File

@ -6,6 +6,7 @@ coverage:
patch:
default:
target: 95%
only_pulls: true
project:
default:
threshold: 1%

View File

@ -17,5 +17,5 @@ indent_size = 4
[*.js]
indent_size = 2
[*.adoc]
[*.{adoc,md}]
max_line_length = 0

View File

@ -1,64 +1,20 @@
{
"root": true,
"extends" : [
"standard",
"plugin:promise/recommended",
],
"plugins": [
"mocha-no-only",
"promise",
"eslint:recommended",
"prettier",
],
"env": {
"browser" : true,
"node" : true,
"mocha" : true,
"jest" : true,
"es2022": true,
"browser": true,
"node": true,
"mocha": true,
},
"globals" : {
"artifacts": false,
"contract": false,
"assert": false,
"web3": false,
"usePlugin": false,
"extendEnvironment": false,
},
"rules": {
// Strict mode
"strict": ["error", "global"],
// Code style
"array-bracket-spacing": ["off"],
"camelcase": ["error", {"properties": "always"}],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": ["error", {"before": false, "after": true}],
"dot-notation": ["error", {"allowKeywords": true, "allowPattern": ""}],
"eol-last": ["error", "always"],
"eqeqeq": ["error", "smart"],
"generator-star-spacing": ["error", "before"],
"indent": ["error", 2],
"linebreak-style": ["error", "unix"],
"max-len": ["error", 120, 2],
"no-debugger": "off",
"no-dupe-args": "error",
"no-dupe-keys": "error",
"no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
"no-redeclare": ["error", {"builtinGlobals": true}],
"no-trailing-spaces": ["error", { "skipBlankLines": false }],
"no-undef": "error",
"no-use-before-define": "off",
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"space-before-function-paren": ["error", "always"],
"mocha-no-only/mocha-no-only": ["error"],
"promise/always-return": "off",
"promise/avoid-new": "off",
},
"parserOptions": {
"ecmaVersion": 2018
"artifacts": "readonly",
"contract": "readonly",
"web3": "readonly",
"extendEnvironment": "readonly",
"expect": "readonly",
}
}

1
.gitattributes vendored
View File

@ -1 +0,0 @@
*.sol linguist-language=Solidity

View File

@ -1,4 +1,4 @@
contact_links:
- name: Support request
- name: Questions & Support Requests
url: https://forum.openzeppelin.com/c/support/contracts/18
about: Ask the community in the Community Forum
about: Ask in the OpenZeppelin Forum

View File

@ -17,4 +17,4 @@ Fixes #???? <!-- Fill in with issue number -->
- [ ] Tests
- [ ] Documentation
- [ ] Changelog entry
- [ ] Changeset entry (run `npx changeset add`)

49
.github/actions/gas-compare/action.yml vendored Normal file
View File

@ -0,0 +1,49 @@
name: Compare gas costs
inputs:
token:
description: github token
required: true
report:
description: report to read from
required: false
default: gasReporterOutput.json
out_report:
description: report to read
required: false
default: ${{ github.ref_name }}.gasreport.json
ref_report:
description: report to read from
required: false
default: ${{ github.base_ref }}.gasreport.json
runs:
using: composite
steps:
- name: Download reference report
if: github.event_name == 'pull_request'
run: |
RUN_ID=`gh run list --repo ${{ github.repository }} --branch ${{ github.base_ref }} --workflow ${{ github.workflow }} --limit 100 --json 'conclusion,databaseId,event' --jq 'map(select(.conclusion=="success" and .event!="pull_request"))[0].databaseId'`
gh run download ${RUN_ID} --repo ${{ github.repository }} -n gasreport
env:
GITHUB_TOKEN: ${{ inputs.token }}
shell: bash
continue-on-error: true
id: reference
- name: Compare reports
if: steps.reference.outcome == 'success' && github.event_name == 'pull_request'
run: |
node scripts/checks/compareGasReports.js ${{ inputs.report }} ${{ inputs.ref_report }} >> $GITHUB_STEP_SUMMARY
env:
STYLE: markdown
shell: bash
- name: Rename report for upload
if: github.event_name != 'pull_request'
run: |
mv ${{ inputs.report }} ${{ inputs.out_report }}
shell: bash
- name: Save report
if: github.event_name != 'pull_request'
uses: actions/upload-artifact@v3
with:
name: gasreport
path: ${{ inputs.out_report }}

19
.github/actions/setup/action.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Setup
runs:
using: composite
steps:
- uses: actions/setup-node@v3
with:
node-version: 14.x
- uses: actions/cache@v3
id: cache
with:
path: '**/node_modules'
key: npm-v3-${{ hashFiles('**/package-lock.json') }}
- name: Install dependencies
run: npm ci
shell: bash
if: steps.cache.outputs.cache-hit != 'true'
env:
SKIP_COMPILE: true

View File

@ -0,0 +1,55 @@
name: Compare storage layouts
inputs:
token:
description: github token
required: true
buildinfo:
description: compilation artifacts
required: false
default: artifacts/build-info/*.json
layout:
description: extracted storage layout
required: false
default: HEAD.layout.json
out_layout:
description: storage layout to upload
required: false
default: ${{ github.ref_name }}.layout.json
ref_layout:
description: storage layout for the reference branch
required: false
default: ${{ github.base_ref }}.layout.json
runs:
using: composite
steps:
- name: Extract layout
run: |
node scripts/checks/extract-layout.js ${{ inputs.buildinfo }} > ${{ inputs.layout }}
shell: bash
- name: Download reference
if: github.event_name == 'pull_request'
run: |
RUN_ID=`gh run list --repo ${{ github.repository }} --branch ${{ github.base_ref }} --workflow ${{ github.workflow }} --limit 100 --json 'conclusion,databaseId,event' --jq 'map(select(.conclusion=="success" and .event!="pull_request"))[0].databaseId'`
gh run download ${RUN_ID} --repo ${{ github.repository }} -n layout
env:
GITHUB_TOKEN: ${{ inputs.token }}
shell: bash
continue-on-error: true
id: reference
- name: Compare layouts
if: steps.reference.outcome == 'success' && github.event_name == 'pull_request'
run: |
node scripts/checks/compare-layout.js --head ${{ inputs.layout }} --ref ${{ inputs.ref_layout }}
shell: bash
- name: Rename artifacts for upload
if: github.event_name != 'pull_request'
run: |
mv ${{ inputs.layout }} ${{ inputs.out_layout }}
shell: bash
- name: Save artifacts
if: github.event_name != 'pull_request'
uses: actions/upload-artifact@v3
with:
name: layout
path: ${{ inputs.out_layout }}

18
.github/workflows/actionlint.yml vendored Normal file
View File

@ -0,0 +1,18 @@
name: lint workflows
on:
pull_request:
paths:
- '.github/**/*.ya?ml'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Add problem matchers
run: |
# https://github.com/rhysd/actionlint/blob/3a2f2c7/docs/usage.md#problem-matchers
curl -LO https://raw.githubusercontent.com/rhysd/actionlint/main/.github/actionlint-matcher.json
echo "::add-matcher::actionlint-matcher.json"
- uses: docker://rhysd/actionlint:latest

28
.github/workflows/changeset.yml vendored Normal file
View File

@ -0,0 +1,28 @@
name: changeset
on:
pull_request:
branches:
- master
types:
- opened
- synchronize
- labeled
- unlabeled
concurrency:
group: changeset-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
if: ${{ !contains(github.event.pull_request.labels.*.name, 'ignore-changeset') }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Include history so Changesets finds merge-base
- name: Set up environment
uses: ./.github/actions/setup
- name: Check changeset
run: npx changeset status --since=origin/${{ github.base_ref }}

111
.github/workflows/checks.yml vendored Normal file
View File

@ -0,0 +1,111 @@
name: checks
on:
push:
branches:
- master
- release-v*
pull_request: {}
workflow_dispatch: {}
concurrency:
group: checks-${{ github.ref }}
cancel-in-progress: true
env:
NODE_OPTIONS: --max_old_space_size=5120
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: npm run lint
tests:
runs-on: ubuntu-latest
env:
FORCE_COLOR: 1
GAS: true
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- name: Run tests and generate gas report
run: npm run test
- name: Check linearisation of the inheritance graph
run: npm run test:inheritance
- name: Check proceduraly generated contracts are up-to-date
run: npm run test:generation
- name: Compare gas costs
uses: ./.github/actions/gas-compare
with:
token: ${{ github.token }}
tests-upgradeable:
runs-on: ubuntu-latest
env:
FORCE_COLOR: 1
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Include history so patch conflicts are resolved automatically
- name: Set up environment
uses: ./.github/actions/setup
- name: Transpile to upgradeable
run: bash scripts/upgradeable/transpile.sh
- name: Run tests
run: npm run test
- name: Check linearisation of the inheritance graph
run: npm run test:inheritance
- name: Check storage layout
uses: ./.github/actions/storage-layout
with:
token: ${{ github.token }}
tests-foundry:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly
- name: Run tests
run: forge test -vv
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: npm run coverage
- uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
slither:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: rm foundry.toml
- uses: crytic/slither-action@v0.3.0
with:
node-version: 18.15
codespell:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run CodeSpell
uses: codespell-project/actions-codespell@v1.0
with:
check_filenames: true
skip: package-lock.json,*.pdf

19
.github/workflows/docs.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Build Docs
on:
push:
branches: [release-v*]
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- run: node scripts/update-docs-branch.js
- run: git push --all origin

View File

@ -0,0 +1,68 @@
name: formal verification
on:
pull_request:
types:
- opened
- reopened
- synchronize
- labeled
workflow_dispatch: {}
env:
PIP_VERSION: '3.10'
JAVA_VERSION: '11'
SOLC_VERSION: '0.8.19'
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
apply-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Apply patches
run: make -C certora apply
verify:
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'formal-verification')
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up environment
uses: ./.github/actions/setup
- name: identify specs that need to be run
id: arguments
run: |
if [[ ${{ github.event_name }} = 'pull_request' ]];
then
RESULT=$(git diff ${{ github.event.pull_request.head.sha }}..${{ github.event.pull_request.base.sha }} --name-only certora/specs/*.spec | while IFS= read -r file; do [[ -f $file ]] && basename "${file%.spec}"; done | tr "\n" " ")
else
RESULT='--all'
fi
echo "result=$RESULT" >> "$GITHUB_OUTPUT"
- name: Install python
uses: actions/setup-python@v4
with:
python-version: ${{ env.PIP_VERSION }}
cache: 'pip'
- name: Install python packages
run: pip install -r requirements.txt
- name: Install java
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: ${{ env.JAVA_VERSION }}
- name: Install solc
run: |
wget https://github.com/ethereum/solidity/releases/download/v${{ env.SOLC_VERSION }}/solc-static-linux
sudo mv solc-static-linux /usr/local/bin/solc
chmod +x /usr/local/bin/solc
- name: Verify specification
run: |
make -C certora apply
node certora/run.js ${{ steps.arguments.outputs.result }} >> "$GITHUB_STEP_SUMMARY"
env:
CERTORAKEY: ${{ secrets.CERTORAKEY }}

218
.github/workflows/release-cycle.yml vendored Normal file
View File

@ -0,0 +1,218 @@
# D: Manual Dispatch
# M: Merge release PR
# C: Commit
# ┌───────────┐ ┌─────────────┐ ┌────────────────┐
# │Development├──D──►RC-Unreleased│ ┌──►Final-Unreleased│
# └───────────┘ └─┬─────────▲─┘ │ └─┬────────────▲─┘
# │ │ │ │ │
# M C D M C
# │ │ │ │ │
# ┌▼─────────┴┐ │ ┌▼────────────┴┐
# │RC-Released├───┘ │Final-Released│
# └───────────┘ └──────────────┘
name: Release Cycle
on:
push:
branches:
- release-v*
workflow_dispatch: {}
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
state:
name: Check state
permissions:
pull-requests: read
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- id: state
name: Get state
uses: actions/github-script@v6
env:
TRIGGERING_ACTOR: ${{ github.triggering_actor }}
with:
result-encoding: string
script: await require('./scripts/release/workflow/state.js')({ github, context, core })
outputs:
# Job Flags
start: ${{ steps.state.outputs.start }}
changesets: ${{ steps.state.outputs.changesets }}
promote: ${{ steps.state.outputs.promote }}
publish: ${{ steps.state.outputs.publish }}
merge: ${{ steps.state.outputs.merge }}
# Global variables
is_prerelease: ${{ steps.state.outputs.is_prerelease }}
start:
needs: state
name: Start new release candidate
permissions:
contents: write
actions: write
if: needs.state.outputs.start == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- id: start
name: Create branch with release candidate
run: bash scripts/release/workflow/start.sh
- name: Re-run workflow
uses: actions/github-script@v6
env:
REF: ${{ steps.start.outputs.branch }}
with:
script: await require('./scripts/release/workflow/rerun.js')({ github, context })
promote:
needs: state
name: Promote to final release
permissions:
contents: write
actions: write
if: needs.state.outputs.promote == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- name: Exit prerelease state
if: needs.state.outputs.is_prerelease == 'true'
run: bash scripts/release/workflow/exit-prerelease.sh
- name: Re-run workflow
uses: actions/github-script@v6
with:
script: await require('./scripts/release/workflow/rerun.js')({ github, context })
changesets:
needs: state
name: Update PR to release
permissions:
contents: write
pull-requests: write
if: needs.state.outputs.changesets == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # To get all tags
- name: Set up environment
uses: ./.github/actions/setup
- name: Set release title
uses: actions/github-script@v6
with:
result-encoding: string
script: await require('./scripts/release/workflow/set-changesets-pr-title.js')({ core })
- name: Create PR
uses: changesets/action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PRERELEASE: ${{ needs.state.outputs.is_prerelease }}
with:
version: npm run version
title: ${{ env.TITLE }}
commit: ${{ env.TITLE }}
body: | # Wait for support on this https://github.com/changesets/action/pull/250
This is an automated PR for releasing ${{ github.repository }}
Check [CHANGELOG.md](${{ github.repository }}/CHANGELOG.md)
publish:
needs: state
name: Publish to npm
environment: npm
permissions:
contents: write
if: needs.state.outputs.publish == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up environment
uses: ./.github/actions/setup
- id: pack
name: Pack
run: bash scripts/release/workflow/pack.sh
env:
PRERELEASE: ${{ needs.state.outputs.is_prerelease }}
- name: Upload tarball artifact
uses: actions/upload-artifact@v3
with:
name: ${{ github.ref_name }}
path: ${{ steps.pack.outputs.tarball }}
- name: Tag
run: npx changeset tag
- name: Publish
run: bash scripts/release/workflow/publish.sh
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
TARBALL: ${{ steps.pack.outputs.tarball }}
TAG: ${{ steps.pack.outputs.tag }}
- name: Push tags
run: git push --tags
- name: Create Github Release
uses: actions/github-script@v6
env:
PRERELEASE: ${{ needs.state.outputs.is_prerelease }}
with:
script: await require('./scripts/release/workflow/github-release.js')({ github, context })
outputs:
tarball_name: ${{ steps.pack.outputs.tarball_name }}
integrity_check:
needs: publish
name: Tarball Integrity Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Download tarball artifact
id: artifact
# Replace with actions/upload-artifact@v3 when
# https://github.com/actions/download-artifact/pull/194 gets released
uses: actions/download-artifact@e9ef242655d12993efdcda9058dee2db83a2cb9b
with:
name: ${{ github.ref_name }}
- name: Check integrity
run: bash scripts/release/workflow/integrity-check.sh
env:
TARBALL: ${{ steps.artifact.outputs.download-path }}/${{ needs.publish.outputs.tarball_name }}
merge:
needs: state
name: Create PR back to master
permissions:
contents: write
pull-requests: write
if: needs.state.outputs.merge == 'true'
runs-on: ubuntu-latest
env:
MERGE_BRANCH: merge/${{ github.ref_name }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # All branches
- name: Set up environment
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- name: Create branch to merge
run: |
git checkout -B "$MERGE_BRANCH" "$GITHUB_REF_NAME"
git push -f origin "$MERGE_BRANCH"
- name: Create PR back to master
uses: actions/github-script@v6
with:
script: |
await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
head: process.env.MERGE_BRANCH,
base: 'master',
title: '${{ format('Merge {0} branch', github.ref_name) }}'
});

View File

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

View File

@ -1,4 +1,4 @@
name: Upgradeable Trigger
name: transpile upgradeable
on:
push:
@ -7,17 +7,24 @@ on:
- release-v*
jobs:
trigger:
transpile:
environment: push-upgradeable
runs-on: ubuntu-latest
steps:
- id: app
uses: getsentry/action-github-app-token@v1
- uses: actions/checkout@v3
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 }}" } }'
repository: OpenZeppelin/openzeppelin-contracts-upgradeable
fetch-depth: 0
token: ${{ secrets.GH_TOKEN_UPGRADEABLE }}
- name: Fetch current non-upgradeable branch
run: |
git fetch "https://github.com/${{ github.repository }}.git" "$REF"
git checkout FETCH_HEAD
env:
REF: ${{ github.ref }}
- name: Set up environment
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- name: Transpile to upgradeable
run: bash scripts/upgradeable/transpile-onto.sh ${{ github.ref_name }} origin/${{ github.ref_name }}
- run: git push origin ${{ github.ref_name }}

18
.gitignore vendored
View File

@ -54,6 +54,18 @@ allFiredEvents
.coverage_cache
.coverage_contracts
# hardhat
cache
artifacts
# hardat-exposed
contracts-exposed
# Hardhat
/cache
/artifacts
# Foundry
/out
# Certora
.certora*
.last_confs
certora_*
.zip-output-url.txt

7
.gitmodules vendored Normal file
View File

@ -0,0 +1,7 @@
[submodule "lib/forge-std"]
branch = v1
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
[submodule "lib/erc4626-tests"]
path = lib/erc4626-tests
url = https://github.com/a16z/erc4626-tests.git

View File

@ -1,10 +1,13 @@
{
"printWidth": 120,
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "avoid",
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 120,
"explicitTypes": "always"
"singleQuote": false
}
}
]

View File

@ -1,15 +1,13 @@
module.exports = {
norpc: true,
testCommand: 'npm test',
compileCommand: 'npm run compile',
skipFiles: [
'mocks',
],
providerOptions: {
default_balance_ether: '10000000000000000000000000',
},
mocha: {
fgrep: '[skip-on-coverage]',
invert: true,
},
}
norpc: true,
testCommand: 'npm test',
compileCommand: 'npm run compile',
skipFiles: ['mocks'],
providerOptions: {
default_balance_ether: '10000000000000000000000000',
},
mocha: {
fgrep: '[skip-on-coverage]',
invert: true,
},
};

View File

@ -1,8 +1,287 @@
# Changelog
## 4.9.3 (2023-07-28)
- `ERC2771Context`: Return the forwarder address whenever the `msg.data` of a call originating from a trusted forwarder is not long enough to contain the request signer address (i.e. `msg.data.length` is less than 20 bytes), as specified by ERC-2771. ([#4481](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4481))
- `ERC2771Context`: Prevent revert in `_msgData()` when a call originating from a trusted forwarder is not long enough to contain the request signer address (i.e. `msg.data.length` is less than 20 bytes). Return the full calldata in that case. ([#4484](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4484))
## 4.9.2 (2023-06-16)
- `MerkleProof`: Fix a bug in `processMultiProof` and `processMultiProofCalldata` that allows proving arbitrary leaves if the tree contains a node with value 0 at depth 1.
## 4.9.1 (2023-06-07)
- `Governor`: Add a mechanism to restrict the address of the proposer using a suffix in the description.
## 4.9.0 (2023-05-23)
- `ReentrancyGuard`: Add a `_reentrancyGuardEntered` function to expose the guard status. ([#3714](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3714))
- `ERC721Wrapper`: add a new extension of the `ERC721` token which wraps an underlying token. Deposit and withdraw guarantee that the ownership of each token is backed by a corresponding underlying token with the same identifier. ([#3863](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3863))
- `EnumerableMap`: add a `keys()` function that returns an array containing all the keys. ([#3920](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3920))
- `Governor`: add a public `cancel(uint256)` function. ([#3983](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3983))
- `Governor`: Enable timestamp operation for blockchains without a stable block time. This is achieved by connecting a Governor's internal clock to match a voting token's EIP-6372 interface. ([#3934](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3934))
- `Strings`: add `equal` method. ([#3774](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3774))
- `IERC5313`: Add an interface for EIP-5313 that is now final. ([#4013](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4013))
- `IERC4906`: Add an interface for ERC-4906 that is now Final. ([#4012](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4012))
- `StorageSlot`: Add support for `string` and `bytes`. ([#4008](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4008))
- `Votes`, `ERC20Votes`, `ERC721Votes`: support timestamp checkpointing using EIP-6372. ([#3934](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3934))
- `ERC4626`: Add mitigation to the inflation attack through virtual shares and assets. ([#3979](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3979))
- `Strings`: add `toString` method for signed integers. ([#3773](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3773))
- `ERC20Wrapper`: Make the `underlying` variable private and add a public accessor. ([#4029](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4029))
- `EIP712`: add EIP-5267 support for better domain discovery. ([#3969](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3969))
- `AccessControlDefaultAdminRules`: Add an extension of `AccessControl` with additional security rules for the `DEFAULT_ADMIN_ROLE`. ([#4009](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4009))
- `SignatureChecker`: Add `isValidERC1271SignatureNow` for checking a signature directly against a smart contract using ERC-1271. ([#3932](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3932))
- `SafeERC20`: Add a `forceApprove` function to improve compatibility with tokens behaving like USDT. ([#4067](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4067))
- `ERC1967Upgrade`: removed contract-wide `oz-upgrades-unsafe-allow delegatecall` annotation, replaced by granular annotation in `UUPSUpgradeable`. ([#3971](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3971))
- `ERC20Wrapper`: self wrapping and deposit by the wrapper itself are now explicitly forbidden. ([#4100](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4100))
- `ECDSA`: optimize bytes32 computation by using assembly instead of `abi.encodePacked`. ([#3853](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3853))
- `ERC721URIStorage`: Emit ERC-4906 `MetadataUpdate` in `_setTokenURI`. ([#4012](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4012))
- `ShortStrings`: Added a library for handling short strings in a gas efficient way, with fallback to storage for longer strings. ([#4023](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4023))
- `SignatureChecker`: Allow return data length greater than 32 from EIP-1271 signers. ([#4038](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4038))
- `UUPSUpgradeable`: added granular `oz-upgrades-unsafe-allow-reachable` annotation to improve upgrade safety checks on latest version of the Upgrades Plugins (starting with `@openzeppelin/upgrades-core@1.21.0`). ([#3971](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3971))
- `Initializable`: optimize `_disableInitializers` by using `!=` instead of `<`. ([#3787](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3787))
- `Ownable2Step`: make `acceptOwnership` public virtual to enable usecases that require overriding it. ([#3960](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3960))
- `UUPSUpgradeable.sol`: Change visibility to the functions `upgradeTo ` and `upgradeToAndCall ` from `external` to `public`. ([#3959](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3959))
- `TimelockController`: Add the `CallSalt` event to emit on operation schedule. ([#4001](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4001))
- Reformatted codebase with latest version of Prettier Solidity. ([#3898](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3898))
- `Math`: optimize `log256` rounding check. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745))
- `ERC20Votes`: optimize by using unchecked arithmetic. ([#3748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3748))
- `Multicall`: annotate `multicall` function as upgrade safe to not raise a flag for its delegatecall. ([#3961](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3961))
- `ERC20Pausable`, `ERC721Pausable`, `ERC1155Pausable`: Add note regarding missing public pausing functionality ([#4007](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4007))
- `ECDSA`: Add a function `toDataWithIntendedValidatorHash` that encodes data with version 0x00 following EIP-191. ([#4063](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4063))
- `MerkleProof`: optimize by using unchecked arithmetic. ([#3745](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3745))
### Breaking changes
- `EIP712`: Addition of ERC5267 support requires support for user defined value types, which was released in Solidity version 0.8.8. This requires a pragma change from `^0.8.0` to `^0.8.8`.
- `EIP712`: Optimization of the cache for the upgradeable version affects the way `name` and `version` are set. This is no longer done through an initializer, and is instead part of the implementation's constructor. As a consequence, all proxies using the same implementation will necessarily share the same `name` and `version`. Additionally, an implementation upgrade risks changing the EIP712 domain unless the same `name` and `version` are used when deploying the new implementation contract.
### Deprecations
- `ERC20Permit`: Added the file `IERC20Permit.sol` and `ERC20Permit.sol` and deprecated `draft-IERC20Permit.sol` and `draft-ERC20Permit.sol` since [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612) is no longer a Draft. Developers are encouraged to update their imports. ([#3793](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3793))
- `Timers`: The `Timers` library is now deprecated and will be removed in the next major release. ([#4062](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4062))
- `ERC777`: The `ERC777` token standard is no longer supported by OpenZeppelin. Our implementation is now deprecated and will be removed in the next major release. The corresponding standard interfaces remain available. ([#4066](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4066))
- `ERC1820Implementer`: The `ERC1820` pseudo-introspection mechanism is no longer supported by OpenZeppelin. Our implementation is now deprecated and will be removed in the next major release. The corresponding standard interfaces remain available. ([#4066](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4066))
## 4.8.3 (2023-04-13)
- `GovernorCompatibilityBravo`: Fix encoding of proposal data when signatures are missing.
- `TransparentUpgradeableProxy`: Fix transparency in case of selector clash with non-decodable calldata or payable mutability. ([#4154](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4154))
## 4.8.2 (2023-03-02)
- `ERC721Consecutive`: Fixed a bug when `_mintConsecutive` is used for batches of size 1 that could lead to balance overflow. Refer to the breaking changes section in the changelog for a note on the behavior of `ERC721._beforeTokenTransfer`.
### Breaking changes
- `ERC721`: The internal function `_beforeTokenTransfer` no longer updates balances, which it previously did when `batchSize` was greater than 1. This change has no consequence unless a custom ERC721 extension is explicitly invoking `_beforeTokenTransfer`. Balance updates in extensions must now be done explicitly using `__unsafe_increaseBalance`, with a name that indicates that there is an invariant that has to be manually verified.
## 4.8.1 (2023-01-12)
- `ERC4626`: Use staticcall instead of call when fetching underlying ERC-20 decimals. ([#3943](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3943))
## 4.8.0 (2022-11-08)
- `TimelockController`: Added a new `admin` constructor parameter that is assigned the admin role instead of the deployer account. ([#3722](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3722))
- `Initializable`: add internal functions `_getInitializedVersion` and `_isInitializing` ([#3598](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3598))
- `ERC165Checker`: add `supportsERC165InterfaceUnchecked` for consulting individual interfaces without the full ERC165 protocol. ([#3339](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3339))
- `Address`: optimize `functionCall` by calling `functionCallWithValue` directly. ([#3468](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3468))
- `Address`: optimize `functionCall` functions by checking contract size only if there is no returned data. ([#3469](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3469))
- `Governor`: make the `relay` function payable, and add support for EOA payments. ([#3730](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3730))
- `GovernorCompatibilityBravo`: remove unused `using` statements. ([#3506](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3506))
- `ERC20`: optimize `_transfer`, `_mint` and `_burn` by using `unchecked` arithmetic when possible. ([#3513](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3513))
- `ERC20Votes`, `ERC721Votes`: optimize `getPastVotes` for looking up recent checkpoints. ([#3673](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3673))
- `ERC20FlashMint`: add an internal `_flashFee` function for overriding. ([#3551](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3551))
- `ERC4626`: use the same `decimals()` as the underlying asset by default (if available). ([#3639](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3639))
- `ERC4626`: add internal `_initialConvertToShares` and `_initialConvertToAssets` functions to customize empty vaults behavior. ([#3639](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3639))
- `ERC721`: optimize transfers by making approval clearing implicit instead of emitting an event. ([#3481](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3481))
- `ERC721`: optimize burn by making approval clearing implicit instead of emitting an event. ([#3538](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3538))
- `ERC721`: Fix balance accounting when a custom `_beforeTokenTransfer` hook results in a transfer of the token under consideration. ([#3611](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3611))
- `ERC721`: use unchecked arithmetic for balance updates. ([#3524](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3524))
- `ERC721Consecutive`: Implementation of EIP-2309 that allows batch minting of ERC721 tokens during construction. ([#3311](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3311))
- `ReentrancyGuard`: Reduce code size impact of the modifier by using internal functions. ([#3515](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3515))
- `SafeCast`: optimize downcasting of signed integers. ([#3565](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3565))
- `ECDSA`: Remove redundant check on the `v` value. ([#3591](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3591))
- `VestingWallet`: add `releasable` getters. ([#3580](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3580))
- `VestingWallet`: remove unused library `Math.sol`. ([#3605](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3605))
- `VestingWallet`: make constructor payable. ([#3665](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3665))
- `Create2`: optimize address computation by using assembly instead of `abi.encodePacked`. ([#3600](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3600))
- `Clones`: optimized the assembly to use only the scratch space during deployments, and optimized `predictDeterministicAddress` to use fewer operations. ([#3640](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3640))
- `Checkpoints`: Use procedural generation to support multiple key/value lengths. ([#3589](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3589))
- `Checkpoints`: Add new lookup mechanisms. ([#3589](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3589))
- `Arrays`: Add `unsafeAccess` functions that allow reading and writing to an element in a storage array bypassing Solidity's "out-of-bounds" check. ([#3589](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3589))
- `Strings`: optimize `toString`. ([#3573](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3573))
- `Ownable2Step`: extension of `Ownable` that makes the ownership transfers a two step process. ([#3620](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3620))
- `Math` and `SignedMath`: optimize function `max` by using `>` instead of `>=`. ([#3679](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3679))
- `Math`: Add `log2`, `log10` and `log256`. ([#3670](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3670))
- Arbitrum: Update the vendored arbitrum contracts to match the nitro upgrade. ([#3692](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3692))
### Breaking changes
- `ERC721`: In order to add support for batch minting via `ERC721Consecutive` it was necessary to make a minor breaking change in the internal interface of `ERC721`. Namely, the hooks `_beforeTokenTransfer` and `_afterTokenTransfer` have one additional argument that may need to be added to overrides:
```diff
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId,
+ uint256 batchSize
) internal virtual override
```
- `ERC4626`: Conversion from shares to assets (and vice-versa) in an empty vault used to consider the possible mismatch between the underlying asset's and the vault's decimals. This initial conversion rate is now set to 1-to-1 irrespective of decimals, which are meant for usability purposes only. The vault now uses the assets decimals by default, so off-chain the numbers should appear the same. Developers overriding the vault decimals to a value that does not match the underlying asset may want to override the `_initialConvertToShares` and `_initialConvertToAssets` to replicate the previous behavior.
- `TimelockController`: During deployment, the TimelockController used to grant the `TIMELOCK_ADMIN_ROLE` to the deployer and to the timelock itself. The deployer was then expected to renounce this role once configuration of the timelock is over. Failing to renounce that role allows the deployer to change the timelock permissions (but not to bypass the delay for any time-locked actions). The role is no longer given to the deployer by default. A new parameter `admin` can be set to a non-zero address to grant the admin role during construction (to the deployer or any other address). Just like previously, this admin role should be renounced after configuration. If this param is given `address(0)`, the role is not allocated and doesn't need to be revoked. In any case, the timelock itself continues to have this role.
### Deprecations
- `EIP712`: Added the file `EIP712.sol` and deprecated `draft-EIP712.sol` since the EIP is no longer a Draft. Developers are encouraged to update their imports. ([#3621](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3621))
```diff
-import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
+import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
```
- `ERC721Votes`: Added the file `ERC721Votes.sol` and deprecated `draft-ERC721Votes.sol` since it no longer depends on a Draft EIP (EIP-712). Developers are encouraged to update their imports. ([#3699](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3699))
```diff
-import "@openzeppelin/contracts/token/ERC721/extensions/draft-ERC721Votes.sol";
+import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Votes.sol";
```
### ERC-721 Compatibility Note
ERC-721 integrators that interpret contract state from events should make sure that they implement the clearing of approval that is implicit in every transfer according to the EIP. Previous versions of OpenZeppelin Contracts emitted an explicit `Approval` event even though it was not required by the specification, and this is no longer the case.
With the new `ERC721Consecutive` extension, the internal workings of `ERC721` are slightly changed. Custom extensions to ERC721 should be reviewed to ensure they remain correct. The internal functions that should be considered are `_ownerOf` (new), `_beforeTokenTransfer`, and `_afterTokenTransfer`.
### ERC-4626 Upgrade Note
Existing `ERC4626` contracts that are upgraded to 4.8 must initialize a new variable that holds the vault token decimals. The recommended way to do this is to use a [reinitializer]:
[reinitializer]: https://docs.openzeppelin.com/contracts/4.x/api/proxy#Initializable-reinitializer-uint8-
```solidity
function migrateToV48() public reinitializer(2) {
__ERC4626_init(IERC20Upgradeable(asset()));
}
```
## 4.7.3 (2022-08-10)
### Breaking changes
- `ECDSA`: `recover(bytes32,bytes)` and `tryRecover(bytes32,bytes)` no longer accept compact signatures to prevent malleability. Compact signature support remains available using `recover(bytes32,bytes32,bytes32)` and `tryRecover(bytes32,bytes32,bytes32)`.
## 4.7.2 (2022-07-25)
- `LibArbitrumL2`, `CrossChainEnabledArbitrumL2`: Fixed detection of cross-chain calls for EOAs. Previously, calls from EOAs would be classified as cross-chain calls. ([#3578](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3578))
- `GovernorVotesQuorumFraction`: Fixed quorum updates so they do not affect past proposals that failed due to lack of quorum. ([#3561](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3561))
- `ERC165Checker`: Added protection against large returndata. ([#3587](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3587))
## 4.7.1 (2022-07-18)
- `SignatureChecker`: Fix an issue that causes `isValidSignatureNow` to revert when the target contract returns ill-encoded data. ([#3552](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3552))
- `ERC165Checker`: Fix an issue that causes `supportsInterface` to revert when the target contract returns ill-encoded data. ([#3552](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3552))
## 4.7.0 (2022-06-29)
- `TimelockController`: Migrate `_call` to `_execute` and allow inheritance and overriding similar to `Governor`. ([#3317](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3317))
- `CrossChainEnabledPolygonChild`: replace the `require` statement with the custom error `NotCrossChainCall`. ([#3380](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3380))
- `ERC20FlashMint`: Add customizable flash fee receiver. ([#3327](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3327))
- `ERC4626`: add an extension of `ERC20` that implements the ERC4626 Tokenized Vault Standard. ([#3171](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3171))
- `SafeERC20`: add `safePermit` as mitigation against phantom permit functions. ([#3280](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3280))
- `Math`: add a `mulDiv` function that can round the result either up or down. ([#3171](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3171))
- `Math`: Add a `sqrt` function to compute square roots of integers, rounding either up or down. ([#3242](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3242))
- `Strings`: add a new overloaded function `toHexString` that converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. ([#3403](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3403))
- `EnumerableMap`: add new `UintToUintMap` map type. ([#3338](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3338))
- `EnumerableMap`: add new `Bytes32ToUintMap` map type. ([#3416](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3416))
- `SafeCast`: add support for many more types, using procedural code generation. ([#3245](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3245))
- `MerkleProof`: add `multiProofVerify` to prove multiple values are part of a Merkle tree. ([#3276](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3276))
- `MerkleProof`: add calldata versions of the functions to avoid copying input arrays to memory and save gas. ([#3200](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3200))
- `ERC721`, `ERC1155`: simplified revert reasons. ([#3254](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3254), ([#3438](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3438)))
- `ERC721`: removed redundant require statement. ([#3434](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3434))
- `PaymentSplitter`: add `releasable` getters. ([#3350](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3350))
- `Initializable`: refactored implementation of modifiers for easier understanding. ([#3450](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3450))
- `Proxies`: remove runtime check of ERC1967 storage slots. ([#3455](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3455))
### Breaking changes
- `Initializable`: functions decorated with the modifier `reinitializer(1)` may no longer invoke each other.
## 4.6.0 (2022-04-26)
- `crosschain`: Add a new set of contracts for cross-chain applications. `CrossChainEnabled` is a base contract with instantiations for several chains and bridges, and `AccessControlCrossChain` is an extension of access control that allows cross-chain operation. ([#3183](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3183))
- `AccessControl`: add a virtual `_checkRole(bytes32)` function that can be overridden to alter the `onlyRole` modifier behavior. ([#3137](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3137))
- `EnumerableMap`: add new `AddressToUintMap` map type. ([#3150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3150))
- `EnumerableMap`: add new `Bytes32ToBytes32Map` map type. ([#3192](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3192))
- `ERC20FlashMint`: support infinite allowance when paying back a flash loan. ([#3226](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3226))
- `ERC20Wrapper`: the `decimals()` function now tries to fetch the value from the underlying token instance. If that calls revert, then the default value is used. ([#3259](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3259))
- `draft-ERC20Permit`: replace `immutable` with `constant` for `_PERMIT_TYPEHASH` since the `keccak256` of string literals is treated specially and the hash is evaluated at compile time. ([#3196](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3196))
- `ERC1155`: Add a `_afterTokenTransfer` hook for improved extensibility. ([#3166](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3166))
- `ERC1155URIStorage`: add a new extension that implements a `_setURI` behavior similar to ERC721's `_setTokenURI`. ([#3210](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3210))
- `DoubleEndedQueue`: a new data structure that supports efficient push and pop to both front and back, useful for FIFO and LIFO queues. ([#3153](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3153))
- `Governor`: improved security of `onlyGovernance` modifier when using an external executor contract (e.g. a timelock) that can operate without necessarily going through the governance protocol. ([#3147](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3147))
- `Governor`: Add a way to parameterize votes. This can be used to implement voting systems such as fractionalized voting, ERC721 based voting, or any number of other systems. The `params` argument added to `_countVote` method, and included in the newly added `_getVotes` method, can be used by counting and voting modules respectively for such purposes. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
- `Governor`: rewording of revert reason for consistency. ([#3275](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3275))
- `Governor`: fix an inconsistency in data locations that could lead to invalid bytecode being produced. ([#3295](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3295))
- `Governor`: Implement `IERC721Receiver` and `IERC1155Receiver` to improve token custody by governors. ([#3230](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3230))
- `TimelockController`: Implement `IERC721Receiver` and `IERC1155Receiver` to improve token custody by timelocks. ([#3230](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3230))
- `TimelockController`: Add a separate canceller role for the ability to cancel. ([#3165](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3165))
- `Initializable`: add a reinitializer modifier that enables the initialization of new modules, added to already initialized contracts through upgradeability. ([#3232](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3232))
- `Initializable`: add an Initialized event that tracks initialized version numbers. ([#3294](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3294))
- `ERC2981`: make `royaltyInfo` public to allow super call in overrides. ([#3305](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3305))
### Upgradeability notice
- `TimelockController`: **(Action needed)** The upgrade from <4.6 to >=4.6 introduces a new `CANCELLER_ROLE` that requires set up to be assignable. After the upgrade, only addresses with this role will have the ability to cancel. Proposers will no longer be able to cancel. Assigning cancellers can be done by an admin (including the timelock itself) once the role admin is set up. To do this, we recommend upgrading to the `TimelockControllerWith46MigrationUpgradeable` contract and then calling the `migrateTo46` function.
### Breaking changes
- `Governor`: Adds internal virtual `_getVotes` method that must be implemented; this is a breaking change for existing concrete extensions to `Governor`. To fix this on an existing voting module extension, rename `getVotes` to `_getVotes` and add a `bytes memory` argument. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
- `Governor`: Adds `params` parameter to internal virtual `_countVote` method; this is a breaking change for existing concrete extensions to `Governor`. To fix this on an existing counting module extension, add a `bytes memory` argument to `_countVote`. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
- `Governor`: Does not emit `VoteCast` event when params data is non-empty; instead emits `VoteCastWithParams` event. To fix this on an integration that consumes the `VoteCast` event, also fetch/monitor `VoteCastWithParams` events. ([#3043](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3043))
- `Votes`: The internal virtual function `_getVotingUnits` was made `view` (which was accidentally missing). Any overrides should now be updated so they are `view` as well.
## 4.5.0 (2022-02-09)
- `ERC2981`: add implementation of the royalty standard, and the respective extensions for `ERC721` and `ERC1155`. ([#3012](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3012))
- `GovernorTimelockControl`: improve the `state()` function to have it reflect cases where a proposal has been canceled directly on the timelock. ([#2977](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2977))
- Preset contracts are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com). ([#2986](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2986))
- `Governor`: add a relay function to help recover assets sent to a governor that is not its own executor (e.g. when using a timelock). ([#2926](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2926))
- `GovernorPreventLateQuorum`: add new module to ensure a minimum voting duration is available after the quorum is reached. ([#2973](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2973))
- `ERC721`: improved revert reason when transferring from wrong owner. ([#2975](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2975))
- `Votes`: Added a base contract for vote tracking with delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944))
- `ERC721Votes`: Added an extension of ERC721 enabled with vote tracking and delegation. ([#2944](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2944))
- `ERC2771Context`: use immutable storage to store the forwarder address, no longer an issue since Solidity >=0.8.8 allows reading immutable variables in the constructor. ([#2917](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2917))
- `Base64`: add a library to parse bytes into base64 strings using `encode(bytes memory)` function, and provide examples to show how to use to build URL-safe `tokenURIs`. ([#2884](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2884))
- `ERC20`: reduce allowance before triggering transfer. ([#3056](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3056))
- `ERC20`: do not update allowance on `transferFrom` when allowance is `type(uint256).max`. ([#3085](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3085))
- `ERC20`: add a `_spendAllowance` internal function. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170))
- `ERC20Burnable`: do not update allowance on `burnFrom` when allowance is `type(uint256).max`. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170))
- `ERC777`: do not update allowance on `transferFrom` when allowance is `type(uint256).max`. ([#3085](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3085))
- `ERC777`: add a `_spendAllowance` internal function. ([#3170](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3170))
- `SignedMath`: a new signed version of the Math library with `max`, `min`, and `average`. ([#2686](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2686))
- `SignedMath`: add an `abs(int256)` method that returns the unsigned absolute value of a signed value. ([#2984](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2984))
- `ERC1967Upgrade`: Refactor the secure upgrade to use `ERC1822` instead of the previous rollback mechanism. This reduces code complexity and attack surface with similar security guarantees. ([#3021](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3021))
- `UUPSUpgradeable`: Add `ERC1822` compliance to support the updated secure upgrade mechanism. ([#3021](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3021))
- Some more 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.
### Breaking changes
- `ERC1967Upgrade`: The function `_upgradeToAndCallSecure` was renamed to `_upgradeToAndCallUUPS`, along with the change in security mechanism described above.
- `Address`: The Solidity pragma is increased from `^0.8.0` to `^0.8.1`. This is required by the `account.code.length` syntax that replaces inline assembly. This may require users to bump their compiler version from `0.8.0` to `0.8.1` or later. Note that other parts of the code already include stricter requirements.
## 4.4.2 (2022-01-11)
### Bugfixes
- `GovernorCompatibilityBravo`: Fix error in the encoding of calldata for proposals submitted through the compatibility interface with explicit signatures. ([#3100](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3100))
## 4.4.1 (2021-12-14)
* `Initializable`: change the existing `initializer` modifier and add a new `onlyInitializing` modifier to prevent reentrancy risk. ([#3006](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3006))
- `Initializable`: change the existing `initializer` modifier and add a new `onlyInitializing` modifier to prevent reentrancy risk. ([#3006](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/3006))
### Breaking change
@ -22,59 +301,59 @@ It is no longer possible to call an `initializer`-protected function from within
## 4.4.0 (2021-11-25)
* `Ownable`: add an internal `_transferOwnership(address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
* `AccessControl`: add internal `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
* `AccessControl`: mark `_setupRole(bytes32,address)` as deprecated in favor of `_grantRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
* `AccessControlEnumerable`: hook into `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2946](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2946))
* `EIP712`: cache `address(this)` to immutable storage to avoid potential issues if a vanilla contract is used in a delegatecall context. ([#2852](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2852))
* Add internal `_setApprovalForAll` to `ERC721` and `ERC1155`. ([#2834](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2834))
* `Governor`: shift vote start and end by one block to better match Compound's GovernorBravo and prevent voting at the Governor level if the voting snapshot is not ready. ([#2892](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2892))
* `GovernorCompatibilityBravo`: consider quorum an inclusive rather than exclusive minimum to match Compound's GovernorBravo. ([#2974](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2974))
* `GovernorSettings`: a new governor module that manages voting settings updatable through governance actions. ([#2904](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2904))
* `PaymentSplitter`: now supports ERC20 assets in addition to Ether. ([#2858](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2858))
* `ECDSA`: add a variant of `toEthSignedMessageHash` for arbitrary length message hashing. ([#2865](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2865))
* `MerkleProof`: add a `processProof` function that returns the rebuilt root hash given a leaf and a proof. ([#2841](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2841))
* `VestingWallet`: new contract that handles the vesting of Ether and ERC20 tokens following a customizable vesting schedule. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748))
* `Governor`: enable receiving Ether when a Timelock contract is not used. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849))
* `GovernorTimelockCompound`: fix ability to use Ether stored in the Timelock contract. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849))
- `Ownable`: add an internal `_transferOwnership(address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
- `AccessControl`: add internal `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
- `AccessControl`: mark `_setupRole(bytes32,address)` as deprecated in favor of `_grantRole(bytes32,address)`. ([#2568](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2568))
- `AccessControlEnumerable`: hook into `_grantRole(bytes32,address)` and `_revokeRole(bytes32,address)`. ([#2946](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2946))
- `EIP712`: cache `address(this)` to immutable storage to avoid potential issues if a vanilla contract is used in a delegatecall context. ([#2852](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2852))
- Add internal `_setApprovalForAll` to `ERC721` and `ERC1155`. ([#2834](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2834))
- `Governor`: shift vote start and end by one block to better match Compound's GovernorBravo and prevent voting at the Governor level if the voting snapshot is not ready. ([#2892](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2892))
- `GovernorCompatibilityBravo`: consider quorum an inclusive rather than exclusive minimum to match Compound's GovernorBravo. ([#2974](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2974))
- `GovernorSettings`: a new governor module that manages voting settings updatable through governance actions. ([#2904](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2904))
- `PaymentSplitter`: now supports ERC20 assets in addition to Ether. ([#2858](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2858))
- `ECDSA`: add a variant of `toEthSignedMessageHash` for arbitrary length message hashing. ([#2865](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2865))
- `MerkleProof`: add a `processProof` function that returns the rebuilt root hash given a leaf and a proof. ([#2841](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2841))
- `VestingWallet`: new contract that handles the vesting of Ether and ERC20 tokens following a customizable vesting schedule. ([#2748](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2748))
- `Governor`: enable receiving Ether when a Timelock contract is not used. ([#2849](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849))
- `GovernorTimelockCompound`: fix ability to use Ether stored in the Timelock contract. ([#2849](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2849))
## 4.3.3
## 4.3.3 (2021-11-08)
* `ERC1155Supply`: Handle `totalSupply` changes by hooking into `_beforeTokenTransfer` to ensure consistency of balances and supply during `IERC1155Receiver.onERC1155Received` calls.
- `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.
- `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.
- `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))
- `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))
- `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)))
- `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`.
@ -82,16 +361,16 @@ It is no longer possible to call an `initializer`-protected function from within
## 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))
- `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 an `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
@ -108,28 +387,28 @@ This release includes two small breaking changes in `TimelockController`.
## 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))
- 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))
- `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
@ -143,56 +422,59 @@ Make sure you're using git or another version control system to be able to recov
### 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.
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.2
## 3.4.2 (2021-07-24)
* `TimelockController`: Add additional isOperationReady check.
- `TimelockController`: Add additional isOperationReady check.
## 3.4.1 (2021-03-03)
* `ERC721`: made `_approve` an internal function (was private).
- `ERC721`: made `_approve` an internal function (was private).
## 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.
- `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))
- `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))
- 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))
- 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))
- `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))
- Proxies: added the proxy contracts from OpenZeppelin SDK. ([#2335](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2335))
#### Proxy changes with respect to OpenZeppelin SDK
@ -204,10 +486,12 @@ Aside from upgrading them from Solidity 0.5 to 0.6, we've changed a few minor th
- `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))
- `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))
- `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.
@ -215,119 +499,134 @@ other ERC20 flavors, since it no longer overrides `_transfer`, `_mint`, and `_bu
## 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))
- `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))
- `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))
- `SafeERC20`: deprecated `safeApprove`. ([#2268](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2268))
## 3.0.2 (2020-06-08)
### Improvements
* Added SPX license identifier to all contracts. ([#2235](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2235))
- Added SPX license identifier to all contracts. ([#2235](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2235))
## 3.0.1 (2020-04-27)
### Bugfixes
* `ERC777`: fixed the `_approve` internal function not validating some of their arguments for non-zero addresses. ([#2213](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2213))
- `ERC777`: fixed the `_approve` internal function not validating some of their arguments for non-zero addresses. ([#2213](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2213))
## 3.0.0 (2020-04-20)
### New features
* `AccessControl`: new contract for managing permissions in a system, replacement for `Ownable` and `Roles`. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
* `SafeCast`: new functions to convert to and from signed and unsigned values: `toUint256` and `toInt256`. ([#2123](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2123))
* `EnumerableMap`: a new data structure for key-value pairs (like `mapping`) that can be iterated over. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
- `AccessControl`: new contract for managing permissions in a system, replacement for `Ownable` and `Roles`. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
- `SafeCast`: new functions to convert to and from signed and unsigned values: `toUint256` and `toInt256`. ([#2123](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2123))
- `EnumerableMap`: a new data structure for key-value pairs (like `mapping`) that can be iterated over. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
### Breaking changes
* `ERC721`: `burn(owner, tokenId)` was removed, use `burn(tokenId)` instead. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
* `ERC721`: `_checkOnERC721Received` was removed. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
* `ERC721`: `_transferFrom` and `_safeTransferFrom` were renamed to `_transfer` and `_safeTransfer`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
* `Ownable`: removed `_transferOwnership`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
* `PullPayment`, `Escrow`: `withdrawWithGas` was removed. The old `withdraw` function now forwards all gas. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
* `Roles` was removed, use `AccessControl` as a replacement. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
* `ECDSA`: when receiving an invalid signature, `recover` now reverts instead of returning the zero address. ([#2114](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2114))
* `Create2`: added an `amount` argument to `deploy` for contracts with `payable` constructors. ([#2117](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2117))
* `Pausable`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
* `Strings`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
* `Counters`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
* `SignedSafeMath`: moved to the `math` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
* `ERC20Snapshot`: moved to the `token/ERC20` directory. `snapshot` was changed into an `internal` function. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
* `Ownable`: moved to the `access` directory. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
* `Ownable`: removed `isOwner`. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
* `Secondary`: removed from the library, use `Ownable` instead. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
* `Escrow`, `ConditionalEscrow`, `RefundEscrow`: these now use `Ownable` instead of `Secondary`, their external API changed accordingly. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
* `ERC20`: removed `_burnFrom`. ([#2119](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2119))
* `Address`: removed `toPayable`, use `payable(address)` instead. ([#2133](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2133))
* `ERC777`: `_send`, `_mint` and `_burn` now use the caller as the operator. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
* `ERC777`: removed `_callsTokensToSend` and `_callTokensReceived`. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
* `EnumerableSet`: renamed `get` to `at`. ([#2151](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2151))
* `ERC165Checker`: functions no longer have a leading underscore. ([#2150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2150))
* `ERC721Metadata`, `ERC721Enumerable`: these contracts were removed, and their functionality merged into `ERC721`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
* `ERC721`: added a constructor for `name` and `symbol`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
* `ERC20Detailed`: this contract was removed and its functionality merged into `ERC20`. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
* `ERC20`: added a constructor for `name` and `symbol`. `decimals` now defaults to 18. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
* `Strings`: renamed `fromUint256` to `toString` ([#2188](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2188))
- `ERC721`: `burn(owner, tokenId)` was removed, use `burn(tokenId)` instead. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
- `ERC721`: `_checkOnERC721Received` was removed. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
- `ERC721`: `_transferFrom` and `_safeTransferFrom` were renamed to `_transfer` and `_safeTransfer`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
- `Ownable`: removed `_transferOwnership`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
- `PullPayment`, `Escrow`: `withdrawWithGas` was removed. The old `withdraw` function now forwards all gas. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
- `Roles` was removed, use `AccessControl` as a replacement. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
- `ECDSA`: when receiving an invalid signature, `recover` now reverts instead of returning the zero address. ([#2114](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2114))
- `Create2`: added an `amount` argument to `deploy` for contracts with `payable` constructors. ([#2117](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2117))
- `Pausable`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
- `Strings`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
- `Counters`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
- `SignedSafeMath`: moved to the `math` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
- `ERC20Snapshot`: moved to the `token/ERC20` directory. `snapshot` was changed into an `internal` function. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
- `Ownable`: moved to the `access` directory. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
- `Ownable`: removed `isOwner`. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
- `Secondary`: removed from the library, use `Ownable` instead. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
- `Escrow`, `ConditionalEscrow`, `RefundEscrow`: these now use `Ownable` instead of `Secondary`, their external API changed accordingly. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
- `ERC20`: removed `_burnFrom`. ([#2119](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2119))
- `Address`: removed `toPayable`, use `payable(address)` instead. ([#2133](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2133))
- `ERC777`: `_send`, `_mint` and `_burn` now use the caller as the operator. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
- `ERC777`: removed `_callsTokensToSend` and `_callTokensReceived`. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
- `EnumerableSet`: renamed `get` to `at`. ([#2151](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2151))
- `ERC165Checker`: functions no longer have a leading underscore. ([#2150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2150))
- `ERC721Metadata`, `ERC721Enumerable`: these contracts were removed, and their functionality merged into `ERC721`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
- `ERC721`: added a constructor for `name` and `symbol`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
- `ERC20Detailed`: this contract was removed and its functionality merged into `ERC20`. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
- `ERC20`: added a constructor for `name` and `symbol`. `decimals` now defaults to 18. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
- `Strings`: renamed `fromUint256` to `toString` ([#2188](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2188))
## 2.5.1 (2020-04-24)
### Bugfixes
* `ERC777`: fixed the `_send` and `_approve` internal functions not validating some of their arguments for non-zero addresses. ([#2212](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2212))
- `ERC777`: fixed the `_send` and `_approve` internal functions not validating some of their arguments for non-zero addresses. ([#2212](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2212))
## 2.5.0 (2020-02-04)
### New features
* `SafeCast.toUintXX`: new library for integer downcasting, which allows for safe operation on smaller types (e.g. `uint32`) when combined with `SafeMath`. ([#1926](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1926))
* `ERC721Metadata`: added `baseURI`, which can be used for dramatic gas savings when all token URIs share a prefix (e.g. `http://api.myapp.com/tokens/<id>`). ([#1970](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1970))
* `EnumerableSet`: new library for storing enumerable sets of values. Only `AddressSet` is supported in this release. ([#2061](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/2061))
* `Create2`: simple library to make usage of the `CREATE2` opcode easier. ([#1744](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1744))
- `SafeCast.toUintXX`: new library for integer downcasting, which allows for safe operation on smaller types (e.g. `uint32`) when combined with `SafeMath`. ([#1926](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1926))
- `ERC721Metadata`: added `baseURI`, which can be used for dramatic gas savings when all token URIs share a prefix (e.g. `http://api.myapp.com/tokens/<id>`). ([#1970](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1970))
- `EnumerableSet`: new library for storing enumerable sets of values. Only `AddressSet` is supported in this release. ([#2061](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/2061))
- `Create2`: simple library to make usage of the `CREATE2` opcode easier. ([#1744](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1744))
### Improvements
* `ERC777`: `_burn` is now internal, providing more flexibility and making it easier to create tokens that deflate. ([#1908](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1908))
* `ReentrancyGuard`: greatly improved gas efficiency by using the net gas metering mechanism introduced in the Istanbul hardfork. ([#1992](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1992), [#1996](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1996))
* `ERC777`: improve extensibility by making `_send` and related functions `internal`. ([#2027](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2027))
* `ERC721`: improved revert reason when transferring tokens to a non-recipient contract. ([#2018](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2018))
- `ERC777`: `_burn` is now internal, providing more flexibility and making it easier to create tokens that deflate. ([#1908](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1908))
- `ReentrancyGuard`: greatly improved gas efficiency by using the net gas metering mechanism introduced in the Istanbul hardfork. ([#1992](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1992), [#1996](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1996))
- `ERC777`: improve extensibility by making `_send` and related functions `internal`. ([#2027](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2027))
- `ERC721`: improved revert reason when transferring tokens to a non-recipient contract. ([#2018](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2018))
### Breaking changes
* `ERC165Checker` now requires a minimum Solidity compiler version of 0.5.10. ([#1829](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1829))
- `ERC165Checker` now requires a minimum Solidity compiler version of 0.5.10. ([#1829](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1829))
## 2.4.0 (2019-10-29)
### New features
* `Address.toPayable`: added a helper to convert between address types without having to resort to low-level casting. ([#1773](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1773))
* Facilities to make metatransaction-enabled contracts through the Gas Station Network. ([#1844](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1844))
* `Address.sendValue`: added a replacement to Solidity's `transfer`, removing the fixed gas stipend. ([#1962](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1962))
* Added replacement for functions that don't forward all gas (which have been deprecated): ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
* `PullPayment.withdrawPaymentsWithGas(address payable payee)`
* `Escrow.withdrawWithGas(address payable payee)`
* `SafeMath`: added support for custom error messages to `sub`, `div` and `mod` functions. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
- `Address.toPayable`: added a helper to convert between address types without having to resort to low-level casting. ([#1773](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1773))
- Facilities to make metatransaction-enabled contracts through the Gas Station Network. ([#1844](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1844))
- `Address.sendValue`: added a replacement to Solidity's `transfer`, removing the fixed gas stipend. ([#1962](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1962))
- Added replacement for functions that don't forward all gas (which have been deprecated): ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
- `PullPayment.withdrawPaymentsWithGas(address payable payee)`
- `Escrow.withdrawWithGas(address payable payee)`
- `SafeMath`: added support for custom error messages to `sub`, `div` and `mod` functions. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
### Improvements
* `Address.isContract`: switched from `extcodesize` to `extcodehash` for less gas usage. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
* `ERC20` and `ERC777` updated to throw custom errors on subtraction overflows. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
- `Address.isContract`: switched from `extcodesize` to `extcodehash` for less gas usage. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
- `ERC20` and `ERC777` updated to throw custom errors on subtraction overflows. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
### Deprecations
* Deprecated functions that don't forward all gas: ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
* `PullPayment.withdrawPayments(address payable payee)`
* `Escrow.withdraw(address payable payee)`
- Deprecated functions that don't forward all gas: ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
- `PullPayment.withdrawPayments(address payable payee)`
- `Escrow.withdraw(address payable payee)`
### Breaking changes
* `Address` now requires a minimum Solidity compiler version of 0.5.5. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
* `SignatureBouncer` has been removed from drafts, both to avoid confusions with the GSN and `GSNRecipientSignature` (previously called `GSNBouncerSignature`) and because the API was not very clear. ([#1879](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1879))
- `Address` now requires a minimum Solidity compiler version of 0.5.5. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
- `SignatureBouncer` has been removed from drafts, both to avoid confusions with the GSN and `GSNRecipientSignature` (previously called `GSNBouncerSignature`) and because the API was not very clear. ([#1879](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1879))
### How to upgrade from 2.4.0-beta
The final 2.4.0 release includes a refactor of the GSN contracts that will be a breaking change for 2.4.0-beta users.
* The default empty implementations of `_preRelayedCall` and `_postRelayedCall` were removed and must now be explicitly implemented always in custom recipients. If your custom recipient didn't include an implementation, you can provide an empty one.
* `GSNRecipient`, `GSNBouncerBase`, and `GSNContext` were all merged into `GSNRecipient`.
* `GSNBouncerSignature` and `GSNBouncerERC20Fee` were renamed to `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
* It is no longer necessary to inherit from `GSNRecipient` when using `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
- The default empty implementations of `_preRelayedCall` and `_postRelayedCall` were removed and must now be explicitly implemented always in custom recipients. If your custom recipient didn't include an implementation, you can provide an empty one.
- `GSNRecipient`, `GSNBouncerBase`, and `GSNContext` were all merged into `GSNRecipient`.
- `GSNBouncerSignature` and `GSNBouncerERC20Fee` were renamed to `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
- It is no longer necessary to inherit from `GSNRecipient` when using `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
For example, a contract using `GSNBouncerSignature` would have to be changed in the following way.
@ -338,81 +637,94 @@ For example, a contract using `GSNBouncerSignature` would have to be changed in
Refer to the table below to adjust your inheritance list.
| 2.4.0-beta | 2.4.0 |
| ---------------------------------- | ---------------------------- |
| `GSNRecipient, GSNBouncerSignature`| `GSNRecipientSignature` |
| `GSNRecipient, GSNBouncerERC20Fee` | `GSNRecipientERC20Fee` |
| `GSNBouncerBase` | `GSNRecipient` |
| 2.4.0-beta | 2.4.0 |
| ----------------------------------- | ----------------------- |
| `GSNRecipient, GSNBouncerSignature` | `GSNRecipientSignature` |
| `GSNRecipient, GSNBouncerERC20Fee` | `GSNRecipientERC20Fee` |
| `GSNBouncerBase` | `GSNRecipient` |
## 2.3.0 (2019-05-27)
### New features
* `ERC1820`: added support for interacting with the [ERC1820](https://eips.ethereum.org/EIPS/eip-1820) registry contract (`IERC1820Registry`), as well as base contracts that can be registered as implementers there. ([#1677](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1677))
* `ERC777`: support for the [ERC777 token](https://eips.ethereum.org/EIPS/eip-777), which has multiple improvements over `ERC20` (but is backwards compatible with it) such as built-in burning, a more straightforward permission system, and optional sender and receiver hooks on transfer (mandatory for contracts!). ([#1684](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1684))
* All contracts now have revert reason strings, which give insight into error conditions, and help debug failing transactions. ([#1704](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1704))
- `ERC1820`: added support for interacting with the [ERC1820](https://eips.ethereum.org/EIPS/eip-1820) registry contract (`IERC1820Registry`), as well as base contracts that can be registered as implementers there. ([#1677](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1677))
- `ERC777`: support for the [ERC777 token](https://eips.ethereum.org/EIPS/eip-777), which has multiple improvements over `ERC20` (but is backwards compatible with it) such as built-in burning, a more straightforward permission system, and optional sender and receiver hooks on transfer (mandatory for contracts!). ([#1684](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1684))
- All contracts now have revert reason strings, which give insight into error conditions, and help debug failing transactions. ([#1704](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1704))
### Improvements
* Reverted the Solidity version bump done in v2.2.0, setting the minimum compiler version to v0.5.0, to prevent unexpected build breakage. Users are encouraged however to stay on top of new compiler releases, which usually include bugfixes. ([#1729](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1729))
- Reverted the Solidity version bump done in v2.2.0, setting the minimum compiler version to v0.5.0, to prevent unexpected build breakage. Users are encouraged however to stay on top of new compiler releases, which usually include bugfixes. ([#1729](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1729))
### Bugfixes
* `PostDeliveryCrowdsale`: some validations where skipped when paired with other crowdsale flavors, such as `AllowanceCrowdsale`, or `MintableCrowdsale` and `ERC20Capped`, which could cause buyers to not be able to claim their purchased tokens. ([#1721](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1721))
* `ERC20._transfer`: the `from` argument was allowed to be the zero address, so it was possible to internally trigger a transfer of 0 tokens from the zero address. This address is not a valid destinatary of transfers, nor can it give or receive allowance, so this behavior was inconsistent. It now reverts. ([#1752](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1752))
- `PostDeliveryCrowdsale`: some validations where skipped when paired with other crowdsale flavors, such as `AllowanceCrowdsale`, or `MintableCrowdsale` and `ERC20Capped`, which could cause buyers to not be able to claim their purchased tokens. ([#1721](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1721))
- `ERC20._transfer`: the `from` argument was allowed to be the zero address, so it was possible to internally trigger a transfer of 0 tokens from the zero address. This address is not a valid destinatary of transfers, nor can it give or receive allowance, so this behavior was inconsistent. It now reverts. ([#1752](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1752))
## 2.2.0 (2019-03-14)
### New features
* `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617))
* `SafeERC20`: `ERC20` contracts with no return value (i.e. that revert on failure) are now supported. ([#1655](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1655))
* `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. ([#1609](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1609))
* `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
* `TimedCrowdsale`: added internal `_extendTime(uint256 newClosingTime)` as well as `TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime)` event allowing to extend the crowdsale, as long as it hasn't already closed.
- `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617))
- `SafeERC20`: `ERC20` contracts with no return value (i.e. that revert on failure) are now supported. ([#1655](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1655))
- `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. ([#1609](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1609))
- `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
- `TimedCrowdsale`: added internal `_extendTime(uint256 newClosingTime)` as well as `TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime)` event allowing to extend the crowdsale, as long as it hasn't already closed.
### Improvements
* Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
* `ECDSA`: `recover` no longer accepts malleable signatures (those using upper-range values for `s`, or 0/1 for `v`). ([#1622](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1622))
* ``ERC721``'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
* Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
- Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
- `ECDSA`: `recover` no longer accepts malleable signatures (those using upper-range values for `s`, or 0/1 for `v`). ([#1622](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1622))
- `ERC721`'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
- Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
### Bugfixes
* (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
- (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
### Breaking changes in drafts
* `TokenMetadata` has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
* The library `Counter` has been renamed to `Counters` and its API has been improved. See an example in `ERC721`, lines [17](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L17) and [204](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L204). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
- `TokenMetadata` has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
- The library `Counter` has been renamed to `Counters` and its API has been improved. See an example in `ERC721`, lines [17](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L17) and [204](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L204). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
## 2.1.3 (2019-02-26)
* Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
- Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
## 2.1.2 (2019-01-17)
* Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`.
- Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`.
## 2.1.1 (2019-01-04)
* Version bump to avoid conflict in the npm registry.
- Version bump to avoid conflict in the npm registry.
## 2.1.0 (2019-01-04)
### New features
* Now targeting the 0.5.x line of Solidity compilers. For 0.4.24 support, use version 2.0 of OpenZeppelin.
* `WhitelistCrowdsale`: a crowdsale where only whitelisted accounts (`WhitelistedRole`) can purchase tokens. Adding or removing accounts from the whitelist is done by whitelist admins (`WhitelistAdminRole`). Similar to the pre-2.0 `WhitelistedCrowdsale`. ([#1525](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1525), [#1589](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1589))
* `RefundablePostDeliveryCrowdsale`: replacement for `RefundableCrowdsale` (deprecated, see below) where tokens are only granted once the crowdsale ends (if it meets its goal). ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))
* `PausableCrowdsale`: allows for pausers (`PauserRole`) to pause token purchases. Other crowdsale operations (e.g. withdrawals and refunds, if applicable) are not affected. ([#832](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/832))
* `ERC20`: `transferFrom` and `_burnFrom ` now emit `Approval` events, to represent the token's state comprehensively through events. ([#1524](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1524))
* `ERC721`: added `_burn(uint256 tokenId)`, replacing the similar deprecated function (see below). ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
* `ERC721`: added `_tokensOfOwner(address owner)`, allowing to internally retrieve the array of an account's owned tokens. ([#1522](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1522))
* Crowdsales: all constructors are now `public`, meaning it is not necessary to extend these contracts in order to deploy them. The exception is `FinalizableCrowdsale`, since it is meaningless unless extended. ([#1564](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1564))
* `SignedSafeMath`: added overflow-safe operations for signed integers (`int256`). ([#1559](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1559), [#1588](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1588))
- Now targeting the 0.5.x line of Solidity compilers. For 0.4.24 support, use version 2.0 of OpenZeppelin.
- `WhitelistCrowdsale`: a crowdsale where only whitelisted accounts (`WhitelistedRole`) can purchase tokens. Adding or removing accounts from the whitelist is done by whitelist admins (`WhitelistAdminRole`). Similar to the pre-2.0 `WhitelistedCrowdsale`. ([#1525](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1525), [#1589](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1589))
- `RefundablePostDeliveryCrowdsale`: replacement for `RefundableCrowdsale` (deprecated, see below) where tokens are only granted once the crowdsale ends (if it meets its goal). ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))
- `PausableCrowdsale`: allows for pausers (`PauserRole`) to pause token purchases. Other crowdsale operations (e.g. withdrawals and refunds, if applicable) are not affected. ([#832](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/832))
- `ERC20`: `transferFrom` and `_burnFrom ` now emit `Approval` events, to represent the token's state comprehensively through events. ([#1524](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1524))
- `ERC721`: added `_burn(uint256 tokenId)`, replacing the similar deprecated function (see below). ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
- `ERC721`: added `_tokensOfOwner(address owner)`, allowing to internally retrieve the array of an account's owned tokens. ([#1522](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1522))
- Crowdsales: all constructors are now `public`, meaning it is not necessary to extend these contracts in order to deploy them. The exception is `FinalizableCrowdsale`, since it is meaningless unless extended. ([#1564](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1564))
- `SignedSafeMath`: added overflow-safe operations for signed integers (`int256`). ([#1559](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1559), [#1588](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1588))
### Improvements
* The compiler version required by `Array` was behind the rest of the libray so it was updated to `v0.4.24`. ([#1553](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1553))
* Now conforming to a 4-space indentation code style. ([1508](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1508))
* `ERC20`: more gas efficient due to removed redundant `require`s. ([#1409](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1409))
* `ERC721`: fixed a bug that prevented internal data structures from being properly cleaned, missing potential gas refunds. ([#1539](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1539) and [#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
* `ERC721`: general gas savings on `transferFrom`, `_mint` and `_burn`, due to redudant `require`s and `SSTORE`s. ([#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
- The compiler version required by `Array` was behind the rest of the library so it was updated to `v0.4.24`. ([#1553](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1553))
- Now conforming to a 4-space indentation code style. ([1508](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1508))
- `ERC20`: more gas efficient due to removed redundant `require`s. ([#1409](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1409))
- `ERC721`: fixed a bug that prevented internal data structures from being properly cleaned, missing potential gas refunds. ([#1539](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1539) and [#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
- `ERC721`: general gas savings on `transferFrom`, `_mint` and `_burn`, due to redundant `require`s and `SSTORE`s. ([#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
### Bugfixes
### Breaking changes
### Deprecations
* `ERC721._burn(address owner, uint256 tokenId)`: due to the `owner` parameter being unnecessary. ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
* `RefundableCrowdsale`: due to trading abuse potential on crowdsales that miss their goal. ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))
- `ERC721._burn(address owner, uint256 tokenId)`: due to the `owner` parameter being unnecessary. ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
- `RefundableCrowdsale`: due to trading abuse potential on crowdsales that miss their goal. ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))

View File

@ -55,7 +55,7 @@ further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at maintainers@openzeppelin.org. All
reported by contacting the project team at contact@openzeppelin.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.

View File

@ -1,64 +1,36 @@
Contributing to OpenZeppelin Contracts
=======
# Contributing Guidelines
We really appreciate and value contributions to OpenZeppelin Contracts. Please take 5' to review the items listed below to make sure that your contributions are merged as soon as possible.
There are many ways to contribute to OpenZeppelin Contracts.
## Contribution guidelines
## Troubleshooting
Smart contracts manage value and are highly vulnerable to errors and attacks. We have very strict [guidelines], please make sure to review them!
You can help other users in the community to solve their smart contract issues in the [OpenZeppelin Forum].
## Creating Pull Requests (PRs)
[OpenZeppelin Forum]: https://forum.openzeppelin.com/
As a contributor, you are expected to fork this repository, work on your own fork and then submit pull requests. The pull requests will be reviewed and eventually merged into the main repo. See ["Fork-a-Repo"](https://help.github.com/articles/fork-a-repo/) for how this works.
## Opening an issue
## A typical workflow
You can [open an issue] to suggest a feature or report a minor bug. For serious bugs please do not open an issue, instead refer to our [security policy] for appropriate steps.
1) Make sure your fork is up to date with the main repository:
If you believe your issue may be due to user error and not a problem in the library, consider instead posting a question on the [OpenZeppelin Forum].
```
cd openzeppelin-contracts
git remote add upstream https://github.com/OpenZeppelin/openzeppelin-contracts.git
git fetch upstream
git pull --rebase upstream master
```
NOTE: The directory `openzeppelin-contracts` represents your fork's local copy.
Before opening an issue, be sure to search through the existing open and closed issues, and consider posting a comment in one of those instead.
2) Branch out from `master` into `fix/some-bug-#123`:
(Postfixing #123 will associate your PR with the issue #123 and make everyone's life easier =D)
```
git checkout -b fix/some-bug-#123
```
When requesting a new feature, include as many details as you can, especially around the use cases that motivate it. Features are prioritized according to the impact they may have on the ecosystem, so we appreciate information showing that the impact could be high.
3) Make your changes, add your files, commit, and push to your fork.
[security policy]: https://github.com/OpenZeppelin/openzeppelin-contracts/security
[open an issue]: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/new/choose
```
git add SomeFile.js
git commit "Fix some bug #123"
git push origin fix/some-bug-#123
```
## Submitting a pull request
4) Run tests, linter, etc. This can be done by running local continuous integration and make sure it passes.
If you would like to contribute code or documentation you may do so by forking the repository and submitting a pull request.
```bash
npm test
npm run lint
```
Any non-trivial code contribution must be first discussed with the maintainers in an issue (see [Opening an issue](#opening-an-issue)). Only very minor changes are accepted without prior discussion.
5) Go to [github.com/OpenZeppelin/openzeppelin-contracts](https://github.com/OpenZeppelin/openzeppelin-contracts) in your web browser and issue a new pull request.
Make sure to read and follow the [engineering guidelines](./GUIDELINES.md). Run linter and tests to make sure your pull request is good before submitting it.
*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.
Changelog entries should be added to each pull request by using [Changesets](https://github.com/changesets/changesets/).
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.
When opening the pull request you will be presented with a template and a series of instructions. Read through it carefully and follow all the steps. Expect a review and feedback from the maintainers afterwards.
*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!
If you have any questions, feel free to post them to github.com/OpenZeppelin/openzeppelin-contracts/issues.
Finally, if you're looking to collaborate and want to find easy tasks to start, look at the issues we marked as ["Good first issue"](https://github.com/OpenZeppelin/openzeppelin-contracts/labels/good%20first%20issue).
Thanks for your time and code!
[guidelines]: GUIDELINES.md
If you're looking for a good place to start, look for issues labelled ["good first issue"](https://github.com/OpenZeppelin/openzeppelin-contracts/labels/good%20first%20issue)!

View File

@ -1,105 +1,117 @@
Design Guidelines
=======
# Engineering Guidelines
These are some global design goals in OpenZeppelin Contracts.
## Testing
#### 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.
Code must be thoroughly tested with quality unit tests.
#### D1 - Simple and Modular
Simpler code means easier audits, and better understanding of what each component does. We look for small files, small contracts, and small functions. If you can separate a contract into two independent functionalities you should probably do it.
We defer to the [Moloch Testing Guide](https://github.com/MolochVentures/moloch/tree/master/test#readme) for specific recommendations, though not all of it is relevant here. Note the introduction:
#### D2 - Naming Matters
> Tests should be written, not only to verify correctness of the target code, but to be comprehensively reviewed by other programmers. Therefore, for mission critical Solidity code, the quality of the tests are just as important (if not more so) than the code itself, and should be written with the highest standards of clarity and elegance.
We take our time with picking names. Code is going to be written once, and read hundreds of times. Renaming for clarity is encouraged.
Every addition or change to the code must come with relevant and comprehensive tests.
#### D3 - Tests
Refactors should avoid simultaneous changes to tests.
Write tests for all your code. We encourage Test Driven Development so we know when our code is right. Even though not all code in the repository is tested at the moment, we aim to test every line of code in the future.
Flaky tests are not acceptable.
#### D4 - Check preconditions and post-conditions
The test suite should run automatically for every change in the repository, and in pull requests tests must pass before merging.
A very important way to prevent vulnerabilities is to catch a contracts inconsistent state as early as possible. This is why we want functions to check pre- and post-conditions for executing its logic. When writing code, ask yourself what you are expecting to be true before and after the function runs, and express it in code.
The test suite coverage must be kept as close to 100% as possible, enforced in pull requests.
#### D5 - Code Consistency
In some cases unit tests may be insufficient and complementary techniques should be used:
Consistency on the way classes are used is paramount to an easier understanding of the library. The codebase should be as unified as possible. Read existing code and get inspired before you write your own. Follow the style guidelines. Dont hesitate to ask for help on how to best write a specific piece of code.
1. Property-based tests (aka. fuzzing) for math-heavy code.
2. Formal verification for state machines.
#### 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.
## Code style
# Style Guidelines
Solidity code should be written in a consistent format enforced by a linter, following the official [Solidity Style Guide](https://docs.soliditylang.org/en/latest/style-guide.html). See below for further [Solidity Conventions](#solidity-conventions).
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.
The code should be simple and straightforward, prioritizing readability and understandability. Consistency and predictability should be maintained across the codebase. In particular, this applies to naming, which should be systematic, clear, and concise.
## Solidity code
Sometimes these guidelines may be broken if doing so brings significant efficiency gains, but explanatory comments should be added.
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).
Modularity should be pursued, but not at the cost of the above priorities.
Any exception or additions specific to our project are documented below.
## Documentation
* Try to avoid acronyms and abbreviations.
For contributors, project guidelines and processes must be documented publicly.
For users, features must be abundantly documented. Documentation should include answers to common questions, solutions to common problems, and recommendations for critical decisions that the user may face.
All changes to the core codebase (excluding tests, auxiliary scripts, etc.) must be documented in a changelog, except for purely cosmetic or documentation changes.
## Peer review
All changes must be submitted through pull requests and go through peer code review.
The review must be approached by the reviewer in a similar way as if it was an audit of the code in question (but importantly it is not a substitute for and should not be considered an audit).
Reviewers should enforce code and project guidelines.
External contributions must be reviewed separately by multiple maintainers.
## Automation
Automation should be used as much as possible to reduce the possibility of human error and forgetfulness.
Automations that make use of sensitive credentials must use secure secret management, and must be strengthened against attacks such as [those on GitHub Actions worklows](https://github.com/nikitastupin/pwnhub).
Some other examples of automation are:
- Looking for common security vulnerabilities or errors in our code (eg. reentrancy analysis).
- Keeping dependencies up to date and monitoring for vulnerable dependencies.
## Pull requests
Pull requests are squash-merged to keep the `master` branch history clean. The title of the pull request becomes the commit message, so it should be written in a consistent format:
1) Begin with a capital letter.
2) Do not end with a period.
3) Write in the imperative: "Add feature X" and not "Adds feature X" or "Added feature X".
This repository does not follow conventional commits, so do not prefix the title with "fix:" or "feat:".
Work in progress pull requests should be submitted as Drafts and should not be prefixed with "WIP:".
Branch names don't matter, and commit messages within a pull request mostly don't matter either, although they can help the review process.
# Solidity Conventions
In addition to the official Solidity Style Guide we have a number of other conventions that must be followed.
* All state variables should be private.
* Private state variables should have an underscore prefix.
Changes to state should be accompanied by events, and in some cases it is not correct to arbitrarily set state. Encapsulating variables as private and only allowing modification via setters enables us to ensure that events and other rules are followed reliably and prevents this kind of user error.
```
contract TestContract {
* Internal or private state variables or functions should have an underscore prefix.
```solidity
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 {
...
}
```
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.
represent, and should be named in the past tense.
```
function _burn(address who, uint256 value) internal {
```solidity
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.
standard specification is used.
* Interface names should have a capital I prefix.
```
interface IERC777 {
```
```solidity
interface IERC777 {
```
## Tests
* Tests Must be Written Elegantly
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.
* 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.
* Unchecked arithmetic blocks should contain comments explaining why overflow is guaranteed not to happen. If the reason is immediately apparent from the line above the unchecked block, the comment may be omitted.

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016-2020 zOS Global Limited
Copyright (c) 2016-2023 zOS Global Limited and contributors
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,10 @@
# <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)
[![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts)
[![GitPOAPs](https://public-api.gitpoap.io/v1/repo/OpenZeppelin/openzeppelin-contracts/badge)](https://www.gitpoap.io/gh/OpenZeppelin/openzeppelin-contracts)
[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-yellow)](https://docs.openzeppelin.com/contracts)
[![Forum](https://img.shields.io/badge/forum-%F0%9F%92%AC-yellow)](https://docs.openzeppelin.com/contracts)
**A library for secure smart contract development.** Build on a solid foundation of community-vetted code.
@ -12,15 +14,19 @@
:mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator.
:building_construction: **Want to scale your decentralized application?** Check out [OpenZeppelin Defender](https://openzeppelin.com/defender) — a secure platform for automating and monitoring your operations.
## Overview
### Installation
```console
```
$ npm install @openzeppelin/contracts
```
OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version.
OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means that your contracts won't break unexpectedly when upgrading to a newer minor version.
An alternative to npm is to use the GitHub repository (`openzeppelin/openzeppelin-contracts`) to retrieve the contracts. When doing this, make sure to specify the tag for a release such as `v4.5.0`, instead of using the `master` branch.
### Usage
@ -39,20 +45,19 @@ contract MyCollectible is ERC721 {
_If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/developing-smart-contracts) to learn about creating a new project and compiling your contracts._
To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs.
To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs.
## Learn More
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:
The guides in the [documentation 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).
* [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn): let your users interact with your contracts without having to pay for gas themselves.
* [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools, including non-overflowing math, signature verification, and trustless paying systems.
* [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools including non-overflowing math, signature verification, and trustless paying systems.
The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the [community forum](https://forum.openzeppelin.com).
Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices.. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve.
Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices. The following articles provide great background reading, though please note that some of the referenced tools have changed, as the tooling in the ecosystem continues to rapidly evolve.
* [The Hitchhikers Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment.
* [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform.
@ -60,15 +65,17 @@ 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 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.
This project is maintained by [OpenZeppelin](https://openzeppelin.com) with the goal of providing a secure and reliable library of smart contract components for the ecosystem. We address security through risk management in various areas such as engineering and open source best practices, scoping and API design, multi-layered review processes, and incident response preparedness.
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 security policy is detailed in [`SECURITY.md`](./SECURITY.md), and specifies how you can report security vulnerabilities, which versions will receive security patches, and how to stay informed about them. We run a [bug bounty program on Immunefi](https://immunefi.com/bounty/openzeppelin) to reward the responsible disclosure of vulnerabilities.
The latest audit was done on October 2018 on version 2.0.0.
The engineering guidelines we follow to promote project quality can be found in [`GUIDELINES.md`](./GUIDELINES.md).
Please report any security issues you find via our [bug bounty program on Immunefi](https://www.immunefi.com/bounty/openzeppelin) or directly to security@openzeppelin.org.
Past audits can be found in [`audits/`](./audits).
Critical bug fixes will be backported to past major releases.
Smart contracts are a nascent technology and carry a high level of technical risk and uncertainty. Although OpenZeppelin is well known for its security audits, using OpenZeppelin Contracts is not a substitute for a security audit.
OpenZeppelin Contracts is made available under the MIT License, which disclaims all warranties in relation to the project and which limits the liability of those that contribute and maintain the project, including OpenZeppelin. As set out further in the Terms, you acknowledge that you are solely responsible for any use of OpenZeppelin Contracts and you assume all risks associated with any such use.
## Contribute
@ -77,3 +84,7 @@ OpenZeppelin Contracts exists thanks to its contributors. There are many ways yo
## License
OpenZeppelin Contracts is released under the [MIT License](LICENSE).
## Legal
Your use of this Project is governed by the terms found at www.openzeppelin.com/tos (the "Terms").

View File

@ -1,36 +1,47 @@
# Releasing
> Visit the documentation for [details about release schedule].
> Visit the documentation for [details about release schedule](https://docs.openzeppelin.com/contracts/releases-stability).
Start on an up-to-date `master` branch.
OpenZeppelin Contracts uses a fully automated release process that takes care of compiling, packaging, and publishing the library, all of which is carried out in a clean CI environment (GitHub Actions), implemented in the ([`release-cycle`](.github/workflows/release-cycle.yml)) workflow. This helps to reduce the potential for human error and inconsistencies, and ensures that the release process is ongoing and reliable.
Create the release branch with `npm run release start minor`.
## Changesets
Publish a release candidate with `npm run release rc`.
[Changesets](https://github.com/changesets/changesets/) is used as part of our release process for `CHANGELOG.md` management. Each change that is relevant for the codebase is expected to include a changeset.
Publish the final release with `npm run release final`.
## Branching model
Follow the general [OpenZeppelin Contracts release checklist].
The release cycle happens on release branches called `release-vX.Y`. Each of these branches starts as a release candidate (rc) and is eventually promoted to final.
[details about release schedule]: https://docs.openzeppelin.com/contracts/releases-stability
[OpenZeppelin Contracts release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md
A release branch can be updated with cherry-picked patches from `master`, or may sometimes be committed to directly in the case of old releases. These commits will lead to a new release candidate or a patch increment depending on the state of the release branch.
```mermaid
%%{init: {'gitGraph': {'mainBranchName': 'master'}} }%%
gitGraph
commit id: "Feature A"
commit id: "Feature B"
branch release-vX.Y
commit id: "Start release"
commit id: "Release vX.Y.0-rc.0"
## Merging the release branch
checkout master
commit id: "Feature C"
commit id: "Fix A"
After the final release, the release branch should be merged back into `master`. This merge must not be squashed because it would lose the tagged release commit. Since the GitHub repo is set up to only allow squashed merges, the merge should be done locally and pushed.
checkout release-vX.Y
cherry-pick id: "Fix A" tag: ""
commit id: "Release vX.Y.0-rc.1"
commit id: "Release vX.Y.0"
Make sure to have the latest changes from `upstream` in your local release branch.
checkout master
merge release-vX.Y
commit id: "Feature D"
commit id: "Patch B"
checkout release-vX.Y
cherry-pick id: "Patch B" tag: ""
commit id: "Release vX.Y.1"
checkout master
merge release-vX.Y
commit id: "Feature E"
```
git checkout release-vX.Y.Z
git pull upstream
```
```
git checkout master
git merge --no-ff release-vX.Y.Z
git push upstream master
```
The release branch can then be deleted on GitHub.

View File

@ -1,18 +1,42 @@
# Security Policy
## Supported Versions
Security vulnerabilities should be disclosed to the project maintainers through [Immunefi], or alternatively by email to security@openzeppelin.com.
The recommendation is to use the latest version available.
[Immunefi]: https://immunefi.com/bounty/openzeppelin
| Version | Supported |
| ------- | ------------------------------------ |
| 4.x | :white_check_mark::white_check_mark: |
| 3.4 | :white_check_mark: |
| 2.5 | :white_check_mark: |
| < 2.0 | :x: |
## Bug Bounty
## Reporting a Vulnerability
Responsible disclosure of security vulnerabilities is rewarded through a bug bounty program on [Immunefi].
Please report any security issues you find to security@openzeppelin.org.
There is a bonus reward for issues introduced in release candidates that are reported before making it into a stable release.
Critical bug fixes will be backported to past major releases.
## Security Patches
Security vulnerabilities will be patched as soon as responsibly possible, and published as an advisory on this repository (see [advisories]) and on the affected npm packages.
[advisories]: https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories
Projects that build on OpenZeppelin Contracts are encouraged to clearly state, in their source code and websites, how to be contacted about security issues in the event that a direct notification is considered necessary. We recommend including it in the NatSpec for the contract as `/// @custom:security-contact security@example.com`.
Additionally, we recommend installing the library through npm and setting up vulnerability alerts such as [Dependabot].
[Dependabot]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security#what-is-dependabot
### Supported Versions
Security patches will be released for the latest minor of a given major release. For example, if an issue is found in versions >=4.6.0 and the latest is 4.8.0, the patch will be released only in version 4.8.1.
Only critical severity bug fixes will be backported to past major releases.
| Version | Critical security fixes | Other security fixes |
| ------- | ----------------------- | -------------------- |
| 4.x | :white_check_mark: | :white_check_mark: |
| 3.4 | :white_check_mark: | :x: |
| 2.5 | :white_check_mark: | :x: |
| < 2.0 | :x: | :x: |
Note as well that the Solidity language itself only guarantees security updates for the latest release.
## Legal
Smart contracts are a nascent techology and carry a high level of technical risk and uncertainty. OpenZeppelin Contracts is made available under the MIT License, which disclaims all warranties in relation to the project and which limits the liability of those that contribute and maintain the project, including OpenZeppelin. Your use of the project is also governed by the terms found at www.openzeppelin.com/tos (the "Terms"). As set out in the Terms, you are solely responsible for any use of OpenZeppelin Contracts and you assume all risks associated with any such use. This Security Policy in no way evidences or represents an on-going duty by any contributor, including OpenZeppelin, to correct any flaws or alert you to all or any of the potential risks of utilizing the project.

View File

@ -1,6 +1,6 @@
# 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.
NOTE ON 2021-07-19: This report makes reference to Zeppelin, OpenZeppelin, OpenZeppelin Contracts, 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 Contracts Community.
March, 2017
Authored by Dennis Peterson and Peter Vessenes
@ -133,7 +133,7 @@ I presume that the goal of this contract is to allow and annotate a migration to
We like these pauses! Note that these allow significant griefing potential by owners, and that this might not be obvious to participants in smart contracts using the OpenZeppelin framework. We would recommend that additional sample logic be added to for instance the TokenContract showing safer use of the pause and resume functions. In particular, we would recommend a timelock after which anyone could unpause the contract.
The modifers use the pattern `if(bool){_;}`. This is fine for functions that return false upon failure, but could be problematic for functions expected to throw upon failure. See our comments above on standardizing on `throw` or `return(false)`.
The modifiers use the pattern `if(bool){_;}`. This is fine for functions that return false upon failure, but could be problematic for functions expected to throw upon failure. See our comments above on standardizing on `throw` or `return(false)`.
## Ownership

Binary file not shown.

BIN
audits/2022-10-ERC4626.pdf Normal file

Binary file not shown.

BIN
audits/2023-05-v4.9.pdf Normal file

Binary file not shown.

16
audits/README.md Normal file
View File

@ -0,0 +1,16 @@
# Audits
| Date | Version | Commit | Auditor | Scope | Links |
| ------------ | ------- | --------- | ------------ | -------------------- | ----------------------------------------------------------- |
| May 2023 | v4.9.0 | `91df66c` | OpenZeppelin | v4.9 Changes | [🔗](./2023-05-v4.9.pdf) |
| October 2022 | v4.8.0 | `14f98db` | OpenZeppelin | ERC4626, Checkpoints | [🔗](./2022-10-ERC4626.pdf) [🔗](./2022-10-Checkpoints.pdf) |
| October 2018 | v2.0.0 | `dac5bcc` | LevelK | Everything | [🔗](./2018-10.pdf) |
| March 2017 | v1.0.4 | `9c5975a` | New Alchemy | Everything | [🔗](./2017-03.md) |
# Formal Verification
| Date | Version | Commit | Tool | Scope | Links |
| ------------ | ------- | --------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| May 2022 | v4.7.0 | `109778c` | Certora | Initializable, GovernorPreventLateQuorum, ERC1155Burnable, ERC1155Pausable, ERC1155Supply, ERC1155Holder, ERC1155Receiver | [🔗](../certora/reports/2022-05.pdf) |
| March 2022 | v4.4.0 | `4088540` | Certora | ERC20Votes, ERC20FlashMint, ERC20Wrapper, TimelockController, ERC721Votes, Votes, AccessControl, ERC1155 | [🔗](../certora/reports/2022-03.pdf) |
| October 2021 | v4.4.0 | `4088540` | Certora | Governor, GovernorCountingSimple, GovernorProposalThreshold, GovernorTimelockControl, GovernorVotes, GovernorVotesQuorumFraction | [🔗](../certora/reports/2021-10.pdf) |

1
certora/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
patched

54
certora/Makefile Normal file
View File

@ -0,0 +1,54 @@
default: help
SRC := ../contracts
DST := patched
DIFF := diff
SRCS := $(shell find $(SRC) -type f)
DSTS := $(shell find $(DST) -type f)
DIFFS := $(shell find $(DIFF) -type f)
###############################################################################
# Apply all patches in the $DIFF folder to the $DST folder
apply: $(DST) $(patsubst $(DIFF)/%.patch,$(DST)/%,$(subst _,/,$(DIFFS)))
# Reset the $DST folder
$(DST): FORCE
@rm -rf $@
@cp -r $(SRC) $@
# Update a solidity file in the $DST directory using the corresponding patch
$(DST)/%.sol: FORCE
@echo Applying patch to $@
@patch -p0 -d $(DST) < $(patsubst $(DST)_%,$(DIFF)/%.patch,$(subst /,_,$@))
###############################################################################
# Record all difference between $SRC and $DST in patches
record: $(DIFF) $(patsubst %,$(DIFF)/%.patch,$(subst /,_,$(subst $(SRC)/,,$(SRCS)) $(subst $(DST)/,,$(DSTS))))
# Create the $DIFF folder
$(DIFF): FORCE
@rm -rf $@
@mkdir $@
# Create the patch file by comparing the source and the destination
$(DIFF)/%.patch: FORCE
@echo Generating patch $@
@diff -ruN \
$(patsubst $(DIFF)/%.patch,$(SRC)/%,$(subst _,/,$@)) \
$(patsubst $(DIFF)/%.patch,$(DST)/%,$(subst _,/,$@)) \
| sed 's+$(SRC)/++g' \
| sed 's+$(DST)/++g' \
> $@
@[ -s $@ ] || rm $@
###############################################################################
help:
@echo "usage:"
@echo " make apply: create $(DST) directory by applying the patches to $(SRC)"
@echo " make record: record the patches capturing the differences between $(SRC) and $(DST)"
@echo " make clean: remove all generated files (those ignored by git)"
clean:
git clean -fdX
FORCE: ;

60
certora/README.md Normal file
View File

@ -0,0 +1,60 @@
# Running the certora verification tool
These instructions detail the process for running Certora Verification Tool on OpenZeppelin Contracts.
Documentation for CVT and the specification language are available [here](https://certora.atlassian.net/wiki/spaces/CPD/overview).
## Prerequisites
Follow the [Certora installation guide](https://docs.certora.com/en/latest/docs/user-guide/getting-started/install.html) in order to get the Certora Prover Package and the `solc` executable folder in your path.
> **Note**
> An API Key is required for local testing. Although the prover will run on a Github Actions' CI environment on selected Pull Requests.
## Running the verification
The Certora Verification Tool proves specs for contracts, which are defined by the `./specs.json` file along with their pre-configured options.
The verification script `./run.js` is used to submit verification jobs to the Certora Verification service.
You can run it from the root of the repository with the following command:
```bash
node certora/run.js [[CONTRACT_NAME:]SPEC_NAME] [OPTIONS...]
```
Where:
- `CONTRACT_NAME` matches the `contract` key in the `./spec.json` file and may be empty. It will run all matching contracts if not provided.
- `SPEC_NAME` refers to a `spec` key from the `./specs.json` file. It will run every spec if not provided.
- `OPTIONS` extend the [Certora Prover CLI options](https://docs.certora.com/en/latest/docs/prover/cli/options.html#certora-prover-cli-options) and will respect the preconfigured options in the `specs.json` file.
> **Note**
> A single spec may be configured to run for multiple contracts, whereas a single contract may run multiple specs.
Example usage:
```bash
node certora/run.js AccessControl # Run the AccessControl spec against every contract implementing it
```
## Adapting to changes in the contracts
Some of our rules require the code to be simplified in various ways. Our primary tool for performing these simplifications is to run verification on a contract that extends the original contracts and overrides some of the methods. These "harness" contracts can be found in the `certora/harness` directory.
This pattern does require some modifications to the original code: some methods need to be made virtual or public, for example. These changes are handled by applying a patch
to the code before verification by running:
```bash
make -C certora apply
```
Before running the `certora/run.js` script, it's required to apply the corresponding patches to the `contracts` directory, placing the output in the `certora/patched` directory. Then, the contracts are verified by running the verification for the `certora/patched` directory.
If the original contracts change, it is possible to create a conflict with the patch. In this case, the verify scripts will report an error message and output rejected changes in the `patched` directory. After merging the changes, run `make record` in the `certora` directory; this will regenerate the patch file, which can then be checked into git.
For more information about the `make` scripts available, run:
```bash
make -C certora help
```

View File

@ -0,0 +1,14 @@
--- token/ERC721/ERC721.sol 2023-03-07 10:48:47.736822221 +0100
+++ token/ERC721/ERC721.sol 2023-03-09 19:49:39.669338673 +0100
@@ -199,6 +199,11 @@
return _owners[tokenId];
}
+ // FV
+ function _getApproved(uint256 tokenId) internal view returns (address) {
+ return _tokenApprovals[tokenId];
+ }
+
/**
* @dev Returns whether `tokenId` exists.
*

View File

@ -0,0 +1,47 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/access/AccessControlDefaultAdminRules.sol";
contract AccessControlDefaultAdminRulesHarness is AccessControlDefaultAdminRules {
uint48 private _delayIncreaseWait;
constructor(
uint48 initialDelay,
address initialDefaultAdmin,
uint48 delayIncreaseWait
) AccessControlDefaultAdminRules(initialDelay, initialDefaultAdmin) {
_delayIncreaseWait = delayIncreaseWait;
}
// FV
function pendingDefaultAdmin_() external view returns (address) {
(address newAdmin, ) = pendingDefaultAdmin();
return newAdmin;
}
function pendingDefaultAdminSchedule_() external view returns (uint48) {
(, uint48 schedule) = pendingDefaultAdmin();
return schedule;
}
function pendingDelay_() external view returns (uint48) {
(uint48 newDelay, ) = pendingDefaultAdminDelay();
return newDelay;
}
function pendingDelaySchedule_() external view returns (uint48) {
(, uint48 schedule) = pendingDefaultAdminDelay();
return schedule;
}
function delayChangeWait_(uint48 newDelay) external view returns (uint48) {
return _delayChangeWait(newDelay);
}
// Overrides
function defaultAdminDelayIncreaseWait() public view override returns (uint48) {
return _delayIncreaseWait;
}
}

View File

@ -0,0 +1,7 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/access/AccessControl.sol";
contract AccessControlHarness is AccessControl {}

View File

@ -0,0 +1,59 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/utils/structs/DoubleEndedQueue.sol";
contract DoubleEndedQueueHarness {
using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
DoubleEndedQueue.Bytes32Deque private _deque;
function pushFront(bytes32 value) external {
_deque.pushFront(value);
}
function pushBack(bytes32 value) external {
_deque.pushBack(value);
}
function popFront() external returns (bytes32 value) {
return _deque.popFront();
}
function popBack() external returns (bytes32 value) {
return _deque.popBack();
}
function clear() external {
_deque.clear();
}
function begin() external view returns (int128) {
return _deque._begin;
}
function end() external view returns (int128) {
return _deque._end;
}
function length() external view returns (uint256) {
return _deque.length();
}
function empty() external view returns (bool) {
return _deque.empty();
}
function front() external view returns (bytes32 value) {
return _deque.front();
}
function back() external view returns (bytes32 value) {
return _deque.back();
}
function at_(uint256 index) external view returns (bytes32 value) {
return _deque.at(index);
}
}

View File

@ -0,0 +1,36 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/token/ERC20/ERC20.sol";
import "../patched/token/ERC20/extensions/ERC20Permit.sol";
import "../patched/token/ERC20/extensions/ERC20FlashMint.sol";
contract ERC20FlashMintHarness is ERC20, ERC20Permit, ERC20FlashMint {
uint256 someFee;
address someFeeReceiver;
constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {}
function mint(address account, uint256 amount) external {
_mint(account, amount);
}
function burn(address account, uint256 amount) external {
_burn(account, amount);
}
// public accessor
function flashFeeReceiver() public view returns (address) {
return someFeeReceiver;
}
// internal hook
function _flashFee(address, uint256) internal view override returns (uint256) {
return someFee;
}
function _flashFeeReceiver() internal view override returns (address) {
return someFeeReceiver;
}
}

View File

@ -0,0 +1,17 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/token/ERC20/extensions/ERC20Permit.sol";
contract ERC20PermitHarness is ERC20Permit {
constructor(string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {}
function mint(address account, uint256 amount) external {
_mint(account, amount);
}
function burn(address account, uint256 amount) external {
_burn(account, amount);
}
}

View File

@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/token/ERC20/extensions/ERC20Wrapper.sol";
contract ERC20WrapperHarness is ERC20Wrapper {
constructor(IERC20 _underlying, string memory _name, string memory _symbol) ERC20(_name, _symbol) ERC20Wrapper(_underlying) {}
function underlyingTotalSupply() public view returns (uint256) {
return underlying().totalSupply();
}
function underlyingBalanceOf(address account) public view returns (uint256) {
return underlying().balanceOf(account);
}
function underlyingAllowanceToThis(address account) public view returns (uint256) {
return underlying().allowance(account, address(this));
}
function recover(address account) public returns (uint256) {
return _recover(account);
}
}

View File

@ -0,0 +1,13 @@
// SPDX-License-Identifier: MIT
import "../patched/interfaces/IERC3156FlashBorrower.sol";
pragma solidity ^0.8.0;
contract ERC3156FlashBorrowerHarness is IERC3156FlashBorrower {
bytes32 somethingToReturn;
function onFlashLoan(address, address, uint256, uint256, bytes calldata) external view override returns (bytes32) {
return somethingToReturn;
}
}

View File

@ -0,0 +1,37 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/token/ERC721/ERC721.sol";
contract ERC721Harness is ERC721 {
constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
function mint(address account, uint256 tokenId) external {
_mint(account, tokenId);
}
function safeMint(address to, uint256 tokenId) external {
_safeMint(to, tokenId);
}
function safeMint(address to, uint256 tokenId, bytes memory data) external {
_safeMint(to, tokenId, data);
}
function burn(uint256 tokenId) external {
_burn(tokenId);
}
function tokenExists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
function unsafeOwnerOf(uint256 tokenId) external view returns (address) {
return _ownerOf(tokenId);
}
function unsafeGetApproved(uint256 tokenId) external view returns (address) {
return _getApproved(tokenId);
}
}

View File

@ -0,0 +1,11 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/interfaces/IERC721Receiver.sol";
contract ERC721ReceiverHarness is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
}

View File

@ -0,0 +1,55 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/utils/structs/EnumerableMap.sol";
contract EnumerableMapHarness {
using EnumerableMap for EnumerableMap.Bytes32ToBytes32Map;
EnumerableMap.Bytes32ToBytes32Map private _map;
function set(bytes32 key, bytes32 value) public returns (bool) {
return _map.set(key, value);
}
function remove(bytes32 key) public returns (bool) {
return _map.remove(key);
}
function contains(bytes32 key) public view returns (bool) {
return _map.contains(key);
}
function length() public view returns (uint256) {
return _map.length();
}
function key_at(uint256 index) public view returns (bytes32) {
(bytes32 key,) = _map.at(index);
return key;
}
function value_at(uint256 index) public view returns (bytes32) {
(,bytes32 value) = _map.at(index);
return value;
}
function tryGet_contains(bytes32 key) public view returns (bool) {
(bool contained,) = _map.tryGet(key);
return contained;
}
function tryGet_value(bytes32 key) public view returns (bytes32) {
(,bytes32 value) = _map.tryGet(key);
return value;
}
function get(bytes32 key) public view returns (bytes32) {
return _map.get(key);
}
function _indexOf(bytes32 key) public view returns (uint256) {
return _map._keys._inner._indexes[key];
}
}

View File

@ -0,0 +1,35 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/utils/structs/EnumerableSet.sol";
contract EnumerableSetHarness {
using EnumerableSet for EnumerableSet.Bytes32Set;
EnumerableSet.Bytes32Set private _set;
function add(bytes32 value) public returns (bool) {
return _set.add(value);
}
function remove(bytes32 value) public returns (bool) {
return _set.remove(value);
}
function contains(bytes32 value) public view returns (bool) {
return _set.contains(value);
}
function length() public view returns (uint256) {
return _set.length();
}
function at_(uint256 index) public view returns (bytes32) {
return _set.at(index);
}
function _indexOf(bytes32 value) public view returns (uint256) {
return _set._inner._indexes[value];
}
}

View File

@ -0,0 +1,23 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../patched/proxy/utils/Initializable.sol";
contract InitializableHarness is Initializable {
function initialize() public initializer {}
function reinitialize(uint8 n) public reinitializer(n) {}
function disable() public { _disableInitializers(); }
function nested_init_init() public initializer { initialize(); }
function nested_init_reinit(uint8 m) public initializer { reinitialize(m); }
function nested_reinit_init(uint8 n) public reinitializer(n) { initialize(); }
function nested_reinit_reinit(uint8 n, uint8 m) public reinitializer(n) { reinitialize(m); }
function version() public view returns (uint8) {
return _getInitializedVersion();
}
function initializing() public view returns (bool) {
return _isInitializing();
}
}

View File

@ -0,0 +1,9 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/access/Ownable2Step.sol";
contract Ownable2StepHarness is Ownable2Step {
function restricted() external onlyOwner {}
}

View File

@ -0,0 +1,9 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/access/Ownable.sol";
contract OwnableHarness is Ownable {
function restricted() external onlyOwner {}
}

View File

@ -0,0 +1,19 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../patched/security/Pausable.sol";
contract PausableHarness is Pausable {
function pause() external {
_pause();
}
function unpause() external {
_unpause();
}
function onlyWhenPaused() external whenPaused {}
function onlyWhenNotPaused() external whenNotPaused {}
}

View File

@ -0,0 +1,12 @@
pragma solidity ^0.8.0;
import "../patched/governance/TimelockController.sol";
contract TimelockControllerHarness is TimelockController {
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors,
address admin
) TimelockController(minDelay, proposers, executors, admin) {}
}

BIN
certora/reports/2021-10.pdf Normal file

Binary file not shown.

BIN
certora/reports/2022-03.pdf Normal file

Binary file not shown.

BIN
certora/reports/2022-05.pdf Normal file

Binary file not shown.

146
certora/run.js Executable file
View File

@ -0,0 +1,146 @@
#!/usr/bin/env node
// USAGE:
// node certora/run.js [[CONTRACT_NAME:]SPEC_NAME]* [--all] [--options OPTIONS...] [--specs PATH]
// EXAMPLES:
// node certora/run.js --all
// node certora/run.js AccessControl
// node certora/run.js AccessControlHarness:AccessControl
const proc = require('child_process');
const { PassThrough } = require('stream');
const events = require('events');
const argv = require('yargs')
.env('')
.options({
all: {
alias: 'a',
type: 'boolean',
},
spec: {
alias: 's',
type: 'string',
default: __dirname + '/specs.json',
},
parallel: {
alias: 'p',
type: 'number',
default: 4,
},
options: {
alias: 'o',
type: 'array',
default: [],
},
}).argv;
function match(entry, request) {
const [reqSpec, reqContract] = request.split(':').reverse();
return entry.spec == reqSpec && (!reqContract || entry.contract == reqContract);
}
const specs = require(argv.spec).filter(s => argv.all || argv._.some(r => match(s, r)));
const limit = require('p-limit')(argv.parallel);
if (argv._.length == 0 && !argv.all) {
console.error(`Warning: No specs requested. Did you forgot to toggle '--all'?`);
}
for (const r of argv._) {
if (!specs.some(s => match(s, r))) {
console.error(`Error: Requested spec '${r}' not found in ${argv.spec}`);
process.exitCode = 1;
}
}
if (process.exitCode) {
process.exit(process.exitCode);
}
for (const { spec, contract, files, options = [] } of specs) {
limit(runCertora, spec, contract, files, [...options.flatMap(opt => opt.split(' ')), ...argv.options]);
}
// Run certora, aggregate the output and print it at the end
async function runCertora(spec, contract, files, options = []) {
const args = [...files, '--verify', `${contract}:certora/specs/${spec}.spec`, ...options];
const child = proc.spawn('certoraRun', args);
const stream = new PassThrough();
const output = collect(stream);
child.stdout.pipe(stream, { end: false });
child.stderr.pipe(stream, { end: false });
// as soon as we have a job id, print the output link
stream.on('data', function logStatusUrl(data) {
const { '-DjobId': jobId, '-DuserId': userId } = Object.fromEntries(
data
.toString('utf8')
.match(/-D\S+=\S+/g)
?.map(s => s.split('=')) || [],
);
if (jobId && userId) {
console.error(`[${spec}] https://prover.certora.com/output/${userId}/${jobId}/`);
stream.off('data', logStatusUrl);
}
});
// wait for process end
const [code, signal] = await events.once(child, 'exit');
// error
if (code || signal) {
console.error(`[${spec}] Exited with code ${code || signal}`);
process.exitCode = 1;
}
// get all output
stream.end();
// write results in markdown format
writeEntry(spec, contract, code || signal, (await output).match(/https:\/\/prover.certora.com\/output\/\S*/)?.[0]);
// write all details
console.error(`+ certoraRun ${args.join(' ')}\n` + (await output));
}
// Collects stream data into a string
async function collect(stream) {
const buffers = [];
for await (const data of stream) {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
buffers.push(buf);
}
return Buffer.concat(buffers).toString('utf8');
}
// Formatting
let hasHeader = false;
function formatRow(...array) {
return ['', ...array, ''].join(' | ');
}
function writeHeader() {
console.log(formatRow('spec', 'contract', 'result', 'status', 'output'));
console.log(formatRow('-', '-', '-', '-', '-'));
}
function writeEntry(spec, contract, success, url) {
if (!hasHeader) {
hasHeader = true;
writeHeader();
}
console.log(
formatRow(
spec,
contract,
success ? ':x:' : ':heavy_check_mark:',
url ? `[link](${url?.replace('/output/', '/jobStatus/')})` : 'error',
url ? `[link](${url})` : 'error',
),
);
}

86
certora/specs.json Normal file
View File

@ -0,0 +1,86 @@
[
{
"spec": "Pausable",
"contract": "PausableHarness",
"files": ["certora/harnesses/PausableHarness.sol"]
},
{
"spec": "AccessControl",
"contract": "AccessControlHarness",
"files": ["certora/harnesses/AccessControlHarness.sol"]
},
{
"spec": "AccessControlDefaultAdminRules",
"contract": "AccessControlDefaultAdminRulesHarness",
"files": ["certora/harnesses/AccessControlDefaultAdminRulesHarness.sol"]
},
{
"spec": "DoubleEndedQueue",
"contract": "DoubleEndedQueueHarness",
"files": ["certora/harnesses/DoubleEndedQueueHarness.sol"]
},
{
"spec": "Ownable",
"contract": "OwnableHarness",
"files": ["certora/harnesses/OwnableHarness.sol"]
},
{
"spec": "Ownable2Step",
"contract": "Ownable2StepHarness",
"files": ["certora/harnesses/Ownable2StepHarness.sol"]
},
{
"spec": "ERC20",
"contract": "ERC20PermitHarness",
"files": ["certora/harnesses/ERC20PermitHarness.sol"],
"options": ["--optimistic_loop"]
},
{
"spec": "ERC20FlashMint",
"contract": "ERC20FlashMintHarness",
"files": [
"certora/harnesses/ERC20FlashMintHarness.sol",
"certora/harnesses/ERC3156FlashBorrowerHarness.sol"
],
"options": ["--optimistic_loop"]
},
{
"spec": "ERC20Wrapper",
"contract": "ERC20WrapperHarness",
"files": [
"certora/harnesses/ERC20PermitHarness.sol",
"certora/harnesses/ERC20WrapperHarness.sol"
],
"options": [
"--link ERC20WrapperHarness:_underlying=ERC20PermitHarness",
"--optimistic_loop"
]
},
{
"spec": "ERC721",
"contract": "ERC721Harness",
"files": ["certora/harnesses/ERC721Harness.sol", "certora/harnesses/ERC721ReceiverHarness.sol"],
"options": ["--optimistic_loop"]
},
{
"spec": "Initializable",
"contract": "InitializableHarness",
"files": ["certora/harnesses/InitializableHarness.sol"]
},
{
"spec": "EnumerableSet",
"contract": "EnumerableSetHarness",
"files": ["certora/harnesses/EnumerableSetHarness.sol"]
},
{
"spec": "EnumerableMap",
"contract": "EnumerableMapHarness",
"files": ["certora/harnesses/EnumerableMapHarness.sol"]
},
{
"spec": "TimelockController",
"contract": "TimelockControllerHarness",
"files": ["certora/harnesses/TimelockControllerHarness.sol"],
"options": ["--optimistic_hashing", "--optimistic_loop"]
}
]

View File

@ -0,0 +1,126 @@
import "helpers/helpers.spec"
import "methods/IAccessControl.spec"
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Definitions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
definition DEFAULT_ADMIN_ROLE() returns bytes32 = 0x0000000000000000000000000000000000000000000000000000000000000000;
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Identify entrypoints: only grantRole, revokeRole and renounceRole can alter permissions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyGrantCanGrant(env e, method f, bytes32 role, address account) {
calldataarg args;
bool hasRoleBefore = hasRole(role, account);
f(e, args);
bool hasRoleAfter = hasRole(role, account);
assert (
!hasRoleBefore &&
hasRoleAfter
) => (
f.selector == grantRole(bytes32, address).selector
);
assert (
hasRoleBefore &&
!hasRoleAfter
) => (
f.selector == revokeRole(bytes32, address).selector ||
f.selector == renounceRole(bytes32, address).selector
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: grantRole only affects the specified user/role combo
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule grantRoleEffect(env e, bytes32 role) {
require nonpayable(e);
bytes32 otherRole;
address account;
address otherAccount;
bool isCallerAdmin = hasRole(getRoleAdmin(role), e.msg.sender);
bool hasOtherRoleBefore = hasRole(otherRole, otherAccount);
grantRole@withrevert(e, role, account);
bool success = !lastReverted;
bool hasOtherRoleAfter = hasRole(otherRole, otherAccount);
// liveness
assert success <=> isCallerAdmin;
// effect
assert success => hasRole(role, account);
// no side effect
assert hasOtherRoleBefore != hasOtherRoleAfter => (role == otherRole && account == otherAccount);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: revokeRole only affects the specified user/role combo
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule revokeRoleEffect(env e, bytes32 role) {
require nonpayable(e);
bytes32 otherRole;
address account;
address otherAccount;
bool isCallerAdmin = hasRole(getRoleAdmin(role), e.msg.sender);
bool hasOtherRoleBefore = hasRole(otherRole, otherAccount);
revokeRole@withrevert(e, role, account);
bool success = !lastReverted;
bool hasOtherRoleAfter = hasRole(otherRole, otherAccount);
// liveness
assert success <=> isCallerAdmin;
// effect
assert success => !hasRole(role, account);
// no side effect
assert hasOtherRoleBefore != hasOtherRoleAfter => (role == otherRole && account == otherAccount);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: renounceRole only affects the specified user/role combo
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule renounceRoleEffect(env e, bytes32 role) {
require nonpayable(e);
bytes32 otherRole;
address account;
address otherAccount;
bool hasOtherRoleBefore = hasRole(otherRole, otherAccount);
renounceRole@withrevert(e, role, account);
bool success = !lastReverted;
bool hasOtherRoleAfter = hasRole(otherRole, otherAccount);
// liveness
assert success <=> account == e.msg.sender;
// effect
assert success => !hasRole(role, account);
// no side effect
assert hasOtherRoleBefore != hasOtherRoleAfter => (role == otherRole && account == otherAccount);
}

View File

@ -0,0 +1,500 @@
import "helpers/helpers.spec"
import "methods/IAccessControlDefaultAdminRules.spec"
import "methods/IAccessControl.spec"
import "AccessControl.spec"
use rule onlyGrantCanGrant filtered {
f -> f.selector != acceptDefaultAdminTransfer().selector
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
function max_uint48() returns mathint {
return (1 << 48) - 1;
}
function nonZeroAccount(address account) returns bool {
return account != 0;
}
function timeSanity(env e) returns bool {
return
e.block.timestamp > 0 && // Avoids 0 schedules
e.block.timestamp + defaultAdminDelay(e) < max_uint48();
}
function delayChangeWaitSanity(env e, uint48 newDelay) returns bool {
return e.block.timestamp + delayChangeWait_(e, newDelay) < max_uint48();
}
function isSet(uint48 schedule) returns bool {
return schedule != 0;
}
function hasPassed(env e, uint48 schedule) returns bool {
return schedule < e.block.timestamp;
}
function min(uint48 a, uint48 b) returns mathint {
return a < b ? a : b;
}
function increasingDelaySchedule(env e, uint48 newDelay) returns mathint {
return e.block.timestamp + min(newDelay, defaultAdminDelayIncreaseWait());
}
function decreasingDelaySchedule(env e, uint48 newDelay) returns mathint {
return e.block.timestamp + defaultAdminDelay(e) - newDelay;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: defaultAdmin holds the DEFAULT_ADMIN_ROLE
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant defaultAdminConsistency(address account)
defaultAdmin() == account <=> hasRole(DEFAULT_ADMIN_ROLE(), account)
{
preserved {
// defaultAdmin() returns the zero address when there's no default admin
require nonZeroAccount(account);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: Only one account holds the DEFAULT_ADMIN_ROLE
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant singleDefaultAdmin(address account, address another)
hasRole(DEFAULT_ADMIN_ROLE(), account) && hasRole(DEFAULT_ADMIN_ROLE(), another) => another == account
// We filter here because we couldn't find a way to force Certora to have an initial state with
// only one DEFAULT_ADMIN_ROLE enforced, so a counter example is a different default admin since inception
// triggering the transfer, which is known to be impossible by definition.
filtered { f -> f.selector != acceptDefaultAdminTransfer().selector }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: DEFAULT_ADMIN_ROLE's admin is always DEFAULT_ADMIN_ROLE
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant defaultAdminRoleAdminConsistency()
getRoleAdmin(DEFAULT_ADMIN_ROLE()) == DEFAULT_ADMIN_ROLE()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: owner is the defaultAdmin
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant ownerConsistency()
defaultAdmin() == owner()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: revokeRole only affects the specified user/role combo
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule revokeRoleEffect(env e, bytes32 role) {
require nonpayable(e);
bytes32 otherRole;
address account;
address otherAccount;
bool isCallerAdmin = hasRole(getRoleAdmin(role), e.msg.sender);
bool hasOtherRoleBefore = hasRole(otherRole, otherAccount);
revokeRole@withrevert(e, role, account);
bool success = !lastReverted;
bool hasOtherRoleAfter = hasRole(otherRole, otherAccount);
// liveness
assert success <=> isCallerAdmin && role != DEFAULT_ADMIN_ROLE(),
"roles can only be revoked by their owner except for the default admin role";
// effect
assert success => !hasRole(role, account), "role is revoked";
// no side effect
assert hasOtherRoleBefore != hasOtherRoleAfter => (role == otherRole && account == otherAccount),
"no other role is affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: renounceRole only affects the specified user/role combo
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule renounceRoleEffect(env e, bytes32 role) {
require nonpayable(e);
bytes32 otherRole;
address account;
address otherAccount;
bool hasOtherRoleBefore = hasRole(otherRole, otherAccount);
uint48 scheduleBefore = pendingDefaultAdminSchedule_();
address pendingAdminBefore = pendingDefaultAdmin_();
renounceRole@withrevert(e, role, account);
bool success = !lastReverted;
bool hasOtherRoleAfter = hasRole(otherRole, otherAccount);
// liveness
assert success <=> (
account == e.msg.sender &&
(
(
role != DEFAULT_ADMIN_ROLE()
) || (
role == DEFAULT_ADMIN_ROLE() &&
pendingAdminBefore == 0 &&
isSet(scheduleBefore) &&
hasPassed(e, scheduleBefore)
)
)
), "an account only can renounce by itself with a delay for the default admin role";
// effect
assert success => !hasRole(role, account), "role is renounced";
// no side effect
assert hasOtherRoleBefore != hasOtherRoleAfter => (role == otherRole && account == otherAccount),
"no other role is affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: defaultAdmin is only affected by accepting an admin transfer or renoucing
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noDefaultAdminChange(env e, method f, calldataarg args) {
require nonZeroAccount(e.msg.sender);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
address adminBefore = defaultAdmin();
f(e, args);
address adminAfter = defaultAdmin();
assert adminBefore != adminAfter => (
f.selector == acceptDefaultAdminTransfer().selector ||
f.selector == renounceRole(bytes32,address).selector
), "default admin is only affected by accepting an admin transfer or renoucing";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pendingDefaultAdmin is only affected by beginning, accepting or canceling an admin transfer
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noPendingDefaultAdminChange(env e, method f, calldataarg args) {
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
address pendingAdminBefore = pendingDefaultAdmin_();
address scheduleBefore = pendingDefaultAdminSchedule_();
f(e, args);
address pendingAdminAfter = pendingDefaultAdmin_();
address scheduleAfter = pendingDefaultAdminSchedule_();
assert (
pendingAdminBefore != pendingAdminAfter ||
scheduleBefore != scheduleAfter
) => (
f.selector == beginDefaultAdminTransfer(address).selector ||
f.selector == acceptDefaultAdminTransfer().selector ||
f.selector == cancelDefaultAdminTransfer().selector
), "pending admin and its schedule is only affected by beginning, accepting or cancelling an admin transfer";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: defaultAdminDelay can't be changed atomically by any function
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noDefaultAdminDelayChange(env e, method f, calldataarg args) {
uint48 delayBefore = defaultAdminDelay(e);
f(e, args);
uint48 delayAfter = defaultAdminDelay(e);
assert delayBefore == delayAfter, "delay can't be changed atomically by any function";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pendingDefaultAdminDelay is only affected by changeDefaultAdminDelay or rollbackDefaultAdminDelay
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noPendingDefaultAdminDelayChange(env e, method f, calldataarg args) {
uint48 pendingDelayBefore = pendingDelay_(e);
f(e, args);
uint48 pendingDelayAfter = pendingDelay_(e);
assert pendingDelayBefore != pendingDelayAfter => (
f.selector == changeDefaultAdminDelay(uint48).selector ||
f.selector == rollbackDefaultAdminDelay().selector
), "pending delay is only affected by changeDefaultAdminDelay or rollbackDefaultAdminDelay";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: defaultAdminDelayIncreaseWait can't be changed atomically by any function
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noDefaultAdminDelayIncreaseWaitChange(env e, method f, calldataarg args) {
uint48 delayIncreaseWaitBefore = defaultAdminDelayIncreaseWait();
f(e, args);
uint48 delayIncreaseWaitAfter = defaultAdminDelayIncreaseWait();
assert delayIncreaseWaitBefore == delayIncreaseWaitAfter,
"delay increase wait can't be changed atomically by any function";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: beginDefaultAdminTransfer sets a pending default admin and its schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule beginDefaultAdminTransfer(env e, address newAdmin) {
require nonpayable(e);
require timeSanity(e);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
beginDefaultAdminTransfer@withrevert(e, newAdmin);
bool success = !lastReverted;
// liveness
assert success <=> e.msg.sender == defaultAdmin(),
"only the current default admin can begin a transfer";
// effect
assert success => pendingDefaultAdmin_() == newAdmin,
"pending default admin is set";
assert success => pendingDefaultAdminSchedule_() == e.block.timestamp + defaultAdminDelay(e),
"pending default admin delay is set";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: A default admin can't change in less than the applied schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pendingDefaultAdminDelayEnforced(env e1, env e2, method f, calldataarg args, address newAdmin) {
require e1.block.timestamp < e2.block.timestamp;
uint48 delayBefore = defaultAdminDelay(e1);
address adminBefore = defaultAdmin();
// There might be a better way to generalize this without requiring `beginDefaultAdminTransfer`, but currently
// it's the only way in which we can attest that only `delayBefore` has passed before a change.
beginDefaultAdminTransfer(e1, newAdmin);
f(e2, args);
address adminAfter = defaultAdmin();
assert adminAfter == newAdmin => ((e2.block.timestamp >= e1.block.timestamp + delayBefore) || adminBefore == newAdmin),
"A delay can't change in less than applied schedule";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: acceptDefaultAdminTransfer updates defaultAdmin resetting the pending admin and its schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule acceptDefaultAdminTransfer(env e) {
require nonpayable(e);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
address pendingAdminBefore = pendingDefaultAdmin_();
uint48 scheduleAfter = pendingDefaultAdminSchedule_();
acceptDefaultAdminTransfer@withrevert(e);
bool success = !lastReverted;
// liveness
assert success <=> e.msg.sender == pendingAdminBefore && isSet(scheduleAfter) && hasPassed(e, scheduleAfter),
"only the pending default admin can accept the role after the schedule has been set and passed";
// effect
assert success => defaultAdmin() == pendingAdminBefore,
"Default admin is set to the previous pending default admin";
assert success => pendingDefaultAdmin_() == 0,
"Pending default admin is reset";
assert success => pendingDefaultAdminSchedule_() == 0,
"Pending default admin delay is reset";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: cancelDefaultAdminTransfer resets pending default admin and its schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cancelDefaultAdminTransfer(env e) {
require nonpayable(e);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
cancelDefaultAdminTransfer@withrevert(e);
bool success = !lastReverted;
// liveness
assert success <=> e.msg.sender == defaultAdmin(),
"only the current default admin can cancel a transfer";
// effect
assert success => pendingDefaultAdmin_() == 0,
"Pending default admin is reset";
assert success => pendingDefaultAdminSchedule_() == 0,
"Pending default admin delay is reset";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: changeDefaultAdminDelay sets a pending default admin delay and its schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule changeDefaultAdminDelay(env e, uint48 newDelay) {
require nonpayable(e);
require timeSanity(e);
require delayChangeWaitSanity(e, newDelay);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
uint48 delayBefore = defaultAdminDelay(e);
changeDefaultAdminDelay@withrevert(e, newDelay);
bool success = !lastReverted;
// liveness
assert success <=> e.msg.sender == defaultAdmin(),
"only the current default admin can begin a delay change";
// effect
assert success => pendingDelay_(e) == newDelay, "pending delay is set";
assert success => (
pendingDelaySchedule_(e) > e.block.timestamp ||
delayBefore == newDelay || // Interpreted as decreasing, x - x = 0
defaultAdminDelayIncreaseWait() == 0
),
"pending delay schedule is set in the future unless accepted edge cases";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: A delay can't change in less than the applied schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pendingDelayWaitEnforced(env e1, env e2, method f, calldataarg args, uint48 newDelay) {
require e1.block.timestamp < e2.block.timestamp;
uint48 delayBefore = defaultAdminDelay(e1);
changeDefaultAdminDelay(e1, newDelay);
f(e2, args);
uint48 delayAfter = defaultAdminDelay(e2);
mathint delayWait = newDelay > delayBefore ? increasingDelaySchedule(e1, newDelay) : decreasingDelaySchedule(e1, newDelay);
assert delayAfter == newDelay => (e2.block.timestamp >= delayWait || delayBefore == newDelay),
"A delay can't change in less than applied schedule";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pending delay wait is set depending on increasing or decreasing the delay
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pendingDelayWait(env e, uint48 newDelay) {
uint48 oldDelay = defaultAdminDelay(e);
changeDefaultAdminDelay(e, newDelay);
assert newDelay > oldDelay => pendingDelaySchedule_(e) == increasingDelaySchedule(e, newDelay),
"Delay wait is the minimum between the new delay and a threshold when the delay is increased";
assert newDelay <= oldDelay => pendingDelaySchedule_(e) == decreasingDelaySchedule(e, newDelay),
"Delay wait is the difference between the current and the new delay when the delay is decreased";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: rollbackDefaultAdminDelay resets the delay and its schedule
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule rollbackDefaultAdminDelay(env e) {
require nonpayable(e);
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
rollbackDefaultAdminDelay@withrevert(e);
bool success = !lastReverted;
// liveness
assert success <=> e.msg.sender == defaultAdmin(),
"only the current default admin can rollback a delay change";
// effect
assert success => pendingDelay_(e) == 0,
"Pending default admin is reset";
assert success => pendingDelaySchedule_(e) == 0,
"Pending default admin delay is reset";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pending default admin and the delay can only change along with their corresponding schedules
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pendingValueAndScheduleCoupling(env e, address newAdmin, uint48 newDelay) {
requireInvariant defaultAdminConsistency(defaultAdmin());
requireInvariant singleDefaultAdmin(e.msg.sender, defaultAdmin());
// Pending admin
address pendingAdminBefore = pendingDefaultAdmin_();
uint48 pendingAdminScheduleBefore = pendingDefaultAdminSchedule_();
beginDefaultAdminTransfer(e, newAdmin);
address pendingAdminAfter = pendingDefaultAdmin_();
uint48 pendingAdminScheduleAfter = pendingDefaultAdminSchedule_();
assert (
pendingAdminScheduleBefore != pendingDefaultAdminSchedule_() &&
pendingAdminBefore == pendingAdminAfter
) => newAdmin == pendingAdminBefore, "pending admin stays the same if the new admin set is the same";
assert (
pendingAdminBefore != pendingAdminAfter &&
pendingAdminScheduleBefore == pendingDefaultAdminSchedule_()
) => (
// Schedule doesn't change if:
// - The defaultAdminDelay was reduced to a value such that added to the block.timestamp is equal to previous schedule
e.block.timestamp + defaultAdminDelay(e) == pendingAdminScheduleBefore
), "pending admin stays the same if a default admin transfer is begun on accepted edge cases";
// Pending delay
address pendingDelayBefore = pendingDelay_(e);
uint48 pendingDelayScheduleBefore = pendingDelaySchedule_(e);
changeDefaultAdminDelay(e, newDelay);
address pendingDelayAfter = pendingDelay_(e);
uint48 pendingDelayScheduleAfter = pendingDelaySchedule_(e);
assert (
pendingDelayScheduleBefore != pendingDelayScheduleAfter &&
pendingDelayBefore == pendingDelayAfter
) => newDelay == pendingDelayBefore || pendingDelayBefore == 0, "pending delay stays the same if the new delay set is the same";
assert (
pendingDelayBefore != pendingDelayAfter &&
pendingDelayScheduleBefore == pendingDelayScheduleAfter
) => (
increasingDelaySchedule(e, newDelay) == pendingDelayScheduleBefore ||
decreasingDelaySchedule(e, newDelay) == pendingDelayScheduleBefore
), "pending delay stays the same if a default admin transfer is begun on accepted edge cases";
}

View File

@ -0,0 +1,366 @@
import "helpers/helpers.spec"
methods {
pushFront(bytes32) envfree
pushBack(bytes32) envfree
popFront() returns (bytes32) envfree
popBack() returns (bytes32) envfree
clear() envfree
// exposed for FV
begin() returns (int128) envfree
end() returns (int128) envfree
// view
length() returns (uint256) envfree
empty() returns (bool) envfree
front() returns (bytes32) envfree
back() returns (bytes32) envfree
at_(uint256) returns (bytes32) envfree // at is a reserved word
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
function min_int128() returns mathint {
return -(1 << 127);
}
function max_int128() returns mathint {
return (1 << 127) - 1;
}
// Could be broken in theory, but not in practice
function boundedQueue() returns bool {
return
max_int128() > to_mathint(end()) &&
min_int128() < to_mathint(begin());
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: end is larger or equal than begin
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant boundariesConsistency()
end() >= begin()
filtered { f -> !f.isView }
{ preserved { require boundedQueue(); } }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: length is end minus begin
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant lengthConsistency()
length() == to_mathint(end()) - to_mathint(begin())
filtered { f -> !f.isView }
{ preserved { require boundedQueue(); } }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: empty() is length 0 and no element exists
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant emptiness()
empty() <=> length() == 0
filtered { f -> !f.isView }
{ preserved { require boundedQueue(); } }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: front points to the first index and back points to the last one
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant queueEndings()
at_(length() - 1) == back() && at_(0) == front()
filtered { f -> !f.isView }
{
preserved {
requireInvariant boundariesConsistency();
require boundedQueue();
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: pushFront adds an element at the beginning of the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pushFront(bytes32 value) {
require boundedQueue();
uint256 lengthBefore = length();
pushFront@withrevert(value);
// liveness
assert !lastReverted, "never reverts";
// effect
assert front() == value, "front set to value";
assert length() == lengthBefore + 1, "queue extended";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pushFront preserves the previous values in the queue with a +1 offset
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pushFrontConsistency(uint256 index) {
require boundedQueue();
bytes32 beforeAt = at_(index);
bytes32 value;
pushFront(value);
// try to read value
bytes32 afterAt = at_@withrevert(index + 1);
assert !lastReverted, "value still there";
assert afterAt == beforeAt, "data is preserved";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: pushBack adds an element at the end of the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pushBack(bytes32 value) {
require boundedQueue();
uint256 lengthBefore = length();
pushBack@withrevert(value);
// liveness
assert !lastReverted, "never reverts";
// effect
assert back() == value, "back set to value";
assert length() == lengthBefore + 1, "queue increased";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: pushBack preserves the previous values in the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pushBackConsistency(uint256 index) {
require boundedQueue();
bytes32 beforeAt = at_(index);
bytes32 value;
pushBack(value);
// try to read value
bytes32 afterAt = at_@withrevert(index);
assert !lastReverted, "value still there";
assert afterAt == beforeAt, "data is preserved";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: popFront removes an element from the beginning of the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule popFront {
requireInvariant boundariesConsistency();
require boundedQueue();
uint256 lengthBefore = length();
bytes32 frontBefore = front@withrevert();
bytes32 popped = popFront@withrevert();
bool success = !lastReverted;
// liveness
assert success <=> lengthBefore != 0, "never reverts if not previously empty";
// effect
assert success => frontBefore == popped, "previous front is returned";
assert success => length() == lengthBefore - 1, "queue decreased";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: at(x) is preserved and offset to at(x - 1) after calling popFront |
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule popFrontConsistency(uint256 index) {
requireInvariant boundariesConsistency();
require boundedQueue();
// Read (any) value that is not the front (this asserts the value exists / the queue is long enough)
require index > 1;
bytes32 before = at_(index);
popFront();
// try to read value
bytes32 after = at_@withrevert(index - 1);
assert !lastReverted, "value still exists in the queue";
assert before == after, "values are offset and not modified";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: popBack removes an element from the end of the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule popBack {
requireInvariant boundariesConsistency();
require boundedQueue();
uint256 lengthBefore = length();
bytes32 backBefore = back@withrevert();
bytes32 popped = popBack@withrevert();
bool success = !lastReverted;
// liveness
assert success <=> lengthBefore != 0, "never reverts if not previously empty";
// effect
assert success => backBefore == popped, "previous back is returned";
assert success => length() == lengthBefore - 1, "queue decreased";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: at(x) is preserved after calling popBack |
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule popBackConsistency(uint256 index) {
requireInvariant boundariesConsistency();
require boundedQueue();
// Read (any) value that is not the back (this asserts the value exists / the queue is long enough)
require index < length() - 1;
bytes32 before = at_(index);
popBack();
// try to read value
bytes32 after = at_@withrevert(index);
assert !lastReverted, "value still exists in the queue";
assert before == after, "values are offset and not modified";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: clear sets length to 0
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule clear {
clear@withrevert();
// liveness
assert !lastReverted, "never reverts";
// effect
assert length() == 0, "sets length to 0";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: front/back access reverts only if the queue is empty or querying out of bounds
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyEmptyRevert(env e) {
require nonpayable(e);
requireInvariant boundariesConsistency();
require boundedQueue();
method f;
calldataarg args;
bool emptyBefore = empty();
f@withrevert(e, args);
assert lastReverted => (
(f.selector == front().selector && emptyBefore) ||
(f.selector == back().selector && emptyBefore) ||
(f.selector == popFront().selector && emptyBefore) ||
(f.selector == popBack().selector && emptyBefore) ||
f.selector == at_(uint256).selector // revert conditions are verified in onlyOutOfBoundsRevert
), "only revert if empty or out of bounds";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: at(index) only reverts if index is out of bounds |
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyOutOfBoundsRevert(uint256 index) {
requireInvariant boundariesConsistency();
require boundedQueue();
at_@withrevert(index);
assert lastReverted <=> index >= length(), "only reverts if index is out of bounds";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: only clear/push/pop operations can change the length of the queue
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noLengthChange(env e) {
requireInvariant boundariesConsistency();
require boundedQueue();
method f;
calldataarg args;
uint256 lengthBefore = length();
f(e, args);
uint256 lengthAfter = length();
assert lengthAfter != lengthBefore => (
(f.selector == pushFront(bytes32).selector && lengthAfter == lengthBefore + 1) ||
(f.selector == pushBack(bytes32).selector && lengthAfter == lengthBefore + 1) ||
(f.selector == popBack().selector && lengthAfter == lengthBefore - 1) ||
(f.selector == popFront().selector && lengthAfter == lengthBefore - 1) ||
(f.selector == clear().selector && lengthAfter == 0)
), "length is only affected by clear/pop/push operations";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: only push/pop can change values bounded in the queue (outside values aren't cleared)
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noDataChange(env e) {
requireInvariant boundariesConsistency();
require boundedQueue();
method f;
calldataarg args;
uint256 index;
bytes32 atBefore = at_(index);
f(e, args);
bytes32 atAfter = at_@withrevert(index);
bool atAfterSuccess = !lastReverted;
assert !atAfterSuccess <=> (
f.selector == clear().selector ||
(f.selector == popBack().selector && index == length()) ||
(f.selector == popFront().selector && index == length())
), "indexes of the queue are only removed by clear or pop";
assert atAfterSuccess && atAfter != atBefore => (
f.selector == popFront().selector ||
f.selector == pushFront(bytes32).selector
), "values of the queue are only changed by popFront or pushFront";
}

414
certora/specs/ERC20.spec Normal file
View File

@ -0,0 +1,414 @@
import "helpers/helpers.spec"
import "methods/IERC20.spec"
import "methods/IERC2612.spec"
methods {
// non standard ERC20 functions
increaseAllowance(address,uint256) returns (bool)
decreaseAllowance(address,uint256) returns (bool)
// exposed for FV
mint(address,uint256)
burn(address,uint256)
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Ghost & hooks: sum of all balances
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
ghost sumOfBalances() returns uint256 {
init_state axiom sumOfBalances() == 0;
}
hook Sstore _balances[KEY address addr] uint256 newValue (uint256 oldValue) STORAGE {
havoc sumOfBalances assuming sumOfBalances@new() == sumOfBalances@old() + newValue - oldValue;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: totalSupply is the sum of all balances
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant totalSupplyIsSumOfBalances()
totalSupply() == sumOfBalances()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: balance of address(0) is 0
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant zeroAddressNoBalance()
balanceOf(0) == 0
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: only mint and burn can change total supply
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noChangeTotalSupply(env e) {
requireInvariant totalSupplyIsSumOfBalances();
method f;
calldataarg args;
uint256 totalSupplyBefore = totalSupply();
f(e, args);
uint256 totalSupplyAfter = totalSupply();
assert totalSupplyAfter > totalSupplyBefore => f.selector == mint(address,uint256).selector;
assert totalSupplyAfter < totalSupplyBefore => f.selector == burn(address,uint256).selector;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: only the token holder or an approved third party can reduce an account's balance
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyAuthorizedCanTransfer(env e) {
requireInvariant totalSupplyIsSumOfBalances();
method f;
calldataarg args;
address account;
uint256 allowanceBefore = allowance(account, e.msg.sender);
uint256 balanceBefore = balanceOf(account);
f(e, args);
uint256 balanceAfter = balanceOf(account);
assert (
balanceAfter < balanceBefore
) => (
f.selector == burn(address,uint256).selector ||
e.msg.sender == account ||
balanceBefore - balanceAfter <= allowanceBefore
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: only the token holder (or a permit) can increase allowance. The spender can decrease it by using it
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyHolderOfSpenderCanChangeAllowance(env e) {
requireInvariant totalSupplyIsSumOfBalances();
method f;
calldataarg args;
address holder;
address spender;
uint256 allowanceBefore = allowance(holder, spender);
f(e, args);
uint256 allowanceAfter = allowance(holder, spender);
assert (
allowanceAfter > allowanceBefore
) => (
(f.selector == approve(address,uint256).selector && e.msg.sender == holder) ||
(f.selector == increaseAllowance(address,uint256).selector && e.msg.sender == holder) ||
(f.selector == permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector)
);
assert (
allowanceAfter < allowanceBefore
) => (
(f.selector == transferFrom(address,address,uint256).selector && e.msg.sender == spender) ||
(f.selector == approve(address,uint256).selector && e.msg.sender == holder ) ||
(f.selector == decreaseAllowance(address,uint256).selector && e.msg.sender == holder ) ||
(f.selector == permit(address,address,uint256,uint256,uint8,bytes32,bytes32).selector)
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: mint behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule mint(env e) {
requireInvariant totalSupplyIsSumOfBalances();
require nonpayable(e);
address to;
address other;
uint256 amount;
// cache state
uint256 toBalanceBefore = balanceOf(to);
uint256 otherBalanceBefore = balanceOf(other);
uint256 totalSupplyBefore = totalSupply();
// run transaction
mint@withrevert(e, to, amount);
// check outcome
if (lastReverted) {
assert to == 0 || totalSupplyBefore + amount > max_uint256;
} else {
// updates balance and totalSupply
assert balanceOf(to) == toBalanceBefore + amount;
assert totalSupply() == totalSupplyBefore + amount;
// no other balance is modified
assert balanceOf(other) != otherBalanceBefore => other == to;
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: burn behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule burn(env e) {
requireInvariant totalSupplyIsSumOfBalances();
require nonpayable(e);
address from;
address other;
uint256 amount;
// cache state
uint256 fromBalanceBefore = balanceOf(from);
uint256 otherBalanceBefore = balanceOf(other);
uint256 totalSupplyBefore = totalSupply();
// run transaction
burn@withrevert(e, from, amount);
// check outcome
if (lastReverted) {
assert from == 0 || fromBalanceBefore < amount;
} else {
// updates balance and totalSupply
assert balanceOf(from) == fromBalanceBefore - amount;
assert totalSupply() == totalSupplyBefore - amount;
// no other balance is modified
assert balanceOf(other) != otherBalanceBefore => other == from;
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: transfer behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule transfer(env e) {
requireInvariant totalSupplyIsSumOfBalances();
require nonpayable(e);
address holder = e.msg.sender;
address recipient;
address other;
uint256 amount;
// cache state
uint256 holderBalanceBefore = balanceOf(holder);
uint256 recipientBalanceBefore = balanceOf(recipient);
uint256 otherBalanceBefore = balanceOf(other);
// run transaction
transfer@withrevert(e, recipient, amount);
// check outcome
if (lastReverted) {
assert holder == 0 || recipient == 0 || amount > holderBalanceBefore;
} else {
// balances of holder and recipient are updated
assert balanceOf(holder) == holderBalanceBefore - (holder == recipient ? 0 : amount);
assert balanceOf(recipient) == recipientBalanceBefore + (holder == recipient ? 0 : amount);
// no other balance is modified
assert balanceOf(other) != otherBalanceBefore => (other == holder || other == recipient);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: transferFrom behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule transferFrom(env e) {
requireInvariant totalSupplyIsSumOfBalances();
require nonpayable(e);
address spender = e.msg.sender;
address holder;
address recipient;
address other;
uint256 amount;
// cache state
uint256 allowanceBefore = allowance(holder, spender);
uint256 holderBalanceBefore = balanceOf(holder);
uint256 recipientBalanceBefore = balanceOf(recipient);
uint256 otherBalanceBefore = balanceOf(other);
// run transaction
transferFrom@withrevert(e, holder, recipient, amount);
// check outcome
if (lastReverted) {
assert holder == 0 || recipient == 0 || spender == 0 || amount > holderBalanceBefore || amount > allowanceBefore;
} else {
// allowance is valid & updated
assert allowanceBefore >= amount;
assert allowance(holder, spender) == (allowanceBefore == max_uint256 ? to_uint256(max_uint256) : allowanceBefore - amount);
// balances of holder and recipient are updated
assert balanceOf(holder) == holderBalanceBefore - (holder == recipient ? 0 : amount);
assert balanceOf(recipient) == recipientBalanceBefore + (holder == recipient ? 0 : amount);
// no other balance is modified
assert balanceOf(other) != otherBalanceBefore => (other == holder || other == recipient);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: approve behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule approve(env e) {
require nonpayable(e);
address holder = e.msg.sender;
address spender;
address otherHolder;
address otherSpender;
uint256 amount;
// cache state
uint256 otherAllowanceBefore = allowance(otherHolder, otherSpender);
// run transaction
approve@withrevert(e, spender, amount);
// check outcome
if (lastReverted) {
assert holder == 0 || spender == 0;
} else {
// allowance is updated
assert allowance(holder, spender) == amount;
// other allowances are untouched
assert allowance(otherHolder, otherSpender) != otherAllowanceBefore => (otherHolder == holder && otherSpender == spender);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: increaseAllowance behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule increaseAllowance(env e) {
require nonpayable(e);
address holder = e.msg.sender;
address spender;
address otherHolder;
address otherSpender;
uint256 amount;
// cache state
uint256 allowanceBefore = allowance(holder, spender);
uint256 otherAllowanceBefore = allowance(otherHolder, otherSpender);
// run transaction
increaseAllowance@withrevert(e, spender, amount);
// check outcome
if (lastReverted) {
assert holder == 0 || spender == 0 || allowanceBefore + amount > max_uint256;
} else {
// allowance is updated
assert allowance(holder, spender) == allowanceBefore + amount;
// other allowances are untouched
assert allowance(otherHolder, otherSpender) != otherAllowanceBefore => (otherHolder == holder && otherSpender == spender);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: decreaseAllowance behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule decreaseAllowance(env e) {
require nonpayable(e);
address holder = e.msg.sender;
address spender;
address otherHolder;
address otherSpender;
uint256 amount;
// cache state
uint256 allowanceBefore = allowance(holder, spender);
uint256 otherAllowanceBefore = allowance(otherHolder, otherSpender);
// run transaction
decreaseAllowance@withrevert(e, spender, amount);
// check outcome
if (lastReverted) {
assert holder == 0 || spender == 0 || allowanceBefore < amount;
} else {
// allowance is updated
assert allowance(holder, spender) == allowanceBefore - amount;
// other allowances are untouched
assert allowance(otherHolder, otherSpender) != otherAllowanceBefore => (otherHolder == holder && otherSpender == spender);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: permit behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule permit(env e) {
require nonpayable(e);
address holder;
address spender;
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
address account1;
address account2;
address account3;
// cache state
uint256 nonceBefore = nonces(holder);
uint256 otherNonceBefore = nonces(account1);
uint256 otherAllowanceBefore = allowance(account2, account3);
// sanity: nonce overflow, which possible in theory, is assumed to be impossible in practice
require nonceBefore < max_uint256;
require otherNonceBefore < max_uint256;
// run transaction
permit@withrevert(e, holder, spender, amount, deadline, v, r, s);
// check outcome
if (lastReverted) {
// Without formally checking the signature, we can't verify exactly the revert causes
assert true;
} else {
// allowance and nonce are updated
assert allowance(holder, spender) == amount;
assert nonces(holder) == nonceBefore + 1;
// deadline was respected
assert deadline >= e.block.timestamp;
// no other allowance or nonce is modified
assert nonces(account1) != otherNonceBefore => account1 == holder;
assert allowance(account2, account3) != otherAllowanceBefore => (account2 == holder && account3 == spender);
}
}

View File

@ -0,0 +1,48 @@
import "helpers/helpers.spec"
import "methods/IERC20.spec"
import "methods/IERC3156.spec"
methods {
// non standard ERC3156 functions
flashFeeReceiver() returns (address) envfree
// function summaries below
_mint(address account, uint256 amount) => specMint(account, amount)
_burn(address account, uint256 amount) => specBurn(account, amount)
_transfer(address from, address to, uint256 amount) => specTransfer(from, to, amount)
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Ghost: track mint and burns in the CVL
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
ghost mapping(address => uint256) trackedMintAmount;
ghost mapping(address => uint256) trackedBurnAmount;
ghost mapping(address => mapping(address => uint256)) trackedTransferedAmount;
function specMint(address account, uint256 amount) returns bool { trackedMintAmount[account] = amount; return true; }
function specBurn(address account, uint256 amount) returns bool { trackedBurnAmount[account] = amount; return true; }
function specTransfer(address from, address to, uint256 amount) returns bool { trackedTransferedAmount[from][to] = amount; return true; }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: When doing a flashLoan, "amount" is minted and burnt, additionally, the fee is either burnt
(if the fee recipient is 0) or transferred (if the fee recipient is not 0)
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule checkMintAndBurn(env e) {
address receiver;
address token;
uint256 amount;
bytes data;
uint256 fees = flashFee(token, amount);
address recipient = flashFeeReceiver();
flashLoan(e, receiver, token, amount, data);
assert trackedMintAmount[receiver] == amount;
assert trackedBurnAmount[receiver] == amount + (recipient == 0 ? fees : 0);
assert (fees > 0 && recipient != 0) => trackedTransferedAmount[receiver][recipient] == fees;
}

View File

@ -0,0 +1,198 @@
import "helpers/helpers.spec"
import "ERC20.spec"
methods {
underlying() returns(address) envfree
underlyingTotalSupply() returns(uint256) envfree
underlyingBalanceOf(address) returns(uint256) envfree
underlyingAllowanceToThis(address) returns(uint256) envfree
depositFor(address, uint256) returns(bool)
withdrawTo(address, uint256) returns(bool)
recover(address) returns(uint256)
}
use invariant totalSupplyIsSumOfBalances
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helper: consequence of `totalSupplyIsSumOfBalances` applied to underlying
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
function underlyingBalancesLowerThanUnderlyingSupply(address a) returns bool {
return underlyingBalanceOf(a) <= underlyingTotalSupply();
}
function sumOfUnderlyingBalancesLowerThanUnderlyingSupply(address a, address b) returns bool {
return a != b => underlyingBalanceOf(a) + underlyingBalanceOf(b) <= underlyingTotalSupply();
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: wrapped token can't be undercollateralized (solvency of the wrapper)
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant totalSupplyIsSmallerThanUnderlyingBalance()
totalSupply() <= underlyingBalanceOf(currentContract) &&
underlyingBalanceOf(currentContract) <= underlyingTotalSupply() &&
underlyingTotalSupply() <= max_uint256
{
preserved {
requireInvariant totalSupplyIsSumOfBalances;
require underlyingBalancesLowerThanUnderlyingSupply(currentContract);
}
preserved depositFor(address account, uint256 amount) with (env e) {
require sumOfUnderlyingBalancesLowerThanUnderlyingSupply(e.msg.sender, currentContract);
}
}
invariant noSelfWrap()
currentContract != underlying()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: depositFor liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule depositFor(env e) {
require nonpayable(e);
address sender = e.msg.sender;
address receiver;
address other;
uint256 amount;
// sanity
requireInvariant noSelfWrap;
requireInvariant totalSupplyIsSumOfBalances;
requireInvariant totalSupplyIsSmallerThanUnderlyingBalance;
require sumOfUnderlyingBalancesLowerThanUnderlyingSupply(currentContract, sender);
uint256 balanceBefore = balanceOf(receiver);
uint256 supplyBefore = totalSupply();
uint256 senderUnderlyingBalanceBefore = underlyingBalanceOf(sender);
uint256 senderUnderlyingAllowanceBefore = underlyingAllowanceToThis(sender);
uint256 wrapperUnderlyingBalanceBefore = underlyingBalanceOf(currentContract);
uint256 underlyingSupplyBefore = underlyingTotalSupply();
uint256 otherBalanceBefore = balanceOf(other);
uint256 otherUnderlyingBalanceBefore = underlyingBalanceOf(other);
depositFor@withrevert(e, receiver, amount);
bool success = !lastReverted;
// liveness
assert success <=> (
sender != currentContract && // invalid sender
sender != 0 && // invalid sender
receiver != 0 && // invalid receiver
amount <= senderUnderlyingBalanceBefore && // deposit doesn't exceed balance
amount <= senderUnderlyingAllowanceBefore // deposit doesn't exceed allowance
);
// effects
assert success => (
balanceOf(receiver) == balanceBefore + amount &&
totalSupply() == supplyBefore + amount &&
underlyingBalanceOf(currentContract) == wrapperUnderlyingBalanceBefore + amount &&
underlyingBalanceOf(sender) == senderUnderlyingBalanceBefore - amount
);
// no side effect
assert underlyingTotalSupply() == underlyingSupplyBefore;
assert balanceOf(other) != otherBalanceBefore => other == receiver;
assert underlyingBalanceOf(other) != otherUnderlyingBalanceBefore => (other == sender || other == currentContract);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: withdrawTo liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule withdrawTo(env e) {
require nonpayable(e);
address sender = e.msg.sender;
address receiver;
address other;
uint256 amount;
// sanity
requireInvariant noSelfWrap;
requireInvariant totalSupplyIsSumOfBalances;
requireInvariant totalSupplyIsSmallerThanUnderlyingBalance;
require sumOfUnderlyingBalancesLowerThanUnderlyingSupply(currentContract, receiver);
uint256 balanceBefore = balanceOf(sender);
uint256 supplyBefore = totalSupply();
uint256 receiverUnderlyingBalanceBefore = underlyingBalanceOf(receiver);
uint256 wrapperUnderlyingBalanceBefore = underlyingBalanceOf(currentContract);
uint256 underlyingSupplyBefore = underlyingTotalSupply();
uint256 otherBalanceBefore = balanceOf(other);
uint256 otherUnderlyingBalanceBefore = underlyingBalanceOf(other);
withdrawTo@withrevert(e, receiver, amount);
bool success = !lastReverted;
// liveness
assert success <=> (
sender != 0 && // invalid sender
receiver != 0 && // invalid receiver
amount <= balanceBefore // withdraw doesn't exceed balance
);
// effects
assert success => (
balanceOf(sender) == balanceBefore - amount &&
totalSupply() == supplyBefore - amount &&
underlyingBalanceOf(currentContract) == wrapperUnderlyingBalanceBefore - (currentContract != receiver ? amount : 0) &&
underlyingBalanceOf(receiver) == receiverUnderlyingBalanceBefore + (currentContract != receiver ? amount : 0)
);
// no side effect
assert underlyingTotalSupply() == underlyingSupplyBefore;
assert balanceOf(other) != otherBalanceBefore => other == sender;
assert underlyingBalanceOf(other) != otherUnderlyingBalanceBefore => (other == receiver || other == currentContract);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: recover liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule recover(env e) {
require nonpayable(e);
address receiver;
address other;
// sanity
requireInvariant noSelfWrap;
requireInvariant totalSupplyIsSumOfBalances;
requireInvariant totalSupplyIsSmallerThanUnderlyingBalance;
uint256 value = underlyingBalanceOf(currentContract) - totalSupply();
uint256 supplyBefore = totalSupply();
uint256 balanceBefore = balanceOf(receiver);
uint256 otherBalanceBefore = balanceOf(other);
uint256 otherUnderlyingBalanceBefore = underlyingBalanceOf(other);
recover@withrevert(e, receiver);
bool success = !lastReverted;
// liveness
assert success <=> receiver != 0;
// effect
assert success => (
balanceOf(receiver) == balanceBefore + value &&
totalSupply() == supplyBefore + value &&
totalSupply() == underlyingBalanceOf(currentContract)
);
// no side effect
assert underlyingBalanceOf(other) == otherUnderlyingBalanceBefore;
assert balanceOf(other) != otherBalanceBefore => other == receiver;
}

589
certora/specs/ERC721.spec Normal file
View File

@ -0,0 +1,589 @@
import "helpers/helpers.spec"
import "methods/IERC721.spec"
methods {
// exposed for FV
mint(address,uint256)
safeMint(address,uint256)
safeMint(address,uint256,bytes)
burn(uint256)
tokenExists(uint256) returns (bool) envfree
unsafeOwnerOf(uint256) returns (address) envfree
unsafeGetApproved(uint256) returns (address) envfree
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
// Could be broken in theory, but not in practice
function balanceLimited(address account) returns bool {
return balanceOf(account) < max_uint256;
}
function helperTransferWithRevert(env e, method f, address from, address to, uint256 tokenId) {
if (f.selector == transferFrom(address,address,uint256).selector) {
transferFrom@withrevert(e, from, to, tokenId);
} else if (f.selector == safeTransferFrom(address,address,uint256).selector) {
safeTransferFrom@withrevert(e, from, to, tokenId);
} else if (f.selector == safeTransferFrom(address,address,uint256,bytes).selector) {
bytes params;
require params.length < 0xffff;
safeTransferFrom@withrevert(e, from, to, tokenId, params);
} else {
calldataarg args;
f@withrevert(e, args);
}
}
function helperMintWithRevert(env e, method f, address to, uint256 tokenId) {
if (f.selector == mint(address,uint256).selector) {
mint@withrevert(e, to, tokenId);
} else if (f.selector == safeMint(address,uint256).selector) {
safeMint@withrevert(e, to, tokenId);
} else if (f.selector == safeMint(address,uint256,bytes).selector) {
bytes params;
require params.length < 0xffff;
safeMint@withrevert(e, to, tokenId, params);
} else {
require false;
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Ghost & hooks: ownership count
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
ghost ownedTotal() returns uint256 {
init_state axiom ownedTotal() == 0;
}
ghost mapping(address => uint256) ownedByUser {
init_state axiom forall address a. ownedByUser[a] == 0;
}
hook Sstore _owners[KEY uint256 tokenId] address newOwner (address oldOwner) STORAGE {
ownedByUser[newOwner] = ownedByUser[newOwner] + to_uint256(newOwner != 0 ? 1 : 0);
ownedByUser[oldOwner] = ownedByUser[oldOwner] - to_uint256(oldOwner != 0 ? 1 : 0);
havoc ownedTotal assuming ownedTotal@new() == ownedTotal@old()
+ to_uint256(newOwner != 0 ? 1 : 0)
- to_uint256(oldOwner != 0 ? 1 : 0);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Ghost & hooks: sum of all balances
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
ghost sumOfBalances() returns uint256 {
init_state axiom sumOfBalances() == 0;
}
hook Sstore _balances[KEY address addr] uint256 newValue (uint256 oldValue) STORAGE {
havoc sumOfBalances assuming sumOfBalances@new() == sumOfBalances@old() + newValue - oldValue;
}
ghost mapping(address => uint256) ghostBalanceOf {
init_state axiom forall address a. ghostBalanceOf[a] == 0;
}
hook Sload uint256 value _balances[KEY address user] STORAGE {
require ghostBalanceOf[user] == value;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: ownedTotal is the sum of all balances
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant ownedTotalIsSumOfBalances()
ownedTotal() == sumOfBalances()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: balanceOf is the number of tokens owned
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant balanceOfConsistency(address user)
balanceOf(user) == ownedByUser[user] &&
balanceOf(user) == ghostBalanceOf[user]
{
preserved {
require balanceLimited(user);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: owner of a token must have some balance
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant ownerHasBalance(uint256 tokenId)
balanceOf(ownerOf(tokenId)) > 0
{
preserved {
requireInvariant balanceOfConsistency(ownerOf(tokenId));
require balanceLimited(ownerOf(tokenId));
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: tokens that do not exist are not owned and not approved
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant notMintedUnset(uint256 tokenId)
(!tokenExists(tokenId) <=> unsafeOwnerOf(tokenId) == 0) &&
(!tokenExists(tokenId) => unsafeGetApproved(tokenId) == 0)
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: ownerOf and getApproved revert if token does not exist
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule notMintedRevert(uint256 tokenId) {
requireInvariant notMintedUnset(tokenId);
bool e = tokenExists(tokenId);
address owner = ownerOf@withrevert(tokenId);
assert e <=> !lastReverted;
assert e => owner == unsafeOwnerOf(tokenId); // notMintedUnset tells us this is non-zero
address approved = getApproved@withrevert(tokenId);
assert e <=> !lastReverted;
assert e => approved == unsafeGetApproved(tokenId);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: unsafeOwnerOf and unsafeGetApproved don't revert
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule unsafeDontRevert(uint256 tokenId) {
unsafeOwnerOf@withrevert(tokenId);
assert !lastReverted;
unsafeGetApproved@withrevert(tokenId);
assert !lastReverted;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: balance of address(0) is 0
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule zeroAddressBalanceRevert() {
balanceOf@withrevert(0);
assert lastReverted;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: total supply can only change through mint and burn
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule supplyChange(env e) {
uint256 supplyBefore = ownedTotal();
method f; calldataarg args; f(e, args);
uint256 supplyAfter = ownedTotal();
assert supplyAfter > supplyBefore => (
supplyAfter == supplyBefore + 1 &&
(
f.selector == mint(address,uint256).selector ||
f.selector == safeMint(address,uint256).selector ||
f.selector == safeMint(address,uint256,bytes).selector
)
);
assert supplyAfter < supplyBefore => (
supplyAfter == supplyBefore - 1 &&
f.selector == burn(uint256).selector
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: balanceOf can only change through mint, burn or transfers. balanceOf cannot change by more than 1.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule balanceChange(env e, address account) {
requireInvariant balanceOfConsistency(account);
require balanceLimited(account);
uint256 balanceBefore = balanceOf(account);
method f; calldataarg args; f(e, args);
uint256 balanceAfter = balanceOf(account);
// balance can change by at most 1
assert balanceBefore != balanceAfter => (
balanceAfter == balanceBefore - 1 ||
balanceAfter == balanceBefore + 1
);
// only selected function can change balances
assert balanceBefore != balanceAfter => (
f.selector == transferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256,bytes).selector ||
f.selector == mint(address,uint256).selector ||
f.selector == safeMint(address,uint256).selector ||
f.selector == safeMint(address,uint256,bytes).selector ||
f.selector == burn(uint256).selector
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: ownership can only change through mint, burn or transfers.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule ownershipChange(env e, uint256 tokenId) {
address ownerBefore = unsafeOwnerOf(tokenId);
method f; calldataarg args; f(e, args);
address ownerAfter = unsafeOwnerOf(tokenId);
assert ownerBefore == 0 && ownerAfter != 0 => (
f.selector == mint(address,uint256).selector ||
f.selector == safeMint(address,uint256).selector ||
f.selector == safeMint(address,uint256,bytes).selector
);
assert ownerBefore != 0 && ownerAfter == 0 => (
f.selector == burn(uint256).selector
);
assert (ownerBefore != ownerAfter && ownerBefore != 0 && ownerAfter != 0) => (
f.selector == transferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256,bytes).selector
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: token approval can only change through approve or transfers (implicitly).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule approvalChange(env e, uint256 tokenId) {
address approvalBefore = unsafeGetApproved(tokenId);
method f; calldataarg args; f(e, args);
address approvalAfter = unsafeGetApproved(tokenId);
// approve can set any value, other functions reset
assert approvalBefore != approvalAfter => (
f.selector == approve(address,uint256).selector ||
(
(
f.selector == transferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256,bytes).selector ||
f.selector == burn(uint256).selector
) && approvalAfter == 0
)
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: approval for all tokens can only change through isApprovedForAll.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule approvedForAllChange(env e, address owner, address spender) {
bool approvedForAllBefore = isApprovedForAll(owner, spender);
method f; calldataarg args; f(e, args);
bool approvedForAllAfter = isApprovedForAll(owner, spender);
assert approvedForAllBefore != approvedForAllAfter => f.selector == setApprovalForAll(address,bool).selector;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: transferFrom behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule transferFrom(env e, address from, address to, uint256 tokenId) {
require nonpayable(e);
address operator = e.msg.sender;
uint256 otherTokenId;
address otherAccount;
requireInvariant ownerHasBalance(tokenId);
require balanceLimited(to);
uint256 balanceOfFromBefore = balanceOf(from);
uint256 balanceOfToBefore = balanceOf(to);
uint256 balanceOfOtherBefore = balanceOf(otherAccount);
address ownerBefore = unsafeOwnerOf(tokenId);
address otherOwnerBefore = unsafeOwnerOf(otherTokenId);
address approvalBefore = unsafeGetApproved(tokenId);
address otherApprovalBefore = unsafeGetApproved(otherTokenId);
transferFrom@withrevert(e, from, to, tokenId);
bool success = !lastReverted;
// liveness
assert success <=> (
from == ownerBefore &&
from != 0 &&
to != 0 &&
(operator == from || operator == approvalBefore || isApprovedForAll(ownerBefore, operator))
);
// effect
assert success => (
balanceOf(from) == balanceOfFromBefore - to_uint256(from != to ? 1 : 0) &&
balanceOf(to) == balanceOfToBefore + to_uint256(from != to ? 1 : 0) &&
unsafeOwnerOf(tokenId) == to &&
unsafeGetApproved(tokenId) == 0
);
// no side effect
assert balanceOf(otherAccount) != balanceOfOtherBefore => (otherAccount == from || otherAccount == to);
assert unsafeOwnerOf(otherTokenId) != otherOwnerBefore => otherTokenId == tokenId;
assert unsafeGetApproved(otherTokenId) != otherApprovalBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: safeTransferFrom behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule safeTransferFrom(env e, method f, address from, address to, uint256 tokenId) filtered { f ->
f.selector == safeTransferFrom(address,address,uint256).selector ||
f.selector == safeTransferFrom(address,address,uint256,bytes).selector
} {
require nonpayable(e);
address operator = e.msg.sender;
uint256 otherTokenId;
address otherAccount;
requireInvariant ownerHasBalance(tokenId);
require balanceLimited(to);
uint256 balanceOfFromBefore = balanceOf(from);
uint256 balanceOfToBefore = balanceOf(to);
uint256 balanceOfOtherBefore = balanceOf(otherAccount);
address ownerBefore = unsafeOwnerOf(tokenId);
address otherOwnerBefore = unsafeOwnerOf(otherTokenId);
address approvalBefore = unsafeGetApproved(tokenId);
address otherApprovalBefore = unsafeGetApproved(otherTokenId);
helperTransferWithRevert(e, f, from, to, tokenId);
bool success = !lastReverted;
assert success <=> (
from == ownerBefore &&
from != 0 &&
to != 0 &&
(operator == from || operator == approvalBefore || isApprovedForAll(ownerBefore, operator))
);
// effect
assert success => (
balanceOf(from) == balanceOfFromBefore - to_uint256(from != to ? 1: 0) &&
balanceOf(to) == balanceOfToBefore + to_uint256(from != to ? 1: 0) &&
unsafeOwnerOf(tokenId) == to &&
unsafeGetApproved(tokenId) == 0
);
// no side effect
assert balanceOf(otherAccount) != balanceOfOtherBefore => (otherAccount == from || otherAccount == to);
assert unsafeOwnerOf(otherTokenId) != otherOwnerBefore => otherTokenId == tokenId;
assert unsafeGetApproved(otherTokenId) != otherApprovalBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: mint behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule mint(env e, address to, uint256 tokenId) {
require nonpayable(e);
requireInvariant notMintedUnset(tokenId);
uint256 otherTokenId;
address otherAccount;
require balanceLimited(to);
uint256 supplyBefore = ownedTotal();
uint256 balanceOfToBefore = balanceOf(to);
uint256 balanceOfOtherBefore = balanceOf(otherAccount);
address ownerBefore = unsafeOwnerOf(tokenId);
address otherOwnerBefore = unsafeOwnerOf(otherTokenId);
mint@withrevert(e, to, tokenId);
bool success = !lastReverted;
// liveness
assert success <=> (
ownerBefore == 0 &&
to != 0
);
// effect
assert success => (
ownedTotal() == supplyBefore + 1 &&
balanceOf(to) == balanceOfToBefore + 1 &&
unsafeOwnerOf(tokenId) == to
);
// no side effect
assert balanceOf(otherAccount) != balanceOfOtherBefore => otherAccount == to;
assert unsafeOwnerOf(otherTokenId) != otherOwnerBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: safeMint behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule safeMint(env e, method f, address to, uint256 tokenId) filtered { f ->
f.selector == safeMint(address,uint256).selector ||
f.selector == safeMint(address,uint256,bytes).selector
} {
require nonpayable(e);
requireInvariant notMintedUnset(tokenId);
uint256 otherTokenId;
address otherAccount;
require balanceLimited(to);
uint256 supplyBefore = ownedTotal();
uint256 balanceOfToBefore = balanceOf(to);
uint256 balanceOfOtherBefore = balanceOf(otherAccount);
address ownerBefore = unsafeOwnerOf(tokenId);
address otherOwnerBefore = unsafeOwnerOf(otherTokenId);
helperMintWithRevert(e, f, to, tokenId);
bool success = !lastReverted;
assert success <=> (
ownerBefore == 0 &&
to != 0
);
// effect
assert success => (
ownedTotal() == supplyBefore + 1 &&
balanceOf(to) == balanceOfToBefore + 1 &&
unsafeOwnerOf(tokenId) == to
);
// no side effect
assert balanceOf(otherAccount) != balanceOfOtherBefore => otherAccount == to;
assert unsafeOwnerOf(otherTokenId) != otherOwnerBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: burn behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule burn(env e, uint256 tokenId) {
require nonpayable(e);
address from = unsafeOwnerOf(tokenId);
uint256 otherTokenId;
address otherAccount;
requireInvariant ownerHasBalance(tokenId);
uint256 supplyBefore = ownedTotal();
uint256 balanceOfFromBefore = balanceOf(from);
uint256 balanceOfOtherBefore = balanceOf(otherAccount);
address ownerBefore = unsafeOwnerOf(tokenId);
address otherOwnerBefore = unsafeOwnerOf(otherTokenId);
address otherApprovalBefore = unsafeGetApproved(otherTokenId);
burn@withrevert(e, tokenId);
bool success = !lastReverted;
// liveness
assert success <=> (
ownerBefore != 0
);
// effect
assert success => (
ownedTotal() == supplyBefore - 1 &&
balanceOf(from) == balanceOfFromBefore - 1 &&
unsafeOwnerOf(tokenId) == 0 &&
unsafeGetApproved(tokenId) == 0
);
// no side effect
assert balanceOf(otherAccount) != balanceOfOtherBefore => otherAccount == from;
assert unsafeOwnerOf(otherTokenId) != otherOwnerBefore => otherTokenId == tokenId;
assert unsafeGetApproved(otherTokenId) != otherApprovalBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: approve behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule approve(env e, address spender, uint256 tokenId) {
require nonpayable(e);
address caller = e.msg.sender;
address owner = unsafeOwnerOf(tokenId);
uint256 otherTokenId;
address otherApprovalBefore = unsafeGetApproved(otherTokenId);
approve@withrevert(e, spender, tokenId);
bool success = !lastReverted;
// liveness
assert success <=> (
owner != 0 &&
owner != spender &&
(owner == caller || isApprovedForAll(owner, caller))
);
// effect
assert success => unsafeGetApproved(tokenId) == spender;
// no side effect
assert unsafeGetApproved(otherTokenId) != otherApprovalBefore => otherTokenId == tokenId;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: setApprovalForAll behavior and side effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule setApprovalForAll(env e, address operator, bool approved) {
require nonpayable(e);
address owner = e.msg.sender;
address otherOwner;
address otherOperator;
bool otherIsApprovedForAllBefore = isApprovedForAll(otherOwner, otherOperator);
setApprovalForAll@withrevert(e, operator, approved);
bool success = !lastReverted;
// liveness
assert success <=> owner != operator;
// effect
assert success => isApprovedForAll(owner, operator) == approved;
// no side effect
assert isApprovedForAll(otherOwner, otherOperator) != otherIsApprovedForAllBefore => (
otherOwner == owner &&
otherOperator == operator
);
}

View File

@ -0,0 +1,334 @@
import "helpers/helpers.spec"
methods {
// library
set(bytes32,bytes32) returns (bool) envfree
remove(bytes32) returns (bool) envfree
contains(bytes32) returns (bool) envfree
length() returns (uint256) envfree
key_at(uint256) returns (bytes32) envfree
value_at(uint256) returns (bytes32) envfree
tryGet_contains(bytes32) returns (bool) envfree
tryGet_value(bytes32) returns (bytes32) envfree
get(bytes32) returns (bytes32) envfree
// FV
_indexOf(bytes32) returns (uint256) envfree
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
function sanity() returns bool {
return length() < max_uint256;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: the value mapping is empty for keys that are not in the EnumerableMap.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant noValueIfNotContained(bytes32 key)
!contains(key) => tryGet_value(key) == 0
{
preserved set(bytes32 otherKey, bytes32 someValue) {
require sanity();
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: All indexed keys are contained
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant indexedContained(uint256 index)
index < length() => contains(key_at(index))
{
preserved {
requireInvariant consistencyIndex(index);
requireInvariant consistencyIndex(to_uint256(length() - 1));
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: A value can only be stored at a single location
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant atUniqueness(uint256 index1, uint256 index2)
index1 == index2 <=> key_at(index1) == key_at(index2)
{
preserved remove(bytes32 key) {
requireInvariant atUniqueness(index1, to_uint256(length() - 1));
requireInvariant atUniqueness(index2, to_uint256(length() - 1));
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: index <> value relationship is consistent
Note that the two consistencyXxx invariants, put together, prove that at_ and _indexOf are inverse of one another.
This proves that we have a bijection between indices (the enumerability part) and keys (the entries that are set
and removed from the EnumerableMap).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant consistencyIndex(uint256 index)
index < length() => _indexOf(key_at(index)) == index + 1
{
preserved remove(bytes32 key) {
requireInvariant consistencyIndex(to_uint256(length() - 1));
}
}
invariant consistencyKey(bytes32 key)
contains(key) => (
_indexOf(key) > 0 &&
_indexOf(key) <= length() &&
key_at(to_uint256(_indexOf(key) - 1)) == key
)
{
preserved remove(bytes32 otherKey) {
requireInvariant consistencyKey(otherKey);
requireInvariant atUniqueness(
to_uint256(_indexOf(key) - 1),
to_uint256(_indexOf(otherKey) - 1)
);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: state only changes by setting or removing elements
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule stateChange(env e, bytes32 key) {
require sanity();
requireInvariant consistencyKey(key);
uint256 lengthBefore = length();
bool containsBefore = contains(key);
bytes32 valueBefore = tryGet_value(key);
method f;
calldataarg args;
f(e, args);
uint256 lengthAfter = length();
bool containsAfter = contains(key);
bytes32 valueAfter = tryGet_value(key);
assert lengthBefore != lengthAfter => (
(f.selector == set(bytes32,bytes32).selector && lengthAfter == lengthBefore + 1) ||
(f.selector == remove(bytes32).selector && lengthAfter == lengthBefore - 1)
);
assert containsBefore != containsAfter => (
(f.selector == set(bytes32,bytes32).selector && containsAfter) ||
(f.selector == remove(bytes32).selector && !containsAfter)
);
assert valueBefore != valueAfter => (
(f.selector == set(bytes32,bytes32).selector && containsAfter) ||
(f.selector == remove(bytes32).selector && !containsAfter && valueAfter == 0)
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: check liveness of view functions.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule liveness_1(bytes32 key) {
requireInvariant consistencyKey(key);
// contains never revert
bool contains = contains@withrevert(key);
assert !lastReverted;
// tryGet never reverts (key)
tryGet_contains@withrevert(key);
assert !lastReverted;
// tryGet never reverts (value)
tryGet_value@withrevert(key);
assert !lastReverted;
// get reverts iff the key is not in the map
get@withrevert(key);
assert !lastReverted <=> contains;
}
rule liveness_2(uint256 index) {
requireInvariant consistencyIndex(index);
// length never revert
uint256 length = length@withrevert();
assert !lastReverted;
// key_at reverts iff the index is out of bound
key_at@withrevert(index);
assert !lastReverted <=> index < length;
// value_at reverts iff the index is out of bound
value_at@withrevert(index);
assert !lastReverted <=> index < length;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: get and tryGet return the expected values.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule getAndTryGet(bytes32 key) {
requireInvariant noValueIfNotContained(key);
bool contained = contains(key);
bool tryContained = tryGet_contains(key);
bytes32 tryValue = tryGet_value(key);
bytes32 value = get@withrevert(key); // revert is not contained
assert contained == tryContained;
assert contained => tryValue == value;
assert !contained => tryValue == 0;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: set key-value in EnumerableMap
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule set(bytes32 key, bytes32 value, bytes32 otherKey) {
require sanity();
uint256 lengthBefore = length();
bool containsBefore = contains(key);
bool containsOtherBefore = contains(otherKey);
bytes32 otherValueBefore = tryGet_value(otherKey);
bool added = set@withrevert(key, value);
bool success = !lastReverted;
assert success && contains(key) && get(key) == value,
"liveness & immediate effect";
assert added <=> !containsBefore,
"return value: added iff not contained";
assert length() == lengthBefore + to_mathint(added ? 1 : 0),
"effect: length increases iff added";
assert added => (key_at(lengthBefore) == key && value_at(lengthBefore) == value),
"effect: add at the end";
assert containsOtherBefore != contains(otherKey) => (added && key == otherKey),
"side effect: other keys are not affected";
assert otherValueBefore != tryGet_value(otherKey) => key == otherKey,
"side effect: values attached to other keys are not affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: remove key from EnumerableMap
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule remove(bytes32 key, bytes32 otherKey) {
requireInvariant consistencyKey(key);
requireInvariant consistencyKey(otherKey);
uint256 lengthBefore = length();
bool containsBefore = contains(key);
bool containsOtherBefore = contains(otherKey);
bytes32 otherValueBefore = tryGet_value(otherKey);
bool removed = remove@withrevert(key);
bool success = !lastReverted;
assert success && !contains(key),
"liveness & immediate effect";
assert removed <=> containsBefore,
"return value: removed iff contained";
assert length() == lengthBefore - to_mathint(removed ? 1 : 0),
"effect: length decreases iff removed";
assert containsOtherBefore != contains(otherKey) => (removed && key == otherKey),
"side effect: other keys are not affected";
assert otherValueBefore != tryGet_value(otherKey) => key == otherKey,
"side effect: values attached to other keys are not affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: when adding a new key, the other keys remain in set, at the same index.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule setEnumerability(bytes32 key, bytes32 value, uint256 index) {
require sanity();
bytes32 atKeyBefore = key_at(index);
bytes32 atValueBefore = value_at(index);
set(key, value);
bytes32 atKeyAfter = key_at@withrevert(index);
assert !lastReverted;
bytes32 atValueAfter = value_at@withrevert(index);
assert !lastReverted;
assert atKeyAfter == atKeyBefore;
assert atValueAfter != atValueBefore => (
key == atKeyBefore &&
value == atValueAfter
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: when removing a existing key, the other keys remain in set, at the same index (except for the last one).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule removeEnumerability(bytes32 key, uint256 index) {
uint256 last = length() - 1;
requireInvariant consistencyKey(key);
requireInvariant consistencyIndex(index);
requireInvariant consistencyIndex(last);
bytes32 atKeyBefore = key_at(index);
bytes32 atValueBefore = value_at(index);
bytes32 lastKeyBefore = key_at(last);
bytes32 lastValueBefore = value_at(last);
remove(key);
// can't read last value & keys (length decreased)
bytes32 atKeyAfter = key_at@withrevert(index);
assert lastReverted <=> index == last;
bytes32 atValueAfter = value_at@withrevert(index);
assert lastReverted <=> index == last;
// One value that is allowed to change is if previous value was removed,
// in that case the last value before took its place.
assert (
index != last &&
atKeyBefore != atKeyAfter
) => (
atKeyBefore == key &&
atKeyAfter == lastKeyBefore
);
assert (
index != last &&
atValueBefore != atValueAfter
) => (
atValueAfter == lastValueBefore
);
}

View File

@ -0,0 +1,247 @@
import "helpers/helpers.spec"
methods {
// library
add(bytes32) returns (bool) envfree
remove(bytes32) returns (bool) envfree
contains(bytes32) returns (bool) envfree
length() returns (uint256) envfree
at_(uint256) returns (bytes32) envfree
// FV
_indexOf(bytes32) returns (uint256) envfree
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
function sanity() returns bool {
return length() < max_uint256;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: All indexed keys are contained
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant indexedContained(uint256 index)
index < length() => contains(at_(index))
{
preserved {
requireInvariant consistencyIndex(index);
requireInvariant consistencyIndex(to_uint256(length() - 1));
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: A value can only be stored at a single location
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant atUniqueness(uint256 index1, uint256 index2)
index1 == index2 <=> at_(index1) == at_(index2)
{
preserved remove(bytes32 key) {
requireInvariant atUniqueness(index1, to_uint256(length() - 1));
requireInvariant atUniqueness(index2, to_uint256(length() - 1));
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: index <> key relationship is consistent
Note that the two consistencyXxx invariants, put together, prove that at_ and _indexOf are inverse of one another.
This proves that we have a bijection between indices (the enumerability part) and keys (the entries that are added
and removed from the EnumerableSet).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant consistencyIndex(uint256 index)
index < length() => _indexOf(at_(index)) == index + 1
{
preserved remove(bytes32 key) {
requireInvariant consistencyIndex(to_uint256(length() - 1));
}
}
invariant consistencyKey(bytes32 key)
contains(key) => (
_indexOf(key) > 0 &&
_indexOf(key) <= length() &&
at_(to_uint256(_indexOf(key) - 1)) == key
)
{
preserved remove(bytes32 otherKey) {
requireInvariant consistencyKey(otherKey);
requireInvariant atUniqueness(
to_uint256(_indexOf(key) - 1),
to_uint256(_indexOf(otherKey) - 1)
);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: state only changes by adding or removing elements
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule stateChange(env e, bytes32 key) {
require sanity();
requireInvariant consistencyKey(key);
uint256 lengthBefore = length();
bool containsBefore = contains(key);
method f;
calldataarg args;
f(e, args);
uint256 lengthAfter = length();
bool containsAfter = contains(key);
assert lengthBefore != lengthAfter => (
(f.selector == add(bytes32).selector && lengthAfter == lengthBefore + 1) ||
(f.selector == remove(bytes32).selector && lengthAfter == lengthBefore - 1)
);
assert containsBefore != containsAfter => (
(f.selector == add(bytes32).selector && containsAfter) ||
(f.selector == remove(bytes32).selector && containsBefore)
);
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: check liveness of view functions.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule liveness_1(bytes32 key) {
requireInvariant consistencyKey(key);
// contains never revert
contains@withrevert(key);
assert !lastReverted;
}
rule liveness_2(uint256 index) {
requireInvariant consistencyIndex(index);
// length never revert
uint256 length = length@withrevert();
assert !lastReverted;
// at reverts iff the index is out of bound
at_@withrevert(index);
assert !lastReverted <=> index < length;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: add key to EnumerableSet if not already contained
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule add(bytes32 key, bytes32 otherKey) {
require sanity();
uint256 lengthBefore = length();
bool containsBefore = contains(key);
bool containsOtherBefore = contains(otherKey);
bool added = add@withrevert(key);
bool success = !lastReverted;
assert success && contains(key),
"liveness & immediate effect";
assert added <=> !containsBefore,
"return value: added iff not contained";
assert length() == lengthBefore + to_mathint(added ? 1 : 0),
"effect: length increases iff added";
assert added => at_(lengthBefore) == key,
"effect: add at the end";
assert containsOtherBefore != contains(otherKey) => (added && key == otherKey),
"side effect: other keys are not affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: remove key from EnumerableSet if already contained
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule remove(bytes32 key, bytes32 otherKey) {
requireInvariant consistencyKey(key);
requireInvariant consistencyKey(otherKey);
uint256 lengthBefore = length();
bool containsBefore = contains(key);
bool containsOtherBefore = contains(otherKey);
bool removed = remove@withrevert(key);
bool success = !lastReverted;
assert success && !contains(key),
"liveness & immediate effect";
assert removed <=> containsBefore,
"return value: removed iff contained";
assert length() == lengthBefore - to_mathint(removed ? 1 : 0),
"effect: length decreases iff removed";
assert containsOtherBefore != contains(otherKey) => (removed && key == otherKey),
"side effect: other keys are not affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: when adding a new key, the other keys remain in set, at the same index.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule addEnumerability(bytes32 key, uint256 index) {
require sanity();
bytes32 atBefore = at_(index);
add(key);
bytes32 atAfter = at_@withrevert(index);
bool atAfterSuccess = !lastReverted;
assert atAfterSuccess;
assert atBefore == atAfter;
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: when removing a existing key, the other keys remain in set, at the same index (except for the last one).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule removeEnumerability(bytes32 key, uint256 index) {
uint256 last = length() - 1;
requireInvariant consistencyKey(key);
requireInvariant consistencyIndex(index);
requireInvariant consistencyIndex(last);
bytes32 atBefore = at_(index);
bytes32 lastBefore = at_(last);
remove(key);
// can't read last value (length decreased)
bytes32 atAfter = at_@withrevert(index);
assert lastReverted <=> index == last;
// One value that is allowed to change is if previous value was removed,
// in that case the last value before took its place.
assert (
index != last &&
atBefore != atAfter
) => (
atBefore == key &&
atAfter == lastBefore
);
}

View File

@ -0,0 +1,165 @@
import "helpers/helpers.spec"
methods {
// initialize, reinitialize, disable
initialize() envfree
reinitialize(uint8) envfree
disable() envfree
nested_init_init() envfree
nested_init_reinit(uint8) envfree
nested_reinit_init(uint8) envfree
nested_reinit_reinit(uint8,uint8) envfree
// view
version() returns uint8 envfree
initializing() returns bool envfree
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Definitions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
definition isUninitialized() returns bool = version() == 0;
definition isInitialized() returns bool = version() > 0;
definition isDisabled() returns bool = version() == 255;
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: A contract must only ever be in an initializing state while in the middle of a transaction execution.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant notInitializing()
!initializing()
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: The version cannot decrease & disable state is irrevocable.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule increasingVersion(env e) {
uint8 versionBefore = version();
bool disabledBefore = isDisabled();
method f; calldataarg args;
f(e, args);
assert versionBefore <= version(), "_initialized must only increase";
assert disabledBefore => isDisabled(), "a disabled initializer must stay disabled";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Cannot initialize a contract that is already initialized.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cannotInitializeTwice() {
require isInitialized();
initialize@withrevert();
assert lastReverted, "contract must only be initialized once";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Cannot initialize once disabled.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cannotInitializeOnceDisabled() {
require isDisabled();
initialize@withrevert();
assert lastReverted, "contract is disabled";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Cannot reinitialize once disabled.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cannotReinitializeOnceDisabled() {
require isDisabled();
uint8 n;
reinitialize@withrevert(n);
assert lastReverted, "contract is disabled";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Cannot nest initializers (after construction).
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cannotNestInitializers_init_init() {
nested_init_init@withrevert();
assert lastReverted, "nested initializers";
}
rule cannotNestInitializers_init_reinit(uint8 m) {
nested_init_reinit@withrevert(m);
assert lastReverted, "nested initializers";
}
rule cannotNestInitializers_reinit_init(uint8 n) {
nested_reinit_init@withrevert(n);
assert lastReverted, "nested initializers";
}
rule cannotNestInitializers_reinit_reinit(uint8 n, uint8 m) {
nested_reinit_reinit@withrevert(n, m);
assert lastReverted, "nested initializers";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Initialize correctly sets the version.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule initializeEffects() {
requireInvariant notInitializing();
bool isUninitializedBefore = isUninitialized();
initialize@withrevert();
bool success = !lastReverted;
assert success <=> isUninitializedBefore, "can only initialize uninitialized contracts";
assert success => version() == 1, "initialize must set version() to 1";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Reinitialize correctly sets the version.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule reinitializeEffects() {
requireInvariant notInitializing();
uint8 versionBefore = version();
uint8 n;
reinitialize@withrevert(n);
bool success = !lastReverted;
assert success <=> versionBefore < n, "can only reinitialize to a latter versions";
assert success => version() == n, "reinitialize must set version() to n";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: Can disable.
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule disableEffect() {
requireInvariant notInitializing();
disable@withrevert();
bool success = !lastReverted;
assert success, "call to _disableInitializers failed";
assert isDisabled(), "disable state not set";
}

View File

@ -0,0 +1,78 @@
import "helpers/helpers.spec"
import "methods/IOwnable.spec"
methods {
restricted()
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: transferOwnership changes ownership
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule transferOwnership(env e) {
require nonpayable(e);
address newOwner;
address current = owner();
transferOwnership@withrevert(e, newOwner);
bool success = !lastReverted;
assert success <=> (e.msg.sender == current && newOwner != 0), "unauthorized caller or invalid arg";
assert success => owner() == newOwner, "current owner changed";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: renounceOwnership removes the owner
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule renounceOwnership(env e) {
require nonpayable(e);
address current = owner();
renounceOwnership@withrevert(e);
bool success = !lastReverted;
assert success <=> e.msg.sender == current, "unauthorized caller";
assert success => owner() == 0, "owner not cleared";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Access control: only current owner can call restricted functions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyCurrentOwnerCanCallOnlyOwner(env e) {
require nonpayable(e);
address current = owner();
calldataarg args;
restricted@withrevert(e, args);
assert !lastReverted <=> e.msg.sender == current, "access control failed";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: ownership can only change in specific ways
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyOwnerOrPendingOwnerCanChangeOwnership(env e) {
address oldCurrent = owner();
method f; calldataarg args;
f(e, args);
address newCurrent = owner();
// If owner changes, must be either transferOwnership or renounceOwnership
assert oldCurrent != newCurrent => (
(e.msg.sender == oldCurrent && newCurrent != 0 && f.selector == transferOwnership(address).selector) ||
(e.msg.sender == oldCurrent && newCurrent == 0 && f.selector == renounceOwnership().selector)
);
}

View File

@ -0,0 +1,108 @@
import "helpers/helpers.spec"
import "methods/IOwnable2Step.spec"
methods {
restricted()
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: transferOwnership sets the pending owner
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule transferOwnership(env e) {
require nonpayable(e);
address newOwner;
address current = owner();
transferOwnership@withrevert(e, newOwner);
bool success = !lastReverted;
assert success <=> e.msg.sender == current, "unauthorized caller";
assert success => pendingOwner() == newOwner, "pending owner not set";
assert success => owner() == current, "current owner changed";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: renounceOwnership removes the owner and the pendingOwner
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule renounceOwnership(env e) {
require nonpayable(e);
address current = owner();
renounceOwnership@withrevert(e);
bool success = !lastReverted;
assert success <=> e.msg.sender == current, "unauthorized caller";
assert success => pendingOwner() == 0, "pending owner not cleared";
assert success => owner() == 0, "owner not cleared";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: acceptOwnership changes owner and reset pending owner
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule acceptOwnership(env e) {
require nonpayable(e);
address current = owner();
address pending = pendingOwner();
acceptOwnership@withrevert(e);
bool success = !lastReverted;
assert success <=> e.msg.sender == pending, "unauthorized caller";
assert success => pendingOwner() == 0, "pending owner not cleared";
assert success => owner() == pending, "owner not transferred";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Access control: only current owner can call restricted functions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule onlyCurrentOwnerCanCallOnlyOwner(env e) {
require nonpayable(e);
address current = owner();
calldataarg args;
restricted@withrevert(e, args);
assert !lastReverted <=> e.msg.sender == current, "access control failed";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: ownership and pending ownership can only change in specific ways
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule ownerOrPendingOwnerChange(env e, method f) {
address oldCurrent = owner();
address oldPending = pendingOwner();
calldataarg args;
f(e, args);
address newCurrent = owner();
address newPending = pendingOwner();
// If owner changes, must be either acceptOwnership or renounceOwnership
assert oldCurrent != newCurrent => (
(e.msg.sender == oldPending && newCurrent == oldPending && newPending == 0 && f.selector == acceptOwnership().selector) ||
(e.msg.sender == oldCurrent && newCurrent == 0 && newPending == 0 && f.selector == renounceOwnership().selector)
);
// If pending changes, must be either acceptance or reset
assert oldPending != newPending => (
(e.msg.sender == oldCurrent && newCurrent == oldCurrent && f.selector == transferOwnership(address).selector) ||
(e.msg.sender == oldPending && newCurrent == oldPending && newPending == 0 && f.selector == acceptOwnership().selector) ||
(e.msg.sender == oldCurrent && newCurrent == 0 && newPending == 0 && f.selector == renounceOwnership().selector)
);
}

View File

@ -0,0 +1,96 @@
import "helpers/helpers.spec"
methods {
paused() returns (bool) envfree
pause()
unpause()
onlyWhenPaused()
onlyWhenNotPaused()
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: _pause pauses the contract
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule pause(env e) {
require nonpayable(e);
bool pausedBefore = paused();
pause@withrevert(e);
bool success = !lastReverted;
bool pausedAfter = paused();
// liveness
assert success <=> !pausedBefore, "works if and only if the contract was not paused before";
// effect
assert success => pausedAfter, "contract must be paused after a successful call";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: _unpause unpauses the contract
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule unpause(env e) {
require nonpayable(e);
bool pausedBefore = paused();
unpause@withrevert(e);
bool success = !lastReverted;
bool pausedAfter = paused();
// liveness
assert success <=> pausedBefore, "works if and only if the contract was paused before";
// effect
assert success => !pausedAfter, "contract must be unpaused after a successful call";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: whenPaused modifier can only be called if the contract is paused
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule whenPaused(env e) {
require nonpayable(e);
onlyWhenPaused@withrevert(e);
assert !lastReverted <=> paused(), "works if and only if the contract is paused";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Function correctness: whenNotPaused modifier can only be called if the contract is not paused
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule whenNotPaused(env e) {
require nonpayable(e);
onlyWhenNotPaused@withrevert(e);
assert !lastReverted <=> !paused(), "works if and only if the contract is not paused";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rules: only _pause and _unpause can change paused status
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule noPauseChange(env e) {
method f;
calldataarg args;
bool pausedBefore = paused();
f(e, args);
bool pausedAfter = paused();
assert pausedBefore != pausedAfter => (
(!pausedAfter && f.selector == unpause().selector) ||
(pausedAfter && f.selector == pause().selector)
), "contract's paused status can only be changed by _pause() or _unpause()";
}

View File

@ -0,0 +1,275 @@
import "helpers/helpers.spec"
import "methods/IAccessControl.spec"
methods {
TIMELOCK_ADMIN_ROLE() returns (bytes32) envfree
PROPOSER_ROLE() returns (bytes32) envfree
EXECUTOR_ROLE() returns (bytes32) envfree
CANCELLER_ROLE() returns (bytes32) envfree
isOperation(bytes32) returns (bool) envfree
isOperationPending(bytes32) returns (bool) envfree
isOperationReady(bytes32) returns (bool)
isOperationDone(bytes32) returns (bool) envfree
getTimestamp(bytes32) returns (uint256) envfree
getMinDelay() returns (uint256) envfree
hashOperation(address, uint256, bytes, bytes32, bytes32) returns(bytes32) envfree
hashOperationBatch(address[], uint256[], bytes[], bytes32, bytes32) returns(bytes32) envfree
schedule(address, uint256, bytes, bytes32, bytes32, uint256)
scheduleBatch(address[], uint256[], bytes[], bytes32, bytes32, uint256)
execute(address, uint256, bytes, bytes32, bytes32)
executeBatch(address[], uint256[], bytes[], bytes32, bytes32)
cancel(bytes32)
updateDelay(uint256)
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Helpers
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
// Uniformly handle scheduling of batched and non-batched operations.
function helperScheduleWithRevert(env e, method f, bytes32 id, uint256 delay) {
if (f.selector == schedule(address, uint256, bytes, bytes32, bytes32, uint256).selector) {
address target; uint256 value; bytes data; bytes32 predecessor; bytes32 salt;
require hashOperation(target, value, data, predecessor, salt) == id; // Correlation
schedule@withrevert(e, target, value, data, predecessor, salt, delay);
} else if (f.selector == scheduleBatch(address[], uint256[], bytes[], bytes32, bytes32, uint256).selector) {
address[] targets; uint256[] values; bytes[] payloads; bytes32 predecessor; bytes32 salt;
require hashOperationBatch(targets, values, payloads, predecessor, salt) == id; // Correlation
scheduleBatch@withrevert(e, targets, values, payloads, predecessor, salt, delay);
} else {
calldataarg args;
f@withrevert(e, args);
}
}
// Uniformly handle execution of batched and non-batched operations.
function helperExecuteWithRevert(env e, method f, bytes32 id, bytes32 predecessor) {
if (f.selector == execute(address, uint256, bytes, bytes32, bytes32).selector) {
address target; uint256 value; bytes data; bytes32 salt;
require hashOperation(target, value, data, predecessor, salt) == id; // Correlation
execute@withrevert(e, target, value, data, predecessor, salt);
} else if (f.selector == executeBatch(address[], uint256[], bytes[], bytes32, bytes32).selector) {
address[] targets; uint256[] values; bytes[] payloads; bytes32 salt;
require hashOperationBatch(targets, values, payloads, predecessor, salt) == id; // Correlation
executeBatch@withrevert(e, targets, values, payloads, predecessor, salt);
} else {
calldataarg args;
f@withrevert(e, args);
}
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Definitions
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
definition DONE_TIMESTAMP() returns uint256 = 1;
definition UNSET() returns uint8 = 0x1;
definition PENDING() returns uint8 = 0x2;
definition DONE() returns uint8 = 0x4;
definition isUnset(bytes32 id) returns bool = !isOperation(id);
definition isPending(bytes32 id) returns bool = isOperationPending(id);
definition isDone(bytes32 id) returns bool = isOperationDone(id);
definition state(bytes32 id) returns uint8 = (isUnset(id) ? UNSET() : 0) | (isPending(id) ? PENDING() : 0) | (isDone(id) ? DONE() : 0);
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariants: consistency of accessors
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant isOperationCheck(bytes32 id)
isOperation(id) <=> getTimestamp(id) > 0
filtered { f -> !f.isView }
invariant isOperationPendingCheck(bytes32 id)
isOperationPending(id) <=> getTimestamp(id) > DONE_TIMESTAMP()
filtered { f -> !f.isView }
invariant isOperationDoneCheck(bytes32 id)
isOperationDone(id) <=> getTimestamp(id) == DONE_TIMESTAMP()
filtered { f -> !f.isView }
invariant isOperationReadyCheck(env e, bytes32 id)
isOperationReady(e, id) <=> (isOperationPending(id) && getTimestamp(id) <= e.block.timestamp)
filtered { f -> !f.isView }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Invariant: a proposal id is either unset, pending or done
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
invariant stateConsistency(bytes32 id, env e)
// Check states are mutually exclusive
(isUnset(id) <=> (!isPending(id) && !isDone(id) )) &&
(isPending(id) <=> (!isUnset(id) && !isDone(id) )) &&
(isDone(id) <=> (!isUnset(id) && !isPending(id))) &&
// Check that the state helper behaves as expected:
(isUnset(id) <=> state(id) == UNSET() ) &&
(isPending(id) <=> state(id) == PENDING() ) &&
(isDone(id) <=> state(id) == DONE() ) &&
// Check substate
isOperationReady(e, id) => isPending(id)
filtered { f -> !f.isView }
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: state transition rules
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule stateTransition(bytes32 id, env e, method f, calldataarg args) {
require e.block.timestamp > 1; // Sanity
uint8 stateBefore = state(id);
f(e, args);
uint8 stateAfter = state(id);
// Cannot jump from UNSET to DONE
assert stateBefore == UNSET() => stateAfter != DONE();
// UNSET PENDING: schedule or scheduleBatch
assert stateBefore == UNSET() && stateAfter == PENDING() => (
f.selector == schedule(address, uint256, bytes, bytes32, bytes32, uint256).selector ||
f.selector == scheduleBatch(address[], uint256[], bytes[], bytes32, bytes32, uint256).selector
);
// PENDING UNSET: cancel
assert stateBefore == PENDING() && stateAfter == UNSET() => (
f.selector == cancel(bytes32).selector
);
// PENDING DONE: execute or executeBatch
assert stateBefore == PENDING() && stateAfter == DONE() => (
f.selector == execute(address, uint256, bytes, bytes32, bytes32).selector ||
f.selector == executeBatch(address[], uint256[], bytes[], bytes32, bytes32).selector
);
// DONE is final
assert stateBefore == DONE() => stateAfter == DONE();
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: minimum delay can only be updated through a timelock execution
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule minDelayOnlyChange(env e) {
uint256 delayBefore = getMinDelay();
method f; calldataarg args;
f(e, args);
assert delayBefore != getMinDelay() => (e.msg.sender == currentContract && f.selector == updateDelay(uint256).selector), "Unauthorized delay update";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: schedule liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule schedule(env e, method f, bytes32 id, uint256 delay) filtered { f ->
f.selector == schedule(address, uint256, bytes, bytes32, bytes32, uint256).selector ||
f.selector == scheduleBatch(address[], uint256[], bytes[], bytes32, bytes32, uint256).selector
} {
require nonpayable(e);
// Basic timestamp assumptions
require e.block.timestamp > 1;
require e.block.timestamp + delay < max_uint256;
require e.block.timestamp + getMinDelay() < max_uint256;
bytes32 otherId; uint256 otherTimestamp = getTimestamp(otherId);
uint8 stateBefore = state(id);
bool isDelaySufficient = delay >= getMinDelay();
bool isProposerBefore = hasRole(PROPOSER_ROLE(), e.msg.sender);
helperScheduleWithRevert(e, f, id, delay);
bool success = !lastReverted;
// liveness
assert success <=> (
stateBefore == UNSET() &&
isDelaySufficient &&
isProposerBefore
);
// effect
assert success => state(id) == PENDING(), "State transition violation";
assert success => getTimestamp(id) == to_uint256(e.block.timestamp + delay), "Proposal timestamp not correctly set";
// no side effect
assert otherTimestamp != getTimestamp(otherId) => id == otherId, "Other proposal affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: execute liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule execute(env e, method f, bytes32 id, bytes32 predecessor) filtered { f ->
f.selector == execute(address, uint256, bytes, bytes32, bytes32).selector ||
f.selector == executeBatch(address[], uint256[], bytes[], bytes32, bytes32).selector
} {
bytes32 otherId; uint256 otherTimestamp = getTimestamp(otherId);
uint8 stateBefore = state(id);
bool isOperationReadyBefore = isOperationReady(e, id);
bool isExecutorOrOpen = hasRole(EXECUTOR_ROLE(), e.msg.sender) || hasRole(EXECUTOR_ROLE(), 0);
bool predecessorDependency = predecessor == 0 || isDone(predecessor);
helperExecuteWithRevert(e, f, id, predecessor);
bool success = !lastReverted;
// The underlying transaction can revert, and that would cause the execution to revert. We can check that all non
// reverting calls meet the requirements in terms of proposal readiness, access control and predecessor dependency.
// We can't however guarantee that these requirements being meet ensure liveness of the proposal, because the
// proposal can revert for reasons beyond our control.
// liveness, should be `<=>` but can only check `=>` (see comment above)
assert success => (
stateBefore == PENDING() &&
isOperationReadyBefore &&
predecessorDependency &&
isExecutorOrOpen
);
// effect
assert success => state(id) == DONE(), "State transition violation";
// no side effect
assert otherTimestamp != getTimestamp(otherId) => id == otherId, "Other proposal affected";
}
/*
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
Rule: cancel liveness and effects
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
*/
rule cancel(env e, bytes32 id) {
require nonpayable(e);
bytes32 otherId; uint256 otherTimestamp = getTimestamp(otherId);
uint8 stateBefore = state(id);
bool isCanceller = hasRole(CANCELLER_ROLE(), e.msg.sender);
cancel@withrevert(e, id);
bool success = !lastReverted;
// liveness
assert success <=> (
stateBefore == PENDING() &&
isCanceller
);
// effect
assert success => state(id) == UNSET(), "State transition violation";
// no side effect
assert otherTimestamp != getTimestamp(otherId) => id == otherId, "Other proposal affected";
}

View File

@ -0,0 +1 @@
definition nonpayable(env e) returns bool = e.msg.value == 0;

View File

@ -0,0 +1,7 @@
methods {
hasRole(bytes32, address) returns(bool) envfree
getRoleAdmin(bytes32) returns(bytes32) envfree
grantRole(bytes32, address)
revokeRole(bytes32, address)
renounceRole(bytes32, address)
}

View File

@ -0,0 +1,36 @@
import "./IERC5313.spec"
methods {
// === View ==
// Default Admin
defaultAdmin() returns(address) envfree
pendingDefaultAdmin() returns(address, uint48) envfree
// Default Admin Delay
defaultAdminDelay() returns(uint48)
pendingDefaultAdminDelay() returns(uint48, uint48)
defaultAdminDelayIncreaseWait() returns(uint48) envfree
// === Mutations ==
// Default Admin
beginDefaultAdminTransfer(address)
cancelDefaultAdminTransfer()
acceptDefaultAdminTransfer()
// Default Admin Delay
changeDefaultAdminDelay(uint48)
rollbackDefaultAdminDelay()
// == FV ==
// Default Admin
pendingDefaultAdmin_() returns (address) envfree
pendingDefaultAdminSchedule_() returns (uint48) envfree
// Default Admin Delay
pendingDelay_() returns (uint48)
pendingDelaySchedule_() returns (uint48)
delayChangeWait_(uint48) returns (uint48)
}

View File

@ -0,0 +1,11 @@
methods {
name() returns (string) envfree => DISPATCHER(true)
symbol() returns (string) envfree => DISPATCHER(true)
decimals() returns (uint8) envfree => DISPATCHER(true)
totalSupply() returns (uint256) envfree => DISPATCHER(true)
balanceOf(address) returns (uint256) envfree => DISPATCHER(true)
allowance(address,address) returns (uint256) envfree => DISPATCHER(true)
approve(address,uint256) returns (bool) => DISPATCHER(true)
transfer(address,uint256) returns (bool) => DISPATCHER(true)
transferFrom(address,address,uint256) returns (bool) => DISPATCHER(true)
}

View File

@ -0,0 +1,5 @@
methods {
permit(address,address,uint256,uint256,uint8,bytes32,bytes32) => DISPATCHER(true)
nonces(address) returns (uint256) envfree => DISPATCHER(true)
DOMAIN_SEPARATOR() returns (bytes32) envfree => DISPATCHER(true)
}

View File

@ -0,0 +1,5 @@
methods {
maxFlashLoan(address) returns (uint256) envfree => DISPATCHER(true)
flashFee(address,uint256) returns (uint256) envfree => DISPATCHER(true)
flashLoan(address,address,uint256,bytes) returns (bool) => DISPATCHER(true)
}

View File

@ -0,0 +1,3 @@
methods {
owner() returns (address) envfree
}

View File

@ -0,0 +1,20 @@
methods {
// IERC721
balanceOf(address) returns (uint256) envfree => DISPATCHER(true)
ownerOf(uint256) returns (address) envfree => DISPATCHER(true)
getApproved(uint256) returns (address) envfree => DISPATCHER(true)
isApprovedForAll(address,address) returns (bool) envfree => DISPATCHER(true)
safeTransferFrom(address,address,uint256,bytes) => DISPATCHER(true)
safeTransferFrom(address,address,uint256) => DISPATCHER(true)
transferFrom(address,address,uint256) => DISPATCHER(true)
approve(address,uint256) => DISPATCHER(true)
setApprovalForAll(address,bool) => DISPATCHER(true)
// IERC721Metadata
name() returns (string) => DISPATCHER(true)
symbol() returns (string) => DISPATCHER(true)
tokenURI(uint256) returns (string) => DISPATCHER(true)
// IERC721Receiver
onERC721Received(address,address,uint256,bytes) returns (bytes4) => DISPATCHER(true)
}

View File

@ -0,0 +1,5 @@
methods {
owner() returns (address) envfree
transferOwnership(address)
renounceOwnership()
}

View File

@ -0,0 +1,7 @@
methods {
owner() returns (address) envfree
pendingOwner() returns (address) envfree
transferOwnership(address)
acceptOwnership()
renounceOwnership()
}

View File

@ -1,5 +1,5 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
@ -19,14 +19,14 @@ import "../utils/introspection/ERC165.sol";
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
@ -44,7 +44,8 @@ import "../utils/introspection/ERC165.sol";
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
@ -67,7 +68,7 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_checkRole(role);
_;
}
@ -81,10 +82,22 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
@ -92,13 +105,13 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
@ -113,7 +126,7 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
@ -126,6 +139,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
@ -139,6 +154,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
@ -157,6 +174,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
@ -171,6 +190,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
@ -201,6 +222,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
@ -213,6 +236,8 @@ abstract contract AccessControl is Context, IAccessControl, ERC165 {
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {

View File

@ -0,0 +1,45 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControlCrossChain.sol)
pragma solidity ^0.8.4;
import "./AccessControl.sol";
import "../crosschain/CrossChainEnabled.sol";
/**
* @dev An extension to {AccessControl} with support for cross-chain access management.
* For each role, is extension implements an equivalent "aliased" role that is used for
* restricting calls originating from other chains.
*
* For example, if a function `myFunction` is protected by `onlyRole(SOME_ROLE)`, and
* if an address `x` has role `SOME_ROLE`, it would be able to call `myFunction` directly.
* A wallet or contract at the same address on another chain would however not be able
* to call this function. In order to do so, it would require to have the role
* `_crossChainRoleAlias(SOME_ROLE)`.
*
* This aliasing is required to protect against multiple contracts living at the same
* address on different chains but controlled by conflicting entities.
*
* _Available since v4.6._
*/
abstract contract AccessControlCrossChain is AccessControl, CrossChainEnabled {
bytes32 public constant CROSSCHAIN_ALIAS = keccak256("CROSSCHAIN_ALIAS");
/**
* @dev See {AccessControl-_checkRole}.
*/
function _checkRole(bytes32 role) internal view virtual override {
if (_isCrossChain()) {
_checkRole(_crossChainRoleAlias(role), _crossChainSender());
} else {
super._checkRole(role);
}
}
/**
* @dev Returns the aliased role corresponding to `role`.
*/
function _crossChainRoleAlias(bytes32 role) internal pure virtual returns (bytes32) {
return role ^ CROSSCHAIN_ALIAS;
}
}

View File

@ -0,0 +1,383 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.0;
import "./AccessControl.sol";
import "./IAccessControlDefaultAdminRules.sol";
import "../utils/math/SafeCast.sol";
import "../interfaces/IERC5313.sol";
/**
* @dev Extension of {AccessControl} that allows specifying special rules to manage
* the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
* over other roles that may potentially have privileged rights in the system.
*
* If a specific role doesn't have an admin role assigned, the holder of the
* `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
*
* This contract implements the following risk mitigations on top of {AccessControl}:
*
* * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
* * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
* * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
* * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
* * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
*
* Example usage:
*
* ```solidity
* contract MyToken is AccessControlDefaultAdminRules {
* constructor() AccessControlDefaultAdminRules(
* 3 days,
* msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
* ) {}
* }
* ```
*
* _Available since v4.9._
*/
abstract contract AccessControlDefaultAdminRules is IAccessControlDefaultAdminRules, IERC5313, AccessControl {
// pending admin pair read/written together frequently
address private _pendingDefaultAdmin;
uint48 private _pendingDefaultAdminSchedule; // 0 == unset
uint48 private _currentDelay;
address private _currentDefaultAdmin;
// pending delay pair read/written together frequently
uint48 private _pendingDelay;
uint48 private _pendingDelaySchedule; // 0 == unset
/**
* @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
*/
constructor(uint48 initialDelay, address initialDefaultAdmin) {
require(initialDefaultAdmin != address(0), "AccessControl: 0 default admin");
_currentDelay = initialDelay;
_grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC5313-owner}.
*/
function owner() public view virtual returns (address) {
return defaultAdmin();
}
///
/// Override AccessControl role management
///
/**
* @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
require(role != DEFAULT_ADMIN_ROLE, "AccessControl: can't directly grant default admin role");
super.grantRole(role, account);
}
/**
* @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
require(role != DEFAULT_ADMIN_ROLE, "AccessControl: can't directly revoke default admin role");
super.revokeRole(role, account);
}
/**
* @dev See {AccessControl-renounceRole}.
*
* For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
* {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
* has also passed when calling this function.
*
* After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
*
* NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
* thereby disabling any functionality that is only available for it, and the possibility of reassigning a
* non-administrated role.
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
(address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
require(
newDefaultAdmin == address(0) && _isScheduleSet(schedule) && _hasSchedulePassed(schedule),
"AccessControl: only can renounce in two delayed steps"
);
delete _pendingDefaultAdminSchedule;
}
super.renounceRole(role, account);
}
/**
* @dev See {AccessControl-_grantRole}.
*
* For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
* role has been previously renounced.
*
* NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
* assignable again. Make sure to guarantee this is the expected behavior in your implementation.
*/
function _grantRole(bytes32 role, address account) internal virtual override {
if (role == DEFAULT_ADMIN_ROLE) {
require(defaultAdmin() == address(0), "AccessControl: default admin already granted");
_currentDefaultAdmin = account;
}
super._grantRole(role, account);
}
/**
* @dev See {AccessControl-_revokeRole}.
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
delete _currentDefaultAdmin;
}
super._revokeRole(role, account);
}
/**
* @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
require(role != DEFAULT_ADMIN_ROLE, "AccessControl: can't violate default admin rules");
super._setRoleAdmin(role, adminRole);
}
///
/// AccessControlDefaultAdminRules accessors
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdmin() public view virtual returns (address) {
return _currentDefaultAdmin;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelay() public view virtual returns (uint48) {
uint48 schedule = _pendingDelaySchedule;
return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
schedule = _pendingDelaySchedule;
return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? (_pendingDelay, schedule) : (0, 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
return 5 days;
}
///
/// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_beginDefaultAdminTransfer(newAdmin);
}
/**
* @dev See {beginDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
_setPendingDefaultAdmin(newAdmin, newSchedule);
emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_cancelDefaultAdminTransfer();
}
/**
* @dev See {cancelDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _cancelDefaultAdminTransfer() internal virtual {
_setPendingDefaultAdmin(address(0), 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function acceptDefaultAdminTransfer() public virtual {
(address newDefaultAdmin, ) = pendingDefaultAdmin();
require(_msgSender() == newDefaultAdmin, "AccessControl: pending admin must accept");
_acceptDefaultAdminTransfer();
}
/**
* @dev See {acceptDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _acceptDefaultAdminTransfer() internal virtual {
(address newAdmin, uint48 schedule) = pendingDefaultAdmin();
require(_isScheduleSet(schedule) && _hasSchedulePassed(schedule), "AccessControl: transfer delay not passed");
_revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
delete _pendingDefaultAdmin;
delete _pendingDefaultAdminSchedule;
}
///
/// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_changeDefaultAdminDelay(newDelay);
}
/**
* @dev See {changeDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
_setPendingDelay(newDelay, newSchedule);
emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_rollbackDefaultAdminDelay();
}
/**
* @dev See {rollbackDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _rollbackDefaultAdminDelay() internal virtual {
_setPendingDelay(0, 0);
}
/**
* @dev Returns the amount of seconds to wait after the `newDelay` will
* become the new {defaultAdminDelay}.
*
* The value returned guarantees that if the delay is reduced, it will go into effect
* after a wait that honors the previously set delay.
*
* See {defaultAdminDelayIncreaseWait}.
*/
function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
uint48 currentDelay = defaultAdminDelay();
// When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
// to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
// to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
// delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
// using milliseconds instead of seconds.
//
// When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
// that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
// For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
return
newDelay > currentDelay
? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
: currentDelay - newDelay;
}
///
/// Private setters
///
/**
* @dev Setter of the tuple for pending admin and its schedule.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
(, uint48 oldSchedule) = pendingDefaultAdmin();
_pendingDefaultAdmin = newAdmin;
_pendingDefaultAdminSchedule = newSchedule;
// An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
if (_isScheduleSet(oldSchedule)) {
// Emit for implicit cancellations when another default admin was scheduled.
emit DefaultAdminTransferCanceled();
}
}
/**
* @dev Setter of the tuple for pending delay and its schedule.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
uint48 oldSchedule = _pendingDelaySchedule;
if (_isScheduleSet(oldSchedule)) {
if (_hasSchedulePassed(oldSchedule)) {
// Materialize a virtual delay
_currentDelay = _pendingDelay;
} else {
// Emit for implicit cancellations when another delay was scheduled.
emit DefaultAdminDelayChangeCanceled();
}
}
_pendingDelay = newDelay;
_pendingDelaySchedule = newSchedule;
}
///
/// Private helpers
///
/**
* @dev Defines if an `schedule` is considered set. For consistency purposes.
*/
function _isScheduleSet(uint48 schedule) private pure returns (bool) {
return schedule != 0;
}
/**
* @dev Defines if an `schedule` is considered passed. For consistency purposes.
*/
function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
return schedule < block.timestamp;
}
}

View File

@ -1,5 +1,5 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
@ -34,7 +34,7 @@ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessCon
* 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) {
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
@ -42,7 +42,7 @@ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessCon
* @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) {
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}

View File

@ -0,0 +1,172 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/IAccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection.
*
* _Available since v4.9._
*/
interface IAccessControlDefaultAdminRules is IAccessControl {
/**
* @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
* address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
* passes.
*/
event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);
/**
* @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
*/
event DefaultAdminTransferCanceled();
/**
* @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
* delay to be applied between default admin transfer after `effectSchedule` has passed.
*/
event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);
/**
* @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
*/
event DefaultAdminDelayChangeCanceled();
/**
* @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
*/
function defaultAdmin() external view returns (address);
/**
* @dev Returns a tuple of a `newAdmin` and an accept schedule.
*
* After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
* by calling {acceptDefaultAdminTransfer}, completing the role transfer.
*
* A zero value only in `acceptSchedule` indicates no pending admin transfer.
*
* NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
*/
function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);
/**
* @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
*
* This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
* the acceptance schedule.
*
* NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
* function returns the new delay. See {changeDefaultAdminDelay}.
*/
function defaultAdminDelay() external view returns (uint48);
/**
* @dev Returns a tuple of `newDelay` and an effect schedule.
*
* After the `schedule` passes, the `newDelay` will get into effect immediately for every
* new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
*
* A zero value only in `effectSchedule` indicates no pending delay change.
*
* NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
* will be zero after the effect schedule.
*/
function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);
/**
* @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
* after the current timestamp plus a {defaultAdminDelay}.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminRoleChangeStarted event.
*/
function beginDefaultAdminTransfer(address newAdmin) external;
/**
* @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function cancelDefaultAdminTransfer() external;
/**
* @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* After calling the function:
*
* - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
* - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
* - {pendingDefaultAdmin} should be reset to zero values.
*
* Requirements:
*
* - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
* - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
*/
function acceptDefaultAdminTransfer() external;
/**
* @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
* into effect after the current timestamp plus a {defaultAdminDelay}.
*
* This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
* method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
* set before calling.
*
* The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
* calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
* complete transfer (including acceptance).
*
* The schedule is designed for two scenarios:
*
* - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
* {defaultAdminDelayIncreaseWait}.
* - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
*
* A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
*/
function changeDefaultAdminDelay(uint48 newDelay) external;
/**
* @dev Cancels a scheduled {defaultAdminDelay} change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function rollbackDefaultAdminDelay() external;
/**
* @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
* to take effect. Default to 5 days.
*
* When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
* the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
* that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
* be overrode for a custom {defaultAdminDelay} increase scheduling.
*
* IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
* there's a risk of setting a high new delay that goes into effect almost immediately without the
* possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
*/
function defaultAdminDelayIncreaseWait() external view returns (uint48);
}

View File

@ -1,5 +1,5 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
@ -29,6 +29,14 @@ abstract contract Ownable is Context {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
@ -37,19 +45,18 @@ abstract contract Ownable is Context {
}
/**
* @dev Throws if called by any account other than the owner.
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner() {
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));

View File

@ -0,0 +1,57 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
}

View File

@ -12,10 +12,16 @@ This directory provides ways to restrict who can access the functions of a contr
{{Ownable}}
{{Ownable2Step}}
{{IAccessControl}}
{{AccessControl}}
{{AccessControlCrossChain}}
{{IAccessControlEnumerable}}
{{AccessControlEnumerable}}
{{AccessControlDefaultAdminRules}}

View File

@ -0,0 +1,54 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (crosschain/CrossChainEnabled.sol)
pragma solidity ^0.8.4;
import "./errors.sol";
/**
* @dev Provides information for building cross-chain aware contracts. This
* abstract contract provides accessors and modifiers to control the execution
* flow when receiving cross-chain messages.
*
* Actual implementations of cross-chain aware contracts, which are based on
* this abstraction, will have to inherit from a bridge-specific
* specialization. Such specializations are provided under
* `crosschain/<chain>/CrossChainEnabled<chain>.sol`.
*
* _Available since v4.6._
*/
abstract contract CrossChainEnabled {
/**
* @dev Throws if the current function call is not the result of a
* cross-chain execution.
*/
modifier onlyCrossChain() {
if (!_isCrossChain()) revert NotCrossChainCall();
_;
}
/**
* @dev Throws if the current function call is not the result of a
* cross-chain execution initiated by `account`.
*/
modifier onlyCrossChainSender(address expected) {
address actual = _crossChainSender();
if (expected != actual) revert InvalidCrossChainSender(actual, expected);
_;
}
/**
* @dev Returns whether the current function call is the result of a
* cross-chain message.
*/
function _isCrossChain() internal view virtual returns (bool);
/**
* @dev Returns the address of the sender of the cross-chain message that
* triggered the current function call.
*
* IMPORTANT: Should revert with `NotCrossChainCall` if the current function
* call is not the result of a cross-chain message.
*/
function _crossChainSender() internal view virtual returns (address);
}

View File

@ -0,0 +1,34 @@
= Cross Chain Awareness
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/crosschain
This directory provides building blocks to improve cross-chain awareness of smart contracts.
- {CrossChainEnabled} is an abstraction that contains accessors and modifiers to control the execution flow when receiving cross-chain messages.
== CrossChainEnabled specializations
The following specializations of {CrossChainEnabled} provide implementations of the {CrossChainEnabled} abstraction for specific bridges. This can be used to complex cross-chain aware components such as {AccessControlCrossChain}.
{{CrossChainEnabledAMB}}
{{CrossChainEnabledArbitrumL1}}
{{CrossChainEnabledArbitrumL2}}
{{CrossChainEnabledOptimism}}
{{CrossChainEnabledPolygonChild}}
== Libraries for cross-chain
In addition to the {CrossChainEnabled} abstraction, cross-chain awareness is also available through libraries. These libraries can be used to build complex designs such as contracts with the ability to interact with multiple bridges.
{{LibAMB}}
{{LibArbitrumL1}}
{{LibArbitrumL2}}
{{LibOptimism}}

View File

@ -0,0 +1,49 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/amb/CrossChainEnabledAMB.sol)
pragma solidity ^0.8.4;
import "../CrossChainEnabled.sol";
import "./LibAMB.sol";
/**
* @dev https://docs.tokenbridge.net/amb-bridge/about-amb-bridge[AMB]
* specialization or the {CrossChainEnabled} abstraction.
*
* As of february 2020, AMB bridges are available between the following chains:
*
* - https://docs.tokenbridge.net/eth-xdai-amb-bridge/about-the-eth-xdai-amb[ETH ⇌ xDai]
* - https://docs.tokenbridge.net/eth-qdai-bridge/about-the-eth-qdai-amb[ETH ⇌ qDai]
* - https://docs.tokenbridge.net/eth-etc-amb-bridge/about-the-eth-etc-amb[ETH ⇌ ETC]
* - https://docs.tokenbridge.net/eth-bsc-amb/about-the-eth-bsc-amb[ETH ⇌ BSC]
* - https://docs.tokenbridge.net/eth-poa-amb-bridge/about-the-eth-poa-amb[ETH ⇌ POA]
* - https://docs.tokenbridge.net/bsc-xdai-amb/about-the-bsc-xdai-amb[BSC ⇌ xDai]
* - https://docs.tokenbridge.net/poa-xdai-amb/about-the-poa-xdai-amb[POA ⇌ xDai]
* - https://docs.tokenbridge.net/rinkeby-xdai-amb-bridge/about-the-rinkeby-xdai-amb[Rinkeby ⇌ xDai]
* - https://docs.tokenbridge.net/kovan-sokol-amb-bridge/about-the-kovan-sokol-amb[Kovan ⇌ Sokol]
*
* _Available since v4.6._
*/
contract CrossChainEnabledAMB is CrossChainEnabled {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable _bridge;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address bridge) {
_bridge = bridge;
}
/**
* @dev see {CrossChainEnabled-_isCrossChain}
*/
function _isCrossChain() internal view virtual override returns (bool) {
return LibAMB.isCrossChain(_bridge);
}
/**
* @dev see {CrossChainEnabled-_crossChainSender}
*/
function _crossChainSender() internal view virtual override onlyCrossChain returns (address) {
return LibAMB.crossChainSender(_bridge);
}
}

View File

@ -0,0 +1,35 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/amb/LibAMB.sol)
pragma solidity ^0.8.4;
import {IAMB as AMB_Bridge} from "../../vendor/amb/IAMB.sol";
import "../errors.sol";
/**
* @dev Primitives for cross-chain aware contracts using the
* https://docs.tokenbridge.net/amb-bridge/about-amb-bridge[AMB]
* family of bridges.
*/
library LibAMB {
/**
* @dev Returns whether the current function call is the result of a
* cross-chain message relayed by `bridge`.
*/
function isCrossChain(address bridge) internal view returns (bool) {
return msg.sender == bridge;
}
/**
* @dev Returns the address of the sender that triggered the current
* cross-chain message through `bridge`.
*
* NOTE: {isCrossChain} should be checked before trying to recover the
* sender, as it will revert with `NotCrossChainCall` if the current
* function call is not the result of a cross-chain message.
*/
function crossChainSender(address bridge) internal view returns (address) {
if (!isCrossChain(bridge)) revert NotCrossChainCall();
return AMB_Bridge(bridge).messageSender();
}
}

View File

@ -0,0 +1,44 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/arbitrum/CrossChainEnabledArbitrumL1.sol)
pragma solidity ^0.8.4;
import "../CrossChainEnabled.sol";
import "./LibArbitrumL1.sol";
/**
* @dev https://arbitrum.io/[Arbitrum] specialization or the
* {CrossChainEnabled} abstraction the L1 side (mainnet).
*
* This version should only be deployed on L1 to process cross-chain messages
* originating from L2. For the other side, use {CrossChainEnabledArbitrumL2}.
*
* The bridge contract is provided and maintained by the arbitrum team. You can
* find the address of this contract on the rinkeby testnet in
* https://developer.offchainlabs.com/docs/useful_addresses[Arbitrum's developer documentation].
*
* _Available since v4.6._
*/
abstract contract CrossChainEnabledArbitrumL1 is CrossChainEnabled {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable _bridge;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address bridge) {
_bridge = bridge;
}
/**
* @dev see {CrossChainEnabled-_isCrossChain}
*/
function _isCrossChain() internal view virtual override returns (bool) {
return LibArbitrumL1.isCrossChain(_bridge);
}
/**
* @dev see {CrossChainEnabled-_crossChainSender}
*/
function _crossChainSender() internal view virtual override onlyCrossChain returns (address) {
return LibArbitrumL1.crossChainSender(_bridge);
}
}

View File

@ -0,0 +1,40 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (crosschain/arbitrum/CrossChainEnabledArbitrumL2.sol)
pragma solidity ^0.8.4;
import "../CrossChainEnabled.sol";
import "./LibArbitrumL2.sol";
/**
* @dev https://arbitrum.io/[Arbitrum] specialization or the
* {CrossChainEnabled} abstraction the L2 side (arbitrum).
*
* This version should only be deployed on L2 to process cross-chain messages
* originating from L1. For the other side, use {CrossChainEnabledArbitrumL1}.
*
* Arbitrum L2 includes the `ArbSys` contract at a fixed address. Therefore,
* this specialization of {CrossChainEnabled} does not include a constructor.
*
* _Available since v4.6._
*
* WARNING: There is currently a bug in Arbitrum that causes this contract to
* fail to detect cross-chain calls when deployed behind a proxy. This will be
* fixed when the network is upgraded to Arbitrum Nitro, currently scheduled for
* August 31st 2022.
*/
abstract contract CrossChainEnabledArbitrumL2 is CrossChainEnabled {
/**
* @dev see {CrossChainEnabled-_isCrossChain}
*/
function _isCrossChain() internal view virtual override returns (bool) {
return LibArbitrumL2.isCrossChain(LibArbitrumL2.ARBSYS);
}
/**
* @dev see {CrossChainEnabled-_crossChainSender}
*/
function _crossChainSender() internal view virtual override onlyCrossChain returns (address) {
return LibArbitrumL2.crossChainSender(LibArbitrumL2.ARBSYS);
}
}

View File

@ -0,0 +1,42 @@
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (crosschain/arbitrum/LibArbitrumL1.sol)
pragma solidity ^0.8.4;
import {IBridge as ArbitrumL1_Bridge} from "../../vendor/arbitrum/IBridge.sol";
import {IOutbox as ArbitrumL1_Outbox} from "../../vendor/arbitrum/IOutbox.sol";
import "../errors.sol";
/**
* @dev Primitives for cross-chain aware contracts for
* https://arbitrum.io/[Arbitrum].
*
* This version should only be used on L1 to process cross-chain messages
* originating from L2. For the other side, use {LibArbitrumL2}.
*/
library LibArbitrumL1 {
/**
* @dev Returns whether the current function call is the result of a
* cross-chain message relayed by the `bridge`.
*/
function isCrossChain(address bridge) internal view returns (bool) {
return msg.sender == bridge;
}
/**
* @dev Returns the address of the sender that triggered the current
* cross-chain message through the `bridge`.
*
* NOTE: {isCrossChain} should be checked before trying to recover the
* sender, as it will revert with `NotCrossChainCall` if the current
* function call is not the result of a cross-chain message.
*/
function crossChainSender(address bridge) internal view returns (address) {
if (!isCrossChain(bridge)) revert NotCrossChainCall();
address sender = ArbitrumL1_Outbox(ArbitrumL1_Bridge(bridge).activeOutbox()).l2ToL1Sender();
require(sender != address(0), "LibArbitrumL1: system messages without sender");
return sender;
}
}

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