Francisco Giordano 3 سال پیش
کامیت
4e65cfbb38
100فایلهای تغییر یافته به همراه5392 افزوده شده و 0 حذف شده
  1. 11 0
      .codecov.yml
  2. 21 0
      .editorconfig
  3. 64 0
      .eslintrc
  4. 1 0
      .gitattributes
  5. 21 0
      .github/ISSUE_TEMPLATE/bug_report.md
  6. 4 0
      .github/ISSUE_TEMPLATE/config.yml
  7. 14 0
      .github/ISSUE_TEMPLATE/feature_request.md
  8. 20 0
      .github/PULL_REQUEST_TEMPLATE.md
  9. 24 0
      .github/workflows/docs.yml
  10. 45 0
      .github/workflows/test.yml
  11. 59 0
      .gitignore
  12. 3 0
      .mocharc.js
  13. 15 0
      .solcover.js
  14. 12 0
      .solhint.json
  15. 267 0
      CHANGELOG.md
  16. 73 0
      CODE_OF_CONDUCT.md
  17. 64 0
      CONTRIBUTING.md
  18. 16 0
      DOCUMENTATION.md
  19. 105 0
      GUIDELINES.md
  20. 22 0
      LICENSE
  21. 77 0
      README.md
  22. 36 0
      RELEASING.md
  23. 290 0
      audit/2017-03.md
  24. BIN
      audit/2018-10.pdf
  25. 20 0
      buidler.config.js
  26. 10 0
      buidler/env-contract.js
  27. 5 0
      contracts/GSN/Context.sol
  28. 230 0
      contracts/GSN/GSNRecipient.sol
  29. 154 0
      contracts/GSN/GSNRecipientERC20Fee.sol
  30. 72 0
      contracts/GSN/GSNRecipientSignature.sol
  31. 269 0
      contracts/GSN/IRelayHub.sol
  32. 76 0
      contracts/GSN/IRelayRecipient.sol
  33. 31 0
      contracts/GSN/README.adoc
  34. 217 0
      contracts/access/AccessControl.sol
  35. 68 0
      contracts/access/Ownable.sol
  36. 101 0
      contracts/access/README.adoc
  37. 300 0
      contracts/access/TimelockController.sol
  38. 86 0
      contracts/cryptography/ECDSA.sol
  39. 33 0
      contracts/cryptography/MerkleProof.sol
  40. 16 0
      contracts/cryptography/README.adoc
  41. 108 0
      contracts/drafts/EIP712.sol
  42. 78 0
      contracts/drafts/ERC20Permit.sol
  43. 51 0
      contracts/drafts/IERC20Permit.sol
  44. 15 0
      contracts/drafts/README.adoc
  45. 54 0
      contracts/introspection/ERC165.sol
  46. 131 0
      contracts/introspection/ERC165Checker.sol
  47. 37 0
      contracts/introspection/ERC1820Implementer.sol
  48. 24 0
      contracts/introspection/IERC165.sol
  49. 19 0
      contracts/introspection/IERC1820Implementer.sol
  50. 111 0
      contracts/introspection/IERC1820Registry.sol
  51. 31 0
      contracts/introspection/README.adoc
  52. 31 0
      contracts/math/Math.sol
  53. 14 0
      contracts/math/README.adoc
  54. 214 0
      contracts/math/SafeMath.sol
  55. 92 0
      contracts/math/SignedSafeMath.sol
  56. 15 0
      contracts/mocks/AccessControlMock.sol
  57. 42 0
      contracts/mocks/AddressImpl.sol
  58. 19 0
      contracts/mocks/ArraysImpl.sol
  59. 12 0
      contracts/mocks/BadBeacon.sol
  60. 50 0
      contracts/mocks/CallReceiverMock.sol
  61. 20 0
      contracts/mocks/ClashingImplementation.sol
  62. 32 0
      contracts/mocks/ClonesMock.sol
  63. 18 0
      contracts/mocks/ConditionalEscrowMock.sol
  64. 29 0
      contracts/mocks/ContextMock.sol
  65. 23 0
      contracts/mocks/CountersImpl.sol
  66. 27 0
      contracts/mocks/Create2Impl.sol
  67. 57 0
      contracts/mocks/DummyImplementation.sol
  68. 17 0
      contracts/mocks/ECDSAMock.sol
  69. 32 0
      contracts/mocks/EIP712External.sol
  70. 13 0
      contracts/mocks/ERC1155BurnableMock.sol
  71. 35 0
      contracts/mocks/ERC1155Mock.sol
  72. 31 0
      contracts/mocks/ERC1155PausableMock.sol
  73. 62 0
      contracts/mocks/ERC1155ReceiverMock.sol
  74. 58 0
      contracts/mocks/ERC165/ERC165InterfacesSupported.sol
  75. 5 0
      contracts/mocks/ERC165/ERC165NotSupported.sol
  76. 25 0
      contracts/mocks/ERC165CheckerMock.sol
  77. 11 0
      contracts/mocks/ERC165Mock.sol
  78. 11 0
      contracts/mocks/ERC1820ImplementerMock.sol
  79. 16 0
      contracts/mocks/ERC20BurnableMock.sol
  80. 15 0
      contracts/mocks/ERC20CappedMock.sol
  81. 11 0
      contracts/mocks/ERC20DecimalsMock.sol
  82. 33 0
      contracts/mocks/ERC20Mock.sol
  83. 33 0
      contracts/mocks/ERC20PausableMock.sol
  84. 24 0
      contracts/mocks/ERC20PermitMock.sol
  85. 29 0
      contracts/mocks/ERC20SnapshotMock.sol
  86. 13 0
      contracts/mocks/ERC721BurnableMock.sol
  87. 31 0
      contracts/mocks/ERC721GSNRecipientMock.sol
  88. 41 0
      contracts/mocks/ERC721Mock.sol
  89. 33 0
      contracts/mocks/ERC721PausableMock.sol
  90. 25 0
      contracts/mocks/ERC721ReceiverMock.sol
  91. 37 0
      contracts/mocks/ERC777Mock.sol
  92. 153 0
      contracts/mocks/ERC777SenderRecipientMock.sol
  93. 48 0
      contracts/mocks/EnumerableMapMock.sol
  94. 98 0
      contracts/mocks/EnumerableSetMock.sol
  95. 17 0
      contracts/mocks/EtherReceiverMock.sol
  96. 20 0
      contracts/mocks/GSNRecipientERC20FeeMock.sol
  97. 38 0
      contracts/mocks/GSNRecipientMock.sol
  98. 16 0
      contracts/mocks/GSNRecipientSignatureMock.sol
  99. 36 0
      contracts/mocks/InitializableMock.sol
  100. 19 0
      contracts/mocks/MathMock.sol

+ 11 - 0
.codecov.yml

@@ -0,0 +1,11 @@
+comment: off
+github_checks:
+  annotations: false
+coverage:
+  status:
+    patch:
+      default:
+        target: 95%
+    project:
+      default:
+        threshold: 1%

+ 21 - 0
.editorconfig

@@ -0,0 +1,21 @@
+# EditorConfig is awesome: https://EditorConfig.org
+
+# top-most EditorConfig file
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+indent_style = space
+insert_final_newline = true
+trim_trailing_whitespace = false
+max_line_length = 120
+
+[*.sol]
+indent_size = 4
+
+[*.js]
+indent_size = 2
+
+[*.adoc]
+max_line_length = 0

+ 64 - 0
.eslintrc

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

+ 1 - 0
.gitattributes

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

+ 21 - 0
.github/ISSUE_TEMPLATE/bug_report.md

@@ -0,0 +1,21 @@
+---
+name: Bug report
+about: Report a bug in OpenZeppelin Contracts
+
+---
+
+<!-- Briefly describe the issue you're experiencing. Tell us what you were trying to do and what happened instead. -->
+
+<!-- Remember, this is not a place to ask for help debugging code. For that, we welcome you in the OpenZeppelin Community Forum: https://forum.openzeppelin.com/. -->
+
+**💻 Environment**
+
+<!-- Tell us what version of OpenZeppelin Contracts you're using, and how you're using it: Truffle, Remix, etc. -->
+
+**📝 Details**
+
+<!-- Describe the problem you have been experiencing in more detail. Include as much information as you think is relevant. Keep in mind that transactions can fail for many reasons; context is key here. -->
+
+**🔢 Code to reproduce bug**
+
+<!-- We will be able to better help if you provide a minimal example that triggers the bug. -->

+ 4 - 0
.github/ISSUE_TEMPLATE/config.yml

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

+ 14 - 0
.github/ISSUE_TEMPLATE/feature_request.md

@@ -0,0 +1,14 @@
+---
+name: Feature request
+about: Suggest an idea for OpenZeppelin Contracts
+
+---
+
+**🧐 Motivation**
+<!-- Is your feature request related to a specific problem? Is it just a crazy idea? Tell us about it! -->
+
+**📝 Details**
+<!-- Please describe your feature request in detail. -->
+
+<!-- Make sure that you have reviewed the OpenZeppelin Contributor Guidelines. -->
+<!-- https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CONTRIBUTING.md -->

+ 20 - 0
.github/PULL_REQUEST_TEMPLATE.md

@@ -0,0 +1,20 @@
+<!-- Thank you for your interest in contributing to OpenZeppelin! -->
+
+<!-- Consider opening an issue for discussion prior to submitting a PR. -->
+<!-- New features will be merged faster if they were first discussed and designed with the team. -->
+
+Fixes #???? <!-- Fill in with issue number -->
+
+<!-- Describe the changes introduced in this pull request. -->
+<!-- Include any context necessary for understanding the PR's purpose. -->
+
+
+#### PR Checklist
+
+<!-- Before merging the pull request all of the following must be complete. -->
+<!-- Feel free to submit a PR or Draft PR even if some items are pending. -->
+<!-- Some of the items may not apply. -->
+
+- [ ] Tests
+- [ ] Documentation
+- [ ] Changelog entry

+ 24 - 0
.github/workflows/docs.yml

@@ -0,0 +1,24 @@
+name: Build Docs
+
+on:
+  push: release-v*
+
+jobs:
+  trigger:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v2
+      - uses: actions/setup-node@v2
+        with:
+          node-version: 12.x
+      - uses: actions/cache@v2
+        id: cache
+        with:
+          path: '**/node_modules'
+          key: npm-v2-${{ hashFiles('**/package-lock.json') }}
+          restore-keys: npm-v2-
+      - run: npm ci
+        if: steps.cache.outputs.cache-hit != 'true'
+      - run: bash scripts/git-user-config.sh
+      - run: node scripts/update-docs-branch.js
+      - run: git push --all origin 

+ 45 - 0
.github/workflows/test.yml

@@ -0,0 +1,45 @@
+name: Test
+
+on:
+  push:
+    branches:
+      - master
+      - release-v*
+  pull_request: {}
+
+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

+ 59 - 0
.gitignore

@@ -0,0 +1,59 @@
+*.swp
+*.swo
+
+# Logs
+logs
+*.log
+
+# Runtime data
+pids
+*.pid
+*.seed
+allFiredEvents
+scTopics
+
+# Coverage directory used by tools like istanbul
+coverage
+coverage.json
+coverageEnv
+
+# node-waf configuration
+.lock-wscript
+
+# Dependency directory
+node_modules
+
+# Debug log from npm
+npm-debug.log
+
+# local env variables
+.env
+
+# truffle build directory
+build/
+
+# macOS
+.DS_Store
+
+# truffle
+.node-xmlhttprequest-*
+
+# IntelliJ IDE
+.idea
+
+# docs artifacts
+docs/modules/api
+
+# only used to package @openzeppelin/contracts
+contracts/build/
+contracts/README.md
+
+# temporary artifact from solidity-coverage
+allFiredEvents
+.coverage_artifacts
+.coverage_cache
+.coverage_contracts
+
+# buidler
+cache
+artifacts

+ 3 - 0
.mocharc.js

@@ -0,0 +1,3 @@
+module.exports = {
+  timeout: 4000,
+};

+ 15 - 0
.solcover.js

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

+ 12 - 0
.solhint.json

@@ -0,0 +1,12 @@
+{
+  "extends": "solhint:recommended",
+  "rules": {
+    "func-order": "off",
+    "mark-callable-contracts": "off",
+    "no-empty-blocks": "off",
+    "compiler-version": "off",
+    "private-vars-leading-underscore": "error",
+    "reason-string": "off",
+    "func-visibility": ["error", { "ignoreConstructors": true }]
+  }
+}

+ 267 - 0
CHANGELOG.md

@@ -0,0 +1,267 @@
+# Changelog
+
+## 3.4.2 (2021-08-26)
+
+ * `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))
+ * `ERC20Permit`: added an implementation of the ERC20 permit extension for gasless token approvals. ([#2237](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237))
+ * Presets: added token presets with preminted fixed supply `ERC20PresetFixedSupply` and `ERC777PresetFixedSupply`. ([#2399](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2399))
+ * `Address`: added `functionDelegateCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333))
+ * `Clones`: added a library for deploying EIP 1167 minimal proxies. ([#2449](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2449))
+ * `Context`: moved from `contracts/GSN` to `contracts/utils`. ([#2453](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2453))
+ * `PaymentSplitter`: replace usage of `.transfer()` with `Address.sendValue` for improved compatibility with smart wallets. ([#2455](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2455))
+ * `UpgradeableProxy`: bubble revert reasons from initialization calls. ([#2454](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2454))
+ * `SafeMath`: fix a memory allocation issue by adding new `SafeMath.tryOp(uint,uint)→(bool,uint)` functions. `SafeMath.op(uint,uint,string)→uint` are now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462))
+ * `EnumerableMap`: fix a memory allocation issue by adding new `EnumerableMap.tryGet(uint)→(bool,address)` functions. `EnumerableMap.get(uint)→string` is now deprecated. ([#2462](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2462))
+ * `ERC165Checker`: added batch `getSupportedInterfaces`. ([#2469](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2469))
+ * `RefundEscrow`: `beneficiaryWithdraw` will forward all available gas to the beneficiary. ([#2480](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2480))
+ * Many view and pure functions have been made virtual to customize them via overrides. In many cases this will not imply that other functions in the contract will automatically adapt to the overridden definitions. People who wish to override should consult the source code to understand the impact and if they need to override any additional functions to achieve the desired behavior.
+
+### Security Fixes
+
+ * `ERC777`: fix potential reentrancy issues for custom extensions to `ERC777`. ([#2483](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483))
+
+If you're using our implementation of ERC777 from version 3.3.0 or earlier, and you define a custom `_beforeTokenTransfer` function that writes to a storage variable, you may be vulnerable to a reentrancy attack. If you're affected and would like assistance please write to security@openzeppelin.com. [Read more in the pull request.](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2483)
+
+## 3.3.0 (2020-11-26)
+
+ * Now supports both Solidity 0.6 and 0.7. Compiling with solc 0.7 will result in warnings. Install the `solc-0.7` tag to compile without warnings.
+ * `Address`: added `functionStaticCall`, similar to the existing `functionCall`. ([#2333](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2333))
+ * `TimelockController`: added a contract to augment access control schemes with a delay. ([#2354](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2354))
+ * `EnumerableSet`: added `Bytes32Set`, for sets of `bytes32`. ([#2395](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2395))
+
+## 3.2.0 (2020-09-10)
+
+### New features
+ * Proxies: added the proxy contracts from OpenZeppelin SDK. ([#2335](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2335))
+
+#### Proxy changes with respect to OpenZeppelin SDK
+
+Aside from upgrading them from Solidity 0.5 to 0.6, we've changed a few minor things from the proxy contracts as they were found in OpenZeppelin SDK.
+
+- `UpgradeabilityProxy` was renamed to `UpgradeableProxy`.
+- `AdminUpgradeabilityProxy` was renamed to `TransparentUpgradeableProxy`.
+- `Proxy._willFallback` was renamed to `Proxy._beforeFallback`.
+- `UpgradeabilityProxy._setImplementation` and `AdminUpgradeabilityProxy._setAdmin` were made private.
+
+### Improvements
+ * `Address.isContract`: switched from `extcodehash` to `extcodesize` for less gas usage. ([#2311](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2311))
+
+### Breaking changes
+ * `ERC20Snapshot`: switched to using `_beforeTokenTransfer` hook instead of overriding ERC20 operations. ([#2312](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2312))
+
+This small change in the way we implemented `ERC20Snapshot` may affect users who are combining this contract with
+other ERC20 flavors, since it no longer overrides `_transfer`, `_mint`, and `_burn`. This can result in having to remove Solidity `override(...)` specifiers in derived contracts for these functions, and to instead have to add it for `_beforeTokenTransfer`. See [Using Hooks](https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks) in the documentation.
+
+## 3.1.0 (2020-06-23)
+
+### New features
+ * `SafeCast`: added functions to downcast signed integers (e.g. `toInt32`), improving usability of `SignedSafeMath`. ([#2243](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2243))
+ * `functionCall`: new helpers that replicate Solidity's function call semantics, reducing the need to rely on `call`. ([#2264](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2264))
+ * `ERC1155`: added support for a base implementation, non-standard extensions and a preset contract. ([#2014](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2014), [#2230](https://github.com/OpenZeppelin/openzeppelin-contracts/issues/2230))
+
+### Improvements
+ * `ReentrancyGuard`: reduced overhead of using the `nonReentrant` modifier. ([#2171](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2171))
+ * `AccessControl`: added a `RoleAdminChanged` event to `_setAdminRole`. ([#2214](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2214))
+ * Made all `public` functions in the token preset contracts `virtual`. ([#2257](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2257))
+
+### Deprecations
+ * `SafeERC20`: deprecated `safeApprove`. ([#2268](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2268))
+
+## 3.0.2 (2020-06-08)
+
+### Improvements
+ * Added SPX license identifier to all contracts. ([#2235](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2235))
+
+## 3.0.1 (2020-04-27)
+
+### Bugfixes
+ * `ERC777`: fixed the `_approve` internal function not validating some of their arguments for non-zero addresses. ([#2213](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2213))
+
+## 3.0.0 (2020-04-20)
+
+### New features
+ * `AccessControl`: new contract for managing permissions in a system, replacement for `Ownable` and `Roles`. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
+ * `SafeCast`: new functions to convert to and from signed and unsigned values: `toUint256` and `toInt256`. ([#2123](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2123))
+ * `EnumerableMap`: a new data structure for key-value pairs (like `mapping`) that can be iterated over. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
+
+### Breaking changes
+ * `ERC721`: `burn(owner, tokenId)` was removed, use `burn(tokenId)` instead. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
+ * `ERC721`: `_checkOnERC721Received` was removed. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
+ * `ERC721`: `_transferFrom` and `_safeTransferFrom` were renamed to `_transfer` and `_safeTransfer`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
+ * `Ownable`: removed `_transferOwnership`. ([#2162](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2162))
+ * `PullPayment`, `Escrow`: `withdrawWithGas` was removed. The old `withdraw` function now forwards all gas. ([#2125](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2125))
+ * `Roles` was removed, use `AccessControl` as a replacement. ([#2112](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2112))
+ * `ECDSA`: when receiving an invalid signature, `recover` now reverts instead of returning the zero address. ([#2114](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2114))
+ * `Create2`: added an `amount` argument to `deploy` for contracts with `payable` constructors. ([#2117](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2117))
+ * `Pausable`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
+ * `Strings`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
+ * `Counters`: moved to the `utils` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
+ * `SignedSafeMath`: moved to the `math` directory. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
+ * `ERC20Snapshot`: moved to the `token/ERC20` directory. `snapshot` was changed into an `internal` function. ([#2122](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2122))
+ * `Ownable`: moved to the `access` directory. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
+ * `Ownable`: removed `isOwner`. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
+ * `Secondary`: removed from the library, use `Ownable` instead. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
+ * `Escrow`, `ConditionalEscrow`, `RefundEscrow`: these now use `Ownable` instead of `Secondary`, their external API changed accordingly. ([#2120](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2120))
+ * `ERC20`: removed `_burnFrom`. ([#2119](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2119))
+ * `Address`: removed `toPayable`, use `payable(address)` instead. ([#2133](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2133))
+ * `ERC777`: `_send`, `_mint` and `_burn` now use the caller as the operator. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
+ * `ERC777`: removed `_callsTokensToSend` and `_callTokensReceived`. ([#2134](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2134))
+ * `EnumerableSet`: renamed `get` to `at`. ([#2151](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2151))
+ * `ERC165Checker`: functions no longer have a leading underscore. ([#2150](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2150))
+ * `ERC721Metadata`, `ERC721Enumerable`: these contracts were removed, and their functionality merged into `ERC721`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
+ * `ERC721`: added a constructor for `name` and `symbol`. ([#2160](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2160))
+ * `ERC20Detailed`: this contract was removed and its functionality merged into `ERC20`. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
+ * `ERC20`: added a constructor for `name` and `symbol`. `decimals` now defaults to 18. ([#2161](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2161))
+ * `Strings`: renamed `fromUint256` to `toString` ([#2188](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2188))
+
+## 2.5.1 (2020-04-24)
+
+### Bugfixes
+ * `ERC777`: fixed the `_send` and `_approve` internal functions not validating some of their arguments for non-zero addresses. ([#2212](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2212))
+
+## 2.5.0 (2020-02-04)
+
+### New features
+ * `SafeCast.toUintXX`: new library for integer downcasting, which allows for safe operation on smaller types (e.g. `uint32`) when combined with `SafeMath`. ([#1926](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1926))
+ * `ERC721Metadata`: added `baseURI`, which can be used for dramatic gas savings when all token URIs share a prefix (e.g. `http://api.myapp.com/tokens/<id>`). ([#1970](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1970))
+ * `EnumerableSet`: new library for storing enumerable sets of values. Only `AddressSet` is supported in this release. ([#2061](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/2061))
+ * `Create2`: simple library to make usage of the `CREATE2` opcode easier. ([#1744](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1744))
+
+### Improvements
+ * `ERC777`: `_burn` is now internal, providing more flexibility and making it easier to create tokens that deflate. ([#1908](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1908))
+ * `ReentrancyGuard`: greatly improved gas efficiency by using the net gas metering mechanism introduced in the Istanbul hardfork. ([#1992](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1992), [#1996](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1996))
+ * `ERC777`: improve extensibility by making `_send` and related functions `internal`. ([#2027](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2027))
+ * `ERC721`: improved revert reason when transferring tokens to a non-recipient contract. ([#2018](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2018))
+
+### Breaking changes
+ * `ERC165Checker` now requires a minimum Solidity compiler version of 0.5.10. ([#1829](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1829))
+
+## 2.4.0 (2019-10-29)
+
+### New features
+ * `Address.toPayable`: added a helper to convert between address types without having to resort to low-level casting. ([#1773](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1773))
+ * Facilities to make metatransaction-enabled contracts through the Gas Station Network. ([#1844](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1844))
+ * `Address.sendValue`: added a replacement to Solidity's `transfer`, removing the fixed gas stipend. ([#1962](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1962))
+ * Added replacement for functions that don't forward all gas (which have been deprecated): ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
+   * `PullPayment.withdrawPaymentsWithGas(address payable payee)`
+   * `Escrow.withdrawWithGas(address payable payee)`
+ * `SafeMath`: added support for custom error messages to `sub`, `div` and `mod` functions. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
+
+### Improvements
+ * `Address.isContract`: switched from `extcodesize` to `extcodehash` for less gas usage. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
+ * `ERC20` and `ERC777` updated to throw custom errors on subtraction overflows. ([#1828](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1828))
+
+### Deprecations
+ * Deprecated functions that don't forward all gas: ([#1976](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1976))
+   * `PullPayment.withdrawPayments(address payable payee)`
+   * `Escrow.withdraw(address payable payee)`
+
+### Breaking changes
+ * `Address` now requires a minimum Solidity compiler version of 0.5.5. ([#1802](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1802))
+ * `SignatureBouncer` has been removed from drafts, both to avoid confusions with the GSN and `GSNRecipientSignature` (previously called `GSNBouncerSignature`) and because the API was not very clear. ([#1879](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/1879))
+
+### How to upgrade from 2.4.0-beta
+
+The final 2.4.0 release includes a refactor of the GSN contracts that will be a breaking change for 2.4.0-beta users.
+
+ * The default empty implementations of `_preRelayedCall` and `_postRelayedCall` were removed and must now be explicitly implemented always in custom recipients. If your custom recipient didn't include an implementation, you can provide an empty one.
+ * `GSNRecipient`, `GSNBouncerBase`, and `GSNContext` were all merged into `GSNRecipient`.
+ * `GSNBouncerSignature` and `GSNBouncerERC20Fee` were renamed to `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
+ * It is no longer necessary to inherit from `GSNRecipient` when using `GSNRecipientSignature` and `GSNRecipientERC20Fee`.
+
+For example, a contract using `GSNBouncerSignature` would have to be changed in the following way.
+
+```diff
+-contract MyDapp is GSNRecipient, GSNBouncerSignature {
++contract MyDapp is GSNRecipientSignature {
+```
+
+Refer to the table below to adjust your inheritance list.
+
+| 2.4.0-beta                         | 2.4.0                        |
+| ---------------------------------- | ---------------------------- |
+| `GSNRecipient, GSNBouncerSignature`| `GSNRecipientSignature`      |
+| `GSNRecipient, GSNBouncerERC20Fee` | `GSNRecipientERC20Fee`       |
+| `GSNBouncerBase`                   | `GSNRecipient`               |
+
+## 2.3.0 (2019-05-27)
+
+### New features
+ * `ERC1820`: added support for interacting with the [ERC1820](https://eips.ethereum.org/EIPS/eip-1820) registry contract (`IERC1820Registry`), as well as base contracts that can be registered as implementers there. ([#1677](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1677))
+ * `ERC777`: support for the [ERC777 token](https://eips.ethereum.org/EIPS/eip-777), which has multiple improvements over `ERC20` (but is backwards compatible with it) such as built-in burning, a more  straightforward permission system, and optional sender and receiver hooks on transfer (mandatory for contracts!). ([#1684](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1684))
+ * All contracts now have revert reason strings, which give insight into error conditions, and help debug failing transactions. ([#1704](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1704))
+
+### Improvements
+ * Reverted the Solidity version bump done in v2.2.0, setting the minimum compiler version to v0.5.0, to prevent unexpected build breakage. Users are encouraged however to stay on top of new compiler releases, which usually include bugfixes. ([#1729](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1729))
+
+### Bugfixes
+ * `PostDeliveryCrowdsale`: some validations where skipped when paired with other crowdsale flavors, such as `AllowanceCrowdsale`, or `MintableCrowdsale` and `ERC20Capped`, which could cause buyers to not be able to claim their purchased tokens. ([#1721](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1721))
+ * `ERC20._transfer`: the `from` argument was allowed to be the zero address, so it was possible to internally trigger a transfer of 0 tokens from the zero address. This address is not a valid destinatary of transfers, nor can it give or receive allowance, so this behavior was inconsistent. It now reverts. ([#1752](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1752))
+
+## 2.2.0 (2019-03-14)
+
+### New features
+ * `ERC20Snapshot`: create snapshots on demand of the token balances and total supply, to later retrieve and e.g. calculate dividends at a past time. ([#1617](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1617))
+ * `SafeERC20`: `ERC20` contracts with no return value (i.e. that revert on failure) are now supported. ([#1655](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1655))
+ * `ERC20`: added internal `_approve(address owner, address spender, uint256 value)`, allowing derived contracts to set the allowance of arbitrary accounts. ([#1609](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1609))
+ * `ERC20Metadata`: added internal `_setTokenURI(string memory tokenURI)`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
+ * `TimedCrowdsale`: added internal `_extendTime(uint256 newClosingTime)` as well as `TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime)` event allowing to extend the crowdsale, as long as it hasn't already closed.
+
+### Improvements
+ * Upgraded the minimum compiler version to v0.5.2: this removes many Solidity warnings that were false positives. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
+ * `ECDSA`: `recover` no longer accepts malleable signatures (those using upper-range values for `s`, or 0/1 for `v`). ([#1622](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1622))
+ * ``ERC721``'s transfers are now more gas efficient due to removal of unnecessary `SafeMath` calls. ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
+ * Fixed variable shadowing issues. ([#1606](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1606))
+
+### Bugfixes
+ * (minor) `SafeERC20`: `safeApprove` wasn't properly checking for a zero allowance when attempting to set a non-zero allowance. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
+
+### Breaking changes in drafts
+ * `TokenMetadata` has been renamed to `ERC20Metadata`. ([#1618](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1618))
+ * The library `Counter` has been renamed to `Counters` and its API has been improved. See an example in `ERC721`, lines [17](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L17) and [204](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/3cb4a00fce1da76196ac0ac3a0ae9702b99642b5/contracts/token/ERC721/ERC721.sol#L204). ([#1610](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1610))
+
+## 2.1.3 (2019-02-26)
+ * Backported `SafeERC20.safeApprove` bugfix. ([#1647](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1647))
+
+## 2.1.2 (2019-01-17)
+ * Removed most of the test suite from the npm package, except `PublicRole.behavior.js`, which may be useful to users testing their own `Roles`.
+
+## 2.1.1 (2019-01-04)
+ * Version bump to avoid conflict in the npm registry.
+
+## 2.1.0 (2019-01-04)
+
+### New features
+ * Now targeting the 0.5.x line of Solidity compilers. For 0.4.24 support, use version 2.0 of OpenZeppelin.
+ * `WhitelistCrowdsale`: a crowdsale where only whitelisted accounts (`WhitelistedRole`) can purchase tokens. Adding or removing accounts from the whitelist is done by whitelist admins (`WhitelistAdminRole`). Similar to the pre-2.0 `WhitelistedCrowdsale`. ([#1525](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1525), [#1589](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1589))
+ * `RefundablePostDeliveryCrowdsale`: replacement for `RefundableCrowdsale` (deprecated, see below) where tokens are only granted once the crowdsale ends (if it meets its goal). ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))
+ * `PausableCrowdsale`: allows for pausers (`PauserRole`) to pause token purchases. Other crowdsale operations (e.g. withdrawals and refunds, if applicable) are not affected. ([#832](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/832))
+ * `ERC20`: `transferFrom` and `_burnFrom ` now emit `Approval` events, to represent the token's state comprehensively through events. ([#1524](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1524))
+ * `ERC721`: added `_burn(uint256 tokenId)`, replacing the similar deprecated function (see below). ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
+ * `ERC721`: added `_tokensOfOwner(address owner)`, allowing to internally retrieve the array of an account's owned tokens. ([#1522](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1522))
+ * Crowdsales: all constructors are now `public`, meaning it is not necessary to extend these contracts in order to deploy them. The exception is `FinalizableCrowdsale`, since it is meaningless unless extended. ([#1564](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1564))
+ * `SignedSafeMath`: added overflow-safe operations for signed integers (`int256`). ([#1559](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1559), [#1588](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1588))
+
+### Improvements
+ * The compiler version required by `Array` was behind the rest of the libray so it was updated to `v0.4.24`. ([#1553](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1553))
+ * Now conforming to a 4-space indentation code style. ([1508](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1508))
+ * `ERC20`: more gas efficient due to removed redundant `require`s. ([#1409](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1409))
+ * `ERC721`: fixed a bug that prevented internal data structures from being properly cleaned, missing potential gas refunds. ([#1539](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1539) and [#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
+ * `ERC721`: general gas savings on `transferFrom`, `_mint` and `_burn`, due to redudant `require`s and `SSTORE`s. ([#1549](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1549))
+
+### Bugfixes
+
+### Breaking changes
+
+### Deprecations
+ * `ERC721._burn(address owner, uint256 tokenId)`: due to the `owner` parameter being unnecessary. ([#1550](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1550))
+ * `RefundableCrowdsale`: due to trading abuse potential on crowdsales that miss their goal. ([#1543](https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1543))

+ 73 - 0
CODE_OF_CONDUCT.md

@@ -0,0 +1,73 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+  advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+  address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at maintainers@openzeppelin.org. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org

+ 64 - 0
CONTRIBUTING.md

@@ -0,0 +1,64 @@
+Contributing to OpenZeppelin Contracts
+=======
+
+We really appreciate and value contributions to OpenZeppelin Contracts. Please take 5' to review the items listed below to make sure that your contributions are merged as soon as possible.
+
+## Contribution guidelines
+
+Smart contracts manage value and are highly vulnerable to errors and attacks. We have very strict [guidelines], please make sure to review them!
+
+## Creating Pull Requests (PRs)
+
+As a contributor, you are expected to fork this repository, work on your own fork and then submit pull requests. The pull requests will be reviewed and eventually merged into the main repo. See ["Fork-a-Repo"](https://help.github.com/articles/fork-a-repo/) for how this works.
+
+## A typical workflow
+
+1) Make sure your fork is up to date with the main repository:
+
+```
+cd openzeppelin-contracts
+git remote add upstream https://github.com/OpenZeppelin/openzeppelin-contracts.git
+git fetch upstream
+git pull --rebase upstream master
+```
+NOTE: The directory `openzeppelin-contracts` represents your fork's local copy.
+
+2) Branch out from `master` into `fix/some-bug-#123`:
+(Postfixing #123 will associate your PR with the issue #123 and make everyone's life easier =D)
+```
+git checkout -b fix/some-bug-#123
+```
+
+3) Make your changes, add your files, commit, and push to your fork.
+
+```
+git add SomeFile.js
+git commit "Fix some bug #123"
+git push origin fix/some-bug-#123
+```
+
+4) Run tests, linter, etc. This can be done by running local continuous integration and make sure it passes.
+
+```bash
+npm test
+npm run lint
+```
+
+5) Go to [github.com/OpenZeppelin/openzeppelin-contracts](https://github.com/OpenZeppelin/openzeppelin-contracts) in your web browser and issue a new pull request.
+
+*IMPORTANT* Read the PR template very carefully and make sure to follow all the instructions. These instructions
+refer to some very important conditions that your PR must meet in order to be accepted, such as making sure that all tests pass, JS linting tests pass, Solidity linting tests pass, etc.
+
+6) Maintainers will review your code and possibly ask for changes before your code is pulled in to the main repository. We'll check that all tests pass, review the coding style, and check for general code correctness. If everything is OK, we'll merge your pull request and your code will be part of OpenZeppelin.
+
+*IMPORTANT* Please pay attention to the maintainer's feedback, since its a necessary step to keep up with the standards OpenZeppelin attains to.
+
+## All set!
+
+If you have any questions, feel free to post them to github.com/OpenZeppelin/openzeppelin-contracts/issues.
+
+Finally, if you're looking to collaborate and want to find easy tasks to start, look at the issues we marked as ["Good first issue"](https://github.com/OpenZeppelin/openzeppelin-contracts/labels/good%20first%20issue).
+
+Thanks for your time and code!
+
+[guidelines]: GUIDELINES.md

+ 16 - 0
DOCUMENTATION.md

@@ -0,0 +1,16 @@
+Documentation is hosted at https://docs.openzeppelin.com/contracts.
+
+All of the content for the site is in this repository. The guides are in the
+[docs](/docs) directory, and the API Reference is extracted from comments in
+the source code. If you want to help improve the content, this is the
+repository you should be contributing to.
+
+[`solidity-docgen`](https://github.com/OpenZeppelin/solidity-docgen) is the
+program that extracts the API Reference from source code.
+
+The [`docs.openzeppelin.com`](https://github.com/OpenZeppelin/docs.openzeppelin.com)
+repository hosts the configuration for the entire site, which includes
+documentation for all of the OpenZeppelin projects.
+
+To run the docs locally you should run `npm run docs:watch` on this
+repository.

+ 105 - 0
GUIDELINES.md

@@ -0,0 +1,105 @@
+Design Guidelines
+=======
+
+These are some global design goals in OpenZeppelin.
+
+#### 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.
+
+#### D1 - Simple and Modular
+Simpler code means easier audits, and better understanding of what each component does. We look for small files, small contracts, and small functions. If you can separate a contract into two independent functionalities you should probably do it.
+
+#### D2 - Naming Matters
+
+We take our time with picking names. Code is going to be written once, and read hundreds of times. Renaming for clarity is encouraged.
+
+#### D3 - Tests
+
+Write tests for all your code. We encourage Test Driven Development so we know when our code is right. Even though not all code in the repository is tested at the moment, we aim to test every line of code in the future.
+
+#### D4 - Check preconditions and post-conditions
+
+A very important way to prevent vulnerabilities is to catch a contract’s inconsistent state as early as possible. This is why we want functions to check pre- and post-conditions for executing its logic. When writing code, ask yourself what you are expecting to be true before and after the function runs, and express it in code.
+
+#### D5 - Code Consistency
+
+Consistency on the way classes are used is paramount to an easier understanding of the library. The codebase should be as unified as possible. Read existing code and get inspired before you write your own. Follow the style guidelines. Don’t hesitate to ask for help on how to best write a specific piece of code.
+
+#### D6 - Regular Audits
+Following good programming practices is a way to reduce the risk of vulnerabilities, but professional code audits are still needed. We will perform regular code audits on major releases, and hire security professionals to provide independent review.
+
+# Style Guidelines
+
+The design guidelines have quite a high abstraction level. These style guidelines are more concrete and easier to apply, and also more opinionated. We value clean code and consistency, and those are prerequisites for us to include new code in the repository. Before proposing a change, please read these guidelines and take some time to familiarize yourself with the style of the existing codebase.
+
+## Solidity code
+
+In order to be consistent with all the other Solidity projects, we follow the
+[official recommendations documented in the Solidity style guide](http://solidity.readthedocs.io/en/latest/style-guide.html).
+
+Any exception or additions specific to our project are documented below.
+
+* Try to avoid acronyms and abbreviations.
+
+* All state variables should be private.
+
+* Private state variables should have an underscore prefix.
+
+    ```
+    contract TestContract {
+      uint256 private _privateVar;
+      uint256 internal _internalVar;
+    }
+    ```
+
+* Parameters must not be prefixed with an underscore.
+
+    ```
+    function test(uint256 testParameter1, uint256 testParameter2) {
+    ...
+    }
+    ```
+
+* Internal and private functions should have an underscore prefix.
+
+    ```
+    function _testInternal() internal {
+      ...
+    }
+    ```
+
+    ```
+    function _testPrivate() private {
+      ...
+    }
+    ```
+
+* Events should be emitted immediately after the state change that they
+  represent, and consequently they should be named in past tense.
+
+    ```
+    function _burn(address who, uint256 value) internal {
+      super._burn(who, value);
+      emit TokensBurned(who, value);
+    }
+    ```
+
+  Some standards (e.g. ERC20) use present tense, and in those cases the
+  standard specification prevails.
+  
+* Interface names should have a capital I prefix.
+
+    ```
+    interface IERC777 {
+    ```
+
+
+## Tests
+
+* Tests Must be Written Elegantly
+
+    Tests are a good way to show how to use the library, and maintaining them is extremely necessary. Don't write long tests, write helper functions to make them be as short and concise as possible (they should take just a few lines each), and use good variable names.
+
+* Tests Must not be Random
+
+    Inputs for tests should not be generated randomly. Accounts used to create test contracts are an exception, those can be random. Also, the type and structure of outputs should be checked.

+ 22 - 0
LICENSE

@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2016-2020 zOS Global Limited
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 77 - 0
README.md

@@ -0,0 +1,77 @@
+# <img src="logo.svg" alt="OpenZeppelin" height="40px">
+
+[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts)
+[![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts)
+[![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts)
+
+**A library for secure smart contract development.** Build on a solid foundation of community-vetted code.
+
+ * 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_).
+
+## Overview
+
+### Installation
+
+```console
+$ npm install @openzeppelin/contracts
+```
+
+OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version.
+
+### Usage
+
+Once installed, you can use the contracts in the library by importing them:
+
+```solidity
+pragma solidity ^0.6.0;
+
+import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
+
+contract MyCollectible is ERC721 {
+    constructor() ERC721("MyCollectible", "MCO") public {
+    }
+}
+```
+
+_If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/developing-smart-contracts) to learn about creating a new project and compiling your contracts._
+
+To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs.
+
+## Learn More
+
+The guides in the [docs site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:
+
+* [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system.
+* [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectives, and distribute them via [Crowdsales](https://docs.openzeppelin.com/contracts/crowdsales).
+* [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn): let your users interact with your contracts without having to pay for gas themselves.
+* [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools, including non-overflowing math, signature verification, and trustless paying systems.
+
+The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the [community forum](https://forum.openzeppelin.com).
+
+Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices.. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve.
+
+* [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment.
+* [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform.
+* For a more in-depth dive, you may read the guide [Designing the Architecture for Your Ethereum Application](https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world.
+
+## 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.
+
+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 latest audit was done on October 2018 on version 2.0.0.
+
+Please report any security issues you find to security@openzeppelin.org.
+
+## 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)!
+
+## License
+
+OpenZeppelin is released under the [MIT License](LICENSE).

+ 36 - 0
RELEASING.md

@@ -0,0 +1,36 @@
+# Releasing
+
+> Visit the documentation for [details about release schedule].
+
+Start on an up-to-date `master` branch.
+
+Create the release branch with `npm run release start minor`.
+
+Publish a release candidate with `npm run release rc`.
+
+Publish the final release with `npm run release final`.
+
+Follow the general [OpenZeppelin 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
+
+
+## Merging the release branch
+
+After the final release, the release branch should be merged back into `master`. This merge must not be squashed because it would lose the tagged release commit. Since the GitHub repo is set up to only allow squashed merges, the merge should be done locally and pushed.
+
+Make sure to have the latest changes from `upstream` in your local release branch.
+
+```
+git checkout release-vX.Y.Z
+git pull upstream
+```
+
+```
+git checkout master
+git merge --no-ff release-vX.Y.Z
+git push upstream master
+```
+
+The release branch can then be deleted on GitHub.

+ 290 - 0
audit/2017-03.md

@@ -0,0 +1,290 @@
+# OpenZeppelin Audit
+
+March, 2017
+Authored by Dennis Peterson and Peter Vessenes
+
+# Introduction
+
+Zeppelin requested that New Alchemy perform an audit of the contracts in their OpenZeppelin library. The OpenZeppelin contracts are a set of contracts intended to be a safe building block for a variety of uses by parties that may not be as sophisticated as the OpenZeppelin team. It is a design goal that the contracts be deployable safely and "as-is".
+
+The contracts are hosted at:
+
+https://github.com/OpenZeppelin/zeppelin-solidity
+
+All the contracts in the "contracts" folder are in scope.
+
+The git commit hash we evaluated is:
+9c5975a706b076b7000e8179f8101e0c61024c87
+
+# Disclaimer
+
+The audit makes no statements or warrantees about utility of the code, safety of the code, suitability of the business model, regulatory regime for the business model, or any other statements about fitness of the contracts to purpose, or their bugfree status. The audit documentation is for discussion purposes only.
+
+# Executive Summary
+
+Overall the OpenZeppelin codebase is of reasonably high quality -- it is clean, modular and follows best practices throughout.
+
+It is still in flux as a codebase, and needs better documentation per file as to expected behavior and future plans. It probably needs more comprehensive and aggressive tests written by people less nice than the current OpenZeppelin team.
+
+We identified two critical errors and one moderate issue, and would not recommend this commit hash for public use until these bugs are remedied.
+
+The repository includes a set of Truffle unit tests, a requirement and best practice for smart contracts like these; we recommend these be bulked up.
+
+# Discussion
+
+## Big Picture: Is This A Worthwhile Project?
+
+As soon as a developer touches OpenZeppelin contracts, they will modify something, leaving them in an un-audited state. We do not recommend developers deploy any unaudited code to the Blockchain if it will handle money, information or other things of value.
+
+> "In accordance with Unix philosophy, Perl gives you enough rope to hang yourself"
+> --Larry Wall
+
+We think this is an incredibly worthwhile project -- aided by the high code quality. Creating a framework that can be easily extended helps increase the average code quality on the Blockchain by charting a course for developers and encouraging containment of modifications to certain sections.
+
+> "Rust: The language that makes you take the safety off before shooting yourself in the foot"
+> -- (@mbrubeck)
+
+We think much more could be done here, and recommend the OpenZeppelin team keep at this and keep focusing on the design goal of removing rope and adding safety.
+
+## Solidity Version Updates Recommended
+
+Most of the code uses Solidity 0.4.11, but some files under `Ownership` are marked 0.4.0. These should be updated.
+
+Solidity 0.4.10 will add several features which could be useful in these contracts:
+
+- `assert(condition)`, which throws if the condition is false
+
+- `revert()`, which rolls back without consuming all remaining gas.
+
+- `address.transfer(value)`, which is like `send` but automatically propagates exceptions, and supports `.gas()`. See https://github.com/ethereum/solidity/issues/610 for more on this.
+
+## Error Handling: Throw vs Return False
+Solidity standards allow two ways to handle an error -- either calling `throw` or returning `false`. Both have benefits. In particular, a `throw` guarantees a complete wipe of the call stack (up to the preceding external call), whereas `false` allows a function to continue.
+
+In general we prefer `throw` in our code audits, because it is simpler -- it's less for an engineer to keep track of. Returning `false` and using logic to check results can quickly become a poorly-tracked state machine, and this sort of complexity can cause errors.
+
+In the OpenZeppelin contracts, both styles are used in different parts of the codebase. `SimpleToken` transfers throw upon failure, while the full ERC20 token returns `false`. Some modifiers `throw`, others just wrap the function body in a conditional, effectively allowing the function to return false if the condition is not met.
+
+We don't love this, and would usually recommend you stick with one style or the other throughout the codebase.
+
+In at least one case, these different techniques are combined cleverly (see the Multisig comments, line 65). As a set of contracts intended for general use, we recommend you either strive for more consistency or document explicit design criteria that govern which techniques are used where.
+
+Note that it may be impossible to use either one in all situations. For example, SafeMath functions pretty much have to throw upon failure, but ERC20 specifies returning booleans. Therefore we make no particular recommendations, but simply point out inconsistencies to consider.
+
+# Critical Issues
+
+## Stuck Ether in Crowdsale contract
+CrowdsaleToken.sol has no provision for withdrawing the raised ether. We *strongly* recommend a standard `withdraw` function be added. There is no scenario in which someone should deploy this contract as is, whether for testing or live.
+
+## Recursive Call in MultisigWallet
+Line 45 of `MultisigWallet.sol` checks if the amount being sent by `execute` is under a daily limit.
+
+This function can only be called by the "Owner". As a first angle of attack, it's worth asking what will happen if the multisig wallet owners reset the daily limit by approving a call to `resetSpentToday`.
+
+If a chain of calls can be constructed in which the owner confirms the `resetSpentToday` function and then withdraws through `execute` in a recursive call, the contract can be drained. In fact, this could be done without a recursive call, just through repeated `execute` calls alternating with the `confirm` calls.
+
+We are still working through the confirmation protocol in `Shareable.sol`, but we are not convinced that this is impossible, in fact it looks possible. The flexibility any shared owner has in being able to revoke confirmation later is another worrisome angle of approach even if some simple patches are included.
+
+This bug has a number of causes that need to be addressed:
+
+1. `resetSpentToday` and `confirm` together do not limit the days on which the function can be called or (it appears) the number of times it can be called.
+1. Once a call has been confirmed and `execute`d it appears that it can be re-executed. This is not good.
+3. `confirmandCheck` doesn't seem to have logic about whether or not the function in question has been called.
+4. Even if it did, `revoke` would need updates and logic to deal with revocation requests after a function call had been completed.
+
+We do not recommend using the MultisigWallet until these issues are fixed.
+
+# Moderate to Minor Issues
+
+## PullPayment
+PullPayment.sol needs some work. It has no explicit provision for cancelling a payment. This would be desirable in a number of scenarios; consider a payee losing their wallet, or giving a griefing address, or just an address that requires more than the default gas offered by `send`.
+
+`asyncSend` has no overflow checking. This is a bad plan. We recommend overflow and underflow checking at the layer closest to the data manipulation.
+
+`asyncSend` allows more balance to be queued up for sending than the contract holds. This is probably a bad idea, or at the very least should be called something different. If the intent is to allow this, it should have provisions for dealing with race conditions between competing `withdrawPayments` calls.
+
+It would be nice to see how many payments are pending. This would imply a bit of a rewrite; we recommend this contract get some design time, and that developers don't rely on it in its current state.
+
+## Shareable Contract
+
+We do not believe the `Shareable.sol` contract is ready for primetime. It is missing functions, and as written may be vulnerable to a reordering attack -- an attack in which a miner or other party "racing" with a smart contract participant inserts their own information into a list or mapping.
+
+The confirmation and revocation code needs to be looked over with a very careful eye imagining extraordinarily bad behavior by shared owners before this contract can be called safe.
+
+No sanity checks on the initial constructor's `required` argument are worrisome as well.
+
+# Line by Line Comments
+
+## Lifecycle
+
+### Killable
+
+Very simple, allows owner to call selfdestruct, sending funds to owner. No issues. However, note that `selfdestruct` should typically not be used; it is common that a developer may want to access data in a former contract, and they may not understand that `selfdestruct` limits access to the contract. We recommend better documentation about this dynamic, and an alternate function name for `kill` like `completelyDestroy` while `kill` would perhaps merely send funds to the owner.
+
+Also note that a killable function allows the owner to take funds regardless of other logic. This may be desirable or undesirable depending on the circumstances. Perhaps `Killable` should have a different name as well.
+
+### Migrations
+
+I presume that the goal of this contract is to allow and annotate a migration to a new smart contract address. We are not clear here how this would be accomplished by the code; we'd like to review with the OpenZeppelin team.
+
+### Pausable
+
+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)`.
+
+## Ownership
+
+### Ownable
+
+Line 19: Modifier throws if doesn't meet condition, in contrast to some other inheritable modifiers (e.g. in Pausable) that use `if(bool){_;}`.
+
+### Claimable
+
+Inherits from Ownable but the existing owner sets a pendingOwner who has to claim ownership.
+
+Line 17: Another modifier that throws.
+
+### DelayedClaimable
+
+Is there any reason to descend from Ownable directly, instead of just Claimable, which descends from Ownable? If not, descending from both just adds confusion.
+
+### Contactable
+
+Allows owner to set a public string of contract information. No issues.
+
+### Shareable
+
+This needs some work. Doesn't check if `_required <= len(_owners)` for instance, that would be a bummer. What if _required were like `MAX - 1`?
+
+I have a general concern about the difference between `owners`, `_owners`, and `owner` in `Ownable.sol`. I recommend "Owners" be renamed. In general we do not recomment single character differences in variable names, although a preceding underscore is not uncommon in Solidity code.
+
+Line 34: "this contract only has six types of events"...actually only two.
+
+Line 61: Why is `ownerIndex` keyed by addresses hashed to `uint`s? Why not use the addresses directly, so `ownerIndex` is less obscure, and so there's stronger typing?
+
+Line 62: Do not love `++i) ... owners[2+ i]`. Makes me do math, which is not what I want to do. I want to not have to do math.
+
+There should probably be a function for adding a new operation, so the developer doesn't have to work directly with the internal data. (This would make the multisig contract even shorter.)
+
+There's a `revoke` function but not a `propose` function that we can see.
+
+Beware reordering. If `propose` allows the user to choose a bytes string for their proposal, bad things(TM) will happen as currently written.
+
+
+### Multisig
+
+Just an interface. Note it allows changing an owner address, but not changing the number of owners. This is somewhat limiting but also simplifies implementation.
+
+## Payment
+
+### PullPayment
+
+Safe from reentrance attack since ether send is at the end, plus it uses `.send()` rather than `.call.value()`.
+
+There's an argument to be made that `.call.value()` is a better option *if* you're sure that it will be done after all state updates, since `.send` will fail if the recipient has an expensive fallback function. However, in the context of a function meant to be embedded in other contracts, it's probably better to use `.send`. One possible compromise is to add a function which allows only the owner to send ether via `.call.value`.
+
+If you don't use `call.value` you should implement a `cancel` function in case some value is pending here.
+
+Line 14:
+Doesn't use safeAdd. Although it appears that payout amounts can only be increased, in fact the payer could lower the payout as much as desired via overflow. Also, the payer could add a large non-overflowing amount, causing the payment to exceed the contract balance and therefore fail when withdraw is attempted.
+
+Recommendation: track the sum of non-withdrawn asyncSends, and don't allow a new one which exceeds the leftover balance. If it's ever desirable to make payments revocable, it should be done explicitly.
+
+## Tokens
+
+### ERC20
+
+Standard ERC20 interface only.
+
+There's a security hole in the standard, reported at Edcon: `approve` does not protect against race conditions and simply replaces the current value. An approved spender could wait for the owner to call `approve` again, then attempt to spend the old limit before the new limit is applied. If successful, this attacker could successfully spend the sum of both limits.
+
+This could be fixed by either (1) including the old limit as a parameter, so the update will fail if some gets spent, or (2) using the value parameter as a delta instead of replacement value.
+
+This is not fixable while adhering to the current full ERC20 standard, though it would be possible to add a "secureApprove" function. The impact isn't extreme since at least you can only be attacked by addresses you approved. Also, users could mitigate this by always setting spending limits to zero and checking for spends, before setting the new limit.
+
+Edcon slides:
+https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view
+
+### ERC20Basic
+
+Simpler interface skipping the Approve function. Note this departs from ERC20 in another way: transfer throws instead of returning false.
+
+### BasicToken
+
+Uses `SafeSub` and `SafeMath`, so transfer `throw`s instead of returning false. This complies with ERC20Basic but not the actual ERC20 standard.
+
+### StandardToken
+
+Implementation of full ERC20 token.
+
+Transfer() and transferFrom() use SafeMath functions, which will cause them to throw instead of returning false. Not a security issue but departs from standard.
+
+### SimpleToken
+
+Sample instantiation of StandardToken. Note that in this sample, decimals is 18 and supply only 10,000, so the supply is a small fraction of a single nominal token.
+
+### CrowdsaleToken
+
+StandardToken which mints tokens at a fixed price when sent ether.
+
+There's no provision for owner withdrawing the ether. As a sample for crowdsales it should be Ownable and allow the owner to withdraw ether, rather than stranding the ether in the contract.
+
+Note: an alternative pattern is a mint() function which is only callable from a separate crowdsale contract, so any sort of rules can be added without modifying the token itself.
+
+### VestedToken
+
+Lines 23, 27:
+Functions `transfer()` and `transferFrom()` have a modifier canTransfer which throws if not enough tokens are available. However, transfer() returns a boolean success. Inconsistent treatment of failure conditions may cause problems for other contracts using the token. (Note that transferableTokens() relies on safeSub(), so will also throw if there's insufficient balance.)
+
+Line 64:
+Delete not actually necessary since the value is overwritten in the next line anyway.
+
+## Root level
+
+### Bounty
+
+Avoids potential race condition by having each researcher deploy a separate contract for attack; if a research manages to break his associated contract, other researchers can't immediately claim the reward, they have to reproduce the attack in their own contracts.
+
+A developer could subvert this intent by implementing `deployContract()` to always return the same address. However, this would break the `researchers` mapping, updating the researcher address associated with the contract. This could be prevented by blocking rewrites in `researchers`.
+
+### DayLimit
+
+The modifier `limitedDaily` calls `underLimit`, which both checks that the spend is below the daily limit, and adds the input value to the daily spend. This is fine if all functions throw upon failure. However, not all OpenZeppelin functions do this; there are functions that returns false, and modifiers that wrap the function body in `if (bool) {_;}`. In these cases, `_value` will be added to `spentToday`, but ether may not actually be sent because other preconditions were not met. (However in the OpenZeppelin multisig this is not a problem.)
+
+Lines 4, 11:
+Comment claims that `DayLimit` is multiowned, and Shareable is imported, but DayLimit does not actually inherit from Shareable. The intent may be for child contracts to inherit from Shareable (as Multisig does); in this case the import should be removed and the comment altered.
+
+Line 46:
+Manual overflow check instead of using safeAdd. Since this is called from a function that throws upon failure anyway, there's no real downside to using safeAdd.
+
+### LimitBalance
+
+No issues.
+
+### MultisigWallet
+
+Lines 28, 76, 80:
+`kill`, `setDailyLimit`, and `resetSpentToday` only happen with multisig approval, and hashes for these actions are logged by Shareable. However, they should probably post their own events for easy reading.
+
+Line 45:
+This call to underLimit will reduce the daily limit, and then either throw or return 0. So in this case there's no danger that the limit will be reduced without the operation going through.
+
+Line 65:
+Shareable's onlyManyOwners will take the user's confirmation, and execute the function body if and only if enough users have confirmed. Whole thing throws if the send fails, which will roll back the confirmation. Confirm returns false if not enough have confirmed yet, true if the whole thing succeeds, and throws only in the exceptional circumstance that the designated transaction unexpectedly fails. Elegant design.
+
+Line 68:
+Throw here is good but note this function can fail either by returning false or by throwing.
+
+Line 92:
+A bit odd to split `clearPending()` between this contract and Shareable. However this does allow contracts inheriting from Shareable to use custom structs for pending transactions.
+
+
+### SafeMath
+
+Another interesting comment from the same Edcon presentation was that the overflow behavior of Solidity is undocumented, so in theory, source code that relies on it could break with a future revision.
+
+However, compiled code should be fine, and in the unlikely event that the compiler is revised in this way, there should be plenty of warning. (But this is an argument for keeping overflow checks isolated in SafeMath.)
+
+Aside from that small caveat, these are fine.
+

BIN
audit/2018-10.pdf


+ 20 - 0
buidler.config.js

@@ -0,0 +1,20 @@
+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.6.12',
+  },
+};

+ 10 - 0
buidler/env-contract.js

@@ -0,0 +1,10 @@
+extendEnvironment(env => {
+  const { contract } = env;
+
+  env.contract = function (name, body) {
+    // remove the default account from the accounts list used in tests, in order
+    // to protect tests against accidentally passing due to the contract
+    // deployer being used subsequently as function caller
+    contract(name, accounts => body(accounts.slice(1)));
+  };
+});

+ 5 - 0
contracts/GSN/Context.sol

@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Context.sol";

+ 230 - 0
contracts/GSN/GSNRecipient.sol

@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.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;
+    }
+}

+ 154 - 0
contracts/GSN/GSNRecipientERC20Fee.sol

@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "./GSNRecipient.sol";
+import "../math/SafeMath.sol";
+import "../access/Ownable.sol";
+import "../token/ERC20/SafeERC20.sol";
+import "../token/ERC20/ERC20.sol";
+
+/**
+ * @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that charges transaction fees in a special purpose ERC20
+ * token, which we refer to as the gas payment token. The amount charged is exactly the amount of Ether charged to the
+ * recipient. This means that the token is essentially pegged to the value of Ether.
+ *
+ * The distribution strategy of the gas payment token to users is not defined by this contract. It's a mintable token
+ * whose only minter is the recipient, so the strategy must be implemented in a derived contract, making use of the
+ * internal {_mint} function.
+ */
+contract GSNRecipientERC20Fee is GSNRecipient {
+    using SafeERC20 for __unstable__ERC20Owned;
+    using SafeMath for uint256;
+
+    enum GSNRecipientERC20FeeErrorCodes {
+        INSUFFICIENT_BALANCE
+    }
+
+    __unstable__ERC20Owned private _token;
+
+    /**
+     * @dev The arguments to the constructor are the details that the gas payment token will have: `name` and `symbol`. `decimals` is hard-coded to 18.
+     */
+    constructor(string memory name, string memory symbol) public {
+        _token = new __unstable__ERC20Owned(name, symbol);
+    }
+
+    /**
+     * @dev Returns the gas payment token.
+     */
+    function token() public view 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) public 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);
+        }
+    }
+}

+ 72 - 0
contracts/GSN/GSNRecipientSignature.sol

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

+ 269 - 0
contracts/GSN/IRelayHub.sol

@@ -0,0 +1,269 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.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);
+}
+

+ 76 - 0
contracts/GSN/IRelayRecipient.sol

@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.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;
+}

+ 31 - 0
contracts/GSN/README.adoc

@@ -0,0 +1,31 @@
+= 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}}

+ 217 - 0
contracts/access/AccessControl.sol

@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/EnumerableSet.sol";
+import "../utils/Address.sol";
+import "../utils/Context.sol";
+
+/**
+ * @dev Contract module that allows children to implement role-based access
+ * control mechanisms.
+ *
+ * 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
+ * using `public constant` hash digests:
+ *
+ * ```
+ * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
+ * ```
+ *
+ * Roles can be used to represent a set of permissions. To restrict access to a
+ * function call, use {hasRole}:
+ *
+ * ```
+ * function foo() public {
+ *     require(hasRole(MY_ROLE, msg.sender));
+ *     ...
+ * }
+ * ```
+ *
+ * Roles can be granted and revoked dynamically via the {grantRole} and
+ * {revokeRole} functions. Each role has an associated admin role, and only
+ * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
+ *
+ * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
+ * that only accounts with this role will be able to grant or revoke other
+ * roles. More complex role relationships can be created by using
+ * {_setRoleAdmin}.
+ *
+ * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
+ * grant and revoke this role. Extra precautions should be taken to secure
+ * accounts that have been granted it.
+ */
+abstract contract AccessControl is Context {
+    using EnumerableSet for EnumerableSet.AddressSet;
+    using Address for address;
+
+    struct RoleData {
+        EnumerableSet.AddressSet members;
+        bytes32 adminRole;
+    }
+
+    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`
+     *
+     * `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 {_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) public view returns (bool) {
+        return _roles[role].members.contains(account);
+    }
+
+    /**
+     * @dev Returns the number of accounts that have `role`. Can be used
+     * together with {getRoleMember} to enumerate all bearers of a role.
+     */
+    function getRoleMemberCount(bytes32 role) public view returns (uint256) {
+        return _roles[role].members.length();
+    }
+
+    /**
+     * @dev Returns one of the accounts that have `role`. `index` must be a
+     * value between 0 and {getRoleMemberCount}, non-inclusive.
+     *
+     * 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 returns (address) {
+        return _roles[role].members.at(index);
+    }
+
+    /**
+     * @dev Returns the admin role that controls `role`. See {grantRole} and
+     * {revokeRole}.
+     *
+     * To change a role's admin, use {_setRoleAdmin}.
+     */
+    function getRoleAdmin(bytes32 role) public view returns (bytes32) {
+        return _roles[role].adminRole;
+    }
+
+    /**
+     * @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) public virtual {
+        require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
+
+        _grantRole(role, account);
+    }
+
+    /**
+     * @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) public virtual {
+        require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
+
+        _revokeRole(role, account);
+    }
+
+    /**
+     * @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) public virtual {
+        require(account == _msgSender(), "AccessControl: can only renounce roles for self");
+
+        _revokeRole(role, account);
+    }
+
+    /**
+     * @dev Grants `role` to `account`.
+     *
+     * If `account` had not been already granted `role`, emits a {RoleGranted}
+     * event. Note that unlike {grantRole}, this function doesn't perform any
+     * checks on the calling account.
+     *
+     * [WARNING]
+     * ====
+     * This function should only be called from the constructor when setting
+     * up the initial roles for the system.
+     *
+     * Using this function in any other way is effectively circumventing the admin
+     * system imposed by {AccessControl}.
+     * ====
+     */
+    function _setupRole(bytes32 role, address account) internal virtual {
+        _grantRole(role, account);
+    }
+
+    /**
+     * @dev Sets `adminRole` as ``role``'s admin role.
+     *
+     * Emits a {RoleAdminChanged} event.
+     */
+    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
+        emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
+        _roles[role].adminRole = adminRole;
+    }
+
+    function _grantRole(bytes32 role, address account) private {
+        if (_roles[role].members.add(account)) {
+            emit RoleGranted(role, account, _msgSender());
+        }
+    }
+
+    function _revokeRole(bytes32 role, address account) private {
+        if (_roles[role].members.remove(account)) {
+            emit RoleRevoked(role, account, _msgSender());
+        }
+    }
+}

+ 68 - 0
contracts/access/Ownable.sol

@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <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
+ * specific functions.
+ *
+ * By default, the owner account will be the one that deploys the contract. This
+ * can later be changed with {transferOwnership}.
+ *
+ * This module is used through inheritance. It will make available the modifier
+ * `onlyOwner`, which can be applied to your functions to restrict their use to
+ * the owner.
+ */
+abstract contract Ownable is Context {
+    address private _owner;
+
+    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
+
+    /**
+     * @dev Initializes the contract setting the deployer as the initial owner.
+     */
+    constructor () internal {
+        address msgSender = _msgSender();
+        _owner = msgSender;
+        emit OwnershipTransferred(address(0), msgSender);
+    }
+
+    /**
+     * @dev Returns the address of the current owner.
+     */
+    function owner() public view virtual returns (address) {
+        return _owner;
+    }
+
+    /**
+     * @dev Throws if called by any account other than the owner.
+     */
+    modifier onlyOwner() {
+        require(owner() == _msgSender(), "Ownable: caller is not the owner");
+        _;
+    }
+
+    /**
+     * @dev Leaves the contract without owner. It will not be possible to call
+     * `onlyOwner` functions anymore. Can only be called by the current owner.
+     *
+     * NOTE: Renouncing ownership will leave the contract without an owner,
+     * thereby removing any functionality that is only available to the owner.
+     */
+    function renounceOwnership() public virtual onlyOwner {
+        emit OwnershipTransferred(_owner, address(0));
+        _owner = address(0);
+    }
+
+    /**
+     * @dev Transfers ownership of the contract to a new account (`newOwner`).
+     * Can only be called by the current owner.
+     */
+    function transferOwnership(address newOwner) public virtual onlyOwner {
+        require(newOwner != address(0), "Ownable: new owner is the zero address");
+        emit OwnershipTransferred(_owner, newOwner);
+        _owner = newOwner;
+    }
+}

+ 101 - 0
contracts/access/README.adoc

@@ -0,0 +1,101 @@
+= Access
+
+[.readme-notice]
+NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/access
+
+This directory provides ways to restrict who can access the functions of a contract or when they can do it.
+
+- {AccessControl} provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts.
+- {Ownable} is a simpler mechanism with a single owner "role" that can be assigned to a single account. This simpler mechanism can be useful for quick tests but projects with production concerns are likely to outgrow it.
+- {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}}
+
+{{AccessControl}}
+
+== Timelock
+
+{{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*:
+** *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.

+ 300 - 0
contracts/access/TimelockController.sol

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

+ 86 - 0
contracts/cryptography/ECDSA.sol

@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.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));
+    }
+}

+ 33 - 0
contracts/cryptography/MerkleProof.sol

@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.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;
+    }
+}

+ 16 - 0
contracts/cryptography/README.adoc

@@ -0,0 +1,16 @@
+= 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}}

+ 108 - 0
contracts/drafts/EIP712.sol

@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
+ *
+ * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
+ * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
+ * they need in their contracts using a combination of `abi.encode` and `keccak256`.
+ *
+ * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
+ * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
+ * ({_hashTypedDataV4}).
+ *
+ * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
+ * the chain id to protect against replay attacks on an eventual fork of the chain.
+ *
+ * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
+ * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
+ *
+ * _Available since v3.4._
+ */
+abstract contract EIP712 {
+    /* solhint-disable var-name-mixedcase */
+    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
+    // invalidate the cached domain separator if the chain id changes.
+    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
+    uint256 private immutable _CACHED_CHAIN_ID;
+
+    bytes32 private immutable _HASHED_NAME;
+    bytes32 private immutable _HASHED_VERSION;
+    bytes32 private immutable _TYPE_HASH;
+    /* solhint-enable var-name-mixedcase */
+
+    /**
+     * @dev Initializes the domain separator and parameter caches.
+     *
+     * The meaning of `name` and `version` is specified in
+     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
+     *
+     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
+     * - `version`: the current major version of the signing domain.
+     *
+     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
+     * contract upgrade].
+     */
+    constructor(string memory name, string memory version) internal {
+        bytes32 hashedName = keccak256(bytes(name));
+        bytes32 hashedVersion = keccak256(bytes(version));
+        bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
+        _HASHED_NAME = hashedName;
+        _HASHED_VERSION = hashedVersion;
+        _CACHED_CHAIN_ID = _getChainId();
+        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
+        _TYPE_HASH = typeHash;
+    }
+
+    /**
+     * @dev Returns the domain separator for the current chain.
+     */
+    function _domainSeparatorV4() internal view virtual returns (bytes32) {
+        if (_getChainId() == _CACHED_CHAIN_ID) {
+            return _CACHED_DOMAIN_SEPARATOR;
+        } else {
+            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
+        }
+    }
+
+    function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
+        return keccak256(
+            abi.encode(
+                typeHash,
+                name,
+                version,
+                _getChainId(),
+                address(this)
+            )
+        );
+    }
+
+    /**
+     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
+     * function returns the hash of the fully encoded EIP712 message for this domain.
+     *
+     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
+     *
+     * ```solidity
+     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
+     *     keccak256("Mail(address to,string contents)"),
+     *     mailTo,
+     *     keccak256(bytes(mailContents))
+     * )));
+     * address signer = ECDSA.recover(digest, signature);
+     * ```
+     */
+    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
+        return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
+    }
+
+    function _getChainId() private view returns (uint256 chainId) {
+        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
+        // solhint-disable-next-line no-inline-assembly
+        assembly {
+            chainId := chainid()
+        }
+    }
+}

+ 78 - 0
contracts/drafts/ERC20Permit.sol

@@ -0,0 +1,78 @@
+// 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.
+ *
+ * _Available since v3.4._
+ */
+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) internal 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();
+    }
+}

+ 51 - 0
contracts/drafts/IERC20Permit.sol

@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Interface 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.
+ */
+interface IERC20Permit {
+    /**
+     * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
+     * given `owner`'s signed approval.
+     *
+     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
+     * ordering also apply here.
+     *
+     * Emits an {Approval} event.
+     *
+     * Requirements:
+     *
+     * - `spender` cannot be the zero address.
+     * - `deadline` must be a timestamp in the future.
+     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
+     * over the EIP712-formatted function arguments.
+     * - the signature must use ``owner``'s current nonce (see {nonces}).
+     *
+     * For more information on the signature format, see the
+     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
+     * section].
+     */
+    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
+
+    /**
+     * @dev Returns the current nonce for `owner`. This value must be
+     * included whenever a signature is generated for {permit}.
+     *
+     * Every successful call to {permit} increases ``owner``'s nonce by one. This
+     * prevents a signature from being used multiple times.
+     */
+    function nonces(address owner) external view returns (uint256);
+
+    /**
+     * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
+     */
+    // solhint-disable-next-line func-name-mixedcase
+    function DOMAIN_SEPARATOR() external view returns (bytes32);
+}

+ 15 - 0
contracts/drafts/README.adoc

@@ -0,0 +1,15 @@
+= 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}}

+ 54 - 0
contracts/introspection/ERC165.sol

@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "./IERC165.sol";
+
+/**
+ * @dev Implementation of the {IERC165} interface.
+ *
+ * Contracts may inherit from this and call {_registerInterface} to declare
+ * their support of an interface.
+ */
+abstract contract ERC165 is IERC165 {
+    /*
+     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
+     */
+    bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
+
+    /**
+     * @dev Mapping of interface ids to whether or not it's supported.
+     */
+    mapping(bytes4 => bool) private _supportedInterfaces;
+
+    constructor () internal {
+        // Derived contracts need only register support for their own interfaces,
+        // we register support for ERC165 itself here
+        _registerInterface(_INTERFACE_ID_ERC165);
+    }
+
+    /**
+     * @dev See {IERC165-supportsInterface}.
+     *
+     * Time complexity O(1), guaranteed to always use less than 30 000 gas.
+     */
+    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
+        return _supportedInterfaces[interfaceId];
+    }
+
+    /**
+     * @dev Registers the contract as an implementer of the interface defined by
+     * `interfaceId`. Support of the actual ERC165 interface is automatic and
+     * registering its interface id is not required.
+     *
+     * See {IERC165-supportsInterface}.
+     *
+     * Requirements:
+     *
+     * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
+     */
+    function _registerInterface(bytes4 interfaceId) internal virtual {
+        require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
+        _supportedInterfaces[interfaceId] = true;
+    }
+}

+ 131 - 0
contracts/introspection/ERC165Checker.sol

@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.2 <0.8.0;
+
+/**
+ * @dev Library used to query support of an interface declared via {IERC165}.
+ *
+ * Note that these functions return the actual result of the query: they do not
+ * `revert` if an interface is not supported. It is up to the caller to decide
+ * what to do in these cases.
+ */
+library ERC165Checker {
+    // As per the EIP-165 spec, no interface should ever match 0xffffffff
+    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
+
+    /*
+     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
+     */
+    bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
+
+    /**
+     * @dev Returns true if `account` supports the {IERC165} interface,
+     */
+    function supportsERC165(address account) internal view returns (bool) {
+        // Any contract that implements ERC165 must explicitly indicate support of
+        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
+        return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
+            !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
+    }
+
+    /**
+     * @dev Returns true if `account` supports the interface defined by
+     * `interfaceId`. Support for {IERC165} itself is queried automatically.
+     *
+     * See {IERC165-supportsInterface}.
+     */
+    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
+        // query support of both ERC165 as per the spec and support of _interfaceId
+        return supportsERC165(account) &&
+            _supportsERC165Interface(account, interfaceId);
+    }
+
+    /**
+     * @dev Returns a boolean array where each value corresponds to the
+     * interfaces passed in and whether they're supported or not. This allows
+     * you to batch check interfaces for a contract where your expectation
+     * is that some interfaces may not be supported.
+     *
+     * See {IERC165-supportsInterface}.
+     *
+     * _Available since v3.4._
+     */
+    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
+        // an array of booleans corresponding to interfaceIds and whether they're supported or not
+        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
+
+        // query support of ERC165 itself
+        if (supportsERC165(account)) {
+            // query support of each interface in interfaceIds
+            for (uint256 i = 0; i < interfaceIds.length; i++) {
+                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
+            }
+        }
+
+        return interfaceIdsSupported;
+    }
+
+    /**
+     * @dev Returns true if `account` supports all the interfaces defined in
+     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
+     *
+     * Batch-querying can lead to gas savings by skipping repeated checks for
+     * {IERC165} support.
+     *
+     * See {IERC165-supportsInterface}.
+     */
+    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
+        // query support of ERC165 itself
+        if (!supportsERC165(account)) {
+            return false;
+        }
+
+        // query support of each interface in _interfaceIds
+        for (uint256 i = 0; i < interfaceIds.length; i++) {
+            if (!_supportsERC165Interface(account, interfaceIds[i])) {
+                return false;
+            }
+        }
+
+        // all interfaces supported
+        return true;
+    }
+
+    /**
+     * @notice Query if a contract implements an interface, does not check ERC165 support
+     * @param account The address of the contract to query for support of an interface
+     * @param interfaceId The interface identifier, as specified in ERC-165
+     * @return true if the contract at account indicates support of the interface with
+     * identifier interfaceId, false otherwise
+     * @dev Assumes that account contains a contract that supports ERC165, otherwise
+     * the behavior of this method is undefined. This precondition can be checked
+     * with {supportsERC165}.
+     * Interface identification is specified in ERC-165.
+     */
+    function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
+        // success determines whether the staticcall succeeded and result determines
+        // whether the contract at account indicates support of _interfaceId
+        (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
+
+        return (success && result);
+    }
+
+    /**
+     * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
+     * @param account The address of the contract to query for support of an interface
+     * @param interfaceId The interface identifier, as specified in ERC-165
+     * @return success true if the STATICCALL succeeded, false otherwise
+     * @return result true if the STATICCALL succeeded and the contract at account
+     * indicates support of the interface with identifier interfaceId, false otherwise
+     */
+    function _callERC165SupportsInterface(address account, bytes4 interfaceId)
+        private
+        view
+        returns (bool, bool)
+    {
+        bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
+        (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
+        if (result.length < 32) return (false, false);
+        return (success, abi.decode(result, (bool)));
+    }
+}

+ 37 - 0
contracts/introspection/ERC1820Implementer.sol

@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "./IERC1820Implementer.sol";
+
+/**
+ * @dev Implementation of the {IERC1820Implementer} interface.
+ *
+ * Contracts may inherit from this and call {_registerInterfaceForAddress} to
+ * declare their willingness to be implementers.
+ * {IERC1820Registry-setInterfaceImplementer} should then be called for the
+ * registration to be complete.
+ */
+contract ERC1820Implementer is IERC1820Implementer {
+    bytes32 constant private _ERC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
+
+    mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces;
+
+    /**
+     * See {IERC1820Implementer-canImplementInterfaceForAddress}.
+     */
+    function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual override returns (bytes32) {
+        return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00);
+    }
+
+    /**
+     * @dev Declares the contract as willing to be an implementer of
+     * `interfaceHash` for `account`.
+     *
+     * See {IERC1820Registry-setInterfaceImplementer} and
+     * {IERC1820Registry-interfaceHash}.
+     */
+    function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
+        _supportedInterfaces[interfaceHash][account] = true;
+    }
+}

+ 24 - 0
contracts/introspection/IERC165.sol

@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Interface of the ERC165 standard, as defined in the
+ * https://eips.ethereum.org/EIPS/eip-165[EIP].
+ *
+ * Implementers can declare support of contract interfaces, which can then be
+ * queried by others ({ERC165Checker}).
+ *
+ * For an implementation, see {ERC165}.
+ */
+interface IERC165 {
+    /**
+     * @dev Returns true if this contract implements the interface defined by
+     * `interfaceId`. See the corresponding
+     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
+     * to learn more about how these ids are created.
+     *
+     * This function call must use less than 30 000 gas.
+     */
+    function supportsInterface(bytes4 interfaceId) external view returns (bool);
+}

+ 19 - 0
contracts/introspection/IERC1820Implementer.sol

@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Interface for an ERC1820 implementer, as defined in the
+ * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP].
+ * Used by contracts that will be registered as implementers in the
+ * {IERC1820Registry}.
+ */
+interface IERC1820Implementer {
+    /**
+     * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
+     * implements `interfaceHash` for `account`.
+     *
+     * See {IERC1820Registry-setInterfaceImplementer}.
+     */
+    function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
+}

+ 111 - 0
contracts/introspection/IERC1820Registry.sol

@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Interface of the global ERC1820 Registry, as defined in the
+ * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
+ * implementers for interfaces in this registry, as well as query support.
+ *
+ * Implementers may be shared by multiple accounts, and can also implement more
+ * than a single interface for each account. Contracts can implement interfaces
+ * for themselves, but externally-owned accounts (EOA) must delegate this to a
+ * contract.
+ *
+ * {IERC165} interfaces can also be queried via the registry.
+ *
+ * For an in-depth explanation and source code analysis, see the EIP text.
+ */
+interface IERC1820Registry {
+    /**
+     * @dev Sets `newManager` as the manager for `account`. A manager of an
+     * account is able to set interface implementers for it.
+     *
+     * By default, each account is its own manager. Passing a value of `0x0` in
+     * `newManager` will reset the manager to this initial state.
+     *
+     * Emits a {ManagerChanged} event.
+     *
+     * Requirements:
+     *
+     * - the caller must be the current manager for `account`.
+     */
+    function setManager(address account, address newManager) external;
+
+    /**
+     * @dev Returns the manager for `account`.
+     *
+     * See {setManager}.
+     */
+    function getManager(address account) external view returns (address);
+
+    /**
+     * @dev Sets the `implementer` contract as ``account``'s implementer for
+     * `interfaceHash`.
+     *
+     * `account` being the zero address is an alias for the caller's address.
+     * The zero address can also be used in `implementer` to remove an old one.
+     *
+     * See {interfaceHash} to learn how these are created.
+     *
+     * Emits an {InterfaceImplementerSet} event.
+     *
+     * Requirements:
+     *
+     * - the caller must be the current manager for `account`.
+     * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
+     * end in 28 zeroes).
+     * - `implementer` must implement {IERC1820Implementer} and return true when
+     * queried for support, unless `implementer` is the caller. See
+     * {IERC1820Implementer-canImplementInterfaceForAddress}.
+     */
+    function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
+
+    /**
+     * @dev Returns the implementer of `interfaceHash` for `account`. If no such
+     * implementer is registered, returns the zero address.
+     *
+     * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
+     * zeroes), `account` will be queried for support of it.
+     *
+     * `account` being the zero address is an alias for the caller's address.
+     */
+    function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
+
+    /**
+     * @dev Returns the interface hash for an `interfaceName`, as defined in the
+     * corresponding
+     * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
+     */
+    function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
+
+    /**
+     *  @notice Updates the cache with whether the contract implements an ERC165 interface or not.
+     *  @param account Address of the contract for which to update the cache.
+     *  @param interfaceId ERC165 interface for which to update the cache.
+     */
+    function updateERC165Cache(address account, bytes4 interfaceId) external;
+
+    /**
+     *  @notice Checks whether a contract implements an ERC165 interface or not.
+     *  If the result is not cached a direct lookup on the contract address is performed.
+     *  If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
+     *  {updateERC165Cache} with the contract address.
+     *  @param account Address of the contract to check.
+     *  @param interfaceId ERC165 interface to check.
+     *  @return True if `account` implements `interfaceId`, false otherwise.
+     */
+    function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
+
+    /**
+     *  @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
+     *  @param account Address of the contract to check.
+     *  @param interfaceId ERC165 interface to check.
+     *  @return True if `account` implements `interfaceId`, false otherwise.
+     */
+    function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
+
+    event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
+
+    event ManagerChanged(address indexed account, address indexed newManager);
+}

+ 31 - 0
contracts/introspection/README.adoc

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

+ 31 - 0
contracts/math/Math.sol

@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Standard math utilities missing in the Solidity language.
+ */
+library Math {
+    /**
+     * @dev Returns the largest of two numbers.
+     */
+    function max(uint256 a, uint256 b) internal pure returns (uint256) {
+        return a >= b ? a : b;
+    }
+
+    /**
+     * @dev Returns the smallest of two numbers.
+     */
+    function min(uint256 a, uint256 b) internal pure returns (uint256) {
+        return a < b ? a : b;
+    }
+
+    /**
+     * @dev Returns the average of two numbers. The result is rounded towards
+     * zero.
+     */
+    function average(uint256 a, uint256 b) internal pure returns (uint256) {
+        // (a + b) / 2 can overflow, so we distribute
+        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
+    }
+}

+ 14 - 0
contracts/math/README.adoc

@@ -0,0 +1,14 @@
+= Math
+
+[.readme-notice]
+NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/math
+
+These are math-related utilities.
+
+== Libraries
+
+{{SafeMath}}
+
+{{SignedSafeMath}}
+
+{{Math}}

+ 214 - 0
contracts/math/SafeMath.sol

@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @dev Wrappers over Solidity's arithmetic operations with added overflow
+ * checks.
+ *
+ * Arithmetic operations in Solidity wrap on overflow. This can easily result
+ * in bugs, because programmers usually assume that an overflow raises an
+ * error, which is the standard behavior in high level programming languages.
+ * `SafeMath` restores this intuition by reverting the transaction when an
+ * operation overflows.
+ *
+ * Using this library instead of the unchecked operations eliminates an entire
+ * class of bugs, so it's recommended to use it always.
+ */
+library SafeMath {
+    /**
+     * @dev Returns the addition of two unsigned integers, with an overflow flag.
+     *
+     * _Available since v3.4._
+     */
+    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
+        uint256 c = a + b;
+        if (c < a) return (false, 0);
+        return (true, c);
+    }
+
+    /**
+     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
+     *
+     * _Available since v3.4._
+     */
+    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
+        if (b > a) return (false, 0);
+        return (true, a - b);
+    }
+
+    /**
+     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
+     *
+     * _Available since v3.4._
+     */
+    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
+        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
+        // benefit is lost if 'b' is also tested.
+        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
+        if (a == 0) return (true, 0);
+        uint256 c = a * b;
+        if (c / a != b) return (false, 0);
+        return (true, c);
+    }
+
+    /**
+     * @dev Returns the division of two unsigned integers, with a division by zero flag.
+     *
+     * _Available since v3.4._
+     */
+    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
+        if (b == 0) return (false, 0);
+        return (true, a / b);
+    }
+
+    /**
+     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
+     *
+     * _Available since v3.4._
+     */
+    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
+        if (b == 0) return (false, 0);
+        return (true, a % b);
+    }
+
+    /**
+     * @dev Returns the addition of two unsigned integers, reverting on
+     * overflow.
+     *
+     * Counterpart to Solidity's `+` operator.
+     *
+     * Requirements:
+     *
+     * - Addition cannot overflow.
+     */
+    function add(uint256 a, uint256 b) internal pure returns (uint256) {
+        uint256 c = a + b;
+        require(c >= a, "SafeMath: addition overflow");
+        return c;
+    }
+
+    /**
+     * @dev Returns the subtraction of two unsigned integers, reverting on
+     * overflow (when the result is negative).
+     *
+     * Counterpart to Solidity's `-` operator.
+     *
+     * Requirements:
+     *
+     * - Subtraction cannot overflow.
+     */
+    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
+        require(b <= a, "SafeMath: subtraction overflow");
+        return a - b;
+    }
+
+    /**
+     * @dev Returns the multiplication of two unsigned integers, reverting on
+     * overflow.
+     *
+     * Counterpart to Solidity's `*` operator.
+     *
+     * Requirements:
+     *
+     * - Multiplication cannot overflow.
+     */
+    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
+        if (a == 0) return 0;
+        uint256 c = a * b;
+        require(c / a == b, "SafeMath: multiplication overflow");
+        return c;
+    }
+
+    /**
+     * @dev Returns the integer division of two unsigned integers, reverting on
+     * division by zero. The result is rounded towards zero.
+     *
+     * Counterpart to Solidity's `/` operator. Note: this function uses a
+     * `revert` opcode (which leaves remaining gas untouched) while Solidity
+     * uses an invalid opcode to revert (consuming all remaining gas).
+     *
+     * Requirements:
+     *
+     * - The divisor cannot be zero.
+     */
+    function div(uint256 a, uint256 b) internal pure returns (uint256) {
+        require(b > 0, "SafeMath: division by zero");
+        return a / b;
+    }
+
+    /**
+     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
+     * reverting when dividing by zero.
+     *
+     * Counterpart to Solidity's `%` operator. This function uses a `revert`
+     * opcode (which leaves remaining gas untouched) while Solidity uses an
+     * invalid opcode to revert (consuming all remaining gas).
+     *
+     * Requirements:
+     *
+     * - The divisor cannot be zero.
+     */
+    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
+        require(b > 0, "SafeMath: modulo by zero");
+        return a % b;
+    }
+
+    /**
+     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
+     * overflow (when the result is negative).
+     *
+     * CAUTION: This function is deprecated because it requires allocating memory for the error
+     * message unnecessarily. For custom revert reasons use {trySub}.
+     *
+     * Counterpart to Solidity's `-` operator.
+     *
+     * Requirements:
+     *
+     * - Subtraction cannot overflow.
+     */
+    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
+        require(b <= a, errorMessage);
+        return a - b;
+    }
+
+    /**
+     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
+     * division by zero. The result is rounded towards zero.
+     *
+     * CAUTION: This function is deprecated because it requires allocating memory for the error
+     * message unnecessarily. For custom revert reasons use {tryDiv}.
+     *
+     * Counterpart to Solidity's `/` operator. Note: this function uses a
+     * `revert` opcode (which leaves remaining gas untouched) while Solidity
+     * uses an invalid opcode to revert (consuming all remaining gas).
+     *
+     * Requirements:
+     *
+     * - The divisor cannot be zero.
+     */
+    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
+        require(b > 0, errorMessage);
+        return a / b;
+    }
+
+    /**
+     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
+     * reverting with custom message when dividing by zero.
+     *
+     * CAUTION: This function is deprecated because it requires allocating memory for the error
+     * message unnecessarily. For custom revert reasons use {tryMod}.
+     *
+     * Counterpart to Solidity's `%` operator. This function uses a `revert`
+     * opcode (which leaves remaining gas untouched) while Solidity uses an
+     * invalid opcode to revert (consuming all remaining gas).
+     *
+     * Requirements:
+     *
+     * - The divisor cannot be zero.
+     */
+    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
+        require(b > 0, errorMessage);
+        return a % b;
+    }
+}

+ 92 - 0
contracts/math/SignedSafeMath.sol

@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+/**
+ * @title SignedSafeMath
+ * @dev Signed math operations with safety checks that revert on error.
+ */
+library SignedSafeMath {
+    int256 constant private _INT256_MIN = -2**255;
+
+    /**
+     * @dev Returns the multiplication of two signed integers, reverting on
+     * overflow.
+     *
+     * Counterpart to Solidity's `*` operator.
+     *
+     * Requirements:
+     *
+     * - Multiplication cannot overflow.
+     */
+    function mul(int256 a, int256 b) internal pure returns (int256) {
+        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
+        // benefit is lost if 'b' is also tested.
+        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
+        if (a == 0) {
+            return 0;
+        }
+
+        require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
+
+        int256 c = a * b;
+        require(c / a == b, "SignedSafeMath: multiplication overflow");
+
+        return c;
+    }
+
+    /**
+     * @dev Returns the integer division of two signed integers. Reverts on
+     * division by zero. The result is rounded towards zero.
+     *
+     * Counterpart to Solidity's `/` operator. Note: this function uses a
+     * `revert` opcode (which leaves remaining gas untouched) while Solidity
+     * uses an invalid opcode to revert (consuming all remaining gas).
+     *
+     * Requirements:
+     *
+     * - The divisor cannot be zero.
+     */
+    function div(int256 a, int256 b) internal pure returns (int256) {
+        require(b != 0, "SignedSafeMath: division by zero");
+        require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
+
+        int256 c = a / b;
+
+        return c;
+    }
+
+    /**
+     * @dev Returns the subtraction of two signed integers, reverting on
+     * overflow.
+     *
+     * Counterpart to Solidity's `-` operator.
+     *
+     * Requirements:
+     *
+     * - Subtraction cannot overflow.
+     */
+    function sub(int256 a, int256 b) internal pure returns (int256) {
+        int256 c = a - b;
+        require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
+
+        return c;
+    }
+
+    /**
+     * @dev Returns the addition of two signed integers, reverting on
+     * overflow.
+     *
+     * Counterpart to Solidity's `+` operator.
+     *
+     * Requirements:
+     *
+     * - Addition cannot overflow.
+     */
+    function add(int256 a, int256 b) internal pure returns (int256) {
+        int256 c = a + b;
+        require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
+
+        return c;
+    }
+}

+ 15 - 0
contracts/mocks/AccessControlMock.sol

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

+ 42 - 0
contracts/mocks/AddressImpl.sol

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

+ 19 - 0
contracts/mocks/ArraysImpl.sol

@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Arrays.sol";
+
+contract ArraysImpl {
+    using Arrays for uint256[];
+
+    uint256[] private _array;
+
+    constructor (uint256[] memory array) public {
+        _array = array;
+    }
+
+    function findUpperBound(uint256 element) external view returns (uint256) {
+        return _array.findUpperBound(element);
+    }
+}

+ 12 - 0
contracts/mocks/BadBeacon.sol

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

+ 50 - 0
contracts/mocks/CallReceiverMock.sol

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

+ 20 - 0
contracts/mocks/ClashingImplementation.sol

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

+ 32 - 0
contracts/mocks/ClonesMock.sol

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

+ 18 - 0
contracts/mocks/ConditionalEscrowMock.sol

@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../payment/escrow/ConditionalEscrow.sol";
+
+// mock class using ConditionalEscrow
+contract ConditionalEscrowMock is ConditionalEscrow {
+    mapping(address => bool) private _allowed;
+
+    function setAllowed(address payee, bool allowed) public {
+        _allowed[payee] = allowed;
+    }
+
+    function withdrawalAllowed(address payee) public view override returns (bool) {
+        return _allowed[payee];
+    }
+}

+ 29 - 0
contracts/mocks/ContextMock.sol

@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Context.sol";
+
+contract ContextMock is Context {
+    event Sender(address sender);
+
+    function msgSender() public {
+        emit Sender(_msgSender());
+    }
+
+    event Data(bytes data, uint256 integerValue, string stringValue);
+
+    function msgData(uint256 integerValue, string memory stringValue) public {
+        emit Data(_msgData(), integerValue, stringValue);
+    }
+}
+
+contract ContextMockCaller {
+    function callSender(ContextMock context) public {
+        context.msgSender();
+    }
+
+    function callData(ContextMock context, uint256 integerValue, string memory stringValue) public {
+        context.msgData(integerValue, stringValue);
+    }
+}

+ 23 - 0
contracts/mocks/CountersImpl.sol

@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Counters.sol";
+
+contract CountersImpl {
+    using Counters for Counters.Counter;
+
+    Counters.Counter private _counter;
+
+    function current() public view returns (uint256) {
+        return _counter.current();
+    }
+
+    function increment() public {
+        _counter.increment();
+    }
+
+    function decrement() public {
+        _counter.decrement();
+    }
+}

+ 27 - 0
contracts/mocks/Create2Impl.sol

@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Create2.sol";
+import "../introspection/ERC1820Implementer.sol";
+
+contract Create2Impl {
+    function deploy(uint256 value, bytes32 salt, bytes memory code) public {
+        Create2.deploy(value, salt, code);
+    }
+
+    function deployERC1820Implementer(uint256 value, bytes32 salt) public {
+        // solhint-disable-next-line indent
+        Create2.deploy(value, salt, type(ERC1820Implementer).creationCode);
+    }
+
+    function computeAddress(bytes32 salt, bytes32 codeHash) public view returns (address) {
+        return Create2.computeAddress(salt, codeHash);
+    }
+
+    function computeAddressWithDeployer(bytes32 salt, bytes32 codeHash, address deployer) public pure returns (address) {
+        return Create2.computeAddress(salt, codeHash, deployer);
+    }
+
+    receive() external payable {}
+}

+ 57 - 0
contracts/mocks/DummyImplementation.sol

@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+abstract contract Impl {
+  function version() public pure virtual returns (string memory); 
+}
+
+contract DummyImplementation {
+  uint256 public value;
+  string public text;
+  uint256[] public values;
+
+  function initializeNonPayable() public {
+    value = 10;
+  }
+
+  function initializePayable() public payable {
+    value = 100;
+  }
+
+  function initializeNonPayableWithValue(uint256 _value) public {
+    value = _value;
+  }
+
+  function initializePayableWithValue(uint256 _value) public payable {
+    value = _value;
+  }
+
+  function initialize(uint256 _value, string memory _text, uint256[] memory _values) public {
+    value = _value;
+    text = _text;
+    values = _values;
+  }
+
+  function get() public pure returns (bool) {
+    return true;
+  }
+
+  function version() public pure virtual returns (string memory) {
+    return "V1";
+  }
+
+  function reverts() public pure {
+    require(false, "DummyImplementation reverted");
+  }
+}
+
+contract DummyImplementationV2 is DummyImplementation {
+  function migrate(uint256 newVal) public payable {
+    value = newVal;
+  }
+
+  function version() public pure override returns (string memory) {
+    return "V2";
+  }
+}

+ 17 - 0
contracts/mocks/ECDSAMock.sol

@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../cryptography/ECDSA.sol";
+
+contract ECDSAMock {
+    using ECDSA for bytes32;
+
+    function recover(bytes32 hash, bytes memory signature) public pure returns (address) {
+        return hash.recover(signature);
+    }
+
+    function toEthSignedMessageHash(bytes32 hash) public pure returns (bytes32) {
+        return hash.toEthSignedMessageHash();
+    }
+}

+ 32 - 0
contracts/mocks/EIP712External.sol

@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../drafts/EIP712.sol";
+import "../cryptography/ECDSA.sol";
+
+contract EIP712External is EIP712 {
+    constructor(string memory name, string memory version) public EIP712(name, version) {}
+
+    function domainSeparator() external view returns (bytes32) {
+        return _domainSeparatorV4();
+    }
+
+    function verify(bytes memory signature, address signer, address mailTo, string memory mailContents) external view {
+        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
+            keccak256("Mail(address to,string contents)"),
+            mailTo,
+            keccak256(bytes(mailContents))
+        )));
+        address recoveredSigner = ECDSA.recover(digest, signature);
+        require(recoveredSigner == signer);
+    }
+
+    function getChainId() external view returns (uint256 chainId) {
+        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
+        // solhint-disable-next-line no-inline-assembly
+        assembly {
+            chainId := chainid()
+        }
+    }
+}

+ 13 - 0
contracts/mocks/ERC1155BurnableMock.sol

@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC1155/ERC1155Burnable.sol";
+
+contract ERC1155BurnableMock is ERC1155Burnable {
+    constructor(string memory uri) public ERC1155(uri) { }
+
+    function mint(address to, uint256 id, uint256 value, bytes memory data) public {
+        _mint(to, id, value, data);
+    }
+}

+ 35 - 0
contracts/mocks/ERC1155Mock.sol

@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC1155/ERC1155.sol";
+
+/**
+ * @title ERC1155Mock
+ * This mock just publicizes internal functions for testing purposes
+ */
+contract ERC1155Mock is ERC1155 {
+    constructor (string memory uri) public ERC1155(uri) {
+        // solhint-disable-previous-line no-empty-blocks
+    }
+
+    function setURI(string memory newuri) public {
+        _setURI(newuri);
+    }
+
+    function mint(address to, uint256 id, uint256 value, bytes memory data) public {
+        _mint(to, id, value, data);
+    }
+
+    function mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) public {
+        _mintBatch(to, ids, values, data);
+    }
+
+    function burn(address owner, uint256 id, uint256 value) public {
+        _burn(owner, id, value);
+    }
+
+    function burnBatch(address owner, uint256[] memory ids, uint256[] memory values) public {
+        _burnBatch(owner, ids, values);
+    }
+}

+ 31 - 0
contracts/mocks/ERC1155PausableMock.sol

@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "./ERC1155Mock.sol";
+import "../token/ERC1155/ERC1155Pausable.sol";
+
+contract ERC1155PausableMock is ERC1155Mock, ERC1155Pausable {
+    constructor(string memory uri) public ERC1155Mock(uri) { }
+
+    function pause() external {
+        _pause();
+    }
+
+    function unpause() external {
+        _unpause();
+    }
+
+    function _beforeTokenTransfer(
+        address operator,
+        address from,
+        address to,
+        uint256[] memory ids,
+        uint256[] memory amounts,
+        bytes memory data
+    )
+        internal virtual override(ERC1155, ERC1155Pausable)
+    {
+        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
+    }
+}

+ 62 - 0
contracts/mocks/ERC1155ReceiverMock.sol

@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC1155/IERC1155Receiver.sol";
+import "./ERC165Mock.sol";
+
+contract ERC1155ReceiverMock is IERC1155Receiver, ERC165Mock {
+    bytes4 private _recRetval;
+    bool private _recReverts;
+    bytes4 private _batRetval;
+    bool private _batReverts;
+
+    event Received(address operator, address from, uint256 id, uint256 value, bytes data, uint256 gas);
+    event BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data, uint256 gas);
+
+    constructor (
+        bytes4 recRetval,
+        bool recReverts,
+        bytes4 batRetval,
+        bool batReverts
+    )
+        public
+    {
+        _recRetval = recRetval;
+        _recReverts = recReverts;
+        _batRetval = batRetval;
+        _batReverts = batReverts;
+    }
+
+    function onERC1155Received(
+        address operator,
+        address from,
+        uint256 id,
+        uint256 value,
+        bytes calldata data
+    )
+        external
+        override
+        returns(bytes4)
+    {
+        require(!_recReverts, "ERC1155ReceiverMock: reverting on receive");
+        emit Received(operator, from, id, value, data, gasleft());
+        return _recRetval;
+    }
+
+    function onERC1155BatchReceived(
+        address operator,
+        address from,
+        uint256[] calldata ids,
+        uint256[] calldata values,
+        bytes calldata data
+    )
+        external
+        override
+        returns(bytes4)
+    {
+        require(!_batReverts, "ERC1155ReceiverMock: reverting on batch receive");
+        emit BatchReceived(operator, from, ids, values, data, gasleft());
+        return _batRetval;
+    }
+}

+ 58 - 0
contracts/mocks/ERC165/ERC165InterfacesSupported.sol

@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../../introspection/IERC165.sol";
+
+/**
+ * https://eips.ethereum.org/EIPS/eip-214#specification
+ * From the specification:
+ * > Any attempts to make state-changing operations inside an execution instance with STATIC set to true will instead
+ * throw an exception.
+ * > These operations include [...], LOG0, LOG1, LOG2, [...]
+ *
+ * therefore, because this contract is staticcall'd we need to not emit events (which is how solidity-coverage works)
+ * solidity-coverage ignores the /mocks folder, so we duplicate its implementation here to avoid instrumenting it
+ */
+contract SupportsInterfaceWithLookupMock is IERC165 {
+    /*
+     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
+     */
+    bytes4 public constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
+
+    /**
+     * @dev A mapping of interface id to whether or not it's supported.
+     */
+    mapping(bytes4 => bool) private _supportedInterfaces;
+
+    /**
+     * @dev A contract implementing SupportsInterfaceWithLookup
+     * implement ERC165 itself.
+     */
+    constructor () public {
+        _registerInterface(INTERFACE_ID_ERC165);
+    }
+
+    /**
+     * @dev Implement supportsInterface(bytes4) using a lookup table.
+     */
+    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
+        return _supportedInterfaces[interfaceId];
+    }
+
+    /**
+     * @dev Private method for registering an interface.
+     */
+    function _registerInterface(bytes4 interfaceId) internal {
+        require(interfaceId != 0xffffffff, "ERC165InterfacesSupported: invalid interface id");
+        _supportedInterfaces[interfaceId] = true;
+    }
+}
+
+contract ERC165InterfacesSupported is SupportsInterfaceWithLookupMock {
+    constructor (bytes4[] memory interfaceIds) public {
+        for (uint256 i = 0; i < interfaceIds.length; i++) {
+            _registerInterface(interfaceIds[i]);
+        }
+    }
+}

+ 5 - 0
contracts/mocks/ERC165/ERC165NotSupported.sol

@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+contract ERC165NotSupported { }

+ 25 - 0
contracts/mocks/ERC165CheckerMock.sol

@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../introspection/ERC165Checker.sol";
+
+contract ERC165CheckerMock {
+    using ERC165Checker for address;
+
+    function supportsERC165(address account) public view returns (bool) {
+        return account.supportsERC165();
+    }
+
+    function supportsInterface(address account, bytes4 interfaceId) public view returns (bool) {
+        return account.supportsInterface(interfaceId);
+    }
+
+    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool) {
+        return account.supportsAllInterfaces(interfaceIds);
+    }
+
+    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) public view returns (bool[] memory) {
+        return account.getSupportedInterfaces(interfaceIds);
+    }
+}

+ 11 - 0
contracts/mocks/ERC165Mock.sol

@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../introspection/ERC165.sol";
+
+contract ERC165Mock is ERC165 {
+    function registerInterface(bytes4 interfaceId) public {
+        _registerInterface(interfaceId);
+    }
+}

+ 11 - 0
contracts/mocks/ERC1820ImplementerMock.sol

@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../introspection/ERC1820Implementer.sol";
+
+contract ERC1820ImplementerMock is ERC1820Implementer {
+    function registerInterfaceForAddress(bytes32 interfaceHash, address account) public {
+        _registerInterfaceForAddress(interfaceHash, account);
+    }
+}

+ 16 - 0
contracts/mocks/ERC20BurnableMock.sol

@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20Burnable.sol";
+
+contract ERC20BurnableMock is ERC20Burnable {
+    constructor (
+        string memory name,
+        string memory symbol,
+        address initialAccount,
+        uint256 initialBalance
+    ) public ERC20(name, symbol) {
+        _mint(initialAccount, initialBalance);
+    }
+}

+ 15 - 0
contracts/mocks/ERC20CappedMock.sol

@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20Capped.sol";
+
+contract ERC20CappedMock is ERC20Capped {
+    constructor (string memory name, string memory symbol, uint256 cap)
+        public ERC20(name, symbol) ERC20Capped(cap)
+    { }
+
+    function mint(address to, uint256 tokenId) public {
+        _mint(to, tokenId);
+    }
+}

+ 11 - 0
contracts/mocks/ERC20DecimalsMock.sol

@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20.sol";
+
+contract ERC20DecimalsMock is ERC20 {
+    constructor (string memory name, string memory symbol, uint8 decimals) public ERC20(name, symbol) {
+        _setupDecimals(decimals);
+    }
+}

+ 33 - 0
contracts/mocks/ERC20Mock.sol

@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20.sol";
+
+// mock class using ERC20
+contract ERC20Mock is ERC20 {
+    constructor (
+        string memory name,
+        string memory symbol,
+        address initialAccount,
+        uint256 initialBalance
+    ) public payable ERC20(name, symbol) {
+        _mint(initialAccount, initialBalance);
+    }
+
+    function mint(address account, uint256 amount) public {
+        _mint(account, amount);
+    }
+
+    function burn(address account, uint256 amount) public {
+        _burn(account, amount);
+    }
+
+    function transferInternal(address from, address to, uint256 value) public {
+        _transfer(from, to, value);
+    }
+
+    function approveInternal(address owner, address spender, uint256 value) public {
+        _approve(owner, spender, value);
+    }
+}

+ 33 - 0
contracts/mocks/ERC20PausableMock.sol

@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20Pausable.sol";
+
+// mock class using ERC20Pausable
+contract ERC20PausableMock is ERC20Pausable {
+    constructor (
+        string memory name,
+        string memory symbol,
+        address initialAccount,
+        uint256 initialBalance
+    ) public ERC20(name, symbol) {
+        _mint(initialAccount, initialBalance);
+    }
+
+    function pause() external {
+        _pause();
+    }
+
+    function unpause() external {
+        _unpause();
+    }
+
+    function mint(address to, uint256 amount) public {
+        _mint(to, amount);
+    }
+
+    function burn(address from, uint256 amount) public {
+        _burn(from, amount);
+    }
+}

+ 24 - 0
contracts/mocks/ERC20PermitMock.sol

@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../drafts/ERC20Permit.sol";
+
+contract ERC20PermitMock is ERC20Permit {
+    constructor (
+        string memory name,
+        string memory symbol,
+        address initialAccount,
+        uint256 initialBalance
+    ) public payable ERC20(name, symbol) ERC20Permit(name) {
+        _mint(initialAccount, initialBalance);
+    }
+
+    function getChainId() external view returns (uint256 chainId) {
+        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
+        // solhint-disable-next-line no-inline-assembly
+        assembly {
+            chainId := chainid()
+        }
+    }
+}

+ 29 - 0
contracts/mocks/ERC20SnapshotMock.sol

@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC20/ERC20Snapshot.sol";
+
+
+contract ERC20SnapshotMock is ERC20Snapshot {
+    constructor(
+        string memory name,
+        string memory symbol,
+        address initialAccount,
+        uint256 initialBalance
+    ) public ERC20(name, symbol) {
+        _mint(initialAccount, initialBalance);
+    }
+
+    function snapshot() public {
+        _snapshot();
+    }
+
+    function mint(address account, uint256 amount) public {
+        _mint(account, amount);
+    }
+
+    function burn(address account, uint256 amount) public {
+        _burn(account, amount);
+    }
+}

+ 13 - 0
contracts/mocks/ERC721BurnableMock.sol

@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC721/ERC721Burnable.sol";
+
+contract ERC721BurnableMock is ERC721Burnable {
+    constructor(string memory name, string memory symbol) public ERC721(name, symbol) { }
+
+    function mint(address to, uint256 tokenId) public {
+        _mint(to, tokenId);
+    }
+}

+ 31 - 0
contracts/mocks/ERC721GSNRecipientMock.sol

@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC721/ERC721.sol";
+import "../GSN/GSNRecipient.sol";
+import "../GSN/GSNRecipientSignature.sol";
+
+/**
+ * @title ERC721GSNRecipientMock
+ * A simple ERC721 mock that has GSN support enabled
+ */
+contract ERC721GSNRecipientMock is ERC721, GSNRecipient, GSNRecipientSignature {
+    constructor(string memory name, string memory symbol, address trustedSigner)
+        public
+        ERC721(name, symbol)
+        GSNRecipientSignature(trustedSigner)
+    { }
+
+    function mint(uint256 tokenId) public {
+        _mint(_msgSender(), tokenId);
+    }
+
+    function _msgSender() internal view override(Context, GSNRecipient) returns (address payable) {
+        return GSNRecipient._msgSender();
+    }
+
+    function _msgData() internal view override(Context, GSNRecipient) returns (bytes memory) {
+        return GSNRecipient._msgData();
+    }
+}

+ 41 - 0
contracts/mocks/ERC721Mock.sol

@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC721/ERC721.sol";
+
+/**
+ * @title ERC721Mock
+ * This mock just provides a public safeMint, mint, and burn functions for testing purposes
+ */
+contract ERC721Mock is ERC721 {
+    constructor (string memory name, string memory symbol) public ERC721(name, symbol) { }
+
+    function exists(uint256 tokenId) public view returns (bool) {
+        return _exists(tokenId);
+    }
+
+    function setTokenURI(uint256 tokenId, string memory uri) public {
+        _setTokenURI(tokenId, uri);
+    }
+
+    function setBaseURI(string memory baseURI) public {
+        _setBaseURI(baseURI);
+    }
+
+    function mint(address to, uint256 tokenId) public {
+        _mint(to, tokenId);
+    }
+
+    function safeMint(address to, uint256 tokenId) public {
+        _safeMint(to, tokenId);
+    }
+
+    function safeMint(address to, uint256 tokenId, bytes memory _data) public {
+        _safeMint(to, tokenId, _data);
+    }
+
+    function burn(uint256 tokenId) public {
+        _burn(tokenId);
+    }
+}

+ 33 - 0
contracts/mocks/ERC721PausableMock.sol

@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC721/ERC721Pausable.sol";
+
+/**
+ * @title ERC721PausableMock
+ * This mock just provides a public mint, burn and exists functions for testing purposes
+ */
+contract ERC721PausableMock is ERC721Pausable {
+    constructor (string memory name, string memory symbol) public ERC721(name, symbol) { }
+
+    function mint(address to, uint256 tokenId) public {
+        super._mint(to, tokenId);
+    }
+
+    function burn(uint256 tokenId) public {
+        super._burn(tokenId);
+    }
+
+    function exists(uint256 tokenId) public view returns (bool) {
+        return super._exists(tokenId);
+    }
+
+    function pause() external {
+        _pause();
+    }
+
+    function unpause() external {
+        _unpause();
+    }
+}

+ 25 - 0
contracts/mocks/ERC721ReceiverMock.sol

@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../token/ERC721/IERC721Receiver.sol";
+
+contract ERC721ReceiverMock is IERC721Receiver {
+    bytes4 private _retval;
+    bool private _reverts;
+
+    event Received(address operator, address from, uint256 tokenId, bytes data, uint256 gas);
+
+    constructor (bytes4 retval, bool reverts) public {
+        _retval = retval;
+        _reverts = reverts;
+    }
+
+    function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
+        public override returns (bytes4)
+    {
+        require(!_reverts, "ERC721ReceiverMock: reverting");
+        emit Received(operator, from, tokenId, data, gasleft());
+        return _retval;
+    }
+}

+ 37 - 0
contracts/mocks/ERC777Mock.sol

@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Context.sol";
+import "../token/ERC777/ERC777.sol";
+
+contract ERC777Mock is Context, ERC777 {
+    event BeforeTokenTransfer();
+
+    constructor(
+        address initialHolder,
+        uint256 initialBalance,
+        string memory name,
+        string memory symbol,
+        address[] memory defaultOperators
+    ) public ERC777(name, symbol, defaultOperators) {
+        _mint(initialHolder, initialBalance, "", "");
+    }
+
+    function mintInternal (
+        address to,
+        uint256 amount,
+        bytes memory userData,
+        bytes memory operatorData
+    ) public {
+        _mint(to, amount, userData, operatorData);
+    }
+
+    function approveInternal(address holder, address spender, uint256 value) public {
+        _approve(holder, spender, value);
+    }
+
+    function _beforeTokenTransfer(address, address, address, uint256) internal override {
+        emit BeforeTokenTransfer();
+    }
+}

+ 153 - 0
contracts/mocks/ERC777SenderRecipientMock.sol

@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/Context.sol";
+import "../token/ERC777/IERC777.sol";
+import "../token/ERC777/IERC777Sender.sol";
+import "../token/ERC777/IERC777Recipient.sol";
+import "../introspection/IERC1820Registry.sol";
+import "../introspection/ERC1820Implementer.sol";
+
+contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer {
+    event TokensToSendCalled(
+        address operator,
+        address from,
+        address to,
+        uint256 amount,
+        bytes data,
+        bytes operatorData,
+        address token,
+        uint256 fromBalance,
+        uint256 toBalance
+    );
+
+    event TokensReceivedCalled(
+        address operator,
+        address from,
+        address to,
+        uint256 amount,
+        bytes data,
+        bytes operatorData,
+        address token,
+        uint256 fromBalance,
+        uint256 toBalance
+    );
+
+    // Emitted in ERC777Mock. Here for easier decoding
+    event BeforeTokenTransfer();
+
+    bool private _shouldRevertSend;
+    bool private _shouldRevertReceive;
+
+    IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
+
+    bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender");
+    bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
+
+    function tokensToSend(
+        address operator,
+        address from,
+        address to,
+        uint256 amount,
+        bytes calldata userData,
+        bytes calldata operatorData
+    ) external override {
+        if (_shouldRevertSend) {
+            revert();
+        }
+
+        IERC777 token = IERC777(_msgSender());
+
+        uint256 fromBalance = token.balanceOf(from);
+        // when called due to burn, to will be the zero address, which will have a balance of 0
+        uint256 toBalance = token.balanceOf(to);
+
+        emit TokensToSendCalled(
+            operator,
+            from,
+            to,
+            amount,
+            userData,
+            operatorData,
+            address(token),
+            fromBalance,
+            toBalance
+        );
+    }
+
+    function tokensReceived(
+        address operator,
+        address from,
+        address to,
+        uint256 amount,
+        bytes calldata userData,
+        bytes calldata operatorData
+    ) external override {
+        if (_shouldRevertReceive) {
+            revert();
+        }
+
+        IERC777 token = IERC777(_msgSender());
+
+        uint256 fromBalance = token.balanceOf(from);
+        // when called due to burn, to will be the zero address, which will have a balance of 0
+        uint256 toBalance = token.balanceOf(to);
+
+        emit TokensReceivedCalled(
+            operator,
+            from,
+            to,
+            amount,
+            userData,
+            operatorData,
+            address(token),
+            fromBalance,
+            toBalance
+        );
+    }
+
+    function senderFor(address account) public {
+        _registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account);
+
+        address self = address(this);
+        if (account == self) {
+            registerSender(self);
+        }
+    }
+
+    function registerSender(address sender) public {
+        _erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender);
+    }
+
+    function recipientFor(address account) public {
+        _registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account);
+
+        address self = address(this);
+        if (account == self) {
+            registerRecipient(self);
+        }
+    }
+
+    function registerRecipient(address recipient) public {
+        _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient);
+    }
+
+    function setShouldRevertSend(bool shouldRevert) public {
+        _shouldRevertSend = shouldRevert;
+    }
+
+    function setShouldRevertReceive(bool shouldRevert) public {
+        _shouldRevertReceive = shouldRevert;
+    }
+
+    function send(IERC777 token, address to, uint256 amount, bytes memory data) public {
+        // This is 777's send function, not the Solidity send function
+        token.send(to, amount, data); // solhint-disable-line check-send-result
+    }
+
+    function burn(IERC777 token, uint256 amount, bytes memory data) public {
+        token.burn(amount, data);
+    }
+}
+

+ 48 - 0
contracts/mocks/EnumerableMapMock.sol

@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/EnumerableMap.sol";
+
+contract EnumerableMapMock {
+    using EnumerableMap for EnumerableMap.UintToAddressMap;
+
+    event OperationResult(bool result);
+
+    EnumerableMap.UintToAddressMap private _map;
+
+    function contains(uint256 key) public view returns (bool) {
+        return _map.contains(key);
+    }
+
+    function set(uint256 key, address value) public {
+        bool result = _map.set(key, value);
+        emit OperationResult(result);
+    }
+
+    function remove(uint256 key) public {
+        bool result = _map.remove(key);
+        emit OperationResult(result);
+    }
+
+    function length() public view returns (uint256) {
+        return _map.length();
+    }
+
+    function at(uint256 index) public view returns (uint256 key, address value) {
+        return _map.at(index);
+    }
+
+
+    function tryGet(uint256 key) public view returns (bool, address) {
+        return _map.tryGet(key);
+    }
+
+    function get(uint256 key) public view returns (address) {
+        return _map.get(key);
+    }
+
+    function getWithMessage(uint256 key, string calldata errorMessage) public view returns (address) {
+        return _map.get(key, errorMessage);
+    }
+}

+ 98 - 0
contracts/mocks/EnumerableSetMock.sol

@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../utils/EnumerableSet.sol";
+
+// Bytes32Set
+contract EnumerableBytes32SetMock {
+    using EnumerableSet for EnumerableSet.Bytes32Set;
+
+    event OperationResult(bool result);
+
+    EnumerableSet.Bytes32Set private _set;
+
+    function contains(bytes32 value) public view returns (bool) {
+        return _set.contains(value);
+    }
+
+    function add(bytes32 value) public {
+        bool result = _set.add(value);
+        emit OperationResult(result);
+    }
+
+    function remove(bytes32 value) public {
+        bool result = _set.remove(value);
+        emit OperationResult(result);
+    }
+
+    function length() public view returns (uint256) {
+        return _set.length();
+    }
+
+    function at(uint256 index) public view returns (bytes32) {
+        return _set.at(index);
+    }
+}
+
+// AddressSet
+contract EnumerableAddressSetMock {
+    using EnumerableSet for EnumerableSet.AddressSet;
+
+    event OperationResult(bool result);
+
+    EnumerableSet.AddressSet private _set;
+
+    function contains(address value) public view returns (bool) {
+        return _set.contains(value);
+    }
+
+    function add(address value) public {
+        bool result = _set.add(value);
+        emit OperationResult(result);
+    }
+
+    function remove(address value) public {
+        bool result = _set.remove(value);
+        emit OperationResult(result);
+    }
+
+    function length() public view returns (uint256) {
+        return _set.length();
+    }
+
+    function at(uint256 index) public view returns (address) {
+        return _set.at(index);
+    }
+}
+
+// UintSet
+contract EnumerableUintSetMock {
+    using EnumerableSet for EnumerableSet.UintSet;
+
+    event OperationResult(bool result);
+
+    EnumerableSet.UintSet private _set;
+
+    function contains(uint256 value) public view returns (bool) {
+        return _set.contains(value);
+    }
+
+    function add(uint256 value) public {
+        bool result = _set.add(value);
+        emit OperationResult(result);
+    }
+
+    function remove(uint256 value) public {
+        bool result = _set.remove(value);
+        emit OperationResult(result);
+    }
+
+    function length() public view returns (uint256) {
+        return _set.length();
+    }
+
+    function at(uint256 index) public view returns (uint256) {
+        return _set.at(index);
+    }
+}

+ 17 - 0
contracts/mocks/EtherReceiverMock.sol

@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+contract EtherReceiverMock {
+    bool private _acceptEther;
+
+    function setAcceptEther(bool acceptEther) public {
+        _acceptEther = acceptEther;
+    }
+
+    receive () external payable {
+        if (!_acceptEther) {
+            revert();
+        }
+    }
+}

+ 20 - 0
contracts/mocks/GSNRecipientERC20FeeMock.sol

@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../GSN/GSNRecipient.sol";
+import "../GSN/GSNRecipientERC20Fee.sol";
+
+contract GSNRecipientERC20FeeMock is GSNRecipient, GSNRecipientERC20Fee {
+    constructor(string memory name, string memory symbol) public GSNRecipientERC20Fee(name, symbol) { }
+
+    function mint(address account, uint256 amount) public {
+        _mint(account, amount);
+    }
+
+    event MockFunctionCalled(uint256 senderBalance);
+
+    function mockFunction() public {
+        emit MockFunctionCalled(token().balanceOf(_msgSender()));
+    }
+}

+ 38 - 0
contracts/mocks/GSNRecipientMock.sol

@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "./ContextMock.sol";
+import "../GSN/GSNRecipient.sol";
+
+// By inheriting from GSNRecipient, Context's internal functions are overridden automatically
+contract GSNRecipientMock is ContextMock, GSNRecipient {
+    function withdrawDeposits(uint256 amount, address payable payee) public {
+        _withdrawDeposits(amount, payee);
+    }
+
+    function acceptRelayedCall(address, address, bytes calldata, uint256, uint256, uint256, uint256, bytes calldata, uint256)
+        external
+        view
+        override
+        returns (uint256, bytes memory)
+    {
+        return (0, "");
+    }
+
+    function _preRelayedCall(bytes memory) internal override returns (bytes32) { }
+
+    function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal override { }
+
+    function upgradeRelayHub(address newRelayHub) public {
+        return _upgradeRelayHub(newRelayHub);
+    }
+
+    function _msgSender() internal override(Context, GSNRecipient) view virtual returns (address payable) {
+        return GSNRecipient._msgSender();
+    }
+
+    function _msgData() internal override(Context, GSNRecipient) view virtual returns (bytes memory) {
+        return GSNRecipient._msgData();
+    }
+}

+ 16 - 0
contracts/mocks/GSNRecipientSignatureMock.sol

@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../GSN/GSNRecipient.sol";
+import "../GSN/GSNRecipientSignature.sol";
+
+contract GSNRecipientSignatureMock is GSNRecipient, GSNRecipientSignature {
+    constructor(address trustedSigner) public GSNRecipientSignature(trustedSigner) { }
+
+    event MockFunctionCalled();
+
+    function mockFunction() public {
+        emit MockFunctionCalled();
+    }
+}

+ 36 - 0
contracts/mocks/InitializableMock.sol

@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../proxy/Initializable.sol";
+
+/**
+ * @title InitializableMock
+ * @dev This contract is a mock to test initializable functionality
+ */
+contract InitializableMock is Initializable {
+
+  bool public initializerRan;
+  uint256 public x;
+
+  function initialize() public initializer {
+    initializerRan = true;
+  }
+
+  function initializeNested() public initializer {
+    initialize();
+  }
+
+  function initializeWithX(uint256 _x) public payable initializer {
+    x = _x;
+  }
+
+  function nonInitializable(uint256 _x) public payable {
+    x = _x;
+  }
+
+  function fail() public pure {
+    require(false, "InitializableMock forced failure");
+  }
+
+}

+ 19 - 0
contracts/mocks/MathMock.sol

@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: MIT
+
+pragma solidity >=0.6.0 <0.8.0;
+
+import "../math/Math.sol";
+
+contract MathMock {
+    function max(uint256 a, uint256 b) public pure returns (uint256) {
+        return Math.max(a, b);
+    }
+
+    function min(uint256 a, uint256 b) public pure returns (uint256) {
+        return Math.min(a, b);
+    }
+
+    function average(uint256 a, uint256 b) public pure returns (uint256) {
+        return Math.average(a, b);
+    }
+}

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است