Compare commits
565 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b8b4ba82c | |||
| 212de08e7f | |||
| 8c49ad74ea | |||
| 0b238a536d | |||
| e4748fbba1 | |||
| b9710923a8 | |||
| 4307d74966 | |||
| 1e7d735389 | |||
| 029706d167 | |||
| 97c46a7d00 | |||
| 80c7a3ef43 | |||
| e30ea41e87 | |||
| 6e0f947c25 | |||
| a2b4181f8c | |||
| fac4326b5a | |||
| 7c75b8aa89 | |||
| 08d109d877 | |||
| 3ac4add548 | |||
| 3aa7ff74b0 | |||
| 994cf9b34b | |||
| f6cd8032ba | |||
| 051cc9e446 | |||
| 54ce38c2e5 | |||
| d506e3b1a5 | |||
| 113443470c | |||
| 35090c1bf1 | |||
| 04204b8fb9 | |||
| 5e00787199 | |||
| 62f2c0531b | |||
| 4fc9fd3efe | |||
| 6d00281593 | |||
| 2b0b0bb186 | |||
| 6766b2de3b | |||
| 4942bd19e2 | |||
| 82a63f6389 | |||
| 488dd562fb | |||
| 61294a62af | |||
| f8157ac854 | |||
| 65b45726b3 | |||
| c019e7c5bb | |||
| de74c8c62c | |||
| b61faf8368 | |||
| c4f76cfa15 | |||
| 6339027a7a | |||
| 46db8a98b0 | |||
| c2077f0034 | |||
| ee4d8380d3 | |||
| 5772512058 | |||
| cd2da98d4d | |||
| e633ee9ed3 | |||
| 3bdf4bfd29 | |||
| 3b9381dfb1 | |||
| 07b1b472c0 | |||
| 4574ce45b6 | |||
| 5ed20f32cf | |||
| 14ca3aeb79 | |||
| 1d2ab4f41c | |||
| be3cfa0f90 | |||
| fcf35e5722 | |||
| a035b235b4 | |||
| 848fef5b6c | |||
| 85627ffa91 | |||
| c12076fb7e | |||
| d4e6236b2b | |||
| 5a75065659 | |||
| cb14ea3c5c | |||
| 7392d83738 | |||
| 28dd490726 | |||
| bc810db320 | |||
| dd01889434 | |||
| 731e199038 | |||
| d4d8d2ed97 | |||
| f81b80fb39 | |||
| 3fb25b604b | |||
| 742e85be7c | |||
| 69c3781043 | |||
| 0762479dd5 | |||
| 049701eacd | |||
| f85eb5b725 | |||
| 9af5af8fff | |||
| d2832ca7a9 | |||
| 2bd75a44bb | |||
| 2a4ca65404 | |||
| 3f49408fb6 | |||
| e7719ded56 | |||
| 668a648bc6 | |||
| 02fcc75bb7 | |||
| ae270b0d89 | |||
| e029096ca4 | |||
| 76eee35971 | |||
| bfff03c0d2 | |||
| 76fca3aec8 | |||
| 74c9130a59 | |||
| 15d5174139 | |||
| 05077f70f1 | |||
| faf5820f03 | |||
| 0eba5112c8 | |||
| b13bdb0249 | |||
| c028c56965 | |||
| 98716177ae | |||
| 52eeebecda | |||
| 6a5bbfc4cb | |||
| 8372b4f923 | |||
| cc1c18098c | |||
| c72281ea45 | |||
| f2a311dc4a | |||
| 8b162e39b5 | |||
| 62eb4568be | |||
| f8bfa560e9 | |||
| 212221d6ff | |||
| c239e1af8d | |||
| f590fcdfe9 | |||
| 9bded169e8 | |||
| dc739dcbe3 | |||
| fd07cc6290 | |||
| f9d9279320 | |||
| abdb20a6bd | |||
| 3e74681e77 | |||
| f6b614a7c5 | |||
| 458697be32 | |||
| af7ec04b78 | |||
| eae2384178 | |||
| 6db2d0ea39 | |||
| 3fe65ef467 | |||
| 525a672862 | |||
| aace774961 | |||
| 6fec54f17f | |||
| 58f635312a | |||
| 3dfc0a44f8 | |||
| be3c5ca504 | |||
| 4cb0926f11 | |||
| 5b6112000c | |||
| afb20119b3 | |||
| 718d0ba2a1 | |||
| 591e30b7b6 | |||
| 24f561a9a1 | |||
| 32b4eee9a3 | |||
| c5a6cae898 | |||
| 63b466901f | |||
| defcf20042 | |||
| b119b564df | |||
| 28986d2f2e | |||
| 85566faeb2 | |||
| bfd05d9646 | |||
| 574f3b89e1 | |||
| ca755ce799 | |||
| fc01c51c13 | |||
| 21c5d623d6 | |||
| 4f8af2dceb | |||
| a81b07ce91 | |||
| f55d2716a8 | |||
| ae54e6de1d | |||
| fb950c6166 | |||
| 6fb1e843cf | |||
| 78deae5a76 | |||
| e298476a90 | |||
| a5e042cedf | |||
| d57593c148 | |||
| 7c47ac7193 | |||
| 8f70c8867e | |||
| b3b83b558e | |||
| 783ac759a9 | |||
| 25eeb80b18 | |||
| 3eb2d43b06 | |||
| ecae978cb5 | |||
| e192fac276 | |||
| 3458c1e854 | |||
| dee772a55f | |||
| 1051db3802 | |||
| a8f35b6c25 | |||
| c366de3626 | |||
| 80d8da0564 | |||
| fd7c4ba8f0 | |||
| 8dd744fc18 | |||
| 828fe365ee | |||
| a65c03bc0d | |||
| 1e815f3308 | |||
| d74605641c | |||
| a9f994f063 | |||
| ef0273fde1 | |||
| da3a9ae18b | |||
| e3391cd65f | |||
| e9e177f53b | |||
| fe38eae6cd | |||
| 915ca181ba | |||
| a0a8bbb57f | |||
| 1ffcb10bd2 | |||
| 10c8fcd3b8 | |||
| cafd900ad6 | |||
| e667ec9533 | |||
| 5ac4d93ae3 | |||
| 0550d13aee | |||
| d95cdaae8e | |||
| 4a9cc8b491 | |||
| 6bd6b76d11 | |||
| 13a6ec753a | |||
| bda61cd5e5 | |||
| b42b05311b | |||
| 553c8fdec7 | |||
| 9a7e4a0112 | |||
| e141d8917a | |||
| 08840b9f8c | |||
| 0c858e2071 | |||
| 4625192940 | |||
| 2a09e50d09 | |||
| 04109f8bee | |||
| 8ef7655e7b | |||
| a05312f1b7 | |||
| abf6024faf | |||
| 6089f11c2f | |||
| 3536587665 | |||
| 7d17acfb2f | |||
| 4961a51cc7 | |||
| 94a0b8f573 | |||
| 0859c70936 | |||
| 6481b05e4f | |||
| c739d1976b | |||
| f6db5c1f30 | |||
| 2f2604d673 | |||
| 0413d58860 | |||
| 86bd4d7389 | |||
| 52d42d6e03 | |||
| 4c8642b70a | |||
| a57e638f57 | |||
| a4cee9ed37 | |||
| 6e5bf05211 | |||
| 65ef662a2b | |||
| 8b8ee57a1a | |||
| a94cf0509f | |||
| cf6e32fc54 | |||
| 3a3e643eb9 | |||
| 462d6fa2b2 | |||
| 70138680cf | |||
| e63b09c9ad | |||
| 3db4393b58 | |||
| 57630d2a64 | |||
| 2b4e023180 | |||
| b5daea6d5f | |||
| 4088540aef | |||
| 09e5888ca8 | |||
| ce51655c81 | |||
| 6dab43c3a9 | |||
| 7579828180 | |||
| 342265d290 | |||
| 5cdf2a8fdf | |||
| fbfe19d6db | |||
| ee14987721 | |||
| 5a398018ee | |||
| a73ad8cc8c | |||
| 46ce0cfa33 | |||
| a51e181e3b | |||
| db58acead1 | |||
| 2b046d79e1 | |||
| a56258945a | |||
| 0a87a4e75b | |||
| 7dcc7b372f | |||
| 9e13852135 | |||
| c9bdb1f0ae | |||
| 7fe5326c2d | |||
| b12af48a7d | |||
| 0db97c9681 | |||
| 88e4b69bfb | |||
| e6f26b46fc | |||
| 7006e4e3e6 | |||
| d244b81972 | |||
| 5b28259dac | |||
| efb5b0a28f | |||
| abeb0fbf5c | |||
| caba6b93ef | |||
| e2fa301bfb | |||
| 29eeb2828e | |||
| 75d422feca | |||
| 6f23efa970 | |||
| 1b27c13096 | |||
| f77fd4667e | |||
| 6af4ed6169 | |||
| 01f2ff1ba1 | |||
| 296223f876 | |||
| 0c4de6721d | |||
| 024cc50df4 | |||
| 6241995ad3 | |||
| d02cc020e8 | |||
| bc5c8e2c9c | |||
| 7237b1672e | |||
| 5e34a84d4a | |||
| 38448c104a | |||
| 8a5b67fb79 | |||
| aefcb3e8aa | |||
| fb36326a58 | |||
| 9b4326d91e | |||
| 6edb6dd1ca | |||
| 0ec7f4c25d | |||
| cec4f2ef57 | |||
| 52188a2127 | |||
| 83644fdb6a | |||
| 56d4063e92 | |||
| 1baa009266 | |||
| 1d2e15fbd7 | |||
| e3cbfcd44b | |||
| 4ac1070cd3 | |||
| bb2b687b46 | |||
| 38c1dd098c | |||
| 494cc6d3a5 | |||
| b174f067df | |||
| 7072b623af | |||
| 4a6d82acb9 | |||
| 9253c614d2 | |||
| 049ff9a3c7 | |||
| 73425c22d8 | |||
| 832ff3b9f9 | |||
| 635e36ff08 | |||
| 6618f9f184 | |||
| 7fcacb549b | |||
| 541e82144f | |||
| 18668870fd | |||
| 694f169832 | |||
| 7279273ebb | |||
| d89f2a4ac6 | |||
| 48375aa908 | |||
| 29957d4a47 | |||
| 4b152bd8ce | |||
| f782943099 | |||
| 3da0cf698f | |||
| e1c0f3eaef | |||
| 8bcf0ad7ab | |||
| 56b3b7a487 | |||
| bbd68b721d | |||
| 2d1e82c901 | |||
| 9a385dcb45 | |||
| 3dadd40034 | |||
| 566a774222 | |||
| 865dc9365c | |||
| 0500c9e53e | |||
| d3c5bdf4de | |||
| 7e41bf2259 | |||
| 6c1a634053 | |||
| f88e555234 | |||
| 87826f807a | |||
| b8fdc620aa | |||
| 466cf05912 | |||
| 8467143f2a | |||
| c346c09b01 | |||
| 3935b907d4 | |||
| 4e2641a915 | |||
| 973b0f883a | |||
| 6d97f09195 | |||
| 1c1ebd765d | |||
| 9eba3ef29a | |||
| e4696f7315 | |||
| 23b3807ea7 | |||
| 15b92e4097 | |||
| 922058dbc8 | |||
| b9e2c7896d | |||
| 9fbc1d71c0 | |||
| 3ae911b442 | |||
| eea376911b | |||
| 1db3037808 | |||
| 556e366ce5 | |||
| 6842518b1b | |||
| 8a775cd8d4 | |||
| 4d0f8c1da8 | |||
| 27e09007cc | |||
| 00128bd260 | |||
| f710bafae8 | |||
| 788d338c9b | |||
| 6f50f6e1ef | |||
| fd111df16d | |||
| 17958adaca | |||
| 0a05f6fa45 | |||
| 78103f3137 | |||
| f7da53cebd | |||
| 75f6dbb86c | |||
| 9d5f77db9d | |||
| b0cf6fbb7a | |||
| e3661abe84 | |||
| 1488d4f678 | |||
| adc50d465c | |||
| f6efd8aced | |||
| ad3c18eb5f | |||
| eabec630b9 | |||
| 406c83649b | |||
| 5f50b9f6e0 | |||
| 1b37c21da5 | |||
| 7144ec8db4 | |||
| f31bb101ad | |||
| 7c754d0665 | |||
| 5f7eda1f98 | |||
| f8f6d56c58 | |||
| 8ad458e955 | |||
| 8ea06b75aa | |||
| c3ae4790c7 | |||
| 5cd86f740d | |||
| aa06c9fbc1 | |||
| 100ca0b8a2 | |||
| 8669481309 | |||
| 1dc4a319ab | |||
| 08ba72afa2 | |||
| 0a905d674b | |||
| 319afebdc0 | |||
| f1e92dd184 | |||
| 9048e565d7 | |||
| 95dec684ad | |||
| 0d40f705a7 | |||
| df8a0fe8dc | |||
| 50a9b4d1e7 | |||
| 2e30b9f382 | |||
| 23869e5b2a | |||
| 3ba2a1354f | |||
| 903df56837 | |||
| 4a53ee5a13 | |||
| cfd6e7eab9 | |||
| a98814b930 | |||
| 10c763da6f | |||
| a020a55f9d | |||
| 6552adafb2 | |||
| 5756e31999 | |||
| 8ae9f0914b | |||
| 3c4a18f0df | |||
| 165e6f1948 | |||
| 750a17653d | |||
| 07b48484ff | |||
| a664fb1e45 | |||
| 2e6ef74593 | |||
| 440b65bf77 | |||
| df7996b671 | |||
| 9a698e6b7b | |||
| 915109b2c4 | |||
| 2fa86736dd | |||
| b9125001f0 | |||
| f17624194b | |||
| 7360a2532d | |||
| 72eb905c58 | |||
| ad90dbdaff | |||
| e0a2b195e4 | |||
| 1c676ac0ec | |||
| 538b6d21b1 | |||
| 3157aff844 | |||
| f4898a2e3a | |||
| 555be63c90 | |||
| 057efbfe95 | |||
| 585db1f667 | |||
| 7f6a1666fa | |||
| 0c621246d3 | |||
| 5bd798c6e1 | |||
| 5ecd2b850c | |||
| 243adff49c | |||
| 378531b709 | |||
| 9584c23594 | |||
| 64f20ec624 | |||
| 783e928ae8 | |||
| a673994de5 | |||
| 9b0e27c98c | |||
| a3712a3288 | |||
| 74e03de760 | |||
| 09e302384a | |||
| 3dc374ddcf | |||
| 90a72f9acd | |||
| 7c1625b0e0 | |||
| cd443f0d5b | |||
| d5194725b7 | |||
| 82e3ec3afe | |||
| 682def9f89 | |||
| 96aece07f3 | |||
| 508a879ef0 | |||
| 5171e46c47 | |||
| 1ee939e7c4 | |||
| 59f33c1cc1 | |||
| fb95a8b34b | |||
| d104ced953 | |||
| 1fd54698ff | |||
| 2658e01baa | |||
| 9612b891c9 | |||
| 27fc833550 | |||
| 0b3e0d74b0 | |||
| d75b4cf613 | |||
| 5aab6ff81b | |||
| f076ff5dbd | |||
| b8ab763581 | |||
| 78a9821129 | |||
| 5dbbda5435 | |||
| b1e0aa487d | |||
| 6505e28c40 | |||
| 7adf0d88a0 | |||
| fc004c0ad2 | |||
| f07c39be8a | |||
| 29ffe6f426 | |||
| ec63c604ab | |||
| 69ca2ad676 | |||
| 3d587f3043 | |||
| ae1e384a9a | |||
| 954f6110d6 | |||
| 4390b8df12 | |||
| cb88e15b33 | |||
| 1705067e65 | |||
| 618a735816 | |||
| 136de91049 | |||
| 103ff8e23d | |||
| e2bf45f262 | |||
| cdb929aada | |||
| 93d990c653 | |||
| 62af16b9f2 | |||
| 3dfd02b4b4 | |||
| 7a7bd8f6d7 | |||
| 16312fcfb9 | |||
| a81a88cca0 | |||
| 5acedf5027 | |||
| 566c601d41 | |||
| ba1d773176 | |||
| 583146f9d6 | |||
| c789941d76 | |||
| 232c355b3a | |||
| 773c7265e8 | |||
| 742c436d28 | |||
| 15214a53ce | |||
| 36b855972b | |||
| d5f4862405 | |||
| 735c03fcf3 | |||
| 4a1985f870 | |||
| 4519c237c5 | |||
| ac8279a0a5 | |||
| 7cab19a2e4 | |||
| 4ee9fd77fd | |||
| 556cdf5f1a | |||
| c760fe9a2e | |||
| 24a0bc23cf | |||
| c3178ff942 | |||
| f8cc8b844a | |||
| e341bdc1b7 | |||
| 09734e8028 | |||
| 7d20d0e2d2 | |||
| 0059b17dfc | |||
| e733b24dfe | |||
| f7c8252611 | |||
| e66e3ca523 | |||
| 24660c3e48 | |||
| ee6348a7a0 | |||
| a44303c373 | |||
| f49e9ee41b | |||
| 1ba03b164a | |||
| 9c1e703990 | |||
| f2112be4d8 | |||
| c82895fb65 | |||
| b840341a77 | |||
| ed7623273a | |||
| 9425a7e0ab | |||
| 93438eca0b | |||
| e28615628b | |||
| fa64a1ced0 | |||
| 0f553e7f9e | |||
| f4e57fd529 | |||
| a0e2bca79a | |||
| 63a0343dda | |||
| 5db7413827 | |||
| d163aeb80d | |||
| 60205944bb | |||
| 03832c130c | |||
| 9f93e25b88 | |||
| afaebc3869 | |||
| fdf57a9788 | |||
| 5609cd4c74 | |||
| a0323d446c | |||
| 0db76e98f9 | |||
| bcc7192af7 | |||
| ff300b10e1 | |||
| 974c534210 |
@ -1,11 +1,9 @@
|
||||
{
|
||||
"extends" : [
|
||||
"standard",
|
||||
"plugin:promise/recommended",
|
||||
"standard"
|
||||
],
|
||||
"plugins": [
|
||||
"mocha-no-only",
|
||||
"promise",
|
||||
"mocha"
|
||||
],
|
||||
"env": {
|
||||
"browser" : true,
|
||||
@ -53,7 +51,7 @@
|
||||
"semi": ["error", "always"],
|
||||
"space-before-function-paren": ["error", "always"],
|
||||
|
||||
"mocha-no-only/mocha-no-only": ["error"],
|
||||
"mocha/no-exclusive-tests": ["error"],
|
||||
|
||||
"promise/always-return": "off",
|
||||
"promise/avoid-new": "off",
|
||||
|
||||
4
.github/ISSUE_TEMPLATE/config.yml
vendored
4
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -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
|
||||
|
||||
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -10,5 +10,5 @@ about: Suggest an idea for OpenZeppelin Contracts
|
||||
**📝 Details**
|
||||
<!-- Please describe your feature request in detail. -->
|
||||
|
||||
<!-- Make sure that you have reviewed the OpenZeppelin Contributor Guidelines. -->
|
||||
<!-- Make sure that you have reviewed the OpenZeppelin Contracts Contributor Guidelines. -->
|
||||
<!-- https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CONTRIBUTING.md -->
|
||||
|
||||
20
.github/actions/setup/action.yml
vendored
Normal file
20
.github/actions/setup/action.yml
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
name: Setup
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 14.x
|
||||
cache: npm
|
||||
- uses: actions/cache@v3
|
||||
id: cache
|
||||
with:
|
||||
path: '**/node_modules'
|
||||
key: npm-v3-${{ hashFiles('**/package-lock.json') }}
|
||||
- name: Install dependencies
|
||||
run: npm ci --prefer-offline
|
||||
shell: bash
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
env:
|
||||
SKIP_COMPILE: true
|
||||
58
.github/workflows/checks.yml
vendored
Normal file
58
.github/workflows/checks.yml
vendored
Normal file
@ -0,0 +1,58 @@
|
||||
name: checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- release-v*
|
||||
pull_request: {}
|
||||
workflow_dispatch: {}
|
||||
|
||||
concurrency:
|
||||
group: checks-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable'
|
||||
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
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up environment
|
||||
uses: ./.github/actions/setup
|
||||
- run: npm run test
|
||||
env:
|
||||
FORCE_COLOR: 1
|
||||
ENABLE_GAS_REPORT: true
|
||||
- run: npm run test:inheritance
|
||||
- run: npm run test:generation
|
||||
if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable'
|
||||
|
||||
coverage:
|
||||
if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up environment
|
||||
uses: ./.github/actions/setup
|
||||
- run: npm run coverage
|
||||
env:
|
||||
NODE_OPTIONS: --max_old_space_size=4096
|
||||
- uses: codecov/codecov-action@v3
|
||||
|
||||
slither:
|
||||
if: github.repository != 'OpenZeppelin/openzeppelin-contracts-upgradeable'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up environment
|
||||
uses: ./.github/actions/setup
|
||||
- uses: crytic/slither-action@v0.1.1
|
||||
16
.github/workflows/docs.yml
vendored
Normal file
16
.github/workflows/docs.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
name: Build Docs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [release-v*]
|
||||
|
||||
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
|
||||
46
.github/workflows/test.yml
vendored
46
.github/workflows/test.yml
vendored
@ -1,46 +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: 10.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
|
||||
|
||||
coverage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 10.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
|
||||
- uses: codecov/codecov-action@v1
|
||||
23
.github/workflows/upgradeable.yml
vendored
Normal file
23
.github/workflows/upgradeable.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
name: Upgradeable Trigger
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- release-v*
|
||||
|
||||
jobs:
|
||||
trigger:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: app
|
||||
uses: getsentry/action-github-app-token@v1
|
||||
with:
|
||||
app_id: ${{ secrets.UPGRADEABLE_APP_ID }}
|
||||
private_key: ${{ secrets.UPGRADEABLE_APP_PK }}
|
||||
- run: |
|
||||
curl -X POST \
|
||||
https://api.github.com/repos/OpenZeppelin/openzeppelin-contracts-upgradeable/dispatches \
|
||||
-H 'Accept: application/vnd.github.v3+json' \
|
||||
-H 'Authorization: token ${{ steps.app.outputs.token }}' \
|
||||
-d '{ "event_type": "Update", "client_payload": { "ref": "${{ github.ref }}" } }'
|
||||
7
.gitignore
vendored
7
.gitignore
vendored
@ -54,6 +54,11 @@ allFiredEvents
|
||||
.coverage_cache
|
||||
.coverage_contracts
|
||||
|
||||
# buidler
|
||||
# hardhat
|
||||
cache
|
||||
artifacts
|
||||
|
||||
# Certora
|
||||
.certora*
|
||||
.last_confs
|
||||
certora_*
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
module.exports = {
|
||||
require: 'hardhat/register',
|
||||
timeout: 4000,
|
||||
};
|
||||
|
||||
14
.prettierrc
Normal file
14
.prettierrc
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.sol",
|
||||
"options": {
|
||||
"singleQuote": false,
|
||||
"printWidth": 120,
|
||||
"explicitTypes": "always"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,12 +1,14 @@
|
||||
{
|
||||
"extends": "solhint:recommended",
|
||||
"rules": {
|
||||
"func-order": "off",
|
||||
"mark-callable-contracts": "off",
|
||||
"no-empty-blocks": "off",
|
||||
"compiler-version": "off",
|
||||
"no-unused-vars": "error",
|
||||
"const-name-snakecase": "error",
|
||||
"contract-name-camelcase": "error",
|
||||
"event-name-camelcase": "error",
|
||||
"func-name-mixedcase": "error",
|
||||
"func-param-name-mixedcase": "error",
|
||||
"modifier-name-mixedcase": "error",
|
||||
"private-vars-leading-underscore": "error",
|
||||
"reason-string": "off",
|
||||
"func-visibility": ["error", { "ignoreConstructors": true }]
|
||||
"var-name-mixedcase": "error",
|
||||
"imports-on-top": "error"
|
||||
}
|
||||
}
|
||||
|
||||
255
CHANGELOG.md
255
CHANGELOG.md
@ -1,6 +1,257 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
## 4.7.1 (2022-07-19)
|
||||
|
||||
* `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 a `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))
|
||||
|
||||
### Breaking change
|
||||
|
||||
It is no longer possible to call an `initializer`-protected function from within another `initializer` function outside the context of a constructor. Projects using OpenZeppelin upgradeable proxies should continue to work as is, since in the common case the initializer is invoked in the constructor directly. If this is not the case for you, the suggested change is to use the new `onlyInitializing` modifier in the following way:
|
||||
|
||||
```diff
|
||||
contract A {
|
||||
- function initialize() public initializer { ... }
|
||||
+ function initialize() internal onlyInitializing { ... }
|
||||
}
|
||||
contract B is A {
|
||||
function initialize() public initializer {
|
||||
A.initialize();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 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))
|
||||
|
||||
## 4.3.3
|
||||
|
||||
* `ERC1155Supply`: Handle `totalSupply` changes by hooking into `_beforeTokenTransfer` to ensure consistency of balances and supply during `IERC1155Receiver.onERC1155Received` calls.
|
||||
|
||||
## 4.3.2 (2021-09-14)
|
||||
|
||||
* `UUPSUpgradeable`: Add modifiers to prevent `upgradeTo` and `upgradeToAndCall` being executed on any contract that is not the active ERC1967 proxy. This prevents these functions being called on implementation contracts or minimal ERC1167 clones, in particular.
|
||||
|
||||
## 4.3.1 (2021-08-26)
|
||||
|
||||
* `TimelockController`: Add additional isOperationReady check.
|
||||
|
||||
## 4.3.0 (2021-08-17)
|
||||
|
||||
* `ERC2771Context`: use private variable from storage to store the forwarder address. Fixes issues where `_msgSender()` was not callable from constructors. ([#2754](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2754))
|
||||
* `EnumerableSet`: add `values()` functions that returns an array containing all values in a single call. ([#2768](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2768))
|
||||
* `Governor`: added a modular system of `Governor` contracts based on `GovernorAlpha` and `GovernorBravo`. ([#2672](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2672))
|
||||
* Add an `interfaces` folder containing solidity interfaces to final ERCs. ([#2517](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2517))
|
||||
* `ECDSA`: add `tryRecover` functions that will not throw if the signature is invalid, and will return an error flag instead. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661))
|
||||
* `SignatureChecker`: Reduce gas usage of the `isValidSignatureNow` function for the "signature by EOA" case. ([#2661](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2661))
|
||||
|
||||
## 4.2.0 (2021-06-30)
|
||||
|
||||
* `ERC20Votes`: add a new extension of the `ERC20` token with support for voting snapshots and delegation. ([#2632](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2632))
|
||||
* `ERC20VotesComp`: Variant of `ERC20Votes` that is compatible with Compound's `Comp` token interface but restricts supply to `uint96`. ([#2706](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2706))
|
||||
* `ERC20Wrapper`: add a new extension of the `ERC20` token which wraps an underlying token. Deposit and withdraw guarantee that the total supply is backed by a corresponding amount of underlying token. ([#2633](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2633))
|
||||
* Enumerables: Improve gas cost of removal in `EnumerableSet` and `EnumerableMap`.
|
||||
* Enumerables: Improve gas cost of lookup in `EnumerableSet` and `EnumerableMap`.
|
||||
* `Counter`: add a reset method. ([#2678](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2678))
|
||||
* Tokens: Wrap definitely safe subtractions in `unchecked` blocks.
|
||||
* `Math`: Add a `ceilDiv` method for performing ceiling division.
|
||||
* `ERC1155Supply`: add a new `ERC1155` extension that keeps track of the totalSupply of each tokenId. ([#2593](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2593))
|
||||
* `BitMaps`: add a new `BitMaps` library that provides a storage efficient datastructure for `uint256` to `bool` mapping with contiguous keys. ([#2710](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2710))
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
* `ERC20FlashMint` is no longer a Draft ERC. ([#2673](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2673)))
|
||||
|
||||
**How to update:** Change your import paths by removing the `draft-` prefix from `@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20FlashMint.sol`.
|
||||
|
||||
> See [Releases and Stability: Drafts](https://docs.openzeppelin.com/contracts/4.x/releases-stability#drafts).
|
||||
|
||||
## 4.1.0 (2021-04-29)
|
||||
|
||||
* `IERC20Metadata`: add a new extended interface that includes the optional `name()`, `symbol()` and `decimals()` functions. ([#2561](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2561))
|
||||
* `ERC777`: make reception acquirement optional in `_mint`. ([#2552](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2552))
|
||||
* `ERC20Permit`: add a `_useNonce` to enable further usage of ERC712 signatures. ([#2565](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2565))
|
||||
* `ERC20FlashMint`: add an implementation of the ERC3156 extension for flash-minting ERC20 tokens. ([#2543](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2543))
|
||||
* `SignatureChecker`: add a signature verification library that supports both EOA and ERC1271 compliant contracts as signers. ([#2532](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2532))
|
||||
* `Multicall`: add abstract contract with `multicall(bytes[] calldata data)` function to bundle multiple calls together ([#2608](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2608))
|
||||
* `ECDSA`: add support for ERC2098 short-signatures. ([#2582](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2582))
|
||||
* `AccessControl`: add a `onlyRole` modifier to restrict specific function to callers bearing a specific role. ([#2609](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2609))
|
||||
* `StorageSlot`: add a library for reading and writing primitive types to specific storage slots. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542))
|
||||
* UUPS Proxies: add `UUPSUpgradeable` to implement the UUPS proxy pattern together with `EIP1967Proxy`. ([#2542](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2542))
|
||||
|
||||
### Breaking changes
|
||||
|
||||
This release includes two small breaking changes in `TimelockController`.
|
||||
|
||||
1. The `onlyRole` modifier in this contract was designed to let anyone through if the role was granted to `address(0)`,
|
||||
allowing the possibility to to make a role "open", which can be used for `EXECUTOR_ROLE`. This modifier is now
|
||||
replaced by `AccessControl.onlyRole`, which does not have this ability. The previous behavior was moved to the
|
||||
modifier `TimelockController.onlyRoleOrOpenRole`.
|
||||
2. It was possible to make `PROPOSER_ROLE` an open role (as described in the previous item) if it was granted to
|
||||
`address(0)`. This would affect the `schedule`, `scheduleBatch`, and `cancel` operations in `TimelockController`.
|
||||
This ability was removed as it does not make sense to open up the `PROPOSER_ROLE` in the same way that it does for
|
||||
`EXECUTOR_ROLE`.
|
||||
|
||||
## 4.0.0 (2021-03-23)
|
||||
|
||||
* Now targeting the 0.8.x line of Solidity compilers. For 0.6.x (resp 0.7.x) support, use version 3.4.0 (resp 3.4.0-solc-0.7) of OpenZeppelin.
|
||||
* `Context`: making `_msgData` return `bytes calldata` instead of `bytes memory` ([#2492](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2492))
|
||||
* `ERC20`: removed the `_setDecimals` function and the storage slot associated to decimals. ([#2502](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2502))
|
||||
* `Strings`: addition of a `toHexString` function. ([#2504](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2504))
|
||||
* `EnumerableMap`: change implementation to optimize for `key → value` lookups instead of enumeration. ([#2518](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2518))
|
||||
* `GSN`: deprecate GSNv1 support in favor of upcoming support for GSNv2. ([#2521](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2521))
|
||||
* `ERC165`: remove uses of storage in the base ERC165 implementation. ERC165 based contracts now use storage-less virtual functions. Old behavior remains available in the `ERC165Storage` extension. ([#2505](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2505))
|
||||
* `Initializable`: make initializer check stricter during construction. ([#2531](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2531))
|
||||
* `ERC721`: remove enumerability of tokens from the base implementation. This feature is now provided separately through the `ERC721Enumerable` extension. ([#2511](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2511))
|
||||
* `AccessControl`: removed enumerability by default for a more lightweight contract. It is now opt-in through `AccessControlEnumerable`. ([#2512](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2512))
|
||||
* Meta Transactions: add `ERC2771Context` and a `MinimalForwarder` for meta-transactions. ([#2508](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2508))
|
||||
* Overall reorganization of the contract folder to improve clarity and discoverability. ([#2503](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2503))
|
||||
* `ERC20Capped`: optimize gas usage by enforcing the check directly in `_mint`. ([#2524](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2524))
|
||||
* Rename `UpgradeableProxy` to `ERC1967Proxy`. ([#2547](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2547))
|
||||
* `ERC777`: optimize the gas costs of the constructor. ([#2551](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2551))
|
||||
* `ERC721URIStorage`: add a new extension that implements the `_setTokenURI` behavior as it was available in 3.4.0. ([#2555](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2555))
|
||||
* `AccessControl`: added ERC165 interface detection. ([#2562](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2562))
|
||||
* `ERC1155`: make `uri` public so overloading function can call it using super. ([#2576](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2576))
|
||||
|
||||
### Bug fixes for beta releases
|
||||
|
||||
* `AccessControlEnumerable`: Fixed `renounceRole` not updating enumerable set of addresses for a role. ([#2572](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2572))
|
||||
|
||||
### How to upgrade from 3.x
|
||||
|
||||
Since this version has moved a few contracts to different directories, users upgrading from a previous version will need to adjust their import statements. To make this easier, the package includes a script that will migrate import statements automatically. After upgrading to the latest version of the package, run:
|
||||
|
||||
```
|
||||
npx openzeppelin-contracts-migrate-imports
|
||||
```
|
||||
|
||||
Make sure you're using git or another version control system to be able to recover from any potential error in our script.
|
||||
|
||||
### How to upgrade from 4.0-beta.x
|
||||
|
||||
Some further changes have been done between the different beta iterations. Transitions made during this period are configured in the `migrate-imports` script. Consequently, you can upgrade from any previous 4.0-beta.x version using the same script as described in the *How to upgrade from 3.x* section.
|
||||
|
||||
## 3.4.2
|
||||
|
||||
* `TimelockController`: Add additional isOperationReady check.
|
||||
|
||||
## 3.4.1 (2021-03-03)
|
||||
|
||||
* `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))
|
||||
@ -250,7 +501,7 @@ Refer to the table below to adjust your inheritance list.
|
||||
* `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))
|
||||
* 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))
|
||||
|
||||
@ -49,9 +49,9 @@ npm run lint
|
||||
*IMPORTANT* Read the PR template very carefully and make sure to follow all the instructions. These instructions
|
||||
refer to some very important conditions that your PR must meet in order to be accepted, such as making sure that all tests pass, JS linting tests pass, Solidity linting tests pass, etc.
|
||||
|
||||
6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin.
|
||||
6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin Contracts.
|
||||
|
||||
*IMPORTANT* Please pay attention to the maintainer's feedback, since its a necessary step to keep up with the standards OpenZeppelin attains to.
|
||||
*IMPORTANT* Please pay attention to the maintainer's feedback, since it's a necessary step to keep up with the standards OpenZeppelin Contracts attains to.
|
||||
|
||||
## All set!
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
Design Guidelines
|
||||
=======
|
||||
|
||||
These are some global design goals in OpenZeppelin.
|
||||
These are some global design goals in OpenZeppelin Contracts.
|
||||
|
||||
#### D0 - Security in Depth
|
||||
We strive to provide secure, tested, audited code. To achieve this, we need to match intention with function. Thus, documentation, code clarity, community review and security discussions are fundamental.
|
||||
|
||||
2
LICENSE
2
LICENSE
@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2020 zOS Global Limited
|
||||
Copyright (c) 2016-2022 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
|
||||
|
||||
22
README.md
22
README.md
@ -9,8 +9,10 @@
|
||||
* Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721).
|
||||
* Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme.
|
||||
* Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems.
|
||||
* First-class integration with the [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn) for systems with no gas fees!
|
||||
* [Audited](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/audit) by leading security firms (_last full audit on v2.0.0_).
|
||||
|
||||
:mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator.
|
||||
|
||||
: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
|
||||
|
||||
@ -22,12 +24,14 @@ $ 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.
|
||||
|
||||
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
|
||||
|
||||
Once installed, you can use the contracts in the library by importing them:
|
||||
|
||||
```solidity
|
||||
pragma solidity ^0.7.0;
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
|
||||
|
||||
@ -60,18 +64,20 @@ Finally, you may want to take a look at the [guides on our blog](https://blog.op
|
||||
|
||||
## Security
|
||||
|
||||
This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience.
|
||||
This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin Contracts is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience.
|
||||
|
||||
The core development principles and strategies that OpenZeppelin is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits.
|
||||
The core development principles and strategies that OpenZeppelin Contracts is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits.
|
||||
|
||||
The latest audit was done on October 2018 on version 2.0.0.
|
||||
|
||||
Please report any security issues you find to security@openzeppelin.org.
|
||||
We have a [**bug bounty program** on Immunefi](https://www.immunefi.com/bounty/openzeppelin). Please report any security issues you find through the Immunefi dashboard, or reach out to security@openzeppelin.com.
|
||||
|
||||
Critical bug fixes will be backported to past major releases.
|
||||
|
||||
## Contribute
|
||||
|
||||
OpenZeppelin exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)!
|
||||
OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)!
|
||||
|
||||
## License
|
||||
|
||||
OpenZeppelin is released under the [MIT License](LICENSE).
|
||||
OpenZeppelin Contracts is released under the [MIT License](LICENSE).
|
||||
|
||||
@ -10,10 +10,10 @@ Publish a release candidate with `npm run release rc`.
|
||||
|
||||
Publish the final release with `npm run release final`.
|
||||
|
||||
Follow the general [OpenZeppelin release checklist].
|
||||
Follow the general [OpenZeppelin Contracts release checklist].
|
||||
|
||||
[details about release schedule]: https://docs.openzeppelin.com/contracts/releases-stability
|
||||
[OpenZeppelin release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md
|
||||
[OpenZeppelin Contracts release checklist]: https://github.com/OpenZeppelin/code-style/blob/master/RELEASE_CHECKLIST.md
|
||||
|
||||
|
||||
## Merging the release branch
|
||||
|
||||
20
SECURITY.md
Normal file
20
SECURITY.md
Normal file
@ -0,0 +1,20 @@
|
||||
# Security Policy
|
||||
|
||||
## Bug Bounty
|
||||
|
||||
We have a [**bug bounty program** on Immunefi](https://www.immunefi.com/bounty/openzeppelin). Please report any security issues you find through the Immunefi dashboard, or reach out to security@openzeppelin.com.
|
||||
|
||||
Critical bug fixes will be backported to past major releases.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
The recommendation is to use the latest version available.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------------------------ |
|
||||
| 4.x | :white_check_mark::white_check_mark: |
|
||||
| 3.4 | :white_check_mark: |
|
||||
| 2.5 | :white_check_mark: |
|
||||
| < 2.0 | :x: |
|
||||
|
||||
Note that the Solidity language itself only guarantees security updates for the latest release.
|
||||
@ -1,5 +1,7 @@
|
||||
# OpenZeppelin Audit
|
||||
|
||||
NOTE ON 2021-07-19: This report makes reference to Zeppelin, OpenZeppelin, OpenZeppelin [C]ontracts, the OpenZeppelin team, and OpenZeppelin library. Many of these things have since been renamed and know that this audit applies to what is currently called the OpenZeppelin Contracts which are maintained by the OpenZeppelin Conracts Community.
|
||||
|
||||
March, 2017
|
||||
Authored by Dennis Peterson and Peter Vessenes
|
||||
|
||||
@ -131,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
|
||||
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
usePlugin('solidity-coverage');
|
||||
usePlugin('@nomiclabs/buidler-truffle5');
|
||||
|
||||
for (const f of fs.readdirSync(path.join(__dirname, 'buidler'))) {
|
||||
require(path.join(__dirname, 'buidler', f));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
networks: {
|
||||
buidlerevm: {
|
||||
blockGasLimit: 10000000,
|
||||
},
|
||||
},
|
||||
solc: {
|
||||
version: '0.7.4',
|
||||
},
|
||||
};
|
||||
24
certora/Makefile
Normal file
24
certora/Makefile
Normal file
@ -0,0 +1,24 @@
|
||||
default: help
|
||||
|
||||
PATCH = applyHarness.patch
|
||||
CONTRACTS_DIR = ../contracts
|
||||
MUNGED_DIR = munged
|
||||
|
||||
help:
|
||||
@echo "usage:"
|
||||
@echo " make clean: remove all generated files (those ignored by git)"
|
||||
@echo " make $(MUNGED_DIR): create $(MUNGED_DIR) directory by applying the patch file to $(CONTRACTS_DIR)"
|
||||
@echo " make record: record a new patch file capturing the differences between $(CONTRACTS_DIR) and $(MUNGED_DIR)"
|
||||
|
||||
munged: $(wildcard $(CONTRACTS_DIR)/*.sol) $(PATCH)
|
||||
rm -rf $@
|
||||
cp -r $(CONTRACTS_DIR) $@
|
||||
patch -p0 -d $@ < $(PATCH)
|
||||
|
||||
record:
|
||||
diff -ruN $(CONTRACTS_DIR) $(MUNGED_DIR) | sed 's+../contracts/++g' | sed 's+munged/++g' > $(PATCH)
|
||||
|
||||
clean:
|
||||
git clean -fdX
|
||||
touch $(PATCH)
|
||||
|
||||
56
certora/README.md
Normal file
56
certora/README.md
Normal file
@ -0,0 +1,56 @@
|
||||
# Running the certora verification tool
|
||||
|
||||
These instructions detail the process for running CVT on the OpenZeppelin (Wizard/Governor) contracts.
|
||||
|
||||
Documentation for CVT and the specification language are available
|
||||
[here](https://certora.atlassian.net/wiki/spaces/CPD/overview)
|
||||
|
||||
## Running the verification
|
||||
|
||||
The scripts in the `certora/scripts` directory are used to submit verification
|
||||
jobs to the Certora verification service. After the job is complete, the results will be available on
|
||||
[the Certora portal](https://vaas-stg.certora.com/).
|
||||
|
||||
These scripts should be run from the root directory; for example by running
|
||||
|
||||
```
|
||||
sh certora/scripts/verifyAll.sh <meaningful comment>
|
||||
```
|
||||
|
||||
The most important of these is `verifyAll.sh`, which checks
|
||||
all of the harnessed contracts (`certora/harness/Wizard*.sol`) against all of
|
||||
the specifications (`certora/spec/*.spec`).
|
||||
|
||||
The other scripts run a subset of the specifications or the contracts. You can
|
||||
verify different contracts or specifications by changing the `--verify` option,
|
||||
and you can run a single rule or method with the `--rule` or `--method` option.
|
||||
|
||||
For example, to verify the `WizardFirstPriority` contract against the
|
||||
`GovernorCountingSimple` specification, you could change the `--verify` line of
|
||||
the `WizardControlFirstPriortity.sh` script to:
|
||||
|
||||
```
|
||||
--verify WizardFirstPriority:certora/specs/GovernorCountingSimple.spec \
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
When one of the `verify` scripts is executed, it first applies the patch file
|
||||
`certora/applyHarness.patch` to the `contracts` directory, placing the output
|
||||
in the `certora/munged` directory. We then verify the contracts in the
|
||||
`certora/munged` 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 `munged` 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.
|
||||
101
certora/applyHarness.patch
Normal file
101
certora/applyHarness.patch
Normal file
@ -0,0 +1,101 @@
|
||||
diff -ruN .gitignore .gitignore
|
||||
--- .gitignore 1969-12-31 19:00:00.000000000 -0500
|
||||
+++ .gitignore 2021-12-09 14:46:33.923637220 -0500
|
||||
@@ -0,0 +1,2 @@
|
||||
+*
|
||||
+!.gitignore
|
||||
diff -ruN governance/compatibility/GovernorCompatibilityBravo.sol governance/compatibility/GovernorCompatibilityBravo.sol
|
||||
--- governance/compatibility/GovernorCompatibilityBravo.sol 2021-12-03 15:24:56.523654357 -0500
|
||||
+++ governance/compatibility/GovernorCompatibilityBravo.sol 2021-12-09 14:46:33.923637220 -0500
|
||||
@@ -245,7 +245,7 @@
|
||||
/**
|
||||
* @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum.
|
||||
*/
|
||||
- function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
+ function _quorumReached(uint256 proposalId) public view virtual override returns (bool) { // HARNESS: changed to public from internal
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
return quorum(proposalSnapshot(proposalId)) <= details.forVotes;
|
||||
}
|
||||
@@ -253,7 +253,7 @@
|
||||
/**
|
||||
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
|
||||
*/
|
||||
- function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
+ function _voteSucceeded(uint256 proposalId) public view virtual override returns (bool) { // HARNESS: changed to public from internal
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
return details.forVotes > details.againstVotes;
|
||||
}
|
||||
diff -ruN governance/extensions/GovernorCountingSimple.sol governance/extensions/GovernorCountingSimple.sol
|
||||
--- governance/extensions/GovernorCountingSimple.sol 2021-12-03 15:24:56.523654357 -0500
|
||||
+++ governance/extensions/GovernorCountingSimple.sol 2021-12-09 14:46:33.923637220 -0500
|
||||
@@ -64,7 +64,7 @@
|
||||
/**
|
||||
* @dev See {Governor-_quorumReached}.
|
||||
*/
|
||||
- function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
+ function _quorumReached(uint256 proposalId) public view virtual override returns (bool) {
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
|
||||
return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes;
|
||||
@@ -73,7 +73,7 @@
|
||||
/**
|
||||
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes.
|
||||
*/
|
||||
- function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
+ function _voteSucceeded(uint256 proposalId) public view virtual override returns (bool) {
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
|
||||
return proposalvote.forVotes > proposalvote.againstVotes;
|
||||
diff -ruN governance/extensions/GovernorTimelockControl.sol governance/extensions/GovernorTimelockControl.sol
|
||||
--- governance/extensions/GovernorTimelockControl.sol 2021-12-03 15:24:56.523654357 -0500
|
||||
+++ governance/extensions/GovernorTimelockControl.sol 2021-12-09 14:46:33.923637220 -0500
|
||||
@@ -111,7 +111,7 @@
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override {
|
||||
- _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
|
||||
+ _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
diff -ruN governance/Governor.sol governance/Governor.sol
|
||||
--- governance/Governor.sol 2021-12-03 15:24:56.523654357 -0500
|
||||
+++ governance/Governor.sol 2021-12-09 14:46:56.411503587 -0500
|
||||
@@ -38,8 +38,8 @@
|
||||
|
||||
string private _name;
|
||||
|
||||
- mapping(uint256 => ProposalCore) private _proposals;
|
||||
-
|
||||
+ mapping(uint256 => ProposalCore) public _proposals;
|
||||
+
|
||||
/**
|
||||
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
|
||||
* sure this modifier is consistent with the execution model.
|
||||
@@ -167,12 +167,12 @@
|
||||
/**
|
||||
* @dev Amount of votes already cast passes the threshold limit.
|
||||
*/
|
||||
- function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
|
||||
+ function _quorumReached(uint256 proposalId) public view virtual returns (bool); // HARNESS: changed to public from internal
|
||||
|
||||
/**
|
||||
* @dev Is the proposal successful or not.
|
||||
*/
|
||||
- function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
|
||||
+ function _voteSucceeded(uint256 proposalId) public view virtual returns (bool); // HARNESS: changed to public from internal
|
||||
|
||||
/**
|
||||
* @dev Register a vote with a given support and voting weight.
|
||||
diff -ruN token/ERC20/extensions/ERC20Votes.sol token/ERC20/extensions/ERC20Votes.sol
|
||||
--- token/ERC20/extensions/ERC20Votes.sol 2021-12-03 15:24:56.527654330 -0500
|
||||
+++ token/ERC20/extensions/ERC20Votes.sol 2021-12-09 14:46:33.927637196 -0500
|
||||
@@ -84,7 +84,7 @@
|
||||
*
|
||||
* - `blockNumber` must have been already mined
|
||||
*/
|
||||
- function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
|
||||
+ function getPastVotes(address account, uint256 blockNumber) public view virtual returns (uint256) {
|
||||
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
|
||||
return _checkpointsLookup(_checkpoints[account], blockNumber);
|
||||
}
|
||||
28
certora/harnesses/ERC20VotesHarness.sol
Normal file
28
certora/harnesses/ERC20VotesHarness.sol
Normal file
@ -0,0 +1,28 @@
|
||||
import "../munged/token/ERC20/extensions/ERC20Votes.sol";
|
||||
|
||||
contract ERC20VotesHarness is ERC20Votes {
|
||||
constructor(string memory name, string memory symbol) ERC20Permit(name) ERC20(name, symbol) {}
|
||||
|
||||
mapping(address => mapping(uint256 => uint256)) public _getPastVotes;
|
||||
|
||||
function _afterTokenTransfer(
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount
|
||||
) internal virtual override {
|
||||
super._afterTokenTransfer(from, to, amount);
|
||||
_getPastVotes[from][block.number] -= amount;
|
||||
_getPastVotes[to][block.number] += amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Change delegation for `delegator` to `delegatee`.
|
||||
*
|
||||
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
|
||||
*/
|
||||
function _delegate(address delegator, address delegatee) internal virtual override{
|
||||
super._delegate(delegator, delegatee);
|
||||
_getPastVotes[delegator][block.number] -= balanceOf(delegator);
|
||||
_getPastVotes[delegatee][block.number] += balanceOf(delegator);
|
||||
}
|
||||
}
|
||||
150
certora/harnesses/WizardControlFirstPriority.sol
Normal file
150
certora/harnesses/WizardControlFirstPriority.sol
Normal file
@ -0,0 +1,150 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.2;
|
||||
|
||||
import "../munged/governance/Governor.sol";
|
||||
import "../munged/governance/extensions/GovernorCountingSimple.sol";
|
||||
import "../munged/governance/extensions/GovernorVotes.sol";
|
||||
import "../munged/governance/extensions/GovernorVotesQuorumFraction.sol";
|
||||
import "../munged/governance/extensions/GovernorTimelockControl.sol";
|
||||
import "../munged/governance/extensions/GovernorProposalThreshold.sol";
|
||||
|
||||
/*
|
||||
Wizard options:
|
||||
ProposalThreshhold = 10
|
||||
ERC20Votes
|
||||
TimelockController
|
||||
*/
|
||||
|
||||
contract WizardControlFirstPriority is Governor, GovernorProposalThreshold, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl {
|
||||
constructor(ERC20Votes _token, TimelockController _timelock, string memory name, uint256 quorumFraction)
|
||||
Governor(name)
|
||||
GovernorVotes(_token)
|
||||
GovernorVotesQuorumFraction(quorumFraction)
|
||||
GovernorTimelockControl(_timelock)
|
||||
{}
|
||||
|
||||
//HARNESS
|
||||
|
||||
function isExecuted(uint256 proposalId) public view returns (bool) {
|
||||
return _proposals[proposalId].executed;
|
||||
}
|
||||
|
||||
function isCanceled(uint256 proposalId) public view returns (bool) {
|
||||
return _proposals[proposalId].canceled;
|
||||
}
|
||||
|
||||
uint256 _votingDelay;
|
||||
|
||||
uint256 _votingPeriod;
|
||||
|
||||
uint256 _proposalThreshold;
|
||||
|
||||
mapping(uint256 => uint256) public ghost_sum_vote_power_by_id;
|
||||
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason
|
||||
) internal override virtual returns (uint256) {
|
||||
|
||||
uint256 deltaWeight = super._castVote(proposalId, account, support, reason); //HARNESS
|
||||
ghost_sum_vote_power_by_id[proposalId] += deltaWeight;
|
||||
|
||||
return deltaWeight;
|
||||
}
|
||||
|
||||
function snapshot(uint256 proposalId) public view returns (uint64) {
|
||||
return _proposals[proposalId].voteStart._deadline;
|
||||
}
|
||||
|
||||
|
||||
function getExecutor() public view returns (address){
|
||||
return _executor();
|
||||
}
|
||||
|
||||
// original code, harnessed
|
||||
|
||||
function votingDelay() public view override returns (uint256) { // HARNESS: pure -> view
|
||||
return _votingDelay; // HARNESS: parametric
|
||||
}
|
||||
|
||||
function votingPeriod() public view override returns (uint256) { // HARNESS: pure -> view
|
||||
return _votingPeriod; // HARNESS: parametric
|
||||
}
|
||||
|
||||
function proposalThreshold() public view override returns (uint256) { // HARNESS: pure -> view
|
||||
return _proposalThreshold; // HARNESS: parametric
|
||||
}
|
||||
|
||||
// original code, not harnessed
|
||||
// The following functions are overrides required by Solidity.
|
||||
|
||||
function quorum(uint256 blockNumber)
|
||||
public
|
||||
view
|
||||
override(IGovernor, GovernorVotesQuorumFraction)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.quorum(blockNumber);
|
||||
}
|
||||
|
||||
function getVotes(address account, uint256 blockNumber)
|
||||
public
|
||||
view
|
||||
override(IGovernor, GovernorVotes)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.getVotes(account, blockNumber);
|
||||
}
|
||||
|
||||
function state(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
override(Governor, GovernorTimelockControl)
|
||||
returns (ProposalState)
|
||||
{
|
||||
return super.state(proposalId);
|
||||
}
|
||||
|
||||
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description)
|
||||
public
|
||||
override(Governor, GovernorProposalThreshold, IGovernor)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.propose(targets, values, calldatas, description);
|
||||
}
|
||||
|
||||
function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
|
||||
internal
|
||||
override(Governor, GovernorTimelockControl)
|
||||
{
|
||||
super._execute(proposalId, targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
|
||||
function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
|
||||
internal
|
||||
override(Governor, GovernorTimelockControl)
|
||||
returns (uint256)
|
||||
{
|
||||
return super._cancel(targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
|
||||
function _executor()
|
||||
internal
|
||||
view
|
||||
override(Governor, GovernorTimelockControl)
|
||||
returns (address)
|
||||
{
|
||||
return super._executor();
|
||||
}
|
||||
|
||||
function supportsInterface(bytes4 interfaceId)
|
||||
public
|
||||
view
|
||||
override(Governor, GovernorTimelockControl)
|
||||
returns (bool)
|
||||
{
|
||||
return super.supportsInterface(interfaceId);
|
||||
}
|
||||
}
|
||||
141
certora/harnesses/WizardFirstTry.sol
Normal file
141
certora/harnesses/WizardFirstTry.sol
Normal file
@ -0,0 +1,141 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.2;
|
||||
|
||||
import "../munged/governance/Governor.sol";
|
||||
import "../munged/governance/extensions/GovernorCountingSimple.sol";
|
||||
import "../munged/governance/extensions/GovernorVotes.sol";
|
||||
import "../munged/governance/extensions/GovernorVotesQuorumFraction.sol";
|
||||
import "../munged/governance/extensions/GovernorTimelockCompound.sol";
|
||||
|
||||
/*
|
||||
Wizard options:
|
||||
ERC20Votes
|
||||
TimelockCompound
|
||||
*/
|
||||
|
||||
contract WizardFirstTry is Governor, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockCompound {
|
||||
constructor(ERC20Votes _token, ICompoundTimelock _timelock, string memory name, uint256 quorumFraction)
|
||||
Governor(name)
|
||||
GovernorVotes(_token)
|
||||
GovernorVotesQuorumFraction(quorumFraction)
|
||||
GovernorTimelockCompound(_timelock)
|
||||
{}
|
||||
|
||||
//HARNESS
|
||||
|
||||
function isExecuted(uint256 proposalId) public view returns (bool) {
|
||||
return _proposals[proposalId].executed;
|
||||
}
|
||||
|
||||
function isCanceled(uint256 proposalId) public view returns (bool) {
|
||||
return _proposals[proposalId].canceled;
|
||||
}
|
||||
|
||||
function snapshot(uint256 proposalId) public view returns (uint64) {
|
||||
return _proposals[proposalId].voteStart._deadline;
|
||||
}
|
||||
|
||||
function getExecutor() public view returns (address){
|
||||
return _executor();
|
||||
}
|
||||
|
||||
uint256 _votingDelay;
|
||||
|
||||
uint256 _votingPeriod;
|
||||
|
||||
mapping(uint256 => uint256) public ghost_sum_vote_power_by_id;
|
||||
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason
|
||||
) internal override virtual returns (uint256) {
|
||||
|
||||
uint256 deltaWeight = super._castVote(proposalId, account, support, reason); //HARNESS
|
||||
ghost_sum_vote_power_by_id[proposalId] += deltaWeight;
|
||||
|
||||
return deltaWeight;
|
||||
}
|
||||
|
||||
// original code, harnessed
|
||||
|
||||
function votingDelay() public view override virtual returns (uint256) { // HARNESS: pure -> view
|
||||
return _votingDelay; // HARNESS: parametric
|
||||
}
|
||||
|
||||
function votingPeriod() public view override virtual returns (uint256) { // HARNESS: pure -> view
|
||||
return _votingPeriod; // HARNESS: parametric
|
||||
}
|
||||
|
||||
// original code, not harnessed
|
||||
// The following functions are overrides required by Solidity.
|
||||
|
||||
function quorum(uint256 blockNumber)
|
||||
public
|
||||
view
|
||||
override(IGovernor, GovernorVotesQuorumFraction)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.quorum(blockNumber);
|
||||
}
|
||||
|
||||
function getVotes(address account, uint256 blockNumber)
|
||||
public
|
||||
view
|
||||
override(IGovernor, GovernorVotes)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.getVotes(account, blockNumber);
|
||||
}
|
||||
|
||||
function state(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
override(Governor, GovernorTimelockCompound)
|
||||
returns (ProposalState)
|
||||
{
|
||||
return super.state(proposalId);
|
||||
}
|
||||
|
||||
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description)
|
||||
public
|
||||
override(Governor, IGovernor)
|
||||
returns (uint256)
|
||||
{
|
||||
return super.propose(targets, values, calldatas, description);
|
||||
}
|
||||
|
||||
function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
|
||||
internal
|
||||
override(Governor, GovernorTimelockCompound)
|
||||
{
|
||||
super._execute(proposalId, targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
|
||||
function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash)
|
||||
internal
|
||||
override(Governor, GovernorTimelockCompound)
|
||||
returns (uint256)
|
||||
{
|
||||
return super._cancel(targets, values, calldatas, descriptionHash);
|
||||
}
|
||||
|
||||
function _executor()
|
||||
internal
|
||||
view
|
||||
override(Governor, GovernorTimelockCompound)
|
||||
returns (address)
|
||||
{
|
||||
return super._executor();
|
||||
}
|
||||
|
||||
function supportsInterface(bytes4 interfaceId)
|
||||
public
|
||||
view
|
||||
override(Governor, GovernorTimelockCompound)
|
||||
returns (bool)
|
||||
{
|
||||
return super.supportsInterface(interfaceId);
|
||||
}
|
||||
}
|
||||
2
certora/munged/.gitignore
vendored
Normal file
2
certora/munged/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
10
certora/scripts/Governor.sh
Executable file
10
certora/scripts/Governor.sh
Executable file
@ -0,0 +1,10 @@
|
||||
make -C certora munged
|
||||
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/GovernorHarness.sol \
|
||||
--verify GovernorHarness:certora/specs/GovernorBase.spec \
|
||||
--solc solc8.0 \
|
||||
--staging shelly/forSasha \
|
||||
--optimistic_loop \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--rule voteStartBeforeVoteEnd \
|
||||
--msg "$1"
|
||||
10
certora/scripts/GovernorCountingSimple-counting.sh
Normal file
10
certora/scripts/GovernorCountingSimple-counting.sh
Normal file
@ -0,0 +1,10 @@
|
||||
make -C certora munged
|
||||
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/GovernorBasicHarness.sol \
|
||||
--verify GovernorBasicHarness:certora/specs/GovernorCountingSimple.spec \
|
||||
--solc solc8.2 \
|
||||
--staging shelly/forSasha \
|
||||
--optimistic_loop \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--rule hasVotedCorrelation \
|
||||
--msg "$1"
|
||||
12
certora/scripts/WizardControlFirstPriority.sh
Normal file
12
certora/scripts/WizardControlFirstPriority.sh
Normal file
@ -0,0 +1,12 @@
|
||||
make -C certora munged
|
||||
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/WizardControlFirstPriority.sol \
|
||||
--link WizardControlFirstPriority:token=ERC20VotesHarness \
|
||||
--verify WizardControlFirstPriority:certora/specs/GovernorBase.spec \
|
||||
--solc solc8.2 \
|
||||
--disableLocalTypeChecking \
|
||||
--staging shelly/forSasha \
|
||||
--optimistic_loop \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--rule canVoteDuringVotingPeriod \
|
||||
--msg "$1"
|
||||
10
certora/scripts/WizardFirstTry.sh
Normal file
10
certora/scripts/WizardFirstTry.sh
Normal file
@ -0,0 +1,10 @@
|
||||
make -C certora munged
|
||||
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/WizardFirstTry.sol \
|
||||
--verify WizardFirstTry:certora/specs/GovernorBase.spec \
|
||||
--solc solc8.2 \
|
||||
--staging shelly/forSasha \
|
||||
--optimistic_loop \
|
||||
--disableLocalTypeChecking \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--msg "$1"
|
||||
14
certora/scripts/sanity.sh
Normal file
14
certora/scripts/sanity.sh
Normal file
@ -0,0 +1,14 @@
|
||||
make -C certora munged
|
||||
|
||||
for f in certora/harnesses/Wizard*.sol
|
||||
do
|
||||
echo "Processing $f"
|
||||
file=$(basename $f)
|
||||
echo ${file%.*}
|
||||
certoraRun certora/harnesses/$file \
|
||||
--verify ${file%.*}:certora/specs/sanity.spec "$@" \
|
||||
--solc solc8.2 --staging shelly/forSasha \
|
||||
--optimistic_loop \
|
||||
--msg "checking sanity on ${file%.*}"
|
||||
--settings -copyLoopUnroll=4
|
||||
done
|
||||
39
certora/scripts/verifyAll.sh
Normal file
39
certora/scripts/verifyAll.sh
Normal file
@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
|
||||
make -C certora munged
|
||||
|
||||
for contract in certora/harnesses/Wizard*.sol;
|
||||
do
|
||||
for spec in certora/specs/*.spec;
|
||||
do
|
||||
contractFile=$(basename $contract)
|
||||
specFile=$(basename $spec)
|
||||
if [[ "${specFile%.*}" != "RulesInProgress" ]];
|
||||
then
|
||||
echo "Processing ${contractFile%.*} with $specFile"
|
||||
if [[ "${contractFile%.*}" = *"WizardControl"* ]];
|
||||
then
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/$contractFile \
|
||||
--link ${contractFile%.*}:token=ERC20VotesHarness \
|
||||
--verify ${contractFile%.*}:certora/specs/$specFile "$@" \
|
||||
--solc solc8.2 \
|
||||
--staging shelly/forSasha \
|
||||
--disableLocalTypeChecking \
|
||||
--optimistic_loop \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--send_only \
|
||||
--msg "checking $specFile on ${contractFile%.*}"
|
||||
else
|
||||
certoraRun certora/harnesses/ERC20VotesHarness.sol certora/harnesses/$contractFile \
|
||||
--verify ${contractFile%.*}:certora/specs/$specFile "$@" \
|
||||
--solc solc8.2 \
|
||||
--staging shelly/forSasha \
|
||||
--disableLocalTypeChecking \
|
||||
--optimistic_loop \
|
||||
--settings -copyLoopUnroll=4 \
|
||||
--send_only \
|
||||
--msg "checking $specFile on ${contractFile%.*}"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
done
|
||||
334
certora/specs/GovernorBase.spec
Normal file
334
certora/specs/GovernorBase.spec
Normal file
@ -0,0 +1,334 @@
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////// Governor.sol base definitions //////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
using ERC20VotesHarness as erc20votes
|
||||
|
||||
methods {
|
||||
proposalSnapshot(uint256) returns uint256 envfree // matches proposalVoteStart
|
||||
proposalDeadline(uint256) returns uint256 envfree // matches proposalVoteEnd
|
||||
hashProposal(address[],uint256[],bytes[],bytes32) returns uint256 envfree
|
||||
isExecuted(uint256) returns bool envfree
|
||||
isCanceled(uint256) returns bool envfree
|
||||
execute(address[], uint256[], bytes[], bytes32) returns uint256
|
||||
hasVoted(uint256, address) returns bool
|
||||
castVote(uint256, uint8) returns uint256
|
||||
updateQuorumNumerator(uint256)
|
||||
queue(address[], uint256[], bytes[], bytes32) returns uint256
|
||||
|
||||
// internal functions made public in harness:
|
||||
_quorumReached(uint256) returns bool
|
||||
_voteSucceeded(uint256) returns bool envfree
|
||||
|
||||
// function summarization
|
||||
proposalThreshold() returns uint256 envfree
|
||||
|
||||
getVotes(address, uint256) returns uint256 => DISPATCHER(true)
|
||||
|
||||
getPastTotalSupply(uint256 t) returns uint256 => PER_CALLEE_CONSTANT
|
||||
getPastVotes(address a, uint256 t) returns uint256 => PER_CALLEE_CONSTANT
|
||||
|
||||
//scheduleBatch(address[],uint256[],bytes[],bytes32,bytes32,uint256) => DISPATCHER(true)
|
||||
//executeBatch(address[], uint256[], bytes[], bytes32, bytes32) => DISPATCHER(true)
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////// Definitions /////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
// proposal was created - relation proved in noStartBeforeCreation
|
||||
definition proposalCreated(uint256 pId) returns bool = proposalSnapshot(pId) > 0;
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////// Helper Functions ///////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
function helperFunctionsWithRevert(uint256 proposalId, method f, env e) {
|
||||
address[] targets; uint256[] values; bytes[] calldatas; string reason; bytes32 descriptionHash;
|
||||
uint8 support; uint8 v; bytes32 r; bytes32 s;
|
||||
if (f.selector == propose(address[], uint256[], bytes[], string).selector) {
|
||||
uint256 result = propose@withrevert(e, targets, values, calldatas, reason);
|
||||
require(result == proposalId);
|
||||
} else if (f.selector == execute(address[], uint256[], bytes[], bytes32).selector) {
|
||||
uint256 result = execute@withrevert(e, targets, values, calldatas, descriptionHash);
|
||||
require(result == proposalId);
|
||||
} else if (f.selector == castVote(uint256, uint8).selector) {
|
||||
castVote@withrevert(e, proposalId, support);
|
||||
} else if (f.selector == castVoteWithReason(uint256, uint8, string).selector) {
|
||||
castVoteWithReason@withrevert(e, proposalId, support, reason);
|
||||
} else if (f.selector == castVoteBySig(uint256, uint8,uint8, bytes32, bytes32).selector) {
|
||||
castVoteBySig@withrevert(e, proposalId, support, v, r, s);
|
||||
} else if (f.selector == queue(address[], uint256[], bytes[], bytes32).selector) {
|
||||
queue@withrevert(e, targets, values, calldatas, descriptionHash);
|
||||
} else {
|
||||
calldataarg args;
|
||||
f@withrevert(e, args);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////// State Diagram //////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// //
|
||||
// castVote(s)() //
|
||||
// ------------- propose() ---------------------- time pass --------------- time passes ----------- //
|
||||
// | No Proposal | --------> | Before Start (Delay) | --------> | Voting Period | ----------------------> | execute() | //
|
||||
// ------------- ---------------------- --------------- -> Executed/Canceled ----------- //
|
||||
// ------------------------------------------------------------|---------------|-------------------------|--------------> //
|
||||
// t start end timelock //
|
||||
// //
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
*/
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////// Global Valid States /////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/*
|
||||
* Start and end date are either initialized (non zero) or uninitialized (zero) simultaneously
|
||||
* This invariant assumes that the block number cannot be 0 at any stage of the contract cycle
|
||||
* This is very safe assumption as usually the 0 block is genesis block which is uploaded with data
|
||||
* by the developers and will not be valid to raise proposals (at the current way that block chain is functioning)
|
||||
*/
|
||||
// To use env with general preserved block disable type checking [--disableLocalTypeChecking]
|
||||
invariant startAndEndDatesNonZero(uint256 pId)
|
||||
proposalSnapshot(pId) != 0 <=> proposalDeadline(pId) != 0
|
||||
{ preserved with (env e){
|
||||
require e.block.number > 0;
|
||||
}}
|
||||
|
||||
|
||||
/*
|
||||
* If a proposal is canceled it must have a start and an end date
|
||||
*/
|
||||
// To use env with general preserved block disable type checking [--disableLocalTypeChecking]
|
||||
invariant canceledImplyStartAndEndDateNonZero(uint pId)
|
||||
isCanceled(pId) => proposalSnapshot(pId) != 0
|
||||
{preserved with (env e){
|
||||
require e.block.number > 0;
|
||||
}}
|
||||
|
||||
|
||||
/*
|
||||
* If a proposal is executed it must have a start and an end date
|
||||
*/
|
||||
// To use env with general preserved block disable type checking [--disableLocalTypeChecking]
|
||||
invariant executedImplyStartAndEndDateNonZero(uint pId)
|
||||
isExecuted(pId) => proposalSnapshot(pId) != 0
|
||||
{ preserved with (env e){
|
||||
requireInvariant startAndEndDatesNonZero(pId);
|
||||
require e.block.number > 0;
|
||||
}}
|
||||
|
||||
|
||||
/*
|
||||
* A proposal starting block number must be less or equal than the proposal end date
|
||||
*/
|
||||
invariant voteStartBeforeVoteEnd(uint256 pId)
|
||||
// from < to <= because snapshot and deadline can be the same block number if delays are set to 0
|
||||
// This is possible before the integration of GovernorSettings.sol to the system.
|
||||
// After integration of GovernorSettings.sol the invariant expression should be changed from <= to <
|
||||
(proposalSnapshot(pId) > 0 => proposalSnapshot(pId) <= proposalDeadline(pId))
|
||||
// (proposalSnapshot(pId) > 0 => proposalSnapshot(pId) <= proposalDeadline(pId))
|
||||
{ preserved {
|
||||
requireInvariant startAndEndDatesNonZero(pId);
|
||||
}}
|
||||
|
||||
|
||||
/*
|
||||
* A proposal cannot be both executed and canceled simultaneously.
|
||||
*/
|
||||
invariant noBothExecutedAndCanceled(uint256 pId)
|
||||
!isExecuted(pId) || !isCanceled(pId)
|
||||
|
||||
|
||||
/*
|
||||
* A proposal could be executed only if quorum was reached and vote succeeded
|
||||
*/
|
||||
rule executionOnlyIfQuoromReachedAndVoteSucceeded(uint256 pId, env e, method f){
|
||||
bool isExecutedBefore = isExecuted(pId);
|
||||
bool quorumReachedBefore = _quorumReached(e, pId);
|
||||
bool voteSucceededBefore = _voteSucceeded(pId);
|
||||
|
||||
calldataarg args;
|
||||
f(e, args);
|
||||
|
||||
bool isExecutedAfter = isExecuted(pId);
|
||||
assert (!isExecutedBefore && isExecutedAfter) => (quorumReachedBefore && voteSucceededBefore), "quorum was changed";
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////// In-State Rules /////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//==========================================
|
||||
//------------- Voting Period --------------
|
||||
//==========================================
|
||||
|
||||
/*
|
||||
* A user cannot vote twice
|
||||
*/
|
||||
// Checked for castVote only. all 3 castVote functions call _castVote, so the completeness of the verification is counted on
|
||||
// the fact that the 3 functions themselves makes no changes, but rather call an internal function to execute.
|
||||
// That means that we do not check those 3 functions directly, however for castVote & castVoteWithReason it is quite trivial
|
||||
// to understand why this is ok. For castVoteBySig we basically assume that the signature referendum is correct without checking it.
|
||||
// We could check each function separately and pass the rule, but that would have uglyfied the code with no concrete
|
||||
// benefit, as it is evident that nothing is happening in the first 2 functions (calling a view function), and we do not desire to check the signature verification.
|
||||
rule doubleVoting(uint256 pId, uint8 sup, method f) {
|
||||
env e;
|
||||
address user = e.msg.sender;
|
||||
bool votedCheck = hasVoted(e, pId, user);
|
||||
|
||||
castVote@withrevert(e, pId, sup);
|
||||
|
||||
assert votedCheck => lastReverted, "double voting accured";
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////// State Transitions Rules //////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//===========================================
|
||||
//-------- Propose() --> End of Time --------
|
||||
//===========================================
|
||||
|
||||
|
||||
/*
|
||||
* Once a proposal is created, voteStart and voteEnd are immutable
|
||||
*/
|
||||
rule immutableFieldsAfterProposalCreation(uint256 pId, method f) {
|
||||
uint256 _voteStart = proposalSnapshot(pId);
|
||||
uint256 _voteEnd = proposalDeadline(pId);
|
||||
|
||||
require proposalCreated(pId); // startDate > 0
|
||||
|
||||
env e; calldataarg arg;
|
||||
f(e, arg);
|
||||
|
||||
uint256 voteStart_ = proposalSnapshot(pId);
|
||||
uint256 voteEnd_ = proposalDeadline(pId);
|
||||
assert _voteStart == voteStart_, "Start date was changed";
|
||||
assert _voteEnd == voteEnd_, "End date was changed";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Voting cannot start at a block number prior to proposal’s creation block number
|
||||
*/
|
||||
rule noStartBeforeCreation(uint256 pId) {
|
||||
uint256 previousStart = proposalSnapshot(pId);
|
||||
// This line makes sure that we see only cases where start date is changed from 0, i.e. creation of proposal
|
||||
// We proved in immutableFieldsAfterProposalCreation that once dates set for proposal, it cannot be changed
|
||||
require !proposalCreated(pId); // previousStart == 0;
|
||||
|
||||
env e; calldataarg args;
|
||||
propose(e, args);
|
||||
|
||||
uint256 newStart = proposalSnapshot(pId);
|
||||
// if created, start is after current block number (creation block)
|
||||
assert(newStart != previousStart => newStart >= e.block.number);
|
||||
}
|
||||
|
||||
|
||||
//============================================
|
||||
//--- End of Voting Period --> End of Time ---
|
||||
//============================================
|
||||
|
||||
|
||||
/*
|
||||
* A proposal can neither be executed nor canceled before it ends
|
||||
*/
|
||||
// By induction it cannot be executed nor canceled before it starts, due to voteStartBeforeVoteEnd
|
||||
rule noExecuteOrCancelBeforeDeadline(uint256 pId, method f){
|
||||
require !isExecuted(pId) && !isCanceled(pId);
|
||||
|
||||
env e; calldataarg args;
|
||||
f(e, args);
|
||||
|
||||
assert e.block.number < proposalDeadline(pId) => (!isExecuted(pId) && !isCanceled(pId)), "executed/cancelled before deadline";
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////// Integrity Of Functions (Unit Tests) /////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////// High Level Rules ////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////// Not Categorized Yet //////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/*
|
||||
* All proposal specific (non-view) functions should revert if proposal is executed
|
||||
*/
|
||||
// In this rule we show that if a function is executed, i.e. execute() was called on the proposal ID,
|
||||
// non of the proposal specific functions can make changes again. In executedOnlyAfterExecuteFunc
|
||||
// we connected the executed attribute to the execute() function, showing that only execute() can
|
||||
// change it, and that it will always change it.
|
||||
rule allFunctionsRevertIfExecuted(method f) filtered { f ->
|
||||
!f.isView && !f.isFallback
|
||||
&& f.selector != updateTimelock(address).selector
|
||||
&& f.selector != updateQuorumNumerator(uint256).selector
|
||||
&& f.selector != queue(address[],uint256[],bytes[],bytes32).selector
|
||||
&& f.selector != relay(address,uint256,bytes).selector
|
||||
&& f.selector != 0xb9a61961 // __acceptAdmin()
|
||||
} {
|
||||
env e; calldataarg args;
|
||||
uint256 pId;
|
||||
require(isExecuted(pId));
|
||||
requireInvariant noBothExecutedAndCanceled(pId);
|
||||
requireInvariant executedImplyStartAndEndDateNonZero(pId);
|
||||
|
||||
helperFunctionsWithRevert(pId, f, e);
|
||||
|
||||
assert(lastReverted, "Function was not reverted");
|
||||
}
|
||||
|
||||
/*
|
||||
* All proposal specific (non-view) functions should revert if proposal is canceled
|
||||
*/
|
||||
rule allFunctionsRevertIfCanceled(method f) filtered {
|
||||
f -> !f.isView && !f.isFallback
|
||||
&& f.selector != updateTimelock(address).selector
|
||||
&& f.selector != updateQuorumNumerator(uint256).selector
|
||||
&& f.selector != queue(address[],uint256[],bytes[],bytes32).selector
|
||||
&& f.selector != relay(address,uint256,bytes).selector
|
||||
&& f.selector != 0xb9a61961 // __acceptAdmin()
|
||||
} {
|
||||
env e; calldataarg args;
|
||||
uint256 pId;
|
||||
require(isCanceled(pId));
|
||||
requireInvariant noBothExecutedAndCanceled(pId);
|
||||
requireInvariant canceledImplyStartAndEndDateNonZero(pId);
|
||||
|
||||
helperFunctionsWithRevert(pId, f, e);
|
||||
|
||||
assert(lastReverted, "Function was not reverted");
|
||||
}
|
||||
|
||||
/*
|
||||
* Proposal can be switched to executed only via execute() function
|
||||
*/
|
||||
rule executedOnlyAfterExecuteFunc(address[] targets, uint256[] values, bytes[] calldatas, bytes32 descriptionHash, method f) {
|
||||
env e; calldataarg args;
|
||||
uint256 pId;
|
||||
bool executedBefore = isExecuted(pId);
|
||||
require(!executedBefore);
|
||||
|
||||
helperFunctionsWithRevert(pId, f, e);
|
||||
|
||||
bool executedAfter = isExecuted(pId);
|
||||
assert(executedAfter != executedBefore => f.selector == execute(address[], uint256[], bytes[], bytes32).selector, "isExecuted only changes in the execute method");
|
||||
}
|
||||
|
||||
221
certora/specs/GovernorCountingSimple.spec
Normal file
221
certora/specs/GovernorCountingSimple.spec
Normal file
@ -0,0 +1,221 @@
|
||||
import "GovernorBase.spec"
|
||||
|
||||
using ERC20VotesHarness as erc20votes
|
||||
|
||||
methods {
|
||||
ghost_sum_vote_power_by_id(uint256) returns uint256 envfree
|
||||
|
||||
quorum(uint256) returns uint256
|
||||
proposalVotes(uint256) returns (uint256, uint256, uint256) envfree
|
||||
|
||||
quorumNumerator() returns uint256
|
||||
_executor() returns address
|
||||
|
||||
erc20votes._getPastVotes(address, uint256) returns uint256
|
||||
|
||||
getExecutor() returns address
|
||||
|
||||
timelock() returns address
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////// GHOSTS /////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//////////// ghosts to keep track of votes counting ////////////
|
||||
|
||||
/*
|
||||
* the sum of voting power of those who voted
|
||||
*/
|
||||
ghost sum_all_votes_power() returns uint256 {
|
||||
init_state axiom sum_all_votes_power() == 0;
|
||||
}
|
||||
|
||||
hook Sstore ghost_sum_vote_power_by_id [KEY uint256 pId] uint256 current_power(uint256 old_power) STORAGE {
|
||||
havoc sum_all_votes_power assuming sum_all_votes_power@new() == sum_all_votes_power@old() - old_power + current_power;
|
||||
}
|
||||
|
||||
/*
|
||||
* sum of all votes casted per proposal
|
||||
*/
|
||||
ghost tracked_weight(uint256) returns uint256 {
|
||||
init_state axiom forall uint256 p. tracked_weight(p) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* sum of all votes casted
|
||||
*/
|
||||
ghost sum_tracked_weight() returns uint256 {
|
||||
init_state axiom sum_tracked_weight() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.againstVotes
|
||||
*/
|
||||
ghost votesAgainst() returns uint256 {
|
||||
init_state axiom votesAgainst() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.forVotes
|
||||
*/
|
||||
ghost votesFor() returns uint256 {
|
||||
init_state axiom votesFor() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.abstainVotes
|
||||
*/
|
||||
ghost votesAbstain() returns uint256 {
|
||||
init_state axiom votesAbstain() == 0;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].againstVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesAgainst assuming votesAgainst@new() == votesAgainst@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].forVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesFor assuming votesFor@new() == votesFor@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].abstainVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesAbstain assuming votesAbstain@new() == votesAbstain@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////// INVARIANTS ////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/*
|
||||
* sum of all votes casted is equal to the sum of voting power of those who voted, per each proposal
|
||||
*/
|
||||
invariant SumOfVotesCastEqualSumOfPowerOfVotedPerProposal(uint256 pId)
|
||||
tracked_weight(pId) == ghost_sum_vote_power_by_id(pId)
|
||||
|
||||
|
||||
/*
|
||||
* sum of all votes casted is equal to the sum of voting power of those who voted
|
||||
*/
|
||||
invariant SumOfVotesCastEqualSumOfPowerOfVoted()
|
||||
sum_tracked_weight() == sum_all_votes_power()
|
||||
|
||||
|
||||
/*
|
||||
* sum of all votes casted is greater or equal to the sum of voting power of those who voted at a specific proposal
|
||||
*/
|
||||
invariant OneIsNotMoreThanAll(uint256 pId)
|
||||
sum_all_votes_power() >= tracked_weight(pId)
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////// RULES //////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/*
|
||||
* Only sender's voting status can be changed by execution of any cast vote function
|
||||
*/
|
||||
// Checked for castVote only. all 3 castVote functions call _castVote, so the completeness of the verification is counted on
|
||||
// the fact that the 3 functions themselves makes no changes, but rather call an internal function to execute.
|
||||
// That means that we do not check those 3 functions directly, however for castVote & castVoteWithReason it is quite trivial
|
||||
// to understand why this is ok. For castVoteBySig we basically assume that the signature referendum is correct without checking it.
|
||||
// We could check each function separately and pass the rule, but that would have uglyfied the code with no concrete
|
||||
// benefit, as it is evident that nothing is happening in the first 2 functions (calling a view function), and we do not desire to check the signature verification.
|
||||
rule noVoteForSomeoneElse(uint256 pId, uint8 sup, method f) {
|
||||
env e; calldataarg args;
|
||||
|
||||
address voter = e.msg.sender;
|
||||
address user;
|
||||
|
||||
bool hasVotedBefore_User = hasVoted(e, pId, user);
|
||||
|
||||
castVote@withrevert(e, pId, sup);
|
||||
require(!lastReverted);
|
||||
|
||||
bool hasVotedAfter_User = hasVoted(e, pId, user);
|
||||
|
||||
assert user != voter => hasVotedBefore_User == hasVotedAfter_User;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Total voting tally is monotonically non-decreasing in every operation
|
||||
*/
|
||||
rule votingWeightMonotonicity(method f){
|
||||
uint256 votingWeightBefore = sum_tracked_weight();
|
||||
|
||||
env e;
|
||||
calldataarg args;
|
||||
f(e, args);
|
||||
|
||||
uint256 votingWeightAfter = sum_tracked_weight();
|
||||
|
||||
assert votingWeightBefore <= votingWeightAfter, "Voting weight was decreased somehow";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* A change in hasVoted must be correlated with an non-decreasing of the vote supports (nondecrease because user can vote with weight 0)
|
||||
*/
|
||||
rule hasVotedCorrelation(uint256 pId, method f, env e, uint256 bn) {
|
||||
address acc = e.msg.sender;
|
||||
|
||||
uint256 againstBefore = votesAgainst();
|
||||
uint256 forBefore = votesFor();
|
||||
uint256 abstainBefore = votesAbstain();
|
||||
|
||||
bool hasVotedBefore = hasVoted(e, pId, acc);
|
||||
|
||||
helperFunctionsWithRevert(pId, f, e);
|
||||
require(!lastReverted);
|
||||
|
||||
uint256 againstAfter = votesAgainst();
|
||||
uint256 forAfter = votesFor();
|
||||
uint256 abstainAfter = votesAbstain();
|
||||
|
||||
bool hasVotedAfter = hasVoted(e, pId, acc);
|
||||
|
||||
assert (!hasVotedBefore && hasVotedAfter) => againstBefore <= againstAfter || forBefore <= forAfter || abstainBefore <= abstainAfter, "no correlation";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Only privileged users can execute privileged operations, e.g. change _quorumNumerator or _timelock
|
||||
*/
|
||||
rule privilegedOnlyNumerator(method f, uint256 newQuorumNumerator){
|
||||
env e;
|
||||
calldataarg arg;
|
||||
uint256 quorumNumBefore = quorumNumerator(e);
|
||||
|
||||
f(e, arg);
|
||||
|
||||
uint256 quorumNumAfter = quorumNumerator(e);
|
||||
address executorCheck = getExecutor(e);
|
||||
|
||||
assert quorumNumBefore != quorumNumAfter => e.msg.sender == executorCheck, "non privileged user changed quorum numerator";
|
||||
}
|
||||
|
||||
rule privilegedOnlyTimelock(method f, uint256 newQuorumNumerator){
|
||||
env e;
|
||||
calldataarg arg;
|
||||
uint256 timelockBefore = timelock(e);
|
||||
|
||||
f(e, arg);
|
||||
|
||||
uint256 timelockAfter = timelock(e);
|
||||
|
||||
assert timelockBefore != timelockAfter => e.msg.sender == timelockBefore, "non privileged user changed timelock";
|
||||
}
|
||||
139
certora/specs/RulesInProgress.spec
Normal file
139
certora/specs/RulesInProgress.spec
Normal file
@ -0,0 +1,139 @@
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
////////////// THIS SPEC IS A RESERVE FOR NOT IN PROGRESS //////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import "GovernorBase.spec"
|
||||
|
||||
using ERC20VotesHarness as erc20votes
|
||||
|
||||
methods {
|
||||
ghost_sum_vote_power_by_id(uint256) returns uint256 envfree
|
||||
|
||||
quorum(uint256) returns uint256
|
||||
proposalVotes(uint256) returns (uint256, uint256, uint256) envfree
|
||||
|
||||
quorumNumerator() returns uint256
|
||||
_executor() returns address
|
||||
|
||||
erc20votes._getPastVotes(address, uint256) returns uint256
|
||||
|
||||
getExecutor() returns address
|
||||
|
||||
timelock() returns address
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////// GHOSTS /////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//////////// ghosts to keep track of votes counting ////////////
|
||||
|
||||
/*
|
||||
* the sum of voting power of those who voted
|
||||
*/
|
||||
ghost sum_all_votes_power() returns uint256 {
|
||||
init_state axiom sum_all_votes_power() == 0;
|
||||
}
|
||||
|
||||
hook Sstore ghost_sum_vote_power_by_id [KEY uint256 pId] uint256 current_power(uint256 old_power) STORAGE {
|
||||
havoc sum_all_votes_power assuming sum_all_votes_power@new() == sum_all_votes_power@old() - old_power + current_power;
|
||||
}
|
||||
|
||||
/*
|
||||
* sum of all votes casted per proposal
|
||||
*/
|
||||
ghost tracked_weight(uint256) returns uint256 {
|
||||
init_state axiom forall uint256 p. tracked_weight(p) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* sum of all votes casted
|
||||
*/
|
||||
ghost sum_tracked_weight() returns uint256 {
|
||||
init_state axiom sum_tracked_weight() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.againstVotes
|
||||
*/
|
||||
ghost votesAgainst() returns uint256 {
|
||||
init_state axiom votesAgainst() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.forVotes
|
||||
*/
|
||||
ghost votesFor() returns uint256 {
|
||||
init_state axiom votesFor() == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* getter for _proposalVotes.abstainVotes
|
||||
*/
|
||||
ghost votesAbstain() returns uint256 {
|
||||
init_state axiom votesAbstain() == 0;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].againstVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesAgainst assuming votesAgainst@new() == votesAgainst@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].forVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesFor assuming votesFor@new() == votesFor@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
hook Sstore _proposalVotes [KEY uint256 pId].abstainVotes uint256 votes(uint256 old_votes) STORAGE {
|
||||
havoc tracked_weight assuming forall uint256 p.(p == pId => tracked_weight@new(p) == tracked_weight@old(p) - old_votes + votes) &&
|
||||
(p != pId => tracked_weight@new(p) == tracked_weight@old(p));
|
||||
havoc sum_tracked_weight assuming sum_tracked_weight@new() == sum_tracked_weight@old() - old_votes + votes;
|
||||
havoc votesAbstain assuming votesAbstain@new() == votesAbstain@old() - old_votes + votes;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////// INVARIANTS ////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////// RULES //////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//NOT FINISHED
|
||||
/*
|
||||
* the sum of voting power of those who voted is less or equal to the maximum possible votes, per each proposal
|
||||
*/
|
||||
rule possibleTotalVotes(uint256 pId, uint8 sup, env e, method f) {
|
||||
|
||||
// add requireinvariant for all i, j. i = i - 1 && i < j => checkpointlookup[i] < checkpointlookup[j];
|
||||
require tracked_weight(pId) <= erc20votes.getPastTotalSupply(e, proposalSnapshot(pId));
|
||||
|
||||
uint256 againstB;
|
||||
uint256 forB;
|
||||
uint256 absatinB;
|
||||
againstB, forB, absatinB = proposalVotes(pId);
|
||||
|
||||
calldataarg args;
|
||||
//f(e, args);
|
||||
|
||||
castVote(e, pId, sup);
|
||||
|
||||
uint256 against;
|
||||
uint256 for;
|
||||
uint256 absatin;
|
||||
against, for, absatin = proposalVotes(pId);
|
||||
|
||||
uint256 ps = proposalSnapshot(pId);
|
||||
|
||||
assert tracked_weight(pId) <= erc20votes.getPastTotalSupply(e, proposalSnapshot(pId)), "bla bla bla";
|
||||
}
|
||||
14
certora/specs/sanity.spec
Normal file
14
certora/specs/sanity.spec
Normal file
@ -0,0 +1,14 @@
|
||||
/*
|
||||
This rule looks for a non-reverting execution path to each method, including those overridden in the harness.
|
||||
A method has such an execution path if it violates this rule.
|
||||
How it works:
|
||||
- If there is a non-reverting execution path, we reach the false assertion, and the sanity fails.
|
||||
- If all execution paths are reverting, we never call the assertion, and the method will pass this rule vacuously.
|
||||
*/
|
||||
|
||||
rule sanity(method f) {
|
||||
env e;
|
||||
calldataarg arg;
|
||||
f(e, arg);
|
||||
assert false;
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
import "../utils/Context.sol";
|
||||
@ -1,230 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
import "../utils/Context.sol";
|
||||
import "./IRelayRecipient.sol";
|
||||
import "./IRelayHub.sol";
|
||||
|
||||
/**
|
||||
* @dev Base GSN recipient contract: includes the {IRelayRecipient} interface
|
||||
* and enables GSN support on all contracts in the inheritance tree.
|
||||
*
|
||||
* TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall},
|
||||
* {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be
|
||||
* provided by derived contracts. See the
|
||||
* xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more
|
||||
* information on how to use the pre-built {GSNRecipientSignature} and
|
||||
* {GSNRecipientERC20Fee}, or how to write your own.
|
||||
*/
|
||||
abstract contract GSNRecipient is IRelayRecipient, Context {
|
||||
// Default RelayHub address, deployed on mainnet and all testnets at the same address
|
||||
address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
|
||||
|
||||
uint256 constant private _RELAYED_CALL_ACCEPTED = 0;
|
||||
uint256 constant private _RELAYED_CALL_REJECTED = 11;
|
||||
|
||||
// How much gas is forwarded to postRelayedCall
|
||||
uint256 constant internal _POST_RELAYED_CALL_MAX_GAS = 100000;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
|
||||
*/
|
||||
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the {IRelayHub} contract for this recipient.
|
||||
*/
|
||||
function getHubAddr() public view virtual override returns (address) {
|
||||
return _relayHub;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
|
||||
* use the default instance.
|
||||
*
|
||||
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
|
||||
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
|
||||
*/
|
||||
function _upgradeRelayHub(address newRelayHub) internal virtual {
|
||||
address currentRelayHub = _relayHub;
|
||||
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
|
||||
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
|
||||
|
||||
emit RelayHubChanged(currentRelayHub, newRelayHub);
|
||||
|
||||
_relayHub = newRelayHub;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
|
||||
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
|
||||
*/
|
||||
// This function is view for future-proofing, it may require reading from
|
||||
// storage in the future.
|
||||
function relayHubVersion() public view virtual returns (string memory) {
|
||||
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
|
||||
return "1.0.0";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Withdraws the recipient's deposits in `RelayHub`.
|
||||
*
|
||||
* Derived contracts should expose this in an external interface with proper access control.
|
||||
*/
|
||||
function _withdrawDeposits(uint256 amount, address payable payee) internal virtual {
|
||||
IRelayHub(getHubAddr()).withdraw(amount, payee);
|
||||
}
|
||||
|
||||
// Overrides for Context's functions: when called from RelayHub, sender and
|
||||
// data require some pre-processing: the actual sender is stored at the end
|
||||
// of the call data, which in turns means it needs to be removed from it
|
||||
// when handling said data.
|
||||
|
||||
/**
|
||||
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
|
||||
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
|
||||
*
|
||||
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
|
||||
*/
|
||||
function _msgSender() internal view virtual override returns (address payable) {
|
||||
if (msg.sender != getHubAddr()) {
|
||||
return msg.sender;
|
||||
} else {
|
||||
return _getRelayedCallSender();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
|
||||
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
|
||||
*
|
||||
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
|
||||
*/
|
||||
function _msgData() internal view virtual override returns (bytes memory) {
|
||||
if (msg.sender != getHubAddr()) {
|
||||
return msg.data;
|
||||
} else {
|
||||
return _getRelayedCallData();
|
||||
}
|
||||
}
|
||||
|
||||
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
|
||||
// internal hook.
|
||||
|
||||
/**
|
||||
* @dev See `IRelayRecipient.preRelayedCall`.
|
||||
*
|
||||
* This function should not be overridden directly, use `_preRelayedCall` instead.
|
||||
*
|
||||
* * Requirements:
|
||||
*
|
||||
* - the caller must be the `RelayHub` contract.
|
||||
*/
|
||||
function preRelayedCall(bytes memory context) public virtual override returns (bytes32) {
|
||||
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
|
||||
return _preRelayedCall(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See `IRelayRecipient.preRelayedCall`.
|
||||
*
|
||||
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
|
||||
* must implement this function with any relayed-call preprocessing they may wish to do.
|
||||
*
|
||||
*/
|
||||
function _preRelayedCall(bytes memory context) internal virtual returns (bytes32);
|
||||
|
||||
/**
|
||||
* @dev See `IRelayRecipient.postRelayedCall`.
|
||||
*
|
||||
* This function should not be overridden directly, use `_postRelayedCall` instead.
|
||||
*
|
||||
* * Requirements:
|
||||
*
|
||||
* - the caller must be the `RelayHub` contract.
|
||||
*/
|
||||
function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override {
|
||||
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
|
||||
_postRelayedCall(context, success, actualCharge, preRetVal);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See `IRelayRecipient.postRelayedCall`.
|
||||
*
|
||||
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
|
||||
* must implement this function with any relayed-call postprocessing they may wish to do.
|
||||
*
|
||||
*/
|
||||
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal virtual;
|
||||
|
||||
/**
|
||||
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
|
||||
* will be charged a fee by RelayHub
|
||||
*/
|
||||
function _approveRelayedCall() internal pure virtual returns (uint256, bytes memory) {
|
||||
return _approveRelayedCall("");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See `GSNRecipient._approveRelayedCall`.
|
||||
*
|
||||
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
|
||||
*/
|
||||
function _approveRelayedCall(bytes memory context) internal pure virtual returns (uint256, bytes memory) {
|
||||
return (_RELAYED_CALL_ACCEPTED, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
|
||||
*/
|
||||
function _rejectRelayedCall(uint256 errorCode) internal pure virtual returns (uint256, bytes memory) {
|
||||
return (_RELAYED_CALL_REJECTED + errorCode, "");
|
||||
}
|
||||
|
||||
/*
|
||||
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
|
||||
* `serviceFee`.
|
||||
*/
|
||||
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure virtual returns (uint256) {
|
||||
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
|
||||
// charged for 1.4 times the spent amount.
|
||||
return (gas * gasPrice * (100 + serviceFee)) / 100;
|
||||
}
|
||||
|
||||
function _getRelayedCallSender() private pure returns (address payable result) {
|
||||
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
|
||||
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
|
||||
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
|
||||
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
|
||||
// bytes. This can always be done due to the 32-byte prefix.
|
||||
|
||||
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
|
||||
// easiest/most-efficient way to perform this operation.
|
||||
|
||||
// These fields are not accessible from assembly
|
||||
bytes memory array = msg.data;
|
||||
uint256 index = msg.data.length;
|
||||
|
||||
// solhint-disable-next-line no-inline-assembly
|
||||
assembly {
|
||||
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
|
||||
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function _getRelayedCallData() private pure returns (bytes memory) {
|
||||
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
|
||||
// we must strip the last 20 bytes (length of an address type) from it.
|
||||
|
||||
uint256 actualDataLength = msg.data.length - 20;
|
||||
bytes memory actualData = new bytes(actualDataLength);
|
||||
|
||||
for (uint256 i = 0; i < actualDataLength; ++i) {
|
||||
actualData[i] = msg.data[i];
|
||||
}
|
||||
|
||||
return actualData;
|
||||
}
|
||||
}
|
||||
@ -1,154 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
import "./GSNRecipient.sol";
|
||||
import "../math/SafeMath.sol";
|
||||
import "../access/Ownable.sol";
|
||||
import "../token/ERC20/SafeERC20.sol";
|
||||
import "../token/ERC20/ERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that charges transaction fees in a special purpose ERC20
|
||||
* token, which we refer to as the gas payment token. The amount charged is exactly the amount of Ether charged to the
|
||||
* recipient. This means that the token is essentially pegged to the value of Ether.
|
||||
*
|
||||
* The distribution strategy of the gas payment token to users is not defined by this contract. It's a mintable token
|
||||
* whose only minter is the recipient, so the strategy must be implemented in a derived contract, making use of the
|
||||
* internal {_mint} function.
|
||||
*/
|
||||
contract GSNRecipientERC20Fee is GSNRecipient {
|
||||
using SafeERC20 for __unstable__ERC20Owned;
|
||||
using SafeMath for uint256;
|
||||
|
||||
enum GSNRecipientERC20FeeErrorCodes {
|
||||
INSUFFICIENT_BALANCE
|
||||
}
|
||||
|
||||
__unstable__ERC20Owned private _token;
|
||||
|
||||
/**
|
||||
* @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
|
||||
*/
|
||||
constructor(string memory name, string memory symbol) {
|
||||
_token = new __unstable__ERC20Owned(name, symbol);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the gas payment token.
|
||||
*/
|
||||
function token() public view virtual returns (__unstable__ERC20Owned) {
|
||||
return _token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal function that mints the gas payment token. Derived contracts should expose this function in their public API, with proper access control mechanisms.
|
||||
*/
|
||||
function _mint(address account, uint256 amount) internal virtual {
|
||||
token().mint(account, amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Ensures that only users with enough gas payment token balance can have transactions relayed through the GSN.
|
||||
*/
|
||||
function acceptRelayedCall(
|
||||
address,
|
||||
address from,
|
||||
bytes memory,
|
||||
uint256 transactionFee,
|
||||
uint256 gasPrice,
|
||||
uint256,
|
||||
uint256,
|
||||
bytes memory,
|
||||
uint256 maxPossibleCharge
|
||||
)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
override
|
||||
returns (uint256, bytes memory)
|
||||
{
|
||||
if (token().balanceOf(from) < maxPossibleCharge) {
|
||||
return _rejectRelayedCall(uint256(GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE));
|
||||
}
|
||||
|
||||
return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Implements the precharge to the user. The maximum possible charge (depending on gas limit, gas price, and
|
||||
* fee) will be deducted from the user balance of gas payment token. Note that this is an overestimation of the
|
||||
* actual charge, necessary because we cannot predict how much gas the execution will actually need. The remainder
|
||||
* is returned to the user in {_postRelayedCall}.
|
||||
*/
|
||||
function _preRelayedCall(bytes memory context) internal virtual override returns (bytes32) {
|
||||
(address from, uint256 maxPossibleCharge) = abi.decode(context, (address, uint256));
|
||||
|
||||
// The maximum token charge is pre-charged from the user
|
||||
token().safeTransferFrom(from, address(this), maxPossibleCharge);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns to the user the extra amount that was previously charged, once the actual execution cost is known.
|
||||
*/
|
||||
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal virtual override {
|
||||
(address from, uint256 maxPossibleCharge, uint256 transactionFee, uint256 gasPrice) =
|
||||
abi.decode(context, (address, uint256, uint256, uint256));
|
||||
|
||||
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
|
||||
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
|
||||
// ERC20 transfer.
|
||||
uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
|
||||
actualCharge = actualCharge.sub(overestimation);
|
||||
|
||||
// After the relayed call has been executed and the actual charge estimated, the excess pre-charge is returned
|
||||
token().safeTransfer(from, maxPossibleCharge.sub(actualCharge));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @title __unstable__ERC20Owned
|
||||
* @dev An ERC20 token owned by another contract, which has minting permissions and can use transferFrom to receive
|
||||
* anyone's tokens. This contract is an internal helper for GSNRecipientERC20Fee, and should not be used
|
||||
* outside of this context.
|
||||
*/
|
||||
// solhint-disable-next-line contract-name-camelcase
|
||||
contract __unstable__ERC20Owned is ERC20, Ownable {
|
||||
uint256 private constant _UINT256_MAX = 2**256 - 1;
|
||||
|
||||
constructor(string memory name, string memory symbol) ERC20(name, symbol) { }
|
||||
|
||||
// The owner (GSNRecipientERC20Fee) can mint tokens
|
||||
function mint(address account, uint256 amount) public virtual onlyOwner {
|
||||
_mint(account, amount);
|
||||
}
|
||||
|
||||
// The owner has 'infinite' allowance for all token holders
|
||||
function allowance(address tokenOwner, address spender) public view virtual override returns (uint256) {
|
||||
if (spender == owner()) {
|
||||
return _UINT256_MAX;
|
||||
} else {
|
||||
return super.allowance(tokenOwner, spender);
|
||||
}
|
||||
}
|
||||
|
||||
// Allowance for the owner cannot be changed (it is always 'infinite')
|
||||
function _approve(address tokenOwner, address spender, uint256 value) internal virtual override {
|
||||
if (spender == owner()) {
|
||||
return;
|
||||
} else {
|
||||
super._approve(tokenOwner, spender, value);
|
||||
}
|
||||
}
|
||||
|
||||
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
|
||||
if (recipient == owner()) {
|
||||
_transfer(sender, recipient, amount);
|
||||
return true;
|
||||
} else {
|
||||
return super.transferFrom(sender, recipient, amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,72 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
import "./GSNRecipient.sol";
|
||||
import "../cryptography/ECDSA.sol";
|
||||
|
||||
/**
|
||||
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that allows relayed transactions through when they are
|
||||
* accompanied by the signature of a trusted signer. The intent is for this signature to be generated by a server that
|
||||
* performs validations off-chain. Note that nothing is charged to the user in this scheme. Thus, the server should make
|
||||
* sure to account for this in their economic and threat model.
|
||||
*/
|
||||
contract GSNRecipientSignature is GSNRecipient {
|
||||
using ECDSA for bytes32;
|
||||
|
||||
address private _trustedSigner;
|
||||
|
||||
enum GSNRecipientSignatureErrorCodes {
|
||||
INVALID_SIGNER
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the trusted signer that is going to be producing signatures to approve relayed calls.
|
||||
*/
|
||||
constructor(address trustedSigner) {
|
||||
require(trustedSigner != address(0), "GSNRecipientSignature: trusted signer is the zero address");
|
||||
_trustedSigner = trustedSigner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Ensures that only transactions with a trusted signature can be relayed through the GSN.
|
||||
*/
|
||||
function acceptRelayedCall(
|
||||
address relay,
|
||||
address from,
|
||||
bytes memory encodedFunction,
|
||||
uint256 transactionFee,
|
||||
uint256 gasPrice,
|
||||
uint256 gasLimit,
|
||||
uint256 nonce,
|
||||
bytes memory approvalData,
|
||||
uint256
|
||||
)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
override
|
||||
returns (uint256, bytes memory)
|
||||
{
|
||||
bytes memory blob = abi.encodePacked(
|
||||
relay,
|
||||
from,
|
||||
encodedFunction,
|
||||
transactionFee,
|
||||
gasPrice,
|
||||
gasLimit,
|
||||
nonce, // Prevents replays on RelayHub
|
||||
getHubAddr(), // Prevents replays in multiple RelayHubs
|
||||
address(this) // Prevents replays in multiple recipients
|
||||
);
|
||||
if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _trustedSigner) {
|
||||
return _approveRelayedCall();
|
||||
} else {
|
||||
return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER));
|
||||
}
|
||||
}
|
||||
|
||||
function _preRelayedCall(bytes memory) internal virtual override returns (bytes32) { }
|
||||
|
||||
function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal virtual override { }
|
||||
}
|
||||
@ -1,269 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
/**
|
||||
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
|
||||
* directly.
|
||||
*
|
||||
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
|
||||
* how to deploy an instance of `RelayHub` on your local test network.
|
||||
*/
|
||||
interface IRelayHub {
|
||||
// Relay management
|
||||
|
||||
/**
|
||||
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
|
||||
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
|
||||
* cannot be its own owner.
|
||||
*
|
||||
* All Ether in this function call will be added to the relay's stake.
|
||||
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
|
||||
*
|
||||
* Emits a {Staked} event.
|
||||
*/
|
||||
function stake(address relayaddr, uint256 unstakeDelay) external payable;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a relay's stake or unstakeDelay are increased
|
||||
*/
|
||||
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
|
||||
|
||||
/**
|
||||
* @dev Registers the caller as a relay.
|
||||
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
|
||||
*
|
||||
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
|
||||
* `transactionFee` is not enforced by {relayCall}.
|
||||
*
|
||||
* Emits a {RelayAdded} event.
|
||||
*/
|
||||
function registerRelay(uint256 transactionFee, string calldata url) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a relay is registered or re-registered. Looking at these events (and filtering out
|
||||
* {RelayRemoved} events) lets a client discover the list of available relays.
|
||||
*/
|
||||
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
|
||||
|
||||
/**
|
||||
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
|
||||
*
|
||||
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
|
||||
* callable.
|
||||
*
|
||||
* Emits a {RelayRemoved} event.
|
||||
*/
|
||||
function removeRelayByOwner(address relay) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
|
||||
*/
|
||||
event RelayRemoved(address indexed relay, uint256 unstakeTime);
|
||||
|
||||
/** Deletes the relay from the system, and gives back its stake to the owner.
|
||||
*
|
||||
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
|
||||
*
|
||||
* Emits an {Unstaked} event.
|
||||
*/
|
||||
function unstake(address relay) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a relay is unstaked for, including the returned stake.
|
||||
*/
|
||||
event Unstaked(address indexed relay, uint256 stake);
|
||||
|
||||
// States a relay can be in
|
||||
enum RelayState {
|
||||
Unknown, // The relay is unknown to the system: it has never been staked for
|
||||
Staked, // The relay has been staked for, but it is not yet active
|
||||
Registered, // The relay has registered itself, and is active (can relay calls)
|
||||
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
|
||||
* to return an empty entry.
|
||||
*/
|
||||
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
|
||||
|
||||
// Balance management
|
||||
|
||||
/**
|
||||
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
|
||||
*
|
||||
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
|
||||
*
|
||||
* Emits a {Deposited} event.
|
||||
*/
|
||||
function depositFor(address target) external payable;
|
||||
|
||||
/**
|
||||
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
|
||||
*/
|
||||
event Deposited(address indexed recipient, address indexed from, uint256 amount);
|
||||
|
||||
/**
|
||||
* @dev Returns an account's deposits. These can be either a contract's funds, or a relay owner's revenue.
|
||||
*/
|
||||
function balanceOf(address target) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
|
||||
* contracts can use it to reduce their funding.
|
||||
*
|
||||
* Emits a {Withdrawn} event.
|
||||
*/
|
||||
function withdraw(uint256 amount, address payable dest) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when an account withdraws funds from `RelayHub`.
|
||||
*/
|
||||
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
|
||||
|
||||
// Relaying
|
||||
|
||||
/**
|
||||
* @dev Checks if the `RelayHub` will accept a relayed operation.
|
||||
* Multiple things must be true for this to happen:
|
||||
* - all arguments must be signed for by the sender (`from`)
|
||||
* - the sender's nonce must be the current one
|
||||
* - the recipient must accept this transaction (via {acceptRelayedCall})
|
||||
*
|
||||
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
|
||||
* code if it returns one in {acceptRelayedCall}.
|
||||
*/
|
||||
function canRelay(
|
||||
address relay,
|
||||
address from,
|
||||
address to,
|
||||
bytes calldata encodedFunction,
|
||||
uint256 transactionFee,
|
||||
uint256 gasPrice,
|
||||
uint256 gasLimit,
|
||||
uint256 nonce,
|
||||
bytes calldata signature,
|
||||
bytes calldata approvalData
|
||||
) external view returns (uint256 status, bytes memory recipientContext);
|
||||
|
||||
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
|
||||
enum PreconditionCheck {
|
||||
OK, // All checks passed, the call can be relayed
|
||||
WrongSignature, // The transaction to relay is not signed by requested sender
|
||||
WrongNonce, // The provided nonce has already been used by the sender
|
||||
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
|
||||
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Relays a transaction.
|
||||
*
|
||||
* For this to succeed, multiple conditions must be met:
|
||||
* - {canRelay} must `return PreconditionCheck.OK`
|
||||
* - the sender must be a registered relay
|
||||
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
|
||||
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
|
||||
* recipient) use all gas available to them
|
||||
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
|
||||
* spent)
|
||||
*
|
||||
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
|
||||
* function and {postRelayedCall} will be called in that order.
|
||||
*
|
||||
* Parameters:
|
||||
* - `from`: the client originating the request
|
||||
* - `to`: the target {IRelayRecipient} contract
|
||||
* - `encodedFunction`: the function call to relay, including data
|
||||
* - `transactionFee`: fee (%) the relay takes over actual gas cost
|
||||
* - `gasPrice`: gas price the client is willing to pay
|
||||
* - `gasLimit`: gas to forward when calling the encoded function
|
||||
* - `nonce`: client's nonce
|
||||
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
|
||||
* - `approvalData`: dapp-specific data forwarded to {acceptRelayedCall}. This value is *not* verified by the
|
||||
* `RelayHub`, but it still can be used for e.g. a signature.
|
||||
*
|
||||
* Emits a {TransactionRelayed} event.
|
||||
*/
|
||||
function relayCall(
|
||||
address from,
|
||||
address to,
|
||||
bytes calldata encodedFunction,
|
||||
uint256 transactionFee,
|
||||
uint256 gasPrice,
|
||||
uint256 gasLimit,
|
||||
uint256 nonce,
|
||||
bytes calldata signature,
|
||||
bytes calldata approvalData
|
||||
) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when an attempt to relay a call failed.
|
||||
*
|
||||
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
|
||||
* actual relayed call was not executed, and the recipient not charged.
|
||||
*
|
||||
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
|
||||
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
|
||||
*/
|
||||
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a transaction is relayed.
|
||||
* Useful when monitoring a relay's operation and relayed calls to a contract
|
||||
*
|
||||
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
|
||||
*
|
||||
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
|
||||
*/
|
||||
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
|
||||
|
||||
// Reason error codes for the TransactionRelayed event
|
||||
enum RelayCallStatus {
|
||||
OK, // The transaction was successfully relayed and execution successful - never included in the event
|
||||
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
|
||||
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
|
||||
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
|
||||
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
|
||||
* spend up to `relayedCallStipend` gas.
|
||||
*/
|
||||
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
|
||||
*/
|
||||
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
|
||||
|
||||
// Relay penalization.
|
||||
// Any account can penalize relays, removing them from the system immediately, and rewarding the
|
||||
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
|
||||
// still loses half of its stake.
|
||||
|
||||
/**
|
||||
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
|
||||
* different data (gas price, gas limit, etc. may be different).
|
||||
*
|
||||
* The (unsigned) transaction data and signature for both transactions must be provided.
|
||||
*/
|
||||
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
|
||||
|
||||
/**
|
||||
* @dev Penalize a relay that sent a transaction that didn't target ``RelayHub``'s {registerRelay} or {relayCall}.
|
||||
*/
|
||||
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
|
||||
|
||||
/**
|
||||
* @dev Emitted when a relay is penalized.
|
||||
*/
|
||||
event Penalized(address indexed relay, address sender, uint256 amount);
|
||||
|
||||
/**
|
||||
* @dev Returns an account's nonce in `RelayHub`.
|
||||
*/
|
||||
function getNonce(address from) external view returns (uint256);
|
||||
}
|
||||
|
||||
@ -1,76 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
/**
|
||||
* @dev Base interface for a contract that will be called via the GSN from {IRelayHub}.
|
||||
*
|
||||
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
|
||||
*/
|
||||
interface IRelayRecipient {
|
||||
/**
|
||||
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
|
||||
*/
|
||||
function getHubAddr() external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
|
||||
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
|
||||
*
|
||||
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
|
||||
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
|
||||
* and the transaction executed with a gas price of at least `gasPrice`. ``relay``'s fee is `transactionFee`, and the
|
||||
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
|
||||
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
|
||||
* over all or some of the previous values.
|
||||
*
|
||||
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
|
||||
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
|
||||
*
|
||||
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
|
||||
* rejected. A regular revert will also trigger a rejection.
|
||||
*/
|
||||
function acceptRelayedCall(
|
||||
address relay,
|
||||
address from,
|
||||
bytes calldata encodedFunction,
|
||||
uint256 transactionFee,
|
||||
uint256 gasPrice,
|
||||
uint256 gasLimit,
|
||||
uint256 nonce,
|
||||
bytes calldata approvalData,
|
||||
uint256 maxPossibleCharge
|
||||
)
|
||||
external
|
||||
view
|
||||
returns (uint256, bytes memory);
|
||||
|
||||
/**
|
||||
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
|
||||
* pre-charge the sender of the transaction.
|
||||
*
|
||||
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
|
||||
*
|
||||
* Returns a value to be passed to {postRelayedCall}.
|
||||
*
|
||||
* {preRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
|
||||
* will not be executed, but the recipient will still be charged for the transaction's cost.
|
||||
*/
|
||||
function preRelayedCall(bytes calldata context) external returns (bytes32);
|
||||
|
||||
/**
|
||||
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
|
||||
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
|
||||
* contract-specific bookkeeping.
|
||||
*
|
||||
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
|
||||
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
|
||||
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
|
||||
*
|
||||
*
|
||||
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
|
||||
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
|
||||
* transaction's cost.
|
||||
*/
|
||||
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
= Gas Station Network (GSN)
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/gsn
|
||||
|
||||
This set of contracts provide all the tools required to make a contract callable via the https://gsn.openzeppelin.com[Gas Station Network].
|
||||
|
||||
TIP: If you're new to the GSN, head over to our xref:learn::sending-gasless-transactions.adoc[overview of the system] and basic guide to xref:ROOT:gsn.adoc[creating a GSN-capable contract].
|
||||
|
||||
The core contract a recipient must inherit from is {GSNRecipient}: it includes all necessary interfaces, as well as some helper methods to make interacting with the GSN easier.
|
||||
|
||||
Utilities to make writing xref:ROOT:gsn-strategies.adoc[GSN strategies] easy are available in {GSNRecipient}, or you can simply use one of our pre-made strategies:
|
||||
|
||||
* {GSNRecipientERC20Fee} charges the end user for gas costs in an application-specific xref:ROOT:tokens.adoc#ERC20[ERC20 token]
|
||||
* {GSNRecipientSignature} accepts all relayed calls that have been signed by a trusted third party (e.g. a private key in a backend)
|
||||
|
||||
You can also take a look at the two contract interfaces that make up the GSN protocol: {IRelayRecipient} and {IRelayHub}, but you won't need to use those directly.
|
||||
|
||||
== Recipient
|
||||
|
||||
{{GSNRecipient}}
|
||||
|
||||
== Strategies
|
||||
|
||||
{{GSNRecipientSignature}}
|
||||
{{GSNRecipientERC20Fee}}
|
||||
|
||||
== Protocol
|
||||
|
||||
{{IRelayRecipient}}
|
||||
{{IRelayHub}}
|
||||
@ -1,14 +1,19 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/EnumerableSet.sol";
|
||||
import "../utils/Address.sol";
|
||||
import "./IAccessControl.sol";
|
||||
import "../utils/Context.sol";
|
||||
import "../utils/Strings.sol";
|
||||
import "../utils/introspection/ERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module that allows children to implement role-based access
|
||||
* control mechanisms.
|
||||
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
|
||||
* members except through off-chain means by accessing the contract event logs. Some
|
||||
* applications may benefit from on-chain enumerability, for those cases see
|
||||
* {AccessControlEnumerable}.
|
||||
*
|
||||
* Roles are referred to by their `bytes32` identifier. These should be exposed
|
||||
* in the external API and be unique. The best way to achieve this is by
|
||||
@ -41,75 +46,77 @@ import "../utils/Context.sol";
|
||||
* grant and revoke this role. Extra precautions should be taken to secure
|
||||
* accounts that have been granted it.
|
||||
*/
|
||||
abstract contract AccessControl is Context {
|
||||
using EnumerableSet for EnumerableSet.AddressSet;
|
||||
using Address for address;
|
||||
|
||||
abstract contract AccessControl is Context, IAccessControl, ERC165 {
|
||||
struct RoleData {
|
||||
EnumerableSet.AddressSet members;
|
||||
mapping(address => bool) members;
|
||||
bytes32 adminRole;
|
||||
}
|
||||
|
||||
mapping (bytes32 => RoleData) private _roles;
|
||||
mapping(bytes32 => RoleData) private _roles;
|
||||
|
||||
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
|
||||
|
||||
/**
|
||||
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
|
||||
* @dev Modifier that checks that an account has a specific role. Reverts
|
||||
* with a standardized message including the required role.
|
||||
*
|
||||
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
|
||||
* {RoleAdminChanged} not being emitted signaling this.
|
||||
* The format of the revert reason is given by the following regular expression:
|
||||
*
|
||||
* _Available since v3.1._
|
||||
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
|
||||
*
|
||||
* _Available since v4.1._
|
||||
*/
|
||||
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
|
||||
modifier onlyRole(bytes32 role) {
|
||||
_checkRole(role);
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is granted `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call, an admin role
|
||||
* bearer except when using {_setupRole}.
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is revoked `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call:
|
||||
* - if using `revokeRole`, it is the admin role bearer
|
||||
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
|
||||
*/
|
||||
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
|
||||
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if `account` has been granted `role`.
|
||||
*/
|
||||
function hasRole(bytes32 role, address account) public view returns (bool) {
|
||||
return _roles[role].members.contains(account);
|
||||
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
|
||||
return _roles[role].members[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of accounts that have `role`. Can be used
|
||||
* together with {getRoleMember} to enumerate all bearers of a role.
|
||||
* @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 getRoleMemberCount(bytes32 role) public view returns (uint256) {
|
||||
return _roles[role].members.length();
|
||||
function _checkRole(bytes32 role) internal view virtual {
|
||||
_checkRole(role, _msgSender());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns one of the accounts that have `role`. `index` must be a
|
||||
* value between 0 and {getRoleMemberCount}, non-inclusive.
|
||||
* @dev Revert with a standard message if `account` is missing `role`.
|
||||
*
|
||||
* Role bearers are not sorted in any particular way, and their ordering may
|
||||
* change at any point.
|
||||
* The format of the revert reason is given by the following regular expression:
|
||||
*
|
||||
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
|
||||
* you perform all queries on the same block. See the following
|
||||
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
|
||||
* for more information.
|
||||
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
|
||||
*/
|
||||
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
|
||||
return _roles[role].members.at(index);
|
||||
function _checkRole(bytes32 role, address account) internal view virtual {
|
||||
if (!hasRole(role, account)) {
|
||||
revert(
|
||||
string(
|
||||
abi.encodePacked(
|
||||
"AccessControl: account ",
|
||||
Strings.toHexString(uint160(account), 20),
|
||||
" is missing role ",
|
||||
Strings.toHexString(uint256(role), 32)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -118,7 +125,7 @@ abstract contract AccessControl is Context {
|
||||
*
|
||||
* To change a role's admin, use {_setRoleAdmin}.
|
||||
*/
|
||||
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
|
||||
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
|
||||
return _roles[role].adminRole;
|
||||
}
|
||||
|
||||
@ -131,10 +138,10 @@ abstract contract AccessControl is Context {
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*
|
||||
* May emit a {RoleGranted} event.
|
||||
*/
|
||||
function grantRole(bytes32 role, address account) public virtual {
|
||||
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
|
||||
|
||||
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
|
||||
_grantRole(role, account);
|
||||
}
|
||||
|
||||
@ -146,10 +153,10 @@ abstract contract AccessControl is Context {
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*
|
||||
* May emit a {RoleRevoked} event.
|
||||
*/
|
||||
function revokeRole(bytes32 role, address account) public virtual {
|
||||
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
|
||||
|
||||
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
|
||||
_revokeRole(role, account);
|
||||
}
|
||||
|
||||
@ -160,14 +167,16 @@ abstract contract AccessControl is Context {
|
||||
* purpose is to provide a mechanism for accounts to lose their privileges
|
||||
* if they are compromised (such as when a trusted device is misplaced).
|
||||
*
|
||||
* If the calling account had been granted `role`, emits a {RoleRevoked}
|
||||
* If the calling account had been revoked `role`, emits a {RoleRevoked}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be `account`.
|
||||
*
|
||||
* May emit a {RoleRevoked} event.
|
||||
*/
|
||||
function renounceRole(bytes32 role, address account) public virtual {
|
||||
function renounceRole(bytes32 role, address account) public virtual override {
|
||||
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
|
||||
|
||||
_revokeRole(role, account);
|
||||
@ -180,6 +189,8 @@ abstract contract AccessControl is Context {
|
||||
* 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
|
||||
@ -188,6 +199,8 @@ abstract contract AccessControl is Context {
|
||||
* Using this function in any other way is effectively circumventing the admin
|
||||
* system imposed by {AccessControl}.
|
||||
* ====
|
||||
*
|
||||
* NOTE: This function is deprecated in favor of {_grantRole}.
|
||||
*/
|
||||
function _setupRole(bytes32 role, address account) internal virtual {
|
||||
_grantRole(role, account);
|
||||
@ -199,18 +212,35 @@ abstract contract AccessControl is Context {
|
||||
* Emits a {RoleAdminChanged} event.
|
||||
*/
|
||||
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
|
||||
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
|
||||
bytes32 previousAdminRole = getRoleAdmin(role);
|
||||
_roles[role].adminRole = adminRole;
|
||||
emit RoleAdminChanged(role, previousAdminRole, adminRole);
|
||||
}
|
||||
|
||||
function _grantRole(bytes32 role, address account) private {
|
||||
if (_roles[role].members.add(account)) {
|
||||
/**
|
||||
* @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)) {
|
||||
_roles[role].members[account] = true;
|
||||
emit RoleGranted(role, account, _msgSender());
|
||||
}
|
||||
}
|
||||
|
||||
function _revokeRole(bytes32 role, address account) private {
|
||||
if (_roles[role].members.remove(account)) {
|
||||
/**
|
||||
* @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)) {
|
||||
_roles[role].members[account] = false;
|
||||
emit RoleRevoked(role, account, _msgSender());
|
||||
}
|
||||
}
|
||||
|
||||
45
contracts/access/AccessControlCrossChain.sol
Normal file
45
contracts/access/AccessControlCrossChain.sol
Normal 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;
|
||||
}
|
||||
}
|
||||
64
contracts/access/AccessControlEnumerable.sol
Normal file
64
contracts/access/AccessControlEnumerable.sol
Normal file
@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./IAccessControlEnumerable.sol";
|
||||
import "./AccessControl.sol";
|
||||
import "../utils/structs/EnumerableSet.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
|
||||
*/
|
||||
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
|
||||
using EnumerableSet for EnumerableSet.AddressSet;
|
||||
|
||||
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
|
||||
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns one of the accounts that have `role`. `index` must be a
|
||||
* value between 0 and {getRoleMemberCount}, non-inclusive.
|
||||
*
|
||||
* Role bearers are not sorted in any particular way, and their ordering may
|
||||
* change at any point.
|
||||
*
|
||||
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
|
||||
* you perform all queries on the same block. See the following
|
||||
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
|
||||
* for more information.
|
||||
*/
|
||||
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
|
||||
return _roleMembers[role].at(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of accounts that have `role`. Can be used
|
||||
* together with {getRoleMember} to enumerate all bearers of a role.
|
||||
*/
|
||||
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
|
||||
return _roleMembers[role].length();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload {_grantRole} to track enumerable memberships
|
||||
*/
|
||||
function _grantRole(bytes32 role, address account) internal virtual override {
|
||||
super._grantRole(role, account);
|
||||
_roleMembers[role].add(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload {_revokeRole} to track enumerable memberships
|
||||
*/
|
||||
function _revokeRole(bytes32 role, address account) internal virtual override {
|
||||
super._revokeRole(role, account);
|
||||
_roleMembers[role].remove(account);
|
||||
}
|
||||
}
|
||||
88
contracts/access/IAccessControl.sol
Normal file
88
contracts/access/IAccessControl.sol
Normal file
@ -0,0 +1,88 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControl declared to support ERC165 detection.
|
||||
*/
|
||||
interface IAccessControl {
|
||||
/**
|
||||
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
|
||||
*
|
||||
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
|
||||
* {RoleAdminChanged} not being emitted signaling this.
|
||||
*
|
||||
* _Available since v3.1._
|
||||
*/
|
||||
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is granted `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call, an admin role
|
||||
* bearer except when using {AccessControl-_setupRole}.
|
||||
*/
|
||||
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` is revoked `role`.
|
||||
*
|
||||
* `sender` is the account that originated the contract call:
|
||||
* - if using `revokeRole`, it is the admin role bearer
|
||||
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
|
||||
*/
|
||||
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
|
||||
|
||||
/**
|
||||
* @dev Returns `true` if `account` has been granted `role`.
|
||||
*/
|
||||
function hasRole(bytes32 role, address account) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Returns the admin role that controls `role`. See {grantRole} and
|
||||
* {revokeRole}.
|
||||
*
|
||||
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
|
||||
*/
|
||||
function getRoleAdmin(bytes32 role) external view returns (bytes32);
|
||||
|
||||
/**
|
||||
* @dev Grants `role` to `account`.
|
||||
*
|
||||
* If `account` had not been already granted `role`, emits a {RoleGranted}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*/
|
||||
function grantRole(bytes32 role, address account) external;
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from `account`.
|
||||
*
|
||||
* If `account` had been granted `role`, emits a {RoleRevoked} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have ``role``'s admin role.
|
||||
*/
|
||||
function revokeRole(bytes32 role, address account) external;
|
||||
|
||||
/**
|
||||
* @dev Revokes `role` from the calling account.
|
||||
*
|
||||
* Roles are often managed via {grantRole} and {revokeRole}: this function's
|
||||
* purpose is to provide a mechanism for accounts to lose their privileges
|
||||
* if they are compromised (such as when a trusted device is misplaced).
|
||||
*
|
||||
* If the calling account had been granted `role`, emits a {RoleRevoked}
|
||||
* event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must be `account`.
|
||||
*/
|
||||
function renounceRole(bytes32 role, address account) external;
|
||||
}
|
||||
31
contracts/access/IAccessControlEnumerable.sol
Normal file
31
contracts/access/IAccessControlEnumerable.sol
Normal file
@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./IAccessControl.sol";
|
||||
|
||||
/**
|
||||
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
|
||||
*/
|
||||
interface IAccessControlEnumerable is IAccessControl {
|
||||
/**
|
||||
* @dev Returns one of the accounts that have `role`. `index` must be a
|
||||
* value between 0 and {getRoleMemberCount}, non-inclusive.
|
||||
*
|
||||
* Role bearers are not sorted in any particular way, and their ordering may
|
||||
* change at any point.
|
||||
*
|
||||
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
|
||||
* you perform all queries on the same block. See the following
|
||||
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
|
||||
* for more information.
|
||||
*/
|
||||
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Returns the number of accounts that have `role`. Can be used
|
||||
* together with {getRoleMember} to enumerate all bearers of a role.
|
||||
*/
|
||||
function getRoleMemberCount(bytes32 role) external view returns (uint256);
|
||||
}
|
||||
@ -1,8 +1,10 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which provides a basic access control mechanism, where
|
||||
* there is an account (an owner) that can be granted exclusive access to
|
||||
@ -23,10 +25,16 @@ abstract contract Ownable is Context {
|
||||
/**
|
||||
* @dev Initializes the contract setting the deployer as the initial owner.
|
||||
*/
|
||||
constructor () {
|
||||
address msgSender = _msgSender();
|
||||
_owner = msgSender;
|
||||
emit OwnershipTransferred(address(0), msgSender);
|
||||
constructor() {
|
||||
_transferOwnership(_msgSender());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Throws if called by any account other than the owner.
|
||||
*/
|
||||
modifier onlyOwner() {
|
||||
_checkOwner();
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -37,11 +45,10 @@ 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");
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -52,8 +59,7 @@ abstract contract Ownable is Context {
|
||||
* thereby removing any functionality that is only available to the owner.
|
||||
*/
|
||||
function renounceOwnership() public virtual onlyOwner {
|
||||
emit OwnershipTransferred(_owner, address(0));
|
||||
_owner = address(0);
|
||||
_transferOwnership(address(0));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -62,7 +68,16 @@ abstract contract Ownable is Context {
|
||||
*/
|
||||
function transferOwnership(address newOwner) public virtual onlyOwner {
|
||||
require(newOwner != address(0), "Ownable: new owner is the zero address");
|
||||
emit OwnershipTransferred(_owner, newOwner);
|
||||
_transferOwnership(newOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers ownership of the contract to a new account (`newOwner`).
|
||||
* Internal function without access restriction.
|
||||
*/
|
||||
function _transferOwnership(address newOwner) internal virtual {
|
||||
address oldOwner = _owner;
|
||||
_owner = newOwner;
|
||||
emit OwnershipTransferred(oldOwner, newOwner);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
= Access
|
||||
= Access Control
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/access
|
||||
@ -7,95 +7,17 @@ This directory provides ways to restrict who can access the functions of a contr
|
||||
|
||||
- {AccessControl} provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts.
|
||||
- {Ownable} is a simpler mechanism with a single owner "role" that can be assigned to a single account. This simpler mechanism can be useful for quick tests but projects with production concerns are likely to outgrow it.
|
||||
- {TimelockController} is used in combination with one of the above two mechanisms. By assigning a role to an instance of the `TimelockController` contract, the access to the functions controlled by that role will be delayed by some amount of time.
|
||||
|
||||
== Authorization
|
||||
|
||||
{{Ownable}}
|
||||
|
||||
{{IAccessControl}}
|
||||
|
||||
{{AccessControl}}
|
||||
|
||||
== Timelock
|
||||
{{AccessControlCrossChain}}
|
||||
|
||||
{{TimelockController}}
|
||||
{{IAccessControlEnumerable}}
|
||||
|
||||
[[timelock-terminology]]
|
||||
==== Terminology
|
||||
|
||||
* *Operation:* A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see xref:access-control.adoc#operation_lifecycle[operation lifecycle]). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content.
|
||||
* *Operation status:*
|
||||
** *Unset:* An operation that is not part of the timelock mechanism.
|
||||
** *Pending:* An operation that has been scheduled, before the timer expires.
|
||||
** *Ready:* An operation that has been scheduled, after the timer expires.
|
||||
** *Done:* An operation that has been executed.
|
||||
* *Predecessor*: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations.
|
||||
* *Role*:
|
||||
** *Proposer:* An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations.
|
||||
** *Executor:* An address (smart contract or EOA) that is in charge of executing operations.
|
||||
|
||||
[[timelock-operation]]
|
||||
==== Operation structure
|
||||
|
||||
Operation executed by the xref:api:access.adoc#TimelockController[`TimelockControler`] can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations.
|
||||
|
||||
Both operations contain:
|
||||
|
||||
* *Target*, the address of the smart contract that the timelock should operate on.
|
||||
* *Value*, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction.
|
||||
* *Data*, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role `ROLE` to `ACCOUNT` can be encode using web3js as follows:
|
||||
|
||||
```javascript
|
||||
const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI()
|
||||
```
|
||||
|
||||
* *Predecessor*, that specifies a dependency between operations. This dependency is optional. Use `bytes32(0)` if the operation does not have any dependency.
|
||||
* *Salt*, used to disambiguate two otherwise identical operations. This can be any random value.
|
||||
|
||||
In the case of batched operations, `target`, `value` and `data` are specified as arrays, which must be of the same length.
|
||||
|
||||
[[timelock-operation-lifecycle]]
|
||||
==== Operation lifecycle
|
||||
|
||||
Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle:
|
||||
|
||||
`Unset` -> `Pending` -> `Pending` + `Ready` -> `Done`
|
||||
|
||||
* By calling xref:api:access.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:access.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:access.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method.
|
||||
* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed.
|
||||
* By calling xref:api:access.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:access.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed.
|
||||
* xref:api:access.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.
|
||||
|
||||
Operations status can be queried using the functions:
|
||||
|
||||
* xref:api:access.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`]
|
||||
* xref:api:access.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`]
|
||||
* xref:api:access.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`]
|
||||
|
||||
[[timelock-roles]]
|
||||
==== Roles
|
||||
|
||||
[[timelock-admin]]
|
||||
===== Admin
|
||||
|
||||
The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, both the timelock and the deployer have this role. After further configuration and testing, the deployer can renounce this role such that all further maintenance operations have to go through the timelock process.
|
||||
|
||||
This role is identified by the *TIMELOCK_ADMIN_ROLE* value: `0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5`
|
||||
|
||||
[[timelock-proposer]]
|
||||
===== Proposer
|
||||
|
||||
The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.
|
||||
|
||||
WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.
|
||||
|
||||
This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1`
|
||||
|
||||
[[timelock-executor]]
|
||||
===== Executor
|
||||
|
||||
The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executor can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers.
|
||||
|
||||
This role is identified by the *EXECUTOR_ROLE* value: `0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63`
|
||||
|
||||
|
||||
WARNING: A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the {AccessControl} documentation to learn more about role management.
|
||||
{{AccessControlEnumerable}}
|
||||
|
||||
54
contracts/crosschain/CrossChainEnabled.sol
Normal file
54
contracts/crosschain/CrossChainEnabled.sol
Normal 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);
|
||||
}
|
||||
34
contracts/crosschain/README.adoc
Normal file
34
contracts/crosschain/README.adoc
Normal 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}}
|
||||
49
contracts/crosschain/amb/CrossChainEnabledAMB.sol
Normal file
49
contracts/crosschain/amb/CrossChainEnabledAMB.sol
Normal 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);
|
||||
}
|
||||
}
|
||||
35
contracts/crosschain/amb/LibAMB.sol
Normal file
35
contracts/crosschain/amb/LibAMB.sol
Normal 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();
|
||||
}
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.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._
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
43
contracts/crosschain/arbitrum/LibArbitrumL1.sol
Normal file
43
contracts/crosschain/arbitrum/LibArbitrumL1.sol
Normal file
@ -0,0 +1,43 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/arbitrum/LibArbitrumL1.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import {IBridge as ArbitrumL1_Bridge} from "../../vendor/arbitrum/IBridge.sol";
|
||||
import {IInbox as ArbitrumL1_Inbox} from "../../vendor/arbitrum/IInbox.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;
|
||||
}
|
||||
}
|
||||
43
contracts/crosschain/arbitrum/LibArbitrumL2.sol
Normal file
43
contracts/crosschain/arbitrum/LibArbitrumL2.sol
Normal file
@ -0,0 +1,43 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/arbitrum/LibArbitrumL2.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import {IArbSys as ArbitrumL2_Bridge} from "../../vendor/arbitrum/IArbSys.sol";
|
||||
import "../errors.sol";
|
||||
|
||||
/**
|
||||
* @dev Primitives for cross-chain aware contracts for
|
||||
* https://arbitrum.io/[Arbitrum].
|
||||
*
|
||||
* This version should only be used on L2 to process cross-chain messages
|
||||
* originating from L1. For the other side, use {LibArbitrumL1}.
|
||||
*/
|
||||
library LibArbitrumL2 {
|
||||
/**
|
||||
* @dev Returns whether the current function call is the result of a
|
||||
* cross-chain message relayed by `arbsys`.
|
||||
*/
|
||||
address public constant ARBSYS = 0x0000000000000000000000000000000000000064;
|
||||
|
||||
function isCrossChain(address arbsys) internal view returns (bool) {
|
||||
return ArbitrumL2_Bridge(arbsys).isTopLevelCall();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the sender that triggered the current
|
||||
* cross-chain message through `arbsys`.
|
||||
*
|
||||
* 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 arbsys) internal view returns (address) {
|
||||
if (!isCrossChain(arbsys)) revert NotCrossChainCall();
|
||||
|
||||
return
|
||||
ArbitrumL2_Bridge(arbsys).wasMyCallersAddressAliased()
|
||||
? ArbitrumL2_Bridge(arbsys).myCallersAddressWithoutAliasing()
|
||||
: msg.sender;
|
||||
}
|
||||
}
|
||||
7
contracts/crosschain/errors.sol
Normal file
7
contracts/crosschain/errors.sol
Normal file
@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (crosschain/errors.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
error NotCrossChainCall();
|
||||
error InvalidCrossChainSender(address actual, address expected);
|
||||
41
contracts/crosschain/optimism/CrossChainEnabledOptimism.sol
Normal file
41
contracts/crosschain/optimism/CrossChainEnabledOptimism.sol
Normal file
@ -0,0 +1,41 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/optimism/CrossChainEnabledOptimism.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "../CrossChainEnabled.sol";
|
||||
import "./LibOptimism.sol";
|
||||
|
||||
/**
|
||||
* @dev https://www.optimism.io/[Optimism] specialization or the
|
||||
* {CrossChainEnabled} abstraction.
|
||||
*
|
||||
* The messenger (`CrossDomainMessenger`) contract is provided and maintained by
|
||||
* the optimism team. You can find the address of this contract on mainnet and
|
||||
* kovan in the https://github.com/ethereum-optimism/optimism/tree/develop/packages/contracts/deployments[deployments section of Optimism monorepo].
|
||||
*
|
||||
* _Available since v4.6._
|
||||
*/
|
||||
abstract contract CrossChainEnabledOptimism is CrossChainEnabled {
|
||||
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
|
||||
address private immutable _messenger;
|
||||
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor(address messenger) {
|
||||
_messenger = messenger;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev see {CrossChainEnabled-_isCrossChain}
|
||||
*/
|
||||
function _isCrossChain() internal view virtual override returns (bool) {
|
||||
return LibOptimism.isCrossChain(_messenger);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev see {CrossChainEnabled-_crossChainSender}
|
||||
*/
|
||||
function _crossChainSender() internal view virtual override onlyCrossChain returns (address) {
|
||||
return LibOptimism.crossChainSender(_messenger);
|
||||
}
|
||||
}
|
||||
36
contracts/crosschain/optimism/LibOptimism.sol
Normal file
36
contracts/crosschain/optimism/LibOptimism.sol
Normal file
@ -0,0 +1,36 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/optimism/LibOptimism.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import {ICrossDomainMessenger as Optimism_Bridge} from "../../vendor/optimism/ICrossDomainMessenger.sol";
|
||||
import "../errors.sol";
|
||||
|
||||
/**
|
||||
* @dev Primitives for cross-chain aware contracts for https://www.optimism.io/[Optimism].
|
||||
* See the https://community.optimism.io/docs/developers/bridge/messaging/#accessing-msg-sender[documentation]
|
||||
* for the functionality used here.
|
||||
*/
|
||||
library LibOptimism {
|
||||
/**
|
||||
* @dev Returns whether the current function call is the result of a
|
||||
* cross-chain message relayed by `messenger`.
|
||||
*/
|
||||
function isCrossChain(address messenger) internal view returns (bool) {
|
||||
return msg.sender == messenger;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the sender that triggered the current
|
||||
* cross-chain message through `messenger`.
|
||||
*
|
||||
* 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 messenger) internal view returns (address) {
|
||||
if (!isCrossChain(messenger)) revert NotCrossChainCall();
|
||||
|
||||
return Optimism_Bridge(messenger).xDomainMessageSender();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (crosschain/polygon/CrossChainEnabledPolygonChild.sol)
|
||||
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "../CrossChainEnabled.sol";
|
||||
import "../../security/ReentrancyGuard.sol";
|
||||
import "../../utils/Address.sol";
|
||||
import "../../vendor/polygon/IFxMessageProcessor.sol";
|
||||
|
||||
address constant DEFAULT_SENDER = 0x000000000000000000000000000000000000dEaD;
|
||||
|
||||
/**
|
||||
* @dev https://polygon.technology/[Polygon] specialization or the
|
||||
* {CrossChainEnabled} abstraction the child side (polygon/mumbai).
|
||||
*
|
||||
* This version should only be deployed on child chain to process cross-chain
|
||||
* messages originating from the parent chain.
|
||||
*
|
||||
* The fxChild contract is provided and maintained by the polygon team. You can
|
||||
* find the address of this contract polygon and mumbai in
|
||||
* https://docs.polygon.technology/docs/develop/l1-l2-communication/fx-portal/#contract-addresses[Polygon's Fx-Portal documentation].
|
||||
*
|
||||
* _Available since v4.6._
|
||||
*/
|
||||
abstract contract CrossChainEnabledPolygonChild is IFxMessageProcessor, CrossChainEnabled, ReentrancyGuard {
|
||||
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
|
||||
address private immutable _fxChild;
|
||||
address private _sender = DEFAULT_SENDER;
|
||||
|
||||
/// @custom:oz-upgrades-unsafe-allow constructor
|
||||
constructor(address fxChild) {
|
||||
_fxChild = fxChild;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev see {CrossChainEnabled-_isCrossChain}
|
||||
*/
|
||||
function _isCrossChain() internal view virtual override returns (bool) {
|
||||
return msg.sender == _fxChild;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev see {CrossChainEnabled-_crossChainSender}
|
||||
*/
|
||||
function _crossChainSender() internal view virtual override onlyCrossChain returns (address) {
|
||||
return _sender;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev External entry point to receive and relay messages originating
|
||||
* from the fxChild.
|
||||
*
|
||||
* Non-reentrancy is crucial to avoid a cross-chain call being able
|
||||
* to impersonate anyone by just looping through this with user-defined
|
||||
* arguments.
|
||||
*
|
||||
* Note: if _fxChild calls any other function that does a delegate-call,
|
||||
* then security could be compromised.
|
||||
*/
|
||||
function processMessageFromRoot(
|
||||
uint256, /* stateId */
|
||||
address rootMessageSender,
|
||||
bytes calldata data
|
||||
) external override nonReentrant {
|
||||
if (!_isCrossChain()) revert NotCrossChainCall();
|
||||
|
||||
_sender = rootMessageSender;
|
||||
Address.functionDelegateCall(address(this), data, "cross-chain execution failed");
|
||||
_sender = DEFAULT_SENDER;
|
||||
}
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
/**
|
||||
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
|
||||
*
|
||||
* These functions can be used to verify that a message was signed by the holder
|
||||
* of the private keys of a given address.
|
||||
*/
|
||||
library ECDSA {
|
||||
/**
|
||||
* @dev Returns the address that signed a hashed message (`hash`) with
|
||||
* `signature`. This address can then be used for verification purposes.
|
||||
*
|
||||
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
|
||||
* this function rejects them by requiring the `s` value to be in the lower
|
||||
* half order, and the `v` value to be either 27 or 28.
|
||||
*
|
||||
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
|
||||
* verification to be secure: it is possible to craft signatures that
|
||||
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
|
||||
* this is by receiving a hash of the original message (which may otherwise
|
||||
* be too long), and then calling {toEthSignedMessageHash} on it.
|
||||
*/
|
||||
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
|
||||
// Check the signature length
|
||||
if (signature.length != 65) {
|
||||
revert("ECDSA: invalid signature length");
|
||||
}
|
||||
|
||||
// Divide the signature in r, s and v variables
|
||||
bytes32 r;
|
||||
bytes32 s;
|
||||
uint8 v;
|
||||
|
||||
// ecrecover takes the signature parameters, and the only way to get them
|
||||
// currently is to use assembly.
|
||||
// solhint-disable-next-line no-inline-assembly
|
||||
assembly {
|
||||
r := mload(add(signature, 0x20))
|
||||
s := mload(add(signature, 0x40))
|
||||
v := byte(0, mload(add(signature, 0x60)))
|
||||
}
|
||||
|
||||
return recover(hash, v, r, s);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
|
||||
* `r` and `s` signature fields separately.
|
||||
*/
|
||||
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
|
||||
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
|
||||
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
|
||||
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
|
||||
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
|
||||
//
|
||||
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
|
||||
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
|
||||
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
|
||||
// these malleable signatures as well.
|
||||
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
|
||||
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
|
||||
|
||||
// If the signature is valid (and not malleable), return the signer address
|
||||
address signer = ecrecover(hash, v, r, s);
|
||||
require(signer != address(0), "ECDSA: invalid signature");
|
||||
|
||||
return signer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
|
||||
* replicates the behavior of the
|
||||
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
|
||||
* JSON-RPC method.
|
||||
*
|
||||
* See {recover}.
|
||||
*/
|
||||
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
|
||||
// 32 is the length in bytes of hash,
|
||||
// enforced by the type signature above
|
||||
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
|
||||
}
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
|
||||
/**
|
||||
* @dev These functions deal with verification of Merkle trees (hash trees),
|
||||
*/
|
||||
library MerkleProof {
|
||||
/**
|
||||
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
|
||||
* defined by `root`. For this, a `proof` must be provided, containing
|
||||
* sibling hashes on the branch from the leaf to the root of the tree. Each
|
||||
* pair of leaves and each pair of pre-images are assumed to be sorted.
|
||||
*/
|
||||
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
|
||||
bytes32 computedHash = leaf;
|
||||
|
||||
for (uint256 i = 0; i < proof.length; i++) {
|
||||
bytes32 proofElement = proof[i];
|
||||
|
||||
if (computedHash <= proofElement) {
|
||||
// Hash(current computed hash + current element of the proof)
|
||||
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
|
||||
} else {
|
||||
// Hash(current element of the proof + current computed hash)
|
||||
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the computed hash (root) is equal to the provided root
|
||||
return computedHash == root;
|
||||
}
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
= Cryptography
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/cryptography
|
||||
|
||||
This collection of libraries provides simple and safe ways to use different cryptographic primitives.
|
||||
|
||||
The following related EIPs are in draft status and can be found in the drafts directory.
|
||||
|
||||
- {EIP712}
|
||||
|
||||
== Libraries
|
||||
|
||||
{{ECDSA}}
|
||||
|
||||
{{MerkleProof}}
|
||||
@ -1,76 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity >=0.6.5 <0.8.0;
|
||||
|
||||
import "../token/ERC20/ERC20.sol";
|
||||
import "./IERC20Permit.sol";
|
||||
import "../cryptography/ECDSA.sol";
|
||||
import "../utils/Counters.sol";
|
||||
import "./EIP712.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
|
||||
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
|
||||
* need to send a transaction, and thus is not required to hold Ether at all.
|
||||
*/
|
||||
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
|
||||
using Counters for Counters.Counter;
|
||||
|
||||
mapping (address => Counters.Counter) private _nonces;
|
||||
|
||||
// solhint-disable-next-line var-name-mixedcase
|
||||
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
||||
|
||||
/**
|
||||
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
|
||||
*
|
||||
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
|
||||
*/
|
||||
constructor(string memory name) EIP712(name, "1") {
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20Permit-permit}.
|
||||
*/
|
||||
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
|
||||
// solhint-disable-next-line not-rely-on-time
|
||||
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
|
||||
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(
|
||||
_PERMIT_TYPEHASH,
|
||||
owner,
|
||||
spender,
|
||||
value,
|
||||
_nonces[owner].current(),
|
||||
deadline
|
||||
)
|
||||
);
|
||||
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
address signer = ECDSA.recover(hash, v, r, s);
|
||||
require(signer == owner, "ERC20Permit: invalid signature");
|
||||
|
||||
_nonces[owner].increment();
|
||||
_approve(owner, spender, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20Permit-nonces}.
|
||||
*/
|
||||
function nonces(address owner) public view override returns (uint256) {
|
||||
return _nonces[owner].current();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
|
||||
return _domainSeparatorV4();
|
||||
}
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
= Draft EIPs
|
||||
|
||||
This directory contains implementations of EIPs that are still in Draft status.
|
||||
|
||||
Due to their nature as drafts, the details of these contracts may change and we cannot guarantee their xref:ROOT:releases-stability.adoc[stability]. Minor releases of OpenZeppelin Contracts may contain breaking changes for the contracts in this directory, which will be duly announced in the https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CHANGELOG.md[changelog]. The EIPs included here are used by projects in production and this may make them less likely to change significantly.
|
||||
|
||||
== Cryptography
|
||||
|
||||
{{EIP712}}
|
||||
|
||||
== ERC 20
|
||||
|
||||
{{IERC20Permit}}
|
||||
|
||||
{{ERC20Permit}}
|
||||
@ -1,10 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (finance/PaymentSplitter.sol)
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/Context.sol";
|
||||
import "../math/SafeMath.sol";
|
||||
import "../token/ERC20/utils/SafeERC20.sol";
|
||||
import "../utils/Address.sol";
|
||||
import "../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @title PaymentSplitter
|
||||
@ -13,17 +14,21 @@ import "../utils/Address.sol";
|
||||
*
|
||||
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
|
||||
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
|
||||
* an amount proportional to the percentage of total shares they were assigned.
|
||||
* an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the
|
||||
* time of contract deployment and can't be updated thereafter.
|
||||
*
|
||||
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
|
||||
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
|
||||
* function.
|
||||
*
|
||||
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
|
||||
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
|
||||
* to run tests before sending real value to this contract.
|
||||
*/
|
||||
contract PaymentSplitter is Context {
|
||||
using SafeMath for uint256;
|
||||
|
||||
event PayeeAdded(address account, uint256 shares);
|
||||
event PaymentReleased(address to, uint256 amount);
|
||||
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
|
||||
event PaymentReceived(address from, uint256 amount);
|
||||
|
||||
uint256 private _totalShares;
|
||||
@ -33,6 +38,9 @@ contract PaymentSplitter is Context {
|
||||
mapping(address => uint256) private _released;
|
||||
address[] private _payees;
|
||||
|
||||
mapping(IERC20 => uint256) private _erc20TotalReleased;
|
||||
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
|
||||
|
||||
/**
|
||||
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
|
||||
* the matching position in the `shares` array.
|
||||
@ -40,8 +48,7 @@ contract PaymentSplitter is Context {
|
||||
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
|
||||
* duplicates in `payees`.
|
||||
*/
|
||||
constructor (address[] memory payees, uint256[] memory shares_) payable {
|
||||
// solhint-disable-next-line max-line-length
|
||||
constructor(address[] memory payees, uint256[] memory shares_) payable {
|
||||
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
|
||||
require(payees.length > 0, "PaymentSplitter: no payees");
|
||||
|
||||
@ -59,7 +66,7 @@ contract PaymentSplitter is Context {
|
||||
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
|
||||
* functions].
|
||||
*/
|
||||
receive () external payable virtual {
|
||||
receive() external payable virtual {
|
||||
emit PaymentReceived(_msgSender(), msg.value);
|
||||
}
|
||||
|
||||
@ -77,6 +84,14 @@ contract PaymentSplitter is Context {
|
||||
return _totalReleased;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
|
||||
* contract.
|
||||
*/
|
||||
function totalReleased(IERC20 token) public view returns (uint256) {
|
||||
return _erc20TotalReleased[token];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of shares held by an account.
|
||||
*/
|
||||
@ -91,6 +106,14 @@ contract PaymentSplitter is Context {
|
||||
return _released[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
|
||||
* IERC20 contract.
|
||||
*/
|
||||
function released(IERC20 token, address account) public view returns (uint256) {
|
||||
return _erc20Released[token][account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the address of the payee number `index`.
|
||||
*/
|
||||
@ -98,6 +121,23 @@ contract PaymentSplitter is Context {
|
||||
return _payees[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of payee's releasable Ether.
|
||||
*/
|
||||
function releasable(address account) public view returns (uint256) {
|
||||
uint256 totalReceived = address(this).balance + totalReleased();
|
||||
return _pendingPayment(account, totalReceived, released(account));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the amount of payee's releasable `token` tokens. `token` should be the address of an
|
||||
* IERC20 contract.
|
||||
*/
|
||||
function releasable(IERC20 token, address account) public view returns (uint256) {
|
||||
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
|
||||
return _pendingPayment(account, totalReceived, released(token, account));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
|
||||
* total shares and their previous withdrawals.
|
||||
@ -105,18 +145,48 @@ contract PaymentSplitter is Context {
|
||||
function release(address payable account) public virtual {
|
||||
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
|
||||
|
||||
uint256 totalReceived = address(this).balance.add(_totalReleased);
|
||||
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]);
|
||||
uint256 payment = releasable(account);
|
||||
|
||||
require(payment != 0, "PaymentSplitter: account is not due payment");
|
||||
|
||||
_released[account] = _released[account].add(payment);
|
||||
_totalReleased = _totalReleased.add(payment);
|
||||
_released[account] += payment;
|
||||
_totalReleased += payment;
|
||||
|
||||
Address.sendValue(account, payment);
|
||||
emit PaymentReleased(account, payment);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
|
||||
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
|
||||
* contract.
|
||||
*/
|
||||
function release(IERC20 token, address account) public virtual {
|
||||
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
|
||||
|
||||
uint256 payment = releasable(token, account);
|
||||
|
||||
require(payment != 0, "PaymentSplitter: account is not due payment");
|
||||
|
||||
_erc20Released[token][account] += payment;
|
||||
_erc20TotalReleased[token] += payment;
|
||||
|
||||
SafeERC20.safeTransfer(token, account, payment);
|
||||
emit ERC20PaymentReleased(token, account, payment);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
|
||||
* already released amounts.
|
||||
*/
|
||||
function _pendingPayment(
|
||||
address account,
|
||||
uint256 totalReceived,
|
||||
uint256 alreadyReleased
|
||||
) private view returns (uint256) {
|
||||
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Add a new payee to the contract.
|
||||
* @param account The address of the payee to add.
|
||||
@ -129,7 +199,7 @@ contract PaymentSplitter is Context {
|
||||
|
||||
_payees.push(account);
|
||||
_shares[account] = shares_;
|
||||
_totalShares = _totalShares.add(shares_);
|
||||
_totalShares = _totalShares + shares_;
|
||||
emit PayeeAdded(account, shares_);
|
||||
}
|
||||
}
|
||||
20
contracts/finance/README.adoc
Normal file
20
contracts/finance/README.adoc
Normal file
@ -0,0 +1,20 @@
|
||||
= Finance
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/finance
|
||||
|
||||
This directory includes primitives for financial systems:
|
||||
|
||||
- {PaymentSplitter} allows to split Ether and ERC20 payments among a group of accounts. The sender does not need to be
|
||||
aware that the assets will be split in this way, since it is handled transparently by the contract. The split can be
|
||||
in equal parts or in any other arbitrary proportion.
|
||||
|
||||
- {VestingWallet} handles the vesting of Ether and ERC20 tokens for a given beneficiary. Custody of multiple tokens can
|
||||
be given to this contract, which will release the token to the beneficiary following a given, customizable, vesting
|
||||
schedule.
|
||||
|
||||
== Contracts
|
||||
|
||||
{{PaymentSplitter}}
|
||||
|
||||
{{VestingWallet}}
|
||||
135
contracts/finance/VestingWallet.sol
Normal file
135
contracts/finance/VestingWallet.sol
Normal file
@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (finance/VestingWallet.sol)
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../token/ERC20/utils/SafeERC20.sol";
|
||||
import "../utils/Address.sol";
|
||||
import "../utils/Context.sol";
|
||||
import "../utils/math/Math.sol";
|
||||
|
||||
/**
|
||||
* @title VestingWallet
|
||||
* @dev This contract handles the vesting of Eth and ERC20 tokens for a given beneficiary. Custody of multiple tokens
|
||||
* can be given to this contract, which will release the token to the beneficiary following a given vesting schedule.
|
||||
* The vesting schedule is customizable through the {vestedAmount} function.
|
||||
*
|
||||
* Any token transferred to this contract will follow the vesting schedule as if they were locked from the beginning.
|
||||
* Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly)
|
||||
* be immediately releasable.
|
||||
*/
|
||||
contract VestingWallet is Context {
|
||||
event EtherReleased(uint256 amount);
|
||||
event ERC20Released(address indexed token, uint256 amount);
|
||||
|
||||
uint256 private _released;
|
||||
mapping(address => uint256) private _erc20Released;
|
||||
address private immutable _beneficiary;
|
||||
uint64 private immutable _start;
|
||||
uint64 private immutable _duration;
|
||||
|
||||
/**
|
||||
* @dev Set the beneficiary, start timestamp and vesting duration of the vesting wallet.
|
||||
*/
|
||||
constructor(
|
||||
address beneficiaryAddress,
|
||||
uint64 startTimestamp,
|
||||
uint64 durationSeconds
|
||||
) {
|
||||
require(beneficiaryAddress != address(0), "VestingWallet: beneficiary is zero address");
|
||||
_beneficiary = beneficiaryAddress;
|
||||
_start = startTimestamp;
|
||||
_duration = durationSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The contract should be able to receive Eth.
|
||||
*/
|
||||
receive() external payable virtual {}
|
||||
|
||||
/**
|
||||
* @dev Getter for the beneficiary address.
|
||||
*/
|
||||
function beneficiary() public view virtual returns (address) {
|
||||
return _beneficiary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the start timestamp.
|
||||
*/
|
||||
function start() public view virtual returns (uint256) {
|
||||
return _start;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Getter for the vesting duration.
|
||||
*/
|
||||
function duration() public view virtual returns (uint256) {
|
||||
return _duration;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of eth already released
|
||||
*/
|
||||
function released() public view virtual returns (uint256) {
|
||||
return _released;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of token already released
|
||||
*/
|
||||
function released(address token) public view virtual returns (uint256) {
|
||||
return _erc20Released[token];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Release the native token (ether) that have already vested.
|
||||
*
|
||||
* Emits a {EtherReleased} event.
|
||||
*/
|
||||
function release() public virtual {
|
||||
uint256 releasable = vestedAmount(uint64(block.timestamp)) - released();
|
||||
_released += releasable;
|
||||
emit EtherReleased(releasable);
|
||||
Address.sendValue(payable(beneficiary()), releasable);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Release the tokens that have already vested.
|
||||
*
|
||||
* Emits a {ERC20Released} event.
|
||||
*/
|
||||
function release(address token) public virtual {
|
||||
uint256 releasable = vestedAmount(token, uint64(block.timestamp)) - released(token);
|
||||
_erc20Released[token] += releasable;
|
||||
emit ERC20Released(token, releasable);
|
||||
SafeERC20.safeTransfer(IERC20(token), beneficiary(), releasable);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Calculates the amount of ether that has already vested. Default implementation is a linear vesting curve.
|
||||
*/
|
||||
function vestedAmount(uint64 timestamp) public view virtual returns (uint256) {
|
||||
return _vestingSchedule(address(this).balance + released(), timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Calculates the amount of tokens that has already vested. Default implementation is a linear vesting curve.
|
||||
*/
|
||||
function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) {
|
||||
return _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Virtual implementation of the vesting formula. This returns the amount vested, as a function of time, for
|
||||
* an asset given its total historical allocation.
|
||||
*/
|
||||
function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) {
|
||||
if (timestamp < start()) {
|
||||
return 0;
|
||||
} else if (timestamp > start() + duration()) {
|
||||
return totalAllocation;
|
||||
} else {
|
||||
return (totalAllocation * (timestamp - start())) / duration();
|
||||
}
|
||||
}
|
||||
}
|
||||
596
contracts/governance/Governor.sol
Normal file
596
contracts/governance/Governor.sol
Normal file
@ -0,0 +1,596 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (governance/Governor.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../token/ERC721/IERC721Receiver.sol";
|
||||
import "../token/ERC1155/IERC1155Receiver.sol";
|
||||
import "../utils/cryptography/ECDSA.sol";
|
||||
import "../utils/cryptography/draft-EIP712.sol";
|
||||
import "../utils/introspection/ERC165.sol";
|
||||
import "../utils/math/SafeCast.sol";
|
||||
import "../utils/structs/DoubleEndedQueue.sol";
|
||||
import "../utils/Address.sol";
|
||||
import "../utils/Context.sol";
|
||||
import "../utils/Timers.sol";
|
||||
import "./IGovernor.sol";
|
||||
|
||||
/**
|
||||
* @dev Core of the governance system, designed to be extended though various modules.
|
||||
*
|
||||
* This contract is abstract and requires several function to be implemented in various modules:
|
||||
*
|
||||
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
|
||||
* - A voting module must implement {_getVotes}
|
||||
* - Additionanly, the {votingPeriod} must also be implemented
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
|
||||
using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
|
||||
using SafeCast for uint256;
|
||||
using Timers for Timers.BlockNumber;
|
||||
|
||||
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
|
||||
bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
|
||||
keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
|
||||
|
||||
struct ProposalCore {
|
||||
Timers.BlockNumber voteStart;
|
||||
Timers.BlockNumber voteEnd;
|
||||
bool executed;
|
||||
bool canceled;
|
||||
}
|
||||
|
||||
string private _name;
|
||||
|
||||
mapping(uint256 => ProposalCore) private _proposals;
|
||||
|
||||
// This queue keeps track of the governor operating on itself. Calls to functions protected by the
|
||||
// {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
|
||||
// consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
|
||||
// execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
|
||||
DoubleEndedQueue.Bytes32Deque private _governanceCall;
|
||||
|
||||
/**
|
||||
* @dev Restricts a function so it can only be executed through governance proposals. For example, governance
|
||||
* parameter setters in {GovernorSettings} are protected using this modifier.
|
||||
*
|
||||
* The governance executing address may be different from the Governor's own address, for example it could be a
|
||||
* timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
|
||||
* functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
|
||||
* for example, additional timelock proposers are not able to change governance parameters without going through the
|
||||
* governance protocol (since v4.6).
|
||||
*/
|
||||
modifier onlyGovernance() {
|
||||
require(_msgSender() == _executor(), "Governor: onlyGovernance");
|
||||
if (_executor() != address(this)) {
|
||||
bytes32 msgDataHash = keccak256(_msgData());
|
||||
// loop until popping the expected operation - throw if deque is empty (operation not authorized)
|
||||
while (_governanceCall.popFront() != msgDataHash) {}
|
||||
}
|
||||
_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the value for {name} and {version}
|
||||
*/
|
||||
constructor(string memory name_) EIP712(name_, version()) {
|
||||
_name = name_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
|
||||
*/
|
||||
receive() external payable virtual {
|
||||
require(_executor() == address(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
|
||||
// In addition to the current interfaceId, also support previous version of the interfaceId that did not
|
||||
// include the castVoteWithReasonAndParams() function as standard
|
||||
return
|
||||
interfaceId ==
|
||||
(type(IGovernor).interfaceId ^
|
||||
this.castVoteWithReasonAndParams.selector ^
|
||||
this.castVoteWithReasonAndParamsBySig.selector ^
|
||||
this.getVotesWithParams.selector) ||
|
||||
interfaceId == type(IGovernor).interfaceId ||
|
||||
interfaceId == type(IERC1155Receiver).interfaceId ||
|
||||
super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-name}.
|
||||
*/
|
||||
function name() public view virtual override returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-version}.
|
||||
*/
|
||||
function version() public view virtual override returns (string memory) {
|
||||
return "1";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-hashProposal}.
|
||||
*
|
||||
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
|
||||
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
|
||||
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
|
||||
* advance, before the proposal is submitted.
|
||||
*
|
||||
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
|
||||
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
|
||||
* across multiple networks. This also means that in order to execute the same operation twice (on the same
|
||||
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
|
||||
*/
|
||||
function hashProposal(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public pure virtual override returns (uint256) {
|
||||
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-state}.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
|
||||
ProposalCore storage proposal = _proposals[proposalId];
|
||||
|
||||
if (proposal.executed) {
|
||||
return ProposalState.Executed;
|
||||
}
|
||||
|
||||
if (proposal.canceled) {
|
||||
return ProposalState.Canceled;
|
||||
}
|
||||
|
||||
uint256 snapshot = proposalSnapshot(proposalId);
|
||||
|
||||
if (snapshot == 0) {
|
||||
revert("Governor: unknown proposal id");
|
||||
}
|
||||
|
||||
if (snapshot >= block.number) {
|
||||
return ProposalState.Pending;
|
||||
}
|
||||
|
||||
uint256 deadline = proposalDeadline(proposalId);
|
||||
|
||||
if (deadline >= block.number) {
|
||||
return ProposalState.Active;
|
||||
}
|
||||
|
||||
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
|
||||
return ProposalState.Succeeded;
|
||||
} else {
|
||||
return ProposalState.Defeated;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalSnapshot}.
|
||||
*/
|
||||
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
return _proposals[proposalId].voteStart.getDeadline();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-proposalDeadline}.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
return _proposals[proposalId].voteEnd.getDeadline();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
|
||||
*/
|
||||
function proposalThreshold() public view virtual returns (uint256) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Amount of votes already cast passes the threshold limit.
|
||||
*/
|
||||
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Is the proposal successful or not.
|
||||
*/
|
||||
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Get the voting weight of `account` at a specific `blockNumber`, for a vote as described by `params`.
|
||||
*/
|
||||
function _getVotes(
|
||||
address account,
|
||||
uint256 blockNumber,
|
||||
bytes memory params
|
||||
) internal view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
|
||||
*
|
||||
* Note: Support is generic and can represent various things depending on the voting system used.
|
||||
*/
|
||||
function _countVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
bytes memory params
|
||||
) internal virtual;
|
||||
|
||||
/**
|
||||
* @dev Default additional encoded parameters used by castVote methods that don't include them
|
||||
*
|
||||
* Note: Should be overridden by specific implementations to use an appropriate value, the
|
||||
* meaning of the additional params, in the context of that implementation
|
||||
*/
|
||||
function _defaultParams() internal view virtual returns (bytes memory) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-propose}.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual override returns (uint256) {
|
||||
require(
|
||||
getVotes(_msgSender(), block.number - 1) >= proposalThreshold(),
|
||||
"Governor: proposer votes below proposal threshold"
|
||||
);
|
||||
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
|
||||
|
||||
require(targets.length == values.length, "Governor: invalid proposal length");
|
||||
require(targets.length == calldatas.length, "Governor: invalid proposal length");
|
||||
require(targets.length > 0, "Governor: empty proposal");
|
||||
|
||||
ProposalCore storage proposal = _proposals[proposalId];
|
||||
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
|
||||
|
||||
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
|
||||
uint64 deadline = snapshot + votingPeriod().toUint64();
|
||||
|
||||
proposal.voteStart.setDeadline(snapshot);
|
||||
proposal.voteEnd.setDeadline(deadline);
|
||||
|
||||
emit ProposalCreated(
|
||||
proposalId,
|
||||
_msgSender(),
|
||||
targets,
|
||||
values,
|
||||
new string[](targets.length),
|
||||
calldatas,
|
||||
snapshot,
|
||||
deadline,
|
||||
description
|
||||
);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-execute}.
|
||||
*/
|
||||
function execute(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public payable virtual override returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
ProposalState status = state(proposalId);
|
||||
require(
|
||||
status == ProposalState.Succeeded || status == ProposalState.Queued,
|
||||
"Governor: proposal not successful"
|
||||
);
|
||||
_proposals[proposalId].executed = true;
|
||||
|
||||
emit ProposalExecuted(proposalId);
|
||||
|
||||
_beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
|
||||
_execute(proposalId, targets, values, calldatas, descriptionHash);
|
||||
_afterExecute(proposalId, targets, values, calldatas, descriptionHash);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
|
||||
*/
|
||||
function _execute(
|
||||
uint256, /* proposalId */
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual {
|
||||
string memory errorMessage = "Governor: call reverted without message";
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
|
||||
Address.verifyCallResult(success, returndata, errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Hook before execution is triggered.
|
||||
*/
|
||||
function _beforeExecute(
|
||||
uint256, /* proposalId */
|
||||
address[] memory targets,
|
||||
uint256[] memory, /* values */
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual {
|
||||
if (_executor() != address(this)) {
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
if (targets[i] == address(this)) {
|
||||
_governanceCall.pushBack(keccak256(calldatas[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Hook after execution is triggered.
|
||||
*/
|
||||
function _afterExecute(
|
||||
uint256, /* proposalId */
|
||||
address[] memory, /* targets */
|
||||
uint256[] memory, /* values */
|
||||
bytes[] memory, /* calldatas */
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual {
|
||||
if (_executor() != address(this)) {
|
||||
if (!_governanceCall.empty()) {
|
||||
_governanceCall.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
|
||||
* canceled to allow distinguishing it from executed proposals.
|
||||
*
|
||||
* Emits a {IGovernor-ProposalCanceled} event.
|
||||
*/
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
ProposalState status = state(proposalId);
|
||||
|
||||
require(
|
||||
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
|
||||
"Governor: proposal not active"
|
||||
);
|
||||
_proposals[proposalId].canceled = true;
|
||||
|
||||
emit ProposalCanceled(proposalId);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-getVotes}.
|
||||
*/
|
||||
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
|
||||
return _getVotes(account, blockNumber, _defaultParams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-getVotesWithParams}.
|
||||
*/
|
||||
function getVotesWithParams(
|
||||
address account,
|
||||
uint256 blockNumber,
|
||||
bytes memory params
|
||||
) public view virtual override returns (uint256) {
|
||||
return _getVotes(account, blockNumber, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVote}.
|
||||
*/
|
||||
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReason}.
|
||||
*/
|
||||
function castVoteWithReason(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason
|
||||
) public virtual override returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReasonAndParams}.
|
||||
*/
|
||||
function castVoteWithReasonAndParams(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params
|
||||
) public virtual override returns (uint256) {
|
||||
address voter = _msgSender();
|
||||
return _castVote(proposalId, voter, support, reason, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteBySig}.
|
||||
*/
|
||||
function castVoteBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual override returns (uint256) {
|
||||
address voter = ECDSA.recover(
|
||||
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
|
||||
v,
|
||||
r,
|
||||
s
|
||||
);
|
||||
return _castVote(proposalId, voter, support, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
|
||||
*/
|
||||
function castVoteWithReasonAndParamsBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual override returns (uint256) {
|
||||
address voter = ECDSA.recover(
|
||||
_hashTypedDataV4(
|
||||
keccak256(
|
||||
abi.encode(
|
||||
EXTENDED_BALLOT_TYPEHASH,
|
||||
proposalId,
|
||||
support,
|
||||
keccak256(bytes(reason)),
|
||||
keccak256(params)
|
||||
)
|
||||
)
|
||||
),
|
||||
v,
|
||||
r,
|
||||
s
|
||||
);
|
||||
|
||||
return _castVote(proposalId, voter, support, reason, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
|
||||
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
|
||||
*
|
||||
* Emits a {IGovernor-VoteCast} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason
|
||||
) internal virtual returns (uint256) {
|
||||
return _castVote(proposalId, account, support, reason, _defaultParams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
|
||||
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
|
||||
*
|
||||
* Emits a {IGovernor-VoteCast} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason,
|
||||
bytes memory params
|
||||
) internal virtual returns (uint256) {
|
||||
ProposalCore storage proposal = _proposals[proposalId];
|
||||
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
|
||||
|
||||
uint256 weight = _getVotes(account, proposal.voteStart.getDeadline(), params);
|
||||
_countVote(proposalId, account, support, weight, params);
|
||||
|
||||
if (params.length == 0) {
|
||||
emit VoteCast(account, proposalId, support, weight, reason);
|
||||
} else {
|
||||
emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
|
||||
}
|
||||
|
||||
return weight;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
|
||||
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
|
||||
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
|
||||
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
|
||||
*/
|
||||
function relay(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) external virtual onlyGovernance {
|
||||
Address.functionCallWithValue(target, data, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
|
||||
* through another contract such as a timelock.
|
||||
*/
|
||||
function _executor() internal view virtual returns (address) {
|
||||
return address(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Receiver-onERC721Received}.
|
||||
*/
|
||||
function onERC721Received(
|
||||
address,
|
||||
address,
|
||||
uint256,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC721Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155Received}.
|
||||
*/
|
||||
function onERC1155Received(
|
||||
address,
|
||||
address,
|
||||
uint256,
|
||||
uint256,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
|
||||
*/
|
||||
function onERC1155BatchReceived(
|
||||
address,
|
||||
address,
|
||||
uint256[] memory,
|
||||
uint256[] memory,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155BatchReceived.selector;
|
||||
}
|
||||
}
|
||||
276
contracts/governance/IGovernor.sol
Normal file
276
contracts/governance/IGovernor.sol
Normal file
@ -0,0 +1,276 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (governance/IGovernor.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/introspection/ERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface of the {Governor} core.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract IGovernor is IERC165 {
|
||||
enum ProposalState {
|
||||
Pending,
|
||||
Active,
|
||||
Canceled,
|
||||
Defeated,
|
||||
Succeeded,
|
||||
Queued,
|
||||
Expired,
|
||||
Executed
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is created.
|
||||
*/
|
||||
event ProposalCreated(
|
||||
uint256 proposalId,
|
||||
address proposer,
|
||||
address[] targets,
|
||||
uint256[] values,
|
||||
string[] signatures,
|
||||
bytes[] calldatas,
|
||||
uint256 startBlock,
|
||||
uint256 endBlock,
|
||||
string description
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is canceled.
|
||||
*/
|
||||
event ProposalCanceled(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a proposal is executed.
|
||||
*/
|
||||
event ProposalExecuted(uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a vote is cast without params.
|
||||
*
|
||||
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
|
||||
*/
|
||||
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a vote is cast with params.
|
||||
*
|
||||
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
|
||||
* `params` are additional encoded parameters. Their intepepretation also depends on the voting module used.
|
||||
*/
|
||||
event VoteCastWithParams(
|
||||
address indexed voter,
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
string reason,
|
||||
bytes params
|
||||
);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Name of the governor instance (used in building the ERC712 domain separator).
|
||||
*/
|
||||
function name() public view virtual returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
|
||||
*/
|
||||
function version() public view virtual returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:voting
|
||||
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
|
||||
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
|
||||
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
|
||||
*
|
||||
* There are 2 standard keys: `support` and `quorum`.
|
||||
*
|
||||
* - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.
|
||||
* - `quorum=bravo` means that only For votes are counted towards quorum.
|
||||
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
|
||||
*
|
||||
* If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique
|
||||
* name that describes the behavior. For example:
|
||||
*
|
||||
* - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain.
|
||||
* - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote.
|
||||
*
|
||||
* NOTE: The string can be decoded by the standard
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
|
||||
* JavaScript class.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function COUNTING_MODE() public pure virtual returns (string memory);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Hashing function used to (re)build the proposal id from the proposal details..
|
||||
*/
|
||||
function hashProposal(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public pure virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Current state of a proposal, following Compound's convention
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual returns (ProposalState);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's
|
||||
* ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the
|
||||
* beginning of the following block.
|
||||
*/
|
||||
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:core
|
||||
* @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote
|
||||
* during this block.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
|
||||
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
|
||||
*/
|
||||
function votingDelay() public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Delay, in number of blocks, between the vote start and vote ends.
|
||||
*
|
||||
* NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
|
||||
* duration compared to the voting delay.
|
||||
*/
|
||||
function votingPeriod() public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:user-config
|
||||
* @dev Minimum number of cast voted required for a proposal to be successful.
|
||||
*
|
||||
* Note: The `blockNumber` parameter corresponds to the snapshot used for counting vote. This allows to scale the
|
||||
* quorum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
|
||||
*/
|
||||
function quorum(uint256 blockNumber) public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:reputation
|
||||
* @dev Voting power of an `account` at a specific `blockNumber`.
|
||||
*
|
||||
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
|
||||
* multiple), {ERC20Votes} tokens.
|
||||
*/
|
||||
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:reputation
|
||||
* @dev Voting power of an `account` at a specific `blockNumber` given additional encoded parameters.
|
||||
*/
|
||||
function getVotesWithParams(
|
||||
address account,
|
||||
uint256 blockNumber,
|
||||
bytes memory params
|
||||
) public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @notice module:voting
|
||||
* @dev Returns weither `account` has cast a vote on `proposalId`.
|
||||
*/
|
||||
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
|
||||
* {IGovernor-votingPeriod} blocks after the voting starts.
|
||||
*
|
||||
* Emits a {ProposalCreated} event.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
|
||||
* deadline to be reached.
|
||||
*
|
||||
* Emits a {ProposalExecuted} event.
|
||||
*
|
||||
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
|
||||
*/
|
||||
function execute(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public payable virtual returns (uint256 proposalId);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVoteWithReason(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason
|
||||
) public virtual returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason and additional encoded parameters
|
||||
*
|
||||
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
|
||||
*/
|
||||
function castVoteWithReasonAndParams(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params
|
||||
) public virtual returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote using the user's cryptographic signature.
|
||||
*
|
||||
* Emits a {VoteCast} event.
|
||||
*/
|
||||
function castVoteBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature.
|
||||
*
|
||||
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
|
||||
*/
|
||||
function castVoteWithReasonAndParamsBySig(
|
||||
uint256 proposalId,
|
||||
uint8 support,
|
||||
string calldata reason,
|
||||
bytes memory params,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual returns (uint256 balance);
|
||||
}
|
||||
176
contracts/governance/README.adoc
Normal file
176
contracts/governance/README.adoc
Normal file
@ -0,0 +1,176 @@
|
||||
= Governance
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance
|
||||
|
||||
This directory includes primitives for on-chain governance.
|
||||
|
||||
== Governor
|
||||
|
||||
This modular system of Governor contracts allows the deployment on-chain voting protocols similar to https://compound.finance/docs/governance[Compound's Governor Alpha & Bravo] and beyond, through the ability to easily customize multiple aspects of the protocol.
|
||||
|
||||
[TIP]
|
||||
====
|
||||
For a guided experience, set up your Governor contract using https://wizard.openzeppelin.com/#governor[Contracts Wizard].
|
||||
|
||||
For a written walkthrough, check out our guide on xref:ROOT:governance.adoc[How to set up on-chain governance].
|
||||
====
|
||||
|
||||
* {Governor}: The core contract that contains all the logic and primitives. It is abstract and requires choosing one of each of the modules below, or custom ones.
|
||||
|
||||
Votes modules determine the source of voting power, and sometimes quorum number.
|
||||
|
||||
* {GovernorVotes}: Extracts voting weight from an {ERC20Votes} token.
|
||||
|
||||
* {GovernorVotesComp}: Extracts voting weight from a COMP-like or {ERC20VotesComp} token.
|
||||
|
||||
* {GovernorVotesQuorumFraction}: Combines with `GovernorVotes` to set the quorum as a fraction of the total token supply.
|
||||
|
||||
Counting modules determine valid voting options.
|
||||
|
||||
* {GovernorCountingSimple}: Simple voting mechanism with 3 voting options: Against, For and Abstain.
|
||||
|
||||
Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a `queue` step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed.
|
||||
|
||||
* {GovernorTimelockControl}: Connects with an instance of {TimelockController}. Allows multiple proposers and executors, in addition to the Governor itself.
|
||||
|
||||
* {GovernorTimelockCompound}: Connects with an instance of Compound's https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol[`Timelock`] contract.
|
||||
|
||||
Other extensions can customize the behavior or interface in multiple ways.
|
||||
|
||||
* {GovernorCompatibilityBravo}: Extends the interface to be fully `GovernorBravo`-compatible. Note that events are compatible regardless of whether this extension is included or not.
|
||||
|
||||
* {GovernorSettings}: Manages some of the settings (voting delay, voting period duration, and proposal threshold) in a way that can be updated through a governance proposal, without requiring an upgrade.
|
||||
|
||||
* {GovernorPreventLateQuorum}: Ensures there is a minimum voting period after quorum is reached as a security protection against large voters.
|
||||
|
||||
In addition to modules and extensions, the core contract requires a few virtual functions to be implemented to your particular specifications:
|
||||
|
||||
* <<Governor-votingDelay-,`votingDelay()`>>: Delay (in number of blocks) since the proposal is submitted until voting power is fixed and voting starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, or delegate their votes.
|
||||
* <<Governor-votingPeriod-,`votingPeriod()`>>: Delay (in number of blocks) since the proposal starts until voting ends.
|
||||
* <<Governor-quorum-uint256-,`quorum(uint256 blockNumber)`>>: Quorum required for a proposal to be successful. This function includes a `blockNumber` argument so the quorum can adapt through time, for example, to follow a token's `totalSupply`.
|
||||
|
||||
NOTE: Functions of the `Governor` contract do not include access control. If you want to restrict access, you should add these checks by overloading the particular functions. Among these, {Governor-_cancel} is internal by default, and you will have to expose it (with the right access control mechanism) yourself if this function is needed.
|
||||
|
||||
=== Core
|
||||
|
||||
{{IGovernor}}
|
||||
|
||||
{{Governor}}
|
||||
|
||||
=== Modules
|
||||
|
||||
{{GovernorCountingSimple}}
|
||||
|
||||
{{GovernorVotes}}
|
||||
|
||||
{{GovernorVotesQuorumFraction}}
|
||||
|
||||
{{GovernorVotesComp}}
|
||||
|
||||
=== Extensions
|
||||
|
||||
{{GovernorTimelockControl}}
|
||||
|
||||
{{GovernorTimelockCompound}}
|
||||
|
||||
{{GovernorSettings}}
|
||||
|
||||
{{GovernorPreventLateQuorum}}
|
||||
|
||||
{{GovernorCompatibilityBravo}}
|
||||
|
||||
=== Deprecated
|
||||
|
||||
{{GovernorProposalThreshold}}
|
||||
|
||||
== Utils
|
||||
|
||||
{{Votes}}
|
||||
|
||||
== Timelock
|
||||
|
||||
In a governance system, the {TimelockController} contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}.
|
||||
|
||||
{{TimelockController}}
|
||||
|
||||
[[timelock-terminology]]
|
||||
==== Terminology
|
||||
|
||||
* *Operation:* A transaction (or a set of transactions) that is the subject of the timelock. It has to be scheduled by a proposer and executed by an executor. The timelock enforces a minimum delay between the proposition and the execution (see xref:access-control.adoc#operation_lifecycle[operation lifecycle]). If the operation contains multiple transactions (batch mode), they are executed atomically. Operations are identified by the hash of their content.
|
||||
* *Operation status:*
|
||||
** *Unset:* An operation that is not part of the timelock mechanism.
|
||||
** *Pending:* An operation that has been scheduled, before the timer expires.
|
||||
** *Ready:* An operation that has been scheduled, after the timer expires.
|
||||
** *Done:* An operation that has been executed.
|
||||
* *Predecessor*: An (optional) dependency between operations. An operation can depend on another operation (its predecessor), forcing the execution order of these two operations.
|
||||
* *Role*:
|
||||
** *Admin:* An address (smart contract or EOA) that is in charge of granting the roles of Proposer and Executor.
|
||||
** *Proposer:* An address (smart contract or EOA) that is in charge of scheduling (and cancelling) operations.
|
||||
** *Executor:* An address (smart contract or EOA) that is in charge of executing operations once the timelock has expired. This role can be given to the zero address to allow anyone to execute operations.
|
||||
|
||||
[[timelock-operation]]
|
||||
==== Operation structure
|
||||
|
||||
Operation executed by the xref:api:governance.adoc#TimelockController[`TimelockController`] can contain one or multiple subsequent calls. Depending on whether you need to multiple calls to be executed atomically, you can either use simple or batched operations.
|
||||
|
||||
Both operations contain:
|
||||
|
||||
* *Target*, the address of the smart contract that the timelock should operate on.
|
||||
* *Value*, in wei, that should be sent with the transaction. Most of the time this will be 0. Ether can be deposited before-end or passed along when executing the transaction.
|
||||
* *Data*, containing the encoded function selector and parameters of the call. This can be produced using a number of tools. For example, a maintenance operation granting role `ROLE` to `ACCOUNT` can be encode using web3js as follows:
|
||||
|
||||
```javascript
|
||||
const data = timelock.contract.methods.grantRole(ROLE, ACCOUNT).encodeABI()
|
||||
```
|
||||
|
||||
* *Predecessor*, that specifies a dependency between operations. This dependency is optional. Use `bytes32(0)` if the operation does not have any dependency.
|
||||
* *Salt*, used to disambiguate two otherwise identical operations. This can be any random value.
|
||||
|
||||
In the case of batched operations, `target`, `value` and `data` are specified as arrays, which must be of the same length.
|
||||
|
||||
[[timelock-operation-lifecycle]]
|
||||
==== Operation lifecycle
|
||||
|
||||
Timelocked operations are identified by a unique id (their hash) and follow a specific lifecycle:
|
||||
|
||||
`Unset` -> `Pending` -> `Pending` + `Ready` -> `Done`
|
||||
|
||||
* By calling xref:api:governance.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:governance.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:governance.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method.
|
||||
* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed.
|
||||
* By calling xref:api:governance.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:governance.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed.
|
||||
* xref:api:governance.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.
|
||||
|
||||
Operations status can be queried using the functions:
|
||||
|
||||
* xref:api:governance.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`]
|
||||
* xref:api:governance.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`]
|
||||
* xref:api:governance.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`]
|
||||
|
||||
[[timelock-roles]]
|
||||
==== Roles
|
||||
|
||||
[[timelock-admin]]
|
||||
===== Admin
|
||||
|
||||
The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, both the timelock and the deployer have this role. After further configuration and testing, the deployer can renounce this role such that all further maintenance operations have to go through the timelock process.
|
||||
|
||||
This role is identified by the *TIMELOCK_ADMIN_ROLE* value: `0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5`
|
||||
|
||||
[[timelock-proposer]]
|
||||
===== Proposer
|
||||
|
||||
The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.
|
||||
|
||||
WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.
|
||||
|
||||
This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1`
|
||||
|
||||
[[timelock-executor]]
|
||||
===== Executor
|
||||
|
||||
The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional executors can reduce the cost (the executing transaction does not require validation by the multisig or DAO that proposed it), while ensuring whoever is in charge of execution cannot trigger actions that have not been scheduled by the proposers. Alternatively, it is possible to allow _any_ address to execute a proposal once the timelock has expired by granting the executor role to the zero address.
|
||||
|
||||
This role is identified by the *EXECUTOR_ROLE* value: `0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63`
|
||||
|
||||
WARNING: A live contract without at least one proposer and one executor is locked. Make sure these roles are filled by reliable entities before the deployer renounces its administrative rights in favour of the timelock contract itself. See the {AccessControl} documentation to learn more about role management.
|
||||
@ -1,10 +1,12 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.7.0) (governance/TimelockController.sol)
|
||||
|
||||
pragma solidity ^0.7.0;
|
||||
pragma experimental ABIEncoderV2;
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./../math/SafeMath.sol";
|
||||
import "./AccessControl.sol";
|
||||
import "../access/AccessControl.sol";
|
||||
import "../token/ERC721/IERC721Receiver.sol";
|
||||
import "../token/ERC1155/IERC1155Receiver.sol";
|
||||
import "../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @dev Contract module which acts as a timelocked controller. When set as the
|
||||
@ -21,11 +23,11 @@ import "./AccessControl.sol";
|
||||
*
|
||||
* _Available since v3.3._
|
||||
*/
|
||||
contract TimelockController is AccessControl {
|
||||
|
||||
contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver {
|
||||
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
|
||||
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
|
||||
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
|
||||
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
|
||||
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
|
||||
|
||||
mapping(bytes32 => uint256) private _timestamps;
|
||||
@ -34,7 +36,15 @@ contract TimelockController is AccessControl {
|
||||
/**
|
||||
* @dev Emitted when a call is scheduled as part of operation `id`.
|
||||
*/
|
||||
event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay);
|
||||
event CallScheduled(
|
||||
bytes32 indexed id,
|
||||
uint256 indexed index,
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes data,
|
||||
bytes32 predecessor,
|
||||
uint256 delay
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a call is performed as part of operation `id`.
|
||||
@ -52,20 +62,35 @@ contract TimelockController is AccessControl {
|
||||
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract with a given `minDelay`.
|
||||
* @dev Initializes the contract with a given `minDelay`, and a list of
|
||||
* initial proposers and executors. The proposers receive both the
|
||||
* proposer and the canceller role (for backward compatibility). The
|
||||
* executors receive the executor role.
|
||||
*
|
||||
* NOTE: At construction, both the deployer and the timelock itself are
|
||||
* administrators. This helps further configuration of the timelock by the
|
||||
* deployer. After configuration is done, it is recommended that the
|
||||
* deployer renounces its admin position and relies on timelocked
|
||||
* operations to perform future maintenance.
|
||||
*/
|
||||
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) {
|
||||
constructor(
|
||||
uint256 minDelay,
|
||||
address[] memory proposers,
|
||||
address[] memory executors
|
||||
) {
|
||||
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
|
||||
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
|
||||
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
|
||||
_setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);
|
||||
|
||||
// deployer + self administration
|
||||
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
|
||||
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
|
||||
|
||||
// register proposers
|
||||
// register proposers and cancellers
|
||||
for (uint256 i = 0; i < proposers.length; ++i) {
|
||||
_setupRole(PROPOSER_ROLE, proposers[i]);
|
||||
_setupRole(CANCELLER_ROLE, proposers[i]);
|
||||
}
|
||||
|
||||
// register executors
|
||||
@ -83,8 +108,10 @@ contract TimelockController is AccessControl {
|
||||
* considered. Granting a role to `address(0)` is equivalent to enabling
|
||||
* this role for everyone.
|
||||
*/
|
||||
modifier onlyRole(bytes32 role) {
|
||||
require(hasRole(role, _msgSender()) || hasRole(role, address(0)), "TimelockController: sender requires permission");
|
||||
modifier onlyRoleOrOpenRole(bytes32 role) {
|
||||
if (!hasRole(role, address(0))) {
|
||||
_checkRole(role, _msgSender());
|
||||
}
|
||||
_;
|
||||
}
|
||||
|
||||
@ -93,11 +120,18 @@ contract TimelockController is AccessControl {
|
||||
*/
|
||||
receive() external payable {}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) {
|
||||
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether an id correspond to a registered operation. This
|
||||
* includes both Pending, Ready and Done operations.
|
||||
*/
|
||||
function isOperation(bytes32 id) public view virtual returns (bool pending) {
|
||||
function isOperation(bytes32 id) public view virtual returns (bool registered) {
|
||||
return getTimestamp(id) > 0;
|
||||
}
|
||||
|
||||
@ -113,7 +147,6 @@ contract TimelockController is AccessControl {
|
||||
*/
|
||||
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
|
||||
uint256 timestamp = getTimestamp(id);
|
||||
// solhint-disable-next-line not-rely-on-time
|
||||
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
|
||||
}
|
||||
|
||||
@ -145,7 +178,13 @@ contract TimelockController is AccessControl {
|
||||
* @dev Returns the identifier of an operation containing a single
|
||||
* transaction.
|
||||
*/
|
||||
function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
|
||||
function hashOperation(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata data,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public pure virtual returns (bytes32 hash) {
|
||||
return keccak256(abi.encode(target, value, data, predecessor, salt));
|
||||
}
|
||||
|
||||
@ -153,8 +192,14 @@ contract TimelockController is AccessControl {
|
||||
* @dev Returns the identifier of an operation containing a batch of
|
||||
* transactions.
|
||||
*/
|
||||
function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
|
||||
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
|
||||
function hashOperationBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public pure virtual returns (bytes32 hash) {
|
||||
return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -166,7 +211,14 @@ contract TimelockController is AccessControl {
|
||||
*
|
||||
* - the caller must have the 'proposer' role.
|
||||
*/
|
||||
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
function schedule(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata data,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt,
|
||||
uint256 delay
|
||||
) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
bytes32 id = hashOperation(target, value, data, predecessor, salt);
|
||||
_schedule(id, delay);
|
||||
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
|
||||
@ -181,14 +233,21 @@ contract TimelockController is AccessControl {
|
||||
*
|
||||
* - the caller must have the 'proposer' role.
|
||||
*/
|
||||
function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
function scheduleBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt,
|
||||
uint256 delay
|
||||
) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
require(targets.length == values.length, "TimelockController: length mismatch");
|
||||
require(targets.length == datas.length, "TimelockController: length mismatch");
|
||||
require(targets.length == payloads.length, "TimelockController: length mismatch");
|
||||
|
||||
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
|
||||
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
|
||||
_schedule(id, delay);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
|
||||
emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
|
||||
}
|
||||
}
|
||||
|
||||
@ -198,8 +257,7 @@ contract TimelockController is AccessControl {
|
||||
function _schedule(bytes32 id, uint256 delay) private {
|
||||
require(!isOperation(id), "TimelockController: operation already scheduled");
|
||||
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
|
||||
// solhint-disable-next-line not-rely-on-time
|
||||
_timestamps[id] = SafeMath.add(block.timestamp, delay);
|
||||
_timestamps[id] = block.timestamp + delay;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -207,9 +265,9 @@ contract TimelockController is AccessControl {
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have the 'proposer' role.
|
||||
* - the caller must have the 'canceller' role.
|
||||
*/
|
||||
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
|
||||
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
|
||||
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
|
||||
delete _timestamps[id];
|
||||
|
||||
@ -225,10 +283,21 @@ contract TimelockController is AccessControl {
|
||||
*
|
||||
* - the caller must have the 'executor' role.
|
||||
*/
|
||||
function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) {
|
||||
bytes32 id = hashOperation(target, value, data, predecessor, salt);
|
||||
_beforeCall(predecessor);
|
||||
_call(id, 0, target, value, data);
|
||||
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
|
||||
// thus any modifications to the operation during reentrancy should be caught.
|
||||
// slither-disable-next-line reentrancy-eth
|
||||
function execute(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata payload,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
|
||||
bytes32 id = hashOperation(target, value, payload, predecessor, salt);
|
||||
|
||||
_beforeCall(id, predecessor);
|
||||
_execute(target, value, payload);
|
||||
emit CallExecuted(id, 0, target, value, payload);
|
||||
_afterCall(id);
|
||||
}
|
||||
|
||||
@ -241,22 +310,46 @@ contract TimelockController is AccessControl {
|
||||
*
|
||||
* - the caller must have the 'executor' role.
|
||||
*/
|
||||
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) {
|
||||
function executeBatch(
|
||||
address[] calldata targets,
|
||||
uint256[] calldata values,
|
||||
bytes[] calldata payloads,
|
||||
bytes32 predecessor,
|
||||
bytes32 salt
|
||||
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
|
||||
require(targets.length == values.length, "TimelockController: length mismatch");
|
||||
require(targets.length == datas.length, "TimelockController: length mismatch");
|
||||
require(targets.length == payloads.length, "TimelockController: length mismatch");
|
||||
|
||||
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
|
||||
_beforeCall(predecessor);
|
||||
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
|
||||
|
||||
_beforeCall(id, predecessor);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
_call(id, i, targets[i], values[i], datas[i]);
|
||||
address target = targets[i];
|
||||
uint256 value = values[i];
|
||||
bytes calldata payload = payloads[i];
|
||||
_execute(target, value, payload);
|
||||
emit CallExecuted(id, i, target, value, payload);
|
||||
}
|
||||
_afterCall(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Execute an operation's call.
|
||||
*/
|
||||
function _execute(
|
||||
address target,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) internal virtual {
|
||||
(bool success, ) = target.call{value: value}(data);
|
||||
require(success, "TimelockController: underlying transaction reverted");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks before execution of an operation's calls.
|
||||
*/
|
||||
function _beforeCall(bytes32 predecessor) private view {
|
||||
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
|
||||
require(isOperationReady(id), "TimelockController: operation is not ready");
|
||||
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
|
||||
}
|
||||
|
||||
@ -268,19 +361,6 @@ contract TimelockController is AccessControl {
|
||||
_timestamps[id] = _DONE_TIMESTAMP;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Execute an operation's call.
|
||||
*
|
||||
* Emits a {CallExecuted} event.
|
||||
*/
|
||||
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private {
|
||||
// solhint-disable-next-line avoid-low-level-calls
|
||||
(bool success,) = target.call{value: value}(data);
|
||||
require(success, "TimelockController: underlying transaction reverted");
|
||||
|
||||
emit CallExecuted(id, index, target, value, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the minimum timelock duration for future operations.
|
||||
*
|
||||
@ -296,4 +376,42 @@ contract TimelockController is AccessControl {
|
||||
emit MinDelayChange(_minDelay, newDelay);
|
||||
_minDelay = newDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Receiver-onERC721Received}.
|
||||
*/
|
||||
function onERC721Received(
|
||||
address,
|
||||
address,
|
||||
uint256,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC721Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155Received}.
|
||||
*/
|
||||
function onERC1155Received(
|
||||
address,
|
||||
address,
|
||||
uint256,
|
||||
uint256,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
|
||||
*/
|
||||
function onERC1155BatchReceived(
|
||||
address,
|
||||
address,
|
||||
uint256[] memory,
|
||||
uint256[] memory,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155BatchReceived.selector;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,289 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/compatibility/GovernorCompatibilityBravo.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../../utils/Counters.sol";
|
||||
import "../../utils/math/SafeCast.sol";
|
||||
import "../extensions/IGovernorTimelock.sol";
|
||||
import "../Governor.sol";
|
||||
import "./IGovernorCompatibilityBravo.sol";
|
||||
|
||||
/**
|
||||
* @dev Compatibility layer that implements GovernorBravo compatibility on to of {Governor}.
|
||||
*
|
||||
* This compatibility layer includes a voting system and requires a {IGovernorTimelock} compatible module to be added
|
||||
* through inheritance. It does not include token bindings, not does it include any variable upgrade patterns.
|
||||
*
|
||||
* NOTE: When using this module, you may need to enable the Solidity optimizer to avoid hitting the contract size limit.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorCompatibilityBravo is IGovernorTimelock, IGovernorCompatibilityBravo, Governor {
|
||||
using Counters for Counters.Counter;
|
||||
using Timers for Timers.BlockNumber;
|
||||
|
||||
enum VoteType {
|
||||
Against,
|
||||
For,
|
||||
Abstain
|
||||
}
|
||||
|
||||
struct ProposalDetails {
|
||||
address proposer;
|
||||
address[] targets;
|
||||
uint256[] values;
|
||||
string[] signatures;
|
||||
bytes[] calldatas;
|
||||
uint256 forVotes;
|
||||
uint256 againstVotes;
|
||||
uint256 abstainVotes;
|
||||
mapping(address => Receipt) receipts;
|
||||
bytes32 descriptionHash;
|
||||
}
|
||||
|
||||
mapping(uint256 => ProposalDetails) private _proposalDetails;
|
||||
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function COUNTING_MODE() public pure virtual override returns (string memory) {
|
||||
return "support=bravo&quorum=bravo";
|
||||
}
|
||||
|
||||
// ============================================== Proposal lifecycle ==============================================
|
||||
/**
|
||||
* @dev See {IGovernor-propose}.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual override(IGovernor, Governor) returns (uint256) {
|
||||
_storeProposal(_msgSender(), targets, values, new string[](calldatas.length), calldatas, description);
|
||||
return super.propose(targets, values, calldatas, description);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-propose}.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
string[] memory signatures,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual override returns (uint256) {
|
||||
_storeProposal(_msgSender(), targets, values, signatures, calldatas, description);
|
||||
return propose(targets, values, _encodeCalldata(signatures, calldatas), description);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-queue}.
|
||||
*/
|
||||
function queue(uint256 proposalId) public virtual override {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
queue(
|
||||
details.targets,
|
||||
details.values,
|
||||
_encodeCalldata(details.signatures, details.calldatas),
|
||||
details.descriptionHash
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-execute}.
|
||||
*/
|
||||
function execute(uint256 proposalId) public payable virtual override {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
execute(
|
||||
details.targets,
|
||||
details.values,
|
||||
_encodeCalldata(details.signatures, details.calldatas),
|
||||
details.descriptionHash
|
||||
);
|
||||
}
|
||||
|
||||
function cancel(uint256 proposalId) public virtual override {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
|
||||
require(
|
||||
_msgSender() == details.proposer || getVotes(details.proposer, block.number - 1) < proposalThreshold(),
|
||||
"GovernorBravo: proposer above threshold"
|
||||
);
|
||||
|
||||
_cancel(
|
||||
details.targets,
|
||||
details.values,
|
||||
_encodeCalldata(details.signatures, details.calldatas),
|
||||
details.descriptionHash
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Encodes calldatas with optional function signature.
|
||||
*/
|
||||
function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
|
||||
private
|
||||
pure
|
||||
returns (bytes[] memory)
|
||||
{
|
||||
bytes[] memory fullcalldatas = new bytes[](calldatas.length);
|
||||
|
||||
for (uint256 i = 0; i < signatures.length; ++i) {
|
||||
fullcalldatas[i] = bytes(signatures[i]).length == 0
|
||||
? calldatas[i]
|
||||
: abi.encodePacked(bytes4(keccak256(bytes(signatures[i]))), calldatas[i]);
|
||||
}
|
||||
|
||||
return fullcalldatas;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Store proposal metadata for later lookup
|
||||
*/
|
||||
function _storeProposal(
|
||||
address proposer,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
string[] memory signatures,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) private {
|
||||
bytes32 descriptionHash = keccak256(bytes(description));
|
||||
uint256 proposalId = hashProposal(targets, values, _encodeCalldata(signatures, calldatas), descriptionHash);
|
||||
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
if (details.descriptionHash == bytes32(0)) {
|
||||
details.proposer = proposer;
|
||||
details.targets = targets;
|
||||
details.values = values;
|
||||
details.signatures = signatures;
|
||||
details.calldatas = calldatas;
|
||||
details.descriptionHash = descriptionHash;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================================== Views =====================================================
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-proposals}.
|
||||
*/
|
||||
function proposals(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
override
|
||||
returns (
|
||||
uint256 id,
|
||||
address proposer,
|
||||
uint256 eta,
|
||||
uint256 startBlock,
|
||||
uint256 endBlock,
|
||||
uint256 forVotes,
|
||||
uint256 againstVotes,
|
||||
uint256 abstainVotes,
|
||||
bool canceled,
|
||||
bool executed
|
||||
)
|
||||
{
|
||||
id = proposalId;
|
||||
eta = proposalEta(proposalId);
|
||||
startBlock = proposalSnapshot(proposalId);
|
||||
endBlock = proposalDeadline(proposalId);
|
||||
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
proposer = details.proposer;
|
||||
forVotes = details.forVotes;
|
||||
againstVotes = details.againstVotes;
|
||||
abstainVotes = details.abstainVotes;
|
||||
|
||||
ProposalState status = state(proposalId);
|
||||
canceled = status == ProposalState.Canceled;
|
||||
executed = status == ProposalState.Executed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-getActions}.
|
||||
*/
|
||||
function getActions(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
override
|
||||
returns (
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
string[] memory signatures,
|
||||
bytes[] memory calldatas
|
||||
)
|
||||
{
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
return (details.targets, details.values, details.signatures, details.calldatas);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-getReceipt}.
|
||||
*/
|
||||
function getReceipt(uint256 proposalId, address voter) public view virtual override returns (Receipt memory) {
|
||||
return _proposalDetails[proposalId].receipts[voter];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernorCompatibilityBravo-quorumVotes}.
|
||||
*/
|
||||
function quorumVotes() public view virtual override returns (uint256) {
|
||||
return quorum(block.number - 1);
|
||||
}
|
||||
|
||||
// ==================================================== Voting ====================================================
|
||||
/**
|
||||
* @dev See {IGovernor-hasVoted}.
|
||||
*/
|
||||
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
|
||||
return _proposalDetails[proposalId].receipts[account].hasVoted;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_quorumReached}. In this module, only forVotes count toward the quorum.
|
||||
*/
|
||||
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
return quorum(proposalSnapshot(proposalId)) <= details.forVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
|
||||
*/
|
||||
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
return details.forVotes > details.againstVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_countVote}. In this module, the support follows Governor Bravo.
|
||||
*/
|
||||
function _countVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
bytes memory // params
|
||||
) internal virtual override {
|
||||
ProposalDetails storage details = _proposalDetails[proposalId];
|
||||
Receipt storage receipt = details.receipts[account];
|
||||
|
||||
require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast");
|
||||
receipt.hasVoted = true;
|
||||
receipt.support = support;
|
||||
receipt.votes = SafeCast.toUint96(weight);
|
||||
|
||||
if (support == uint8(VoteType.Against)) {
|
||||
details.againstVotes += weight;
|
||||
} else if (support == uint8(VoteType.For)) {
|
||||
details.forVotes += weight;
|
||||
} else if (support == uint8(VoteType.Abstain)) {
|
||||
details.abstainVotes += weight;
|
||||
} else {
|
||||
revert("GovernorCompatibilityBravo: invalid vote type");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (governance/compatibility/IGovernorCompatibilityBravo.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../IGovernor.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface extension that adds missing functions to the {Governor} core to provide `GovernorBravo` compatibility.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract IGovernorCompatibilityBravo is IGovernor {
|
||||
/**
|
||||
* @dev Proposal structure from Compound Governor Bravo. Not actually used by the compatibility layer, as
|
||||
* {{proposal}} returns a very different structure.
|
||||
*/
|
||||
struct Proposal {
|
||||
uint256 id;
|
||||
address proposer;
|
||||
uint256 eta;
|
||||
address[] targets;
|
||||
uint256[] values;
|
||||
string[] signatures;
|
||||
bytes[] calldatas;
|
||||
uint256 startBlock;
|
||||
uint256 endBlock;
|
||||
uint256 forVotes;
|
||||
uint256 againstVotes;
|
||||
uint256 abstainVotes;
|
||||
bool canceled;
|
||||
bool executed;
|
||||
mapping(address => Receipt) receipts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Receipt structure from Compound Governor Bravo
|
||||
*/
|
||||
struct Receipt {
|
||||
bool hasVoted;
|
||||
uint8 support;
|
||||
uint96 votes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface.
|
||||
*/
|
||||
function quorumVotes() public view virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"The official record of all proposals ever proposed"_.
|
||||
*/
|
||||
function proposals(uint256)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
returns (
|
||||
uint256 id,
|
||||
address proposer,
|
||||
uint256 eta,
|
||||
uint256 startBlock,
|
||||
uint256 endBlock,
|
||||
uint256 forVotes,
|
||||
uint256 againstVotes,
|
||||
uint256 abstainVotes,
|
||||
bool canceled,
|
||||
bool executed
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"Function used to propose a new proposal"_.
|
||||
*/
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
string[] memory signatures,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"Queues a proposal of state succeeded"_.
|
||||
*/
|
||||
function queue(uint256 proposalId) public virtual;
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"Executes a queued proposal if eta has passed"_.
|
||||
*/
|
||||
function execute(uint256 proposalId) public payable virtual;
|
||||
|
||||
/**
|
||||
* @dev Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold.
|
||||
*/
|
||||
function cancel(uint256 proposalId) public virtual;
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"Gets actions of a proposal"_.
|
||||
*/
|
||||
function getActions(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
returns (
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
string[] memory signatures,
|
||||
bytes[] memory calldatas
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_.
|
||||
*/
|
||||
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
|
||||
}
|
||||
107
contracts/governance/extensions/GovernorCountingSimple.sol
Normal file
107
contracts/governance/extensions/GovernorCountingSimple.sol
Normal file
@ -0,0 +1,107 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorCountingSimple.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for simple, 3 options, vote counting.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorCountingSimple is Governor {
|
||||
/**
|
||||
* @dev Supported vote types. Matches Governor Bravo ordering.
|
||||
*/
|
||||
enum VoteType {
|
||||
Against,
|
||||
For,
|
||||
Abstain
|
||||
}
|
||||
|
||||
struct ProposalVote {
|
||||
uint256 againstVotes;
|
||||
uint256 forVotes;
|
||||
uint256 abstainVotes;
|
||||
mapping(address => bool) hasVoted;
|
||||
}
|
||||
|
||||
mapping(uint256 => ProposalVote) private _proposalVotes;
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-COUNTING_MODE}.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function COUNTING_MODE() public pure virtual override returns (string memory) {
|
||||
return "support=bravo&quorum=for,abstain";
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-hasVoted}.
|
||||
*/
|
||||
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
|
||||
return _proposalVotes[proposalId].hasVoted[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Accessor to the internal vote counts.
|
||||
*/
|
||||
function proposalVotes(uint256 proposalId)
|
||||
public
|
||||
view
|
||||
virtual
|
||||
returns (
|
||||
uint256 againstVotes,
|
||||
uint256 forVotes,
|
||||
uint256 abstainVotes
|
||||
)
|
||||
{
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
return (proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_quorumReached}.
|
||||
*/
|
||||
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
|
||||
return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes.
|
||||
*/
|
||||
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
|
||||
return proposalvote.forVotes > proposalvote.againstVotes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
|
||||
*/
|
||||
function _countVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
uint256 weight,
|
||||
bytes memory // params
|
||||
) internal virtual override {
|
||||
ProposalVote storage proposalvote = _proposalVotes[proposalId];
|
||||
|
||||
require(!proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast");
|
||||
proposalvote.hasVoted[account] = true;
|
||||
|
||||
if (support == uint8(VoteType.Against)) {
|
||||
proposalvote.againstVotes += weight;
|
||||
} else if (support == uint8(VoteType.For)) {
|
||||
proposalvote.forVotes += weight;
|
||||
} else if (support == uint8(VoteType.Abstain)) {
|
||||
proposalvote.abstainVotes += weight;
|
||||
} else {
|
||||
revert("GovernorVotingSimple: invalid value for enum VoteType");
|
||||
}
|
||||
}
|
||||
}
|
||||
108
contracts/governance/extensions/GovernorPreventLateQuorum.sol
Normal file
108
contracts/governance/extensions/GovernorPreventLateQuorum.sol
Normal file
@ -0,0 +1,108 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorPreventLateQuorum.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
import "../../utils/math/Math.sol";
|
||||
|
||||
/**
|
||||
* @dev A module that ensures there is a minimum voting period after quorum is reached. This prevents a large voter from
|
||||
* swaying a vote and triggering quorum at the last minute, by ensuring there is always time for other voters to react
|
||||
* and try to oppose the decision.
|
||||
*
|
||||
* If a vote causes quorum to be reached, the proposal's voting period may be extended so that it does not end before at
|
||||
* least a given number of blocks have passed (the "vote extension" parameter). This parameter can be set by the
|
||||
* governance executor (e.g. through a governance proposal).
|
||||
*
|
||||
* _Available since v4.5._
|
||||
*/
|
||||
abstract contract GovernorPreventLateQuorum is Governor {
|
||||
using SafeCast for uint256;
|
||||
using Timers for Timers.BlockNumber;
|
||||
|
||||
uint64 private _voteExtension;
|
||||
mapping(uint256 => Timers.BlockNumber) private _extendedDeadlines;
|
||||
|
||||
/// @dev Emitted when a proposal deadline is pushed back due to reaching quorum late in its voting period.
|
||||
event ProposalExtended(uint256 indexed proposalId, uint64 extendedDeadline);
|
||||
|
||||
/// @dev Emitted when the {lateQuorumVoteExtension} parameter is changed.
|
||||
event LateQuorumVoteExtensionSet(uint64 oldVoteExtension, uint64 newVoteExtension);
|
||||
|
||||
/**
|
||||
* @dev Initializes the vote extension parameter: the number of blocks that are required to pass since a proposal
|
||||
* reaches quorum until its voting period ends. If necessary the voting period will be extended beyond the one set
|
||||
* at proposal creation.
|
||||
*/
|
||||
constructor(uint64 initialVoteExtension) {
|
||||
_setLateQuorumVoteExtension(initialVoteExtension);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the proposal deadline, which may have been extended beyond that set at proposal creation, if the
|
||||
* proposal reached quorum late in the voting period. See {Governor-proposalDeadline}.
|
||||
*/
|
||||
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
return Math.max(super.proposalDeadline(proposalId), _extendedDeadlines[proposalId].getDeadline());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Casts a vote and detects if it caused quorum to be reached, potentially extending the voting period. See
|
||||
* {Governor-_castVote}.
|
||||
*
|
||||
* May emit a {ProposalExtended} event.
|
||||
*/
|
||||
function _castVote(
|
||||
uint256 proposalId,
|
||||
address account,
|
||||
uint8 support,
|
||||
string memory reason,
|
||||
bytes memory params
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 result = super._castVote(proposalId, account, support, reason, params);
|
||||
|
||||
Timers.BlockNumber storage extendedDeadline = _extendedDeadlines[proposalId];
|
||||
|
||||
if (extendedDeadline.isUnset() && _quorumReached(proposalId)) {
|
||||
uint64 extendedDeadlineValue = block.number.toUint64() + lateQuorumVoteExtension();
|
||||
|
||||
if (extendedDeadlineValue > proposalDeadline(proposalId)) {
|
||||
emit ProposalExtended(proposalId, extendedDeadlineValue);
|
||||
}
|
||||
|
||||
extendedDeadline.setDeadline(extendedDeadlineValue);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current value of the vote extension parameter: the number of blocks that are required to pass
|
||||
* from the time a proposal reaches quorum until its voting period ends.
|
||||
*/
|
||||
function lateQuorumVoteExtension() public view virtual returns (uint64) {
|
||||
return _voteExtension;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the {lateQuorumVoteExtension}. This operation can only be performed by the governance executor,
|
||||
* generally through a governance proposal.
|
||||
*
|
||||
* Emits a {LateQuorumVoteExtensionSet} event.
|
||||
*/
|
||||
function setLateQuorumVoteExtension(uint64 newVoteExtension) public virtual onlyGovernance {
|
||||
_setLateQuorumVoteExtension(newVoteExtension);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the {lateQuorumVoteExtension}. This is an internal function that can be exposed in a public function
|
||||
* like {setLateQuorumVoteExtension} if another access control mechanism is needed.
|
||||
*
|
||||
* Emits a {LateQuorumVoteExtensionSet} event.
|
||||
*/
|
||||
function _setLateQuorumVoteExtension(uint64 newVoteExtension) internal virtual {
|
||||
emit LateQuorumVoteExtensionSet(_voteExtension, newVoteExtension);
|
||||
_voteExtension = newVoteExtension;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorProposalThreshold.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for proposal restriction to token holders with a minimum balance.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
* _Deprecated since v4.4._
|
||||
*/
|
||||
abstract contract GovernorProposalThreshold is Governor {
|
||||
function propose(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
string memory description
|
||||
) public virtual override returns (uint256) {
|
||||
return super.propose(targets, values, calldatas, description);
|
||||
}
|
||||
}
|
||||
114
contracts/governance/extensions/GovernorSettings.sol
Normal file
114
contracts/governance/extensions/GovernorSettings.sol
Normal file
@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for settings updatable through governance.
|
||||
*
|
||||
* _Available since v4.4._
|
||||
*/
|
||||
abstract contract GovernorSettings is Governor {
|
||||
uint256 private _votingDelay;
|
||||
uint256 private _votingPeriod;
|
||||
uint256 private _proposalThreshold;
|
||||
|
||||
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
|
||||
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
|
||||
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
|
||||
|
||||
/**
|
||||
* @dev Initialize the governance parameters.
|
||||
*/
|
||||
constructor(
|
||||
uint256 initialVotingDelay,
|
||||
uint256 initialVotingPeriod,
|
||||
uint256 initialProposalThreshold
|
||||
) {
|
||||
_setVotingDelay(initialVotingDelay);
|
||||
_setVotingPeriod(initialVotingPeriod);
|
||||
_setProposalThreshold(initialProposalThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-votingDelay}.
|
||||
*/
|
||||
function votingDelay() public view virtual override returns (uint256) {
|
||||
return _votingDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IGovernor-votingPeriod}.
|
||||
*/
|
||||
function votingPeriod() public view virtual override returns (uint256) {
|
||||
return _votingPeriod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {Governor-proposalThreshold}.
|
||||
*/
|
||||
function proposalThreshold() public view virtual override returns (uint256) {
|
||||
return _proposalThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the voting delay. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {VotingDelaySet} event.
|
||||
*/
|
||||
function setVotingDelay(uint256 newVotingDelay) public virtual onlyGovernance {
|
||||
_setVotingDelay(newVotingDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the voting period. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {VotingPeriodSet} event.
|
||||
*/
|
||||
function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance {
|
||||
_setVotingPeriod(newVotingPeriod);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Update the proposal threshold. This operation can only be performed through a governance proposal.
|
||||
*
|
||||
* Emits a {ProposalThresholdSet} event.
|
||||
*/
|
||||
function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance {
|
||||
_setProposalThreshold(newProposalThreshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the voting delay.
|
||||
*
|
||||
* Emits a {VotingDelaySet} event.
|
||||
*/
|
||||
function _setVotingDelay(uint256 newVotingDelay) internal virtual {
|
||||
emit VotingDelaySet(_votingDelay, newVotingDelay);
|
||||
_votingDelay = newVotingDelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the voting period.
|
||||
*
|
||||
* Emits a {VotingPeriodSet} event.
|
||||
*/
|
||||
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
|
||||
// voting period must be at least one block long
|
||||
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
|
||||
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
|
||||
_votingPeriod = newVotingPeriod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal setter for the proposal threshold.
|
||||
*
|
||||
* Emits a {ProposalThresholdSet} event.
|
||||
*/
|
||||
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
|
||||
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
|
||||
_proposalThreshold = newProposalThreshold;
|
||||
}
|
||||
}
|
||||
193
contracts/governance/extensions/GovernorTimelockCompound.sol
Normal file
193
contracts/governance/extensions/GovernorTimelockCompound.sol
Normal file
@ -0,0 +1,193 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorTimelockCompound.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./IGovernorTimelock.sol";
|
||||
import "../Governor.sol";
|
||||
import "../../utils/math/SafeCast.sol";
|
||||
import "../../vendor/compound/ICompoundTimelock.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} that binds the execution process to a Compound Timelock. This adds a delay, enforced by
|
||||
* the external timelock to all successful proposal (in addition to the voting duration). The {Governor} needs to be
|
||||
* the admin of the timelock for any operation to be performed. A public, unrestricted,
|
||||
* {GovernorTimelockCompound-__acceptAdmin} is available to accept ownership of the timelock.
|
||||
*
|
||||
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
|
||||
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
|
||||
* inaccessible.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorTimelockCompound is IGovernorTimelock, Governor {
|
||||
using SafeCast for uint256;
|
||||
using Timers for Timers.Timestamp;
|
||||
|
||||
struct ProposalTimelock {
|
||||
Timers.Timestamp timer;
|
||||
}
|
||||
|
||||
ICompoundTimelock private _timelock;
|
||||
|
||||
mapping(uint256 => ProposalTimelock) private _proposalTimelocks;
|
||||
|
||||
/**
|
||||
* @dev Emitted when the timelock controller used for proposal execution is modified.
|
||||
*/
|
||||
event TimelockChange(address oldTimelock, address newTimelock);
|
||||
|
||||
/**
|
||||
* @dev Set the timelock.
|
||||
*/
|
||||
constructor(ICompoundTimelock timelockAddress) {
|
||||
_updateTimelock(timelockAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
|
||||
return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-state} function with added support for the `Queued` and `Expired` status.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
|
||||
ProposalState status = super.state(proposalId);
|
||||
|
||||
if (status != ProposalState.Succeeded) {
|
||||
return status;
|
||||
}
|
||||
|
||||
uint256 eta = proposalEta(proposalId);
|
||||
if (eta == 0) {
|
||||
return status;
|
||||
} else if (block.timestamp >= eta + _timelock.GRACE_PERIOD()) {
|
||||
return ProposalState.Expired;
|
||||
} else {
|
||||
return ProposalState.Queued;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the address of the timelock
|
||||
*/
|
||||
function timelock() public view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the eta of a queued proposal
|
||||
*/
|
||||
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
return _proposalTimelocks[proposalId].timer.getDeadline();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to queue a proposal to the timelock.
|
||||
*/
|
||||
function queue(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public virtual override returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
|
||||
|
||||
uint256 eta = block.timestamp + _timelock.delay();
|
||||
_proposalTimelocks[proposalId].timer.setDeadline(eta.toUint64());
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
require(
|
||||
!_timelock.queuedTransactions(keccak256(abi.encode(targets[i], values[i], "", calldatas[i], eta))),
|
||||
"GovernorTimelockCompound: identical proposal action already queued"
|
||||
);
|
||||
_timelock.queueTransaction(targets[i], values[i], "", calldatas[i], eta);
|
||||
}
|
||||
|
||||
emit ProposalQueued(proposalId, eta);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden execute function that run the already queued proposal through the timelock.
|
||||
*/
|
||||
function _execute(
|
||||
uint256 proposalId,
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 /*descriptionHash*/
|
||||
) internal virtual override {
|
||||
uint256 eta = proposalEta(proposalId);
|
||||
require(eta > 0, "GovernorTimelockCompound: proposal not yet queued");
|
||||
Address.sendValue(payable(_timelock), msg.value);
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
_timelock.executeTransaction(targets[i], values[i], "", calldatas[i], eta);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
|
||||
* been queued.
|
||||
*/
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
|
||||
|
||||
uint256 eta = proposalEta(proposalId);
|
||||
if (eta > 0) {
|
||||
for (uint256 i = 0; i < targets.length; ++i) {
|
||||
_timelock.cancelTransaction(targets[i], values[i], "", calldatas[i], eta);
|
||||
}
|
||||
_proposalTimelocks[proposalId].timer.reset();
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. In this case, the timelock.
|
||||
*/
|
||||
function _executor() internal view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Accept admin right over the timelock.
|
||||
*/
|
||||
// solhint-disable-next-line private-vars-leading-underscore
|
||||
function __acceptAdmin() public {
|
||||
_timelock.acceptAdmin();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
|
||||
* must be proposed, scheduled, and executed through governance proposals.
|
||||
*
|
||||
* For security reasons, the timelock must be handed over to another admin before setting up a new one. The two
|
||||
* operations (hand over the timelock) and do the update can be batched in a single proposal.
|
||||
*
|
||||
* Note that if the timelock admin has been handed over in a previous operation, we refuse updates made through the
|
||||
* timelock if admin of the timelock has already been accepted and the operation is executed outside the scope of
|
||||
* governance.
|
||||
|
||||
* CAUTION: It is not recommended to change the timelock while there are other queued governance proposals.
|
||||
*/
|
||||
function updateTimelock(ICompoundTimelock newTimelock) external virtual onlyGovernance {
|
||||
_updateTimelock(newTimelock);
|
||||
}
|
||||
|
||||
function _updateTimelock(ICompoundTimelock newTimelock) private {
|
||||
emit TimelockChange(address(_timelock), address(newTimelock));
|
||||
_timelock = newTimelock;
|
||||
}
|
||||
}
|
||||
166
contracts/governance/extensions/GovernorTimelockControl.sol
Normal file
166
contracts/governance/extensions/GovernorTimelockControl.sol
Normal file
@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorTimelockControl.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./IGovernorTimelock.sol";
|
||||
import "../Governor.sol";
|
||||
import "../TimelockController.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a
|
||||
* delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The
|
||||
* {Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly.
|
||||
*
|
||||
* Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,
|
||||
* the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be
|
||||
* inaccessible.
|
||||
*
|
||||
* WARNING: Setting up the TimelockController to have additional proposers besides the governor is very risky, as it
|
||||
* grants them powers that they must be trusted or known not to use: 1) {onlyGovernance} functions like {relay} are
|
||||
* available to them through the timelock, and 2) approved governance proposals can be blocked by them, effectively
|
||||
* executing a Denial of Service attack. This risk will be mitigated in a future release.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorTimelockControl is IGovernorTimelock, Governor {
|
||||
TimelockController private _timelock;
|
||||
mapping(uint256 => bytes32) private _timelockIds;
|
||||
|
||||
/**
|
||||
* @dev Emitted when the timelock controller used for proposal execution is modified.
|
||||
*/
|
||||
event TimelockChange(address oldTimelock, address newTimelock);
|
||||
|
||||
/**
|
||||
* @dev Set the timelock.
|
||||
*/
|
||||
constructor(TimelockController timelockAddress) {
|
||||
_updateTimelock(timelockAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) {
|
||||
return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-state} function with added support for the `Queued` status.
|
||||
*/
|
||||
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) {
|
||||
ProposalState status = super.state(proposalId);
|
||||
|
||||
if (status != ProposalState.Succeeded) {
|
||||
return status;
|
||||
}
|
||||
|
||||
// core tracks execution, so we just have to check if successful proposal have been queued.
|
||||
bytes32 queueid = _timelockIds[proposalId];
|
||||
if (queueid == bytes32(0)) {
|
||||
return status;
|
||||
} else if (_timelock.isOperationDone(queueid)) {
|
||||
return ProposalState.Executed;
|
||||
} else if (_timelock.isOperationPending(queueid)) {
|
||||
return ProposalState.Queued;
|
||||
} else {
|
||||
return ProposalState.Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the address of the timelock
|
||||
*/
|
||||
function timelock() public view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public accessor to check the eta of a queued proposal
|
||||
*/
|
||||
function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {
|
||||
uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);
|
||||
return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Function to queue a proposal to the timelock.
|
||||
*/
|
||||
function queue(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public virtual override returns (uint256) {
|
||||
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
|
||||
|
||||
require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful");
|
||||
|
||||
uint256 delay = _timelock.getMinDelay();
|
||||
_timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);
|
||||
_timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);
|
||||
|
||||
emit ProposalQueued(proposalId, block.timestamp + delay);
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden execute function that run the already queued proposal through the timelock.
|
||||
*/
|
||||
function _execute(
|
||||
uint256, /* proposalId */
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override {
|
||||
_timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already
|
||||
* been queued.
|
||||
*/
|
||||
// This function can reenter through the external call to the timelock, but we assume the timelock is trusted and
|
||||
// well behaved (according to TimelockController) and this will not happen.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
function _cancel(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) internal virtual override returns (uint256) {
|
||||
uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
|
||||
|
||||
if (_timelockIds[proposalId] != 0) {
|
||||
_timelock.cancel(_timelockIds[proposalId]);
|
||||
delete _timelockIds[proposalId];
|
||||
}
|
||||
|
||||
return proposalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Address through which the governor executes action. In this case, the timelock.
|
||||
*/
|
||||
function _executor() internal view virtual override returns (address) {
|
||||
return address(_timelock);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates
|
||||
* must be proposed, scheduled, and executed through governance proposals.
|
||||
*
|
||||
* CAUTION: It is not recommended to change the timelock while there are other queued governance proposals.
|
||||
*/
|
||||
function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance {
|
||||
_updateTimelock(newTimelock);
|
||||
}
|
||||
|
||||
function _updateTimelock(TimelockController newTimelock) private {
|
||||
emit TimelockChange(address(_timelock), address(newTimelock));
|
||||
_timelock = newTimelock;
|
||||
}
|
||||
}
|
||||
31
contracts/governance/extensions/GovernorVotes.sol
Normal file
31
contracts/governance/extensions/GovernorVotes.sol
Normal file
@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorVotes.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
import "../utils/IVotes.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorVotes is Governor {
|
||||
IVotes public immutable token;
|
||||
|
||||
constructor(IVotes tokenAddress) {
|
||||
token = tokenAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}).
|
||||
*/
|
||||
function _getVotes(
|
||||
address account,
|
||||
uint256 blockNumber,
|
||||
bytes memory /*params*/
|
||||
) internal view virtual override returns (uint256) {
|
||||
return token.getPastVotes(account, blockNumber);
|
||||
}
|
||||
}
|
||||
31
contracts/governance/extensions/GovernorVotesComp.sol
Normal file
31
contracts/governance/extensions/GovernorVotesComp.sol
Normal file
@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/extensions/GovernorVotesComp.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../Governor.sol";
|
||||
import "../../token/ERC20/extensions/ERC20VotesComp.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for voting weight extraction from a Comp token.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorVotesComp is Governor {
|
||||
ERC20VotesComp public immutable token;
|
||||
|
||||
constructor(ERC20VotesComp token_) {
|
||||
token = token_;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}).
|
||||
*/
|
||||
function _getVotes(
|
||||
address account,
|
||||
uint256 blockNumber,
|
||||
bytes memory /*params*/
|
||||
) internal view virtual override returns (uint256) {
|
||||
return token.getPriorVotes(account, blockNumber);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorVotesQuorumFraction.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./GovernorVotes.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a
|
||||
* fraction of the total supply.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract GovernorVotesQuorumFraction is GovernorVotes {
|
||||
uint256 private _quorumNumerator;
|
||||
|
||||
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator);
|
||||
|
||||
/**
|
||||
* @dev Initialize quorum as a fraction of the token's total supply.
|
||||
*
|
||||
* The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum is
|
||||
* specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be
|
||||
* customized by overriding {quorumDenominator}.
|
||||
*/
|
||||
constructor(uint256 quorumNumeratorValue) {
|
||||
_updateQuorumNumerator(quorumNumeratorValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current quorum numerator. See {quorumDenominator}.
|
||||
*/
|
||||
function quorumNumerator() public view virtual returns (uint256) {
|
||||
return _quorumNumerator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the quorum denominator. Defaults to 100, but may be overridden.
|
||||
*/
|
||||
function quorumDenominator() public view virtual returns (uint256) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the quorum for a block number, in terms of number of votes: `supply * numerator / denominator`.
|
||||
*/
|
||||
function quorum(uint256 blockNumber) public view virtual override returns (uint256) {
|
||||
return (token.getPastTotalSupply(blockNumber) * quorumNumerator()) / quorumDenominator();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the quorum numerator.
|
||||
*
|
||||
* Emits a {QuorumNumeratorUpdated} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - Must be called through a governance proposal.
|
||||
* - New numerator must be smaller or equal to the denominator.
|
||||
*/
|
||||
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
|
||||
_updateQuorumNumerator(newQuorumNumerator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Changes the quorum numerator.
|
||||
*
|
||||
* Emits a {QuorumNumeratorUpdated} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - New numerator must be smaller or equal to the denominator.
|
||||
*/
|
||||
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual {
|
||||
require(
|
||||
newQuorumNumerator <= quorumDenominator(),
|
||||
"GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator"
|
||||
);
|
||||
|
||||
uint256 oldQuorumNumerator = _quorumNumerator;
|
||||
_quorumNumerator = newQuorumNumerator;
|
||||
|
||||
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
|
||||
}
|
||||
}
|
||||
26
contracts/governance/extensions/IGovernorTimelock.sol
Normal file
26
contracts/governance/extensions/IGovernorTimelock.sol
Normal file
@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (governance/extensions/IGovernorTimelock.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../IGovernor.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of the {IGovernor} for timelock supporting modules.
|
||||
*
|
||||
* _Available since v4.3._
|
||||
*/
|
||||
abstract contract IGovernorTimelock is IGovernor {
|
||||
event ProposalQueued(uint256 proposalId, uint256 eta);
|
||||
|
||||
function timelock() public view virtual returns (address);
|
||||
|
||||
function proposalEta(uint256 proposalId) public view virtual returns (uint256);
|
||||
|
||||
function queue(
|
||||
address[] memory targets,
|
||||
uint256[] memory values,
|
||||
bytes[] memory calldatas,
|
||||
bytes32 descriptionHash
|
||||
) public virtual returns (uint256 proposalId);
|
||||
}
|
||||
61
contracts/governance/utils/IVotes.sol
Normal file
61
contracts/governance/utils/IVotes.sol
Normal file
@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
/**
|
||||
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
|
||||
*
|
||||
* _Available since v4.5._
|
||||
*/
|
||||
interface IVotes {
|
||||
/**
|
||||
* @dev Emitted when an account changes their delegate.
|
||||
*/
|
||||
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
|
||||
|
||||
/**
|
||||
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
|
||||
*/
|
||||
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
|
||||
|
||||
/**
|
||||
* @dev Returns the current amount of votes that `account` has.
|
||||
*/
|
||||
function getVotes(address account) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
|
||||
*/
|
||||
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
|
||||
*
|
||||
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
|
||||
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
|
||||
* vote.
|
||||
*/
|
||||
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the delegate that `account` has chosen.
|
||||
*/
|
||||
function delegates(address account) external view returns (address);
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from the sender to `delegatee`.
|
||||
*/
|
||||
function delegate(address delegatee) external;
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from signer to `delegatee`.
|
||||
*/
|
||||
function delegateBySig(
|
||||
address delegatee,
|
||||
uint256 nonce,
|
||||
uint256 expiry,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) external;
|
||||
}
|
||||
211
contracts/governance/utils/Votes.sol
Normal file
211
contracts/governance/utils/Votes.sol
Normal file
@ -0,0 +1,211 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v4.6.0) (governance/utils/Votes.sol)
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../../utils/Context.sol";
|
||||
import "../../utils/Counters.sol";
|
||||
import "../../utils/Checkpoints.sol";
|
||||
import "../../utils/cryptography/draft-EIP712.sol";
|
||||
import "./IVotes.sol";
|
||||
|
||||
/**
|
||||
* @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
|
||||
* transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
|
||||
* "representative" that will pool delegated voting units from different accounts and can then use it to vote in
|
||||
* decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
|
||||
* delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
|
||||
*
|
||||
* This contract is often combined with a token contract such that voting units correspond to token units. For an
|
||||
* example, see {ERC721Votes}.
|
||||
*
|
||||
* The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
|
||||
* at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
|
||||
* cost of this history tracking optional.
|
||||
*
|
||||
* When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
|
||||
* {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
|
||||
* previous example, it would be included in {ERC721-_beforeTokenTransfer}).
|
||||
*
|
||||
* _Available since v4.5._
|
||||
*/
|
||||
abstract contract Votes is IVotes, Context, EIP712 {
|
||||
using Checkpoints for Checkpoints.History;
|
||||
using Counters for Counters.Counter;
|
||||
|
||||
bytes32 private constant _DELEGATION_TYPEHASH =
|
||||
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
|
||||
|
||||
mapping(address => address) private _delegation;
|
||||
mapping(address => Checkpoints.History) private _delegateCheckpoints;
|
||||
Checkpoints.History private _totalCheckpoints;
|
||||
|
||||
mapping(address => Counters.Counter) private _nonces;
|
||||
|
||||
/**
|
||||
* @dev Returns the current amount of votes that `account` has.
|
||||
*/
|
||||
function getVotes(address account) public view virtual override returns (uint256) {
|
||||
return _delegateCheckpoints[account].latest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `blockNumber` must have been already mined
|
||||
*/
|
||||
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
|
||||
return _delegateCheckpoints[account].getAtBlock(blockNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
|
||||
*
|
||||
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
|
||||
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
|
||||
* vote.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `blockNumber` must have been already mined
|
||||
*/
|
||||
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
|
||||
require(blockNumber < block.number, "Votes: block not yet mined");
|
||||
return _totalCheckpoints.getAtBlock(blockNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the current total supply of votes.
|
||||
*/
|
||||
function _getTotalSupply() internal view virtual returns (uint256) {
|
||||
return _totalCheckpoints.latest();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the delegate that `account` has chosen.
|
||||
*/
|
||||
function delegates(address account) public view virtual override returns (address) {
|
||||
return _delegation[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from the sender to `delegatee`.
|
||||
*/
|
||||
function delegate(address delegatee) public virtual override {
|
||||
address account = _msgSender();
|
||||
_delegate(account, delegatee);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegates votes from signer to `delegatee`.
|
||||
*/
|
||||
function delegateBySig(
|
||||
address delegatee,
|
||||
uint256 nonce,
|
||||
uint256 expiry,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual override {
|
||||
require(block.timestamp <= expiry, "Votes: signature expired");
|
||||
address signer = ECDSA.recover(
|
||||
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
|
||||
v,
|
||||
r,
|
||||
s
|
||||
);
|
||||
require(nonce == _useNonce(signer), "Votes: invalid nonce");
|
||||
_delegate(signer, delegatee);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Delegate all of `account`'s voting units to `delegatee`.
|
||||
*
|
||||
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
|
||||
*/
|
||||
function _delegate(address account, address delegatee) internal virtual {
|
||||
address oldDelegate = delegates(account);
|
||||
_delegation[account] = delegatee;
|
||||
|
||||
emit DelegateChanged(account, oldDelegate, delegatee);
|
||||
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
|
||||
* should be zero. Total supply of voting units will be adjusted with mints and burns.
|
||||
*/
|
||||
function _transferVotingUnits(
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount
|
||||
) internal virtual {
|
||||
if (from == address(0)) {
|
||||
_totalCheckpoints.push(_add, amount);
|
||||
}
|
||||
if (to == address(0)) {
|
||||
_totalCheckpoints.push(_subtract, amount);
|
||||
}
|
||||
_moveDelegateVotes(delegates(from), delegates(to), amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves delegated votes from one delegate to another.
|
||||
*/
|
||||
function _moveDelegateVotes(
|
||||
address from,
|
||||
address to,
|
||||
uint256 amount
|
||||
) private {
|
||||
if (from != to && amount > 0) {
|
||||
if (from != address(0)) {
|
||||
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);
|
||||
emit DelegateVotesChanged(from, oldValue, newValue);
|
||||
}
|
||||
if (to != address(0)) {
|
||||
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);
|
||||
emit DelegateVotesChanged(to, oldValue, newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _add(uint256 a, uint256 b) private pure returns (uint256) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
|
||||
return a - b;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Consumes a nonce.
|
||||
*
|
||||
* Returns the current value and increments nonce.
|
||||
*/
|
||||
function _useNonce(address owner) internal virtual returns (uint256 current) {
|
||||
Counters.Counter storage nonce = _nonces[owner];
|
||||
current = nonce.current();
|
||||
nonce.increment();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns an address nonce.
|
||||
*/
|
||||
function nonces(address owner) public view virtual returns (uint256) {
|
||||
return _nonces[owner].current();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the contract's {EIP712} domain separator.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view returns (bytes32) {
|
||||
return _domainSeparatorV4();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Must return the voting units held by an account.
|
||||
*/
|
||||
function _getVotingUnits(address) internal view virtual returns (uint256);
|
||||
}
|
||||
6
contracts/interfaces/IERC1155.sol
Normal file
6
contracts/interfaces/IERC1155.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../token/ERC1155/IERC1155.sol";
|
||||
6
contracts/interfaces/IERC1155MetadataURI.sol
Normal file
6
contracts/interfaces/IERC1155MetadataURI.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155MetadataURI.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../token/ERC1155/extensions/IERC1155MetadataURI.sol";
|
||||
6
contracts/interfaces/IERC1155Receiver.sol
Normal file
6
contracts/interfaces/IERC1155Receiver.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../token/ERC1155/IERC1155Receiver.sol";
|
||||
19
contracts/interfaces/IERC1271.sol
Normal file
19
contracts/interfaces/IERC1271.sol
Normal file
@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC1271 standard signature validation method for
|
||||
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
|
||||
*
|
||||
* _Available since v4.1._
|
||||
*/
|
||||
interface IERC1271 {
|
||||
/**
|
||||
* @dev Should return whether the signature provided is valid for the provided data
|
||||
* @param hash Hash of the data to be signed
|
||||
* @param signature Signature byte array associated with _data
|
||||
*/
|
||||
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
|
||||
}
|
||||
95
contracts/interfaces/IERC1363.sol
Normal file
95
contracts/interfaces/IERC1363.sol
Normal file
@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "./IERC20.sol";
|
||||
import "./IERC165.sol";
|
||||
|
||||
interface IERC1363 is IERC165, IERC20 {
|
||||
/*
|
||||
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
|
||||
* 0x4bbee2df ===
|
||||
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
|
||||
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
|
||||
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
|
||||
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
|
||||
*/
|
||||
|
||||
/*
|
||||
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
|
||||
* 0xfb9ec8ce ===
|
||||
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
|
||||
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
|
||||
*/
|
||||
|
||||
/**
|
||||
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
|
||||
* @param to address The address which you want to transfer to
|
||||
* @param value uint256 The amount of tokens to be transferred
|
||||
* @return true unless throwing
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
|
||||
* @param to address The address which you want to transfer to
|
||||
* @param value uint256 The amount of tokens to be transferred
|
||||
* @param data bytes Additional data with no specified format, sent in call to `to`
|
||||
* @return true unless throwing
|
||||
*/
|
||||
function transferAndCall(
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
|
||||
* @param from address The address which you want to send tokens from
|
||||
* @param to address The address which you want to transfer to
|
||||
* @param value uint256 The amount of tokens to be transferred
|
||||
* @return true unless throwing
|
||||
*/
|
||||
function transferFromAndCall(
|
||||
address from,
|
||||
address to,
|
||||
uint256 value
|
||||
) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Transfer tokens from one address to another and then call `onTransferReceived` on receiver
|
||||
* @param from address The address which you want to send tokens from
|
||||
* @param to address The address which you want to transfer to
|
||||
* @param value uint256 The amount of tokens to be transferred
|
||||
* @param data bytes Additional data with no specified format, sent in call to `to`
|
||||
* @return true unless throwing
|
||||
*/
|
||||
function transferFromAndCall(
|
||||
address from,
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
|
||||
* and then call `onApprovalReceived` on spender.
|
||||
* @param spender address The address which will spend the funds
|
||||
* @param value uint256 The amount of tokens to be spent
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
|
||||
* and then call `onApprovalReceived` on spender.
|
||||
* @param spender address The address which will spend the funds
|
||||
* @param value uint256 The amount of tokens to be spent
|
||||
* @param data bytes Additional data with no specified format, sent in call to `spender`
|
||||
*/
|
||||
function approveAndCall(
|
||||
address spender,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) external returns (bool);
|
||||
}
|
||||
32
contracts/interfaces/IERC1363Receiver.sol
Normal file
32
contracts/interfaces/IERC1363Receiver.sol
Normal file
@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
interface IERC1363Receiver {
|
||||
/*
|
||||
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
|
||||
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
|
||||
*/
|
||||
|
||||
/**
|
||||
* @notice Handle the receipt of ERC1363 tokens
|
||||
* @dev Any ERC1363 smart contract calls this function on the recipient
|
||||
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
|
||||
* transfer. Return of other than the magic value MUST result in the
|
||||
* transaction being reverted.
|
||||
* Note: the token contract address is always the message sender.
|
||||
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
|
||||
* @param from address The address which are token transferred from
|
||||
* @param value uint256 The amount of tokens transferred
|
||||
* @param data bytes Additional data with no specified format
|
||||
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
|
||||
* unless throwing
|
||||
*/
|
||||
function onTransferReceived(
|
||||
address operator,
|
||||
address from,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) external returns (bytes4);
|
||||
}
|
||||
30
contracts/interfaces/IERC1363Spender.sol
Normal file
30
contracts/interfaces/IERC1363Spender.sol
Normal file
@ -0,0 +1,30 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1363Spender.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
interface IERC1363Spender {
|
||||
/*
|
||||
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
|
||||
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
|
||||
*/
|
||||
|
||||
/**
|
||||
* @notice Handle the approval of ERC1363 tokens
|
||||
* @dev Any ERC1363 smart contract calls this function on the recipient
|
||||
* after an `approve`. This function MAY throw to revert and reject the
|
||||
* approval. Return of other than the magic value MUST result in the
|
||||
* transaction being reverted.
|
||||
* Note: the token contract address is always the message sender.
|
||||
* @param owner address The address which called `approveAndCall` function
|
||||
* @param value uint256 The amount of tokens to be spent
|
||||
* @param data bytes Additional data with no specified format
|
||||
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
|
||||
* unless throwing
|
||||
*/
|
||||
function onApprovalReceived(
|
||||
address owner,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) external returns (bytes4);
|
||||
}
|
||||
6
contracts/interfaces/IERC165.sol
Normal file
6
contracts/interfaces/IERC165.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/introspection/IERC165.sol";
|
||||
6
contracts/interfaces/IERC1820Implementer.sol
Normal file
6
contracts/interfaces/IERC1820Implementer.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1820Implementer.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/introspection/IERC1820Implementer.sol";
|
||||
6
contracts/interfaces/IERC1820Registry.sol
Normal file
6
contracts/interfaces/IERC1820Registry.sol
Normal file
@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1820Registry.sol)
|
||||
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "../utils/introspection/IERC1820Registry.sol";
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user