Commit 8fc99cff by Francisco Giordano

Transpile 4f7fa769

parents
comment: off
github_checks:
annotations: false
coverage:
status:
patch:
default:
target: 95%
project:
default:
threshold: 1%
# 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
{
"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
}
}
*.sol linguist-language=Solidity
---
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. -->
contact_links:
- name: Support request
url: https://forum.openzeppelin.com/c/support/contracts/18
about: Ask the community in the Community Forum
---
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 -->
<!-- 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
name: Merge upstream
on:
workflow_dispatch: {}
schedule:
- cron: '0 10 * * *'
jobs:
update:
runs-on: ubuntu-latest
steps:
- uses: rokroskar/workflow-run-cleanup-action@v0.2.2
env:
GITHUB_TOKEN: ${{github.token}}
- uses: actions/checkout@v2
with:
ref: upstream-patched
fetch-depth: 0
ssh-key: ${{secrets.DEPLOY_KEY}}
- run: bash scripts/upgradeable/git-user-config.sh
- run: bash scripts/upgradeable/merge-upstream.sh
- run: git push
name: Test
on:
push:
branches:
- master
- release-v*
pull_request: {}
workflow_dispatch: {}
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 10.x
- uses: actions/cache@v2
id: cache
with:
path: '**/node_modules'
key: npm-v2-${{ hashFiles('**/package-lock.json') }}
restore-keys: npm-v2-
- run: npm ci
if: steps.cache.outputs.cache-hit != 'true'
- run: bash scripts/upgradeable/transpile.sh
if: github.event_name == 'pull_request'
- run: npm run test
env:
FORCE_COLOR: 1
ENABLE_GAS_REPORT: true
- name: Print gas report
run: cat gas-report.txt
name: Transpile
on:
workflow_dispatch: {}
push:
branches: [upstream-patched]
jobs:
transpile:
runs-on: ubuntu-latest
steps:
- uses: rokroskar/workflow-run-cleanup-action@v0.2.2
env:
GITHUB_TOKEN: ${{github.token}}
- uses: actions/checkout@v2
with:
ref: upstream-patched
fetch-depth: 0
ssh-key: ${{secrets.DEPLOY_KEY}}
- uses: actions/setup-node@v1
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: bash scripts/upgradeable/git-user-config.sh
- run: bash scripts/upgradeable/transpile-onto.sh master origin/master
- run: git push origin master
*.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
# hardhat
cache
artifacts
module.exports = {
timeout: 4000,
};
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,
},
}
{
"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 }]
}
}
This diff is collapsed. Click to expand it.
# 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
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
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.
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.
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.
# <img src="icon.svg" alt="OpenZeppelin" height="40px" align="left"> OpenZeppelin Contracts Upgradeable
[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts/upgradeable)
[![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts-upgradeable.svg)](https://www.npmjs.org/package/@openzeppelin/contracts-upgradeable)
This repository hosts the Upgradeable variant of [OpenZeppelin Contracts], meant for use in upgradeable contracts. This variant is available as separate package called `@openzeppelin/contracts-upgradeable`.
[OpenZeppelin Contracts]: https://github.com/OpenZeppelin/openzeppelin-contracts
It follows all of the rules for [Writing Upgradeable Contracts]: constructors are replaced by initializer functions, state variables are initialized in initializer functions, and we additionally check for storage incompatibilities across minor versions.
[Writing Upgradeable Contracts]: https://docs.openzeppelin.com/upgrades-plugins/writing-upgradeable
> :warning: **Warning**
>
> There will be storage incompatibilities across major versions of this package, which makes it unsafe to upgrade a deployed contract from one major version to another, for example from 3.4.0 to 4.0.0.
>
> Similarly, it is not safe to upgrade from `@openzeppelin/contracts-ethereum-package` (a similar previous package) to `@openzeppelin/contracts-upgradeable`.
>
> **It is strongly encouraged to use these contracts together with a tool that can automatically guarantee the safety of an upgradeable contract, such as the [OpenZeppelin Upgrades Plugins](https://github.com/OpenZeppelin/openzeppelin-upgrades).**
## Overview
### Installation
```console
$ npm install @openzeppelin/contracts-upgradeable
```
### Usage
The package replicates the structure of the main OpenZeppelin Contracts package, but every file and contract has the suffix `Upgradeable`.
```diff
-import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
+import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
-contract MyCollectible is ERC721 {
+contract MyCollectible is ERC721Upgradeable {
```
Constructors are replaced by internal initializer functions following the naming convention `__{ContractName}_init`. Since these are internal, you must always define your own public initializer function and call the parent initializer of the contract you extend.
```diff
- constructor() ERC721("MyCollectible", "MCO") {
+ function initialize() initializer public {
+ __ERC721_init("MyCollectible", "MCO");
}
```
> **Caution**
>
> Use with multiple inheritance requires special care. Initializer functions are not linearized by the compiler like constructors. Because of this, each `__{ContractName}_init` function embeds the linearized calls to all parent initializers. As a consequence, calling two of these `init` functions can potentially initialize the same contract twice.
>
> The function `__{ContractName}_init_unchained` found in every contract is the initializer function minus the calls to parent initializers, and can be used to avoid the double initialization problem, but doing this manually is not recommended. We hope to be able to implement safety checks for this in future versions of the Upgrades Plugins.
_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).
# 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.
# Technical notes about the Upgradeable repository
## [Branches](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/branches)
### `upstream-patched`
Contains a patched version of the vanilla Contracts repo. It adds the scripts to transpile and GitHub Actions for it to work automatically, changes the package name, etc.
Eventually it may also include small changes to the Solidity code, such as reordering of state variables, in order to ensure storage compatibility.
It's an important goal that this branch should be easy to merge with the vanilla Contracts repo, avoiding merge conflicts as much as possible. This is necessary to reduce manual intervention and ensure automation runs smoothly.
### `master`
Contains the actual transpiled code, which is generated automatically based on `upstream-patched`. The contents of this branch should never be manually changed, because they will be overwritten automatically with the transpiled version of `upstream-patched`. Instead, changes should be made in `upstream-patched`.
### `upstream-v3.2.0-patched`, `release-v3.2.0`
I created thes branches in order to release `v3.2.0`, because the `master` branch was already ahead. The first is vanilla v3.2.0 with `upstream-patched` rebased onto it. The second is the transpiled version built using the script shown below.
## [Actions Workflows](https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/actions)
### [Merge upstream](/.github/workflows/merge-upstream.yml)
All this does is fetch the latest changes from vanilla Contracts repo, tries to merge them into `upstream-patched`, and then pushes the updated branch. If the merge has conflicts, the worfklow will fail. We should be notified of this so that we can manually run the merge and resolve the conflicts. This should not happen often.
Runs on a schedule every morning. Can also be triggered manually from the Actions page.
### [Transpile](/.github/workflows/transpile.yml)
Runs every time `upstream-patched` is pushed to (for example as part of the Merge upstream workflow), transpiles the contents of that branch, and pushes the results as a new commit on the `master` branch.
### [Test](/.github/workflows/test.yml)
Runs normal Contracts tests on the `master` and `release-v*` branches.
## Scripts
### `transpile-onto.sh`
```
bash scripts/upgradeable/transpile-onto.sh <target> [base]
```
Transpiles the contents of the current git branch and commits the result as a new commit on branch `<target>`. If branch `<target>` doesn't exist, it will copy the commit history of `[base]` (this is used in GitHub Actions, but is usually not necessary locally).
This script can be used manually to build transpiled versions of specific commits, or branches other than the `master` Contracts branch.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* 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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping (address => bool) 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 Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)));
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 override {
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, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
uint256[49] private __gap;
}
= 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.
== Authorization
{{Ownable}}
{{AccessControl}}
{{AccessControlEnumerable}}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/math/SafeMathUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal initializer {
__Context_init_unchained();
__PaymentSplitter_init_unchained(payees, shares_);
}
function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal initializer {
// solhint-disable-next-line max-line-length
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive () external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = totalReceived * _shares[account] / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
AddressUpgradeable.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
uint256[45] private __gap;
}
= Finance
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/finance
This directory includes primitives for financial systems. We currently only offer the {PaymentSplitter} contract, but we want to grow this directory so we welcome ideas.
== PaymentSplitter
{{PaymentSplitter}}
= Governance
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/governance
This directory includes primitives for on-chain governance. We currently only offer the {TimelockController} contract, that can be used as a component in a governance systems to introduce a delay between a proposal and its execution.
== 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:governance.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:governance.adoc#TimelockController-schedule-address-uint256-bytes-bytes32-bytes32-uint256-[`schedule`] (or xref:api:governance.adoc#TimelockController-scheduleBatch-address---uint256---bytes---bytes32-bytes32-uint256-[`scheduleBatch`]), a proposer moves the operation from the `Unset` to the `Pending` state. This starts a timer that must be longer than the minimum delay. The timer expires at a timestamp accessible through the xref:api:governance.adoc#TimelockController-getTimestamp-bytes32-[`getTimestamp`] method.
* Once the timer expires, the operation automatically gets the `Ready` state. At this point, it can be executed.
* By calling xref:api:governance.adoc#TimelockController-TimelockController-execute-address-uint256-bytes-bytes32-bytes32-[`execute`] (or xref:api:governance.adoc#TimelockController-executeBatch-address---uint256---bytes---bytes32-bytes32-[`executeBatch`]), an executor triggers the operation's underlying transactions and moves it to the `Done` state. If the operation has a predecessor, it has to be in the `Done` state for this transition to succeed.
* xref:api:governance.adoc#TimelockController-TimelockController-cancel-bytes32-[`cancel`] allows proposers to cancel any `Pending` operation. This resets the operation to the `Unset` state. It is thus possible for a proposer to re-schedule an operation that has been cancelled. In this case, the timer restarts when the operation is re-scheduled.
Operations status can be queried using the functions:
* xref:api:governance.adoc#TimelockController-isOperationPending-bytes32-[`isOperationPending(bytes32)`]
* xref:api:governance.adoc#TimelockController-isOperationReady-bytes32-[`isOperationReady(bytes32)`]
* xref:api:governance.adoc#TimelockController-isOperationDone-bytes32-[`isOperationDone(bytes32)`]
[[timelock-roles]]
==== Roles
[[timelock-admin]]
===== Admin
The admins are in charge of managing proposers and executors. For the timelock to be self-governed, this role should only be given to the timelock itself. Upon deployment, both the timelock and the deployer have this role. After further configuration and testing, the deployer can renounce this role such that all further maintenance operations have to go through the timelock process.
This role is identified by the *TIMELOCK_ADMIN_ROLE* value: `0x5f58e3a2316349923ce3780f8d587db2d72378aed66a8261c916544fa6846ca5`
[[timelock-proposer]]
===== Proposer
The proposers are in charge of scheduling (and cancelling) operations. This is a critical role, that should be given to governing entities. This could be an EOA, a multisig, or a DAO.
WARNING: *Proposer fight:* Having multiple proposers, while providing redundancy in case one becomes unavailable, can be dangerous. As proposer have their say on all operations, they could cancel operations they disagree with, including operations to remove them for the proposers.
This role is identified by the *PROPOSER_ROLE* value: `0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1`
[[timelock-executor]]
===== Executor
The executors are in charge of executing the operations scheduled by the proposers once the timelock expires. Logic dictates that multisig or DAO that are proposers should also be executors in order to guarantee operations that have been scheduled will eventually be executed. However, having additional 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.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271Upgradeable {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashBorrowerUpgradeable {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
/**
* @dev Interface of the ERC3156 FlashLender, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*/
interface IERC3156FlashLenderUpgradeable {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/*
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
address _trustedForwarder;
function __ERC2771Context_init(address trustedForwarder) internal initializer {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address trustedForwarder) internal initializer {
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder) public view virtual returns(bool) {
return forwarder == _trustedForwarder;
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) }
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length-20];
} else {
return super._msgData();
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSAUpgradeable.sol";
import "../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/*
* @dev Simple minimal forwarder to be used together with an ERC2771 compatible contract. See {ERC2771Context}.
*/
contract MinimalForwarderUpgradeable is Initializable, EIP712Upgradeable {
using ECDSAUpgradeable for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
bytes32 private constant TYPEHASH = keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)");
mapping(address => uint256) private _nonces;
function __MinimalForwarder_init() internal initializer {
__EIP712_init_unchained("MinimalForwarder", "0.0.1");
__MinimalForwarder_init_unchained();
}
function __MinimalForwarder_init_unchained() internal initializer {}
function getNonce(address from) public view returns (uint256) {
return _nonces[from];
}
function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(keccak256(abi.encode(
TYPEHASH,
req.from,
req.to,
req.value,
req.gas,
req.nonce,
keccak256(req.data)
))).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) {
require(verify(req, signature), "MinimalForwarder: signature does not match request");
_nonces[req.from] = req.nonce + 1;
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from));
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.gas / 63);
return (success, returndata);
}
uint256[49] private __gap;
}
= Meta Transactions
[.readme-notice]
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/metatx
== Core
{{ERC2771Context}}
== Utils
{{MinimalForwarder}}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControlEnumerableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract AccessControlEnumerableMockUpgradeable is Initializable, AccessControlEnumerableUpgradeable {
function __AccessControlEnumerableMock_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__AccessControlEnumerableMock_init_unchained();
}
function __AccessControlEnumerableMock_init_unchained() internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public {
_setRoleAdmin(roleId, adminRoleId);
}
function senderProtected(bytes32 roleId) public onlyRole(roleId) {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/AccessControlUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract AccessControlMockUpgradeable is Initializable, AccessControlUpgradeable {
function __AccessControlMock_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlMock_init_unchained();
}
function __AccessControlMock_init_unchained() internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public {
_setRoleAdmin(roleId, adminRoleId);
}
function senderProtected(bytes32 roleId) public onlyRole(roleId) {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract AddressImplUpgradeable is Initializable {
function __AddressImpl_init() internal initializer {
__AddressImpl_init_unchained();
}
function __AddressImpl_init_unchained() internal initializer {
}
string public sharedAnswer;
event CallReturnValue(string data);
function isContract(address account) external view returns (bool) {
return AddressUpgradeable.isContract(account);
}
function sendValue(address payable receiver, uint256 amount) external {
AddressUpgradeable.sendValue(receiver, amount);
}
function functionCall(address target, bytes calldata data) external {
bytes memory returnData = AddressUpgradeable.functionCall(target, data);
emit CallReturnValue(abi.decode(returnData, (string)));
}
function functionCallWithValue(address target, bytes calldata data, uint256 value) external payable {
bytes memory returnData = AddressUpgradeable.functionCallWithValue(target, data, value);
emit CallReturnValue(abi.decode(returnData, (string)));
}
function functionStaticCall(address target, bytes calldata data) external {
bytes memory returnData = AddressUpgradeable.functionStaticCall(target, data);
emit CallReturnValue(abi.decode(returnData, (string)));
}
// sendValue's tests require the contract to hold Ether
receive () external payable { }
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ArraysUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ArraysImplUpgradeable is Initializable {
using ArraysUpgradeable for uint256[];
uint256[] private _array;
function __ArraysImpl_init(uint256[] memory array) internal initializer {
__ArraysImpl_init_unchained(array);
}
function __ArraysImpl_init_unchained(uint256[] memory array) internal initializer {
_array = array;
}
function findUpperBound(uint256 element) external view returns (uint256) {
return _array.findUpperBound(element);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
contract BadBeaconNoImplUpgradeable is Initializable {
function __BadBeaconNoImpl_init() internal initializer {
__BadBeaconNoImpl_init_unchained();
}
function __BadBeaconNoImpl_init_unchained() internal initializer {
}
uint256[50] private __gap;
}
contract BadBeaconNotContractUpgradeable is Initializable {
function __BadBeaconNotContract_init() internal initializer {
__BadBeaconNotContract_init_unchained();
}
function __BadBeaconNotContract_init_unchained() internal initializer {
}
function implementation() external pure returns (address) {
return address(0x1);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
contract CallReceiverMockUpgradeable is Initializable {
function __CallReceiverMock_init() internal initializer {
__CallReceiverMock_init_unchained();
}
function __CallReceiverMock_init_unchained() internal initializer {
}
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";
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ClashingImplementationUpgradeable is Initializable {
function __ClashingImplementation_init() internal initializer {
__ClashingImplementation_init_unchained();
}
function __ClashingImplementation_init_unchained() internal initializer {
}
function admin() external pure returns (address) {
return 0x0000000000000000000000000000000011111142;
}
function delegatedFunction() external pure returns (bool) {
return true;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/ClonesUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ClonesMockUpgradeable is Initializable {
function __ClonesMock_init() internal initializer {
__ClonesMock_init_unchained();
}
function __ClonesMock_init_unchained() internal initializer {
}
using AddressUpgradeable for address;
using ClonesUpgradeable for address;
event NewInstance(address instance);
function clone(address implementation, bytes calldata initdata) public payable {
_initAndEmit(implementation.clone(), initdata);
}
function cloneDeterministic(address implementation, bytes32 salt, bytes calldata initdata) public payable {
_initAndEmit(implementation.cloneDeterministic(salt), initdata);
}
function predictDeterministicAddress(address implementation, bytes32 salt) public view returns (address predicted) {
return implementation.predictDeterministicAddress(salt);
}
function _initAndEmit(address instance, bytes memory initdata) private {
if (initdata.length > 0) {
instance.functionCallWithValue(initdata, msg.value);
}
emit NewInstance(instance);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/escrow/ConditionalEscrowUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
// mock class using ConditionalEscrow
contract ConditionalEscrowMockUpgradeable is Initializable, ConditionalEscrowUpgradeable {
function __ConditionalEscrowMock_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Escrow_init_unchained();
__ConditionalEscrow_init_unchained();
__ConditionalEscrowMock_init_unchained();
}
function __ConditionalEscrowMock_init_unchained() internal initializer {
}
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];
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ContextMockUpgradeable is Initializable, ContextUpgradeable {
function __ContextMock_init() internal initializer {
__Context_init_unchained();
__ContextMock_init_unchained();
}
function __ContextMock_init_unchained() internal initializer {
}
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);
}
uint256[50] private __gap;
}
contract ContextMockCallerUpgradeable is Initializable {
function __ContextMockCaller_init() internal initializer {
__ContextMockCaller_init_unchained();
}
function __ContextMockCaller_init_unchained() internal initializer {
}
function callSender(ContextMockUpgradeable context) public {
context.msgSender();
}
function callData(ContextMockUpgradeable context, uint256 integerValue, string memory stringValue) public {
context.msgData(integerValue, stringValue);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/CountersUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract CountersImplUpgradeable is Initializable {
function __CountersImpl_init() internal initializer {
__CountersImpl_init_unchained();
}
function __CountersImpl_init_unchained() internal initializer {
}
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _counter;
function current() public view returns (uint256) {
return _counter.current();
}
function increment() public {
_counter.increment();
}
function decrement() public {
_counter.decrement();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Create2Upgradeable.sol";
import "../utils/introspection/ERC1820ImplementerUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract Create2ImplUpgradeable is Initializable {
function __Create2Impl_init() internal initializer {
__Create2Impl_init_unchained();
}
function __Create2Impl_init_unchained() internal initializer {
}
function deploy(uint256 value, bytes32 salt, bytes memory code) public {
Create2Upgradeable.deploy(value, salt, code);
}
function deployERC1820Implementer(uint256 value, bytes32 salt) public {
// solhint-disable-next-line indent
Create2Upgradeable.deploy(value, salt, type(ERC1820ImplementerUpgradeable).creationCode);
}
function computeAddress(bytes32 salt, bytes32 codeHash) public view returns (address) {
return Create2Upgradeable.computeAddress(salt, codeHash);
}
function computeAddressWithDeployer(bytes32 salt, bytes32 codeHash, address deployer) public pure returns (address) {
return Create2Upgradeable.computeAddress(salt, codeHash, deployer);
}
receive() external payable {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
abstract contract ImplUpgradeable is Initializable {
function __Impl_init() internal initializer {
__Impl_init_unchained();
}
function __Impl_init_unchained() internal initializer {
}
function version() public pure virtual returns (string memory);
uint256[50] private __gap;
}
contract DummyImplementationUpgradeable is Initializable {
function __DummyImplementation_init() internal initializer {
__DummyImplementation_init_unchained();
}
function __DummyImplementation_init_unchained() internal initializer {
}
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");
}
uint256[47] private __gap;
}
contract DummyImplementationV2Upgradeable is Initializable, DummyImplementationUpgradeable {
function __DummyImplementationV2_init() internal initializer {
__DummyImplementation_init_unchained();
__DummyImplementationV2_init_unchained();
}
function __DummyImplementationV2_init_unchained() internal initializer {
}
function migrate(uint256 newVal) public payable {
value = newVal;
}
function version() public pure override returns (string memory) {
return "V2";
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSAUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ECDSAMockUpgradeable is Initializable {
function __ECDSAMock_init() internal initializer {
__ECDSAMock_init_unchained();
}
function __ECDSAMock_init_unchained() internal initializer {
}
using ECDSAUpgradeable 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();
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../utils/cryptography/ECDSAUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract EIP712ExternalUpgradeable is Initializable, EIP712Upgradeable {
function __EIP712External_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
__EIP712External_init_unchained(name, version);
}
function __EIP712External_init_unchained(string memory name, string memory version) internal initializer {}
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 = ECDSAUpgradeable.recover(digest, signature);
require(recoveredSigner == signer);
}
function getChainId() external view returns (uint256) {
return block.chainid;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/extensions/ERC1155BurnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC1155BurnableMockUpgradeable is Initializable, ERC1155BurnableUpgradeable {
function __ERC1155BurnableMock_init(string memory uri) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri);
__ERC1155Burnable_init_unchained();
__ERC1155BurnableMock_init_unchained(uri);
}
function __ERC1155BurnableMock_init_unchained(string memory uri) internal initializer { }
function mint(address to, uint256 id, uint256 value, bytes memory data) public {
_mint(to, id, value, data);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/ERC1155Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title ERC1155Mock
* This mock just publicizes internal functions for testing purposes
*/
contract ERC1155MockUpgradeable is Initializable, ERC1155Upgradeable {
function __ERC1155Mock_init(string memory uri) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri);
__ERC1155Mock_init_unchained(uri);
}
function __ERC1155Mock_init_unchained(string memory uri) internal initializer {
// 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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155MockUpgradeable.sol";
import "../token/ERC1155/extensions/ERC1155PausableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC1155PausableMockUpgradeable is Initializable, ERC1155MockUpgradeable, ERC1155PausableUpgradeable {
function __ERC1155PausableMock_init(string memory uri) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri);
__ERC1155Mock_init_unchained(uri);
__Pausable_init_unchained();
__ERC1155Pausable_init_unchained();
__ERC1155PausableMock_init_unchained(uri);
}
function __ERC1155PausableMock_init_unchained(string memory uri) internal initializer { }
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(ERC1155Upgradeable, ERC1155PausableUpgradeable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC1155ReceiverMockUpgradeable is Initializable, IERC1155ReceiverUpgradeable, ERC165Upgradeable {
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);
function __ERC1155ReceiverMock_init(
bytes4 recRetval,
bool recReverts,
bytes4 batRetval,
bool batReverts
) internal initializer {
__ERC165_init_unchained();
__ERC1155ReceiverMock_init_unchained(recRetval, recReverts, batRetval, batReverts);
}
function __ERC1155ReceiverMock_init_unchained(
bytes4 recRetval,
bool recReverts,
bytes4 batRetval,
bool batReverts
) internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/OwnableUpgradeable.sol";
import "../interfaces/IERC1271Upgradeable.sol";
import "../utils/cryptography/ECDSAUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC1271WalletMockUpgradeable is Initializable, OwnableUpgradeable, IERC1271Upgradeable {
function __ERC1271WalletMock_init(address originalOwner) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC1271WalletMock_init_unchained(originalOwner);
}
function __ERC1271WalletMock_init_unchained(address originalOwner) internal initializer {
transferOwnership(originalOwner);
}
function isValidSignature(bytes32 hash, bytes memory signature) public view override returns (bytes4 magicValue) {
return ECDSAUpgradeable.recover(hash, signature) == owner() ? this.isValidSignature.selector : bytes4(0);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 SupportsInterfaceWithLookupMockUpgradeable is Initializable, IERC165Upgradeable {
/*
* 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.
*/
function __SupportsInterfaceWithLookupMock_init() internal initializer {
__SupportsInterfaceWithLookupMock_init_unchained();
}
function __SupportsInterfaceWithLookupMock_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
contract ERC165InterfacesSupportedUpgradeable is Initializable, SupportsInterfaceWithLookupMockUpgradeable {
function __ERC165InterfacesSupported_init(bytes4[] memory interfaceIds) internal initializer {
__SupportsInterfaceWithLookupMock_init_unchained();
__ERC165InterfacesSupported_init_unchained(interfaceIds);
}
function __ERC165InterfacesSupported_init_unchained(bytes4[] memory interfaceIds) internal initializer {
for (uint256 i = 0; i < interfaceIds.length; i++) {
_registerInterface(interfaceIds[i]);
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../proxy/utils/Initializable.sol";
contract ERC165MissingDataUpgradeable is Initializable {
function __ERC165MissingData_init() internal initializer {
__ERC165MissingData_init_unchained();
}
function __ERC165MissingData_init_unchained() internal initializer {
}
function supportsInterface(bytes4 interfaceId) public view {} // missing return
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../proxy/utils/Initializable.sol";
contract ERC165NotSupportedUpgradeable is Initializable { function __ERC165NotSupported_init() internal initializer {
__ERC165NotSupported_init_unchained();
}
function __ERC165NotSupported_init_unchained() internal initializer {
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165CheckerUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC165CheckerMockUpgradeable is Initializable {
function __ERC165CheckerMock_init() internal initializer {
__ERC165CheckerMock_init_unchained();
}
function __ERC165CheckerMock_init_unchained() internal initializer {
}
using ERC165CheckerUpgradeable 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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC165MockUpgradeable is Initializable, ERC165Upgradeable {
function __ERC165Mock_init() internal initializer {
__ERC165_init_unchained();
__ERC165Mock_init_unchained();
}
function __ERC165Mock_init_unchained() internal initializer {
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165StorageUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC165StorageMockUpgradeable is Initializable, ERC165StorageUpgradeable {
function __ERC165StorageMock_init() internal initializer {
__ERC165_init_unchained();
__ERC165Storage_init_unchained();
__ERC165StorageMock_init_unchained();
}
function __ERC165StorageMock_init_unchained() internal initializer {
}
function registerInterface(bytes4 interfaceId) public {
_registerInterface(interfaceId);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/ERC1820ImplementerUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC1820ImplementerMockUpgradeable is Initializable, ERC1820ImplementerUpgradeable {
function __ERC1820ImplementerMock_init() internal initializer {
__ERC1820Implementer_init_unchained();
__ERC1820ImplementerMock_init_unchained();
}
function __ERC1820ImplementerMock_init_unchained() internal initializer {
}
function registerInterfaceForAddress(bytes32 interfaceHash, address account) public {
_registerInterfaceForAddress(interfaceHash, account);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20BurnableMockUpgradeable is Initializable, ERC20BurnableUpgradeable {
function __ERC20BurnableMock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__ERC20BurnableMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20BurnableMock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_mint(initialAccount, initialBalance);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20CappedUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20CappedMockUpgradeable is Initializable, ERC20CappedUpgradeable {
function __ERC20CappedMock_init(string memory name, string memory symbol, uint256 cap) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Capped_init_unchained(cap);
__ERC20CappedMock_init_unchained(name, symbol, cap);
}
function __ERC20CappedMock_init_unchained(string memory name, string memory symbol, uint256 cap) internal initializer { }
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/ERC20Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20DecimalsMockUpgradeable is Initializable, ERC20Upgradeable {
uint8 private _decimals;
function __ERC20DecimalsMock_init(string memory name_, string memory symbol_, uint8 decimals_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
__ERC20DecimalsMock_init_unchained(name_, symbol_, decimals_);
}
function __ERC20DecimalsMock_init_unchained(string memory name_, string memory symbol_, uint8 decimals_) internal initializer {
_decimals = decimals_;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/ERC20Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
// mock class using ERC20
contract ERC20MockUpgradeable is Initializable, ERC20Upgradeable {
function __ERC20Mock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Mock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20Mock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
// mock class using ERC20Pausable
contract ERC20PausableMockUpgradeable is Initializable, ERC20PausableUpgradeable {
function __ERC20PausableMock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PausableMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20PausableMock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20PermitMockUpgradeable is Initializable, ERC20PermitUpgradeable {
function __ERC20PermitMock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
__ERC20PermitMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20PermitMock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_mint(initialAccount, initialBalance);
}
function getChainId() external view returns (uint256) {
return block.chainid;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20SnapshotMockUpgradeable is Initializable, ERC20SnapshotUpgradeable {
function __ERC20SnapshotMock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Snapshot_init_unchained();
__ERC20SnapshotMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20SnapshotMock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ContextMockUpgradeable.sol";
import "../metatx/ERC2771ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
// By inheriting from ERC2771Context, Context's internal functions are overridden automatically
contract ERC2771ContextMockUpgradeable is Initializable, ContextMockUpgradeable, ERC2771ContextUpgradeable {
function __ERC2771ContextMock_init(address trustedForwarder) internal initializer {
__Context_init_unchained();
__ContextMock_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
__ERC2771ContextMock_init_unchained(trustedForwarder);
}
function __ERC2771ContextMock_init_unchained(address trustedForwarder) internal initializer {}
function _msgSender() internal override(ContextUpgradeable, ERC2771ContextUpgradeable) view virtual returns (address) {
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData() internal override(ContextUpgradeable, ERC2771ContextUpgradeable) view virtual returns (bytes calldata) {
return ERC2771ContextUpgradeable._msgData();
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC3156Upgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev WARNING: this IERC3156FlashBorrower mock implementation is for testing purposes ONLY.
* Writing a secure flash lock borrower is not an easy task, and should be done with the utmost care.
* This is not an example of how it should be done, and no pattern present in this mock should be considered secure.
* Following best practices, always have your contract properly audited before using them to manipulate important funds on
* live networks.
*/
contract ERC3156FlashBorrowerMockUpgradeable is Initializable, IERC3156FlashBorrowerUpgradeable {
bytes32 constant internal RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
bool _enableApprove;
bool _enableReturn;
event BalanceOf(address token, address account, uint256 value);
event TotalSupply(address token, uint256 value);
function __ERC3156FlashBorrowerMock_init(bool enableReturn, bool enableApprove) internal initializer {
__ERC3156FlashBorrowerMock_init_unchained(enableReturn, enableApprove);
}
function __ERC3156FlashBorrowerMock_init_unchained(bool enableReturn, bool enableApprove) internal initializer {
_enableApprove = enableApprove;
_enableReturn = enableReturn;
}
function onFlashLoan(
address /*initiator*/,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) public override returns (bytes32) {
require(msg.sender == token);
emit BalanceOf(token, address(this), IERC20Upgradeable(token).balanceOf(address(this)));
emit TotalSupply(token, IERC20Upgradeable(token).totalSupply());
if (data.length > 0) {
// WARNING: This code is for testing purposes only! Do not use.
AddressUpgradeable.functionCall(token, data);
}
if (_enableApprove) {
IERC20Upgradeable(token).approve(token, amount + fee);
}
return _enableReturn ? RETURN_VALUE : bytes32(0);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/extensions/draft-ERC20FlashMintUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC20FlashMintMockUpgradeable is Initializable, ERC20FlashMintUpgradeable {
function __ERC20FlashMintMock_init(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20FlashMint_init_unchained();
__ERC20FlashMintMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20FlashMintMock_init_unchained(
string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance
) internal initializer {
_mint(initialAccount, initialBalance);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC721BurnableMockUpgradeable is Initializable, ERC721BurnableUpgradeable {
function __ERC721BurnableMock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
__ERC721Burnable_init_unchained();
__ERC721BurnableMock_init_unchained(name, symbol);
}
function __ERC721BurnableMock_init_unchained(string memory name, string memory symbol) internal initializer { }
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title ERC721Mock
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721EnumerableMockUpgradeable is Initializable, ERC721EnumerableUpgradeable {
string private _baseTokenURI;
function __ERC721EnumerableMock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
__ERC721Enumerable_init_unchained();
__ERC721EnumerableMock_init_unchained(name, symbol);
}
function __ERC721EnumerableMock_init_unchained(string memory name, string memory symbol) internal initializer { }
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata newBaseTokenURI) public {
_baseTokenURI = newBaseTokenURI;
}
function baseURI() public view returns (string memory) {
return _baseURI();
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/ERC721Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title ERC721Mock
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721MockUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721Mock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
__ERC721Mock_init_unchained(name, symbol);
}
function __ERC721Mock_init_unchained(string memory name, string memory symbol) internal initializer { }
function baseURI() public view returns (string memory) {
return _baseURI();
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/ERC721PausableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title ERC721PausableMock
* This mock just provides a public mint, burn and exists functions for testing purposes
*/
contract ERC721PausableMockUpgradeable is Initializable, ERC721PausableUpgradeable {
function __ERC721PausableMock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
__ERC721PausableMock_init_unchained(name, symbol);
}
function __ERC721PausableMock_init_unchained(string memory name, string memory symbol) internal initializer { }
function pause() external {
_pause();
}
function unpause() external {
_unpause();
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721ReceiverUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC721ReceiverMockUpgradeable is Initializable, IERC721ReceiverUpgradeable {
enum Error {
None,
RevertWithMessage,
RevertWithoutMessage,
Panic
}
bytes4 private _retval;
Error private _error;
event Received(address operator, address from, uint256 tokenId, bytes data, uint256 gas);
function __ERC721ReceiverMock_init(bytes4 retval, Error error) internal initializer {
__ERC721ReceiverMock_init_unchained(retval, error);
}
function __ERC721ReceiverMock_init_unchained(bytes4 retval, Error error) internal initializer {
_retval = retval;
_error = error;
}
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public override returns (bytes4)
{
if (_error == Error.RevertWithMessage) {
revert("ERC721ReceiverMock: reverting");
} else if (_error == Error.RevertWithoutMessage) {
revert();
} else if (_error == Error.Panic) {
uint256 a = uint256(0) / uint256(0);
a;
}
emit Received(operator, from, tokenId, data, gasleft());
return _retval;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @title ERC721Mock
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721URIStorageMockUpgradeable is Initializable, ERC721URIStorageUpgradeable {
string private _baseTokenURI;
function __ERC721URIStorageMock_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
__ERC721URIStorage_init_unchained();
__ERC721URIStorageMock_init_unchained(name, symbol);
}
function __ERC721URIStorageMock_init_unchained(string memory name, string memory symbol) internal initializer { }
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata newBaseTokenURI) public {
_baseTokenURI = newBaseTokenURI;
}
function baseURI() public view returns (string memory) {
return _baseURI();
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
_setTokenURI(tokenId, _tokenURI);
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../token/ERC777/ERC777Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC777MockUpgradeable is Initializable, ContextUpgradeable, ERC777Upgradeable {
event BeforeTokenTransfer();
function __ERC777Mock_init(
address initialHolder,
uint256 initialBalance,
string memory name,
string memory symbol,
address[] memory defaultOperators
) internal initializer {
__Context_init_unchained();
__ERC777_init_unchained(name, symbol, defaultOperators);
__ERC777Mock_init_unchained(initialHolder, initialBalance, name, symbol, defaultOperators);
}
function __ERC777Mock_init_unchained(
address initialHolder,
uint256 initialBalance,
string memory name,
string memory symbol,
address[] memory defaultOperators
) internal initializer {
_mint(initialHolder, initialBalance, "", "");
}
function mintInternal (
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) public {
_mint(to, amount, userData, operatorData);
}
function mintInternalExtended (
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) public {
_mint(to, amount, userData, operatorData, requireReceptionAck);
}
function approveInternal(address holder, address spender, uint256 value) public {
_approve(holder, spender, value);
}
function _beforeTokenTransfer(address, address, address, uint256) internal override {
emit BeforeTokenTransfer();
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC777/IERC777Upgradeable.sol";
import "../token/ERC777/IERC777SenderUpgradeable.sol";
import "../token/ERC777/IERC777RecipientUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/introspection/IERC1820RegistryUpgradeable.sol";
import "../utils/introspection/ERC1820ImplementerUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ERC777SenderRecipientMockUpgradeable is Initializable, ContextUpgradeable, IERC777SenderUpgradeable, IERC777RecipientUpgradeable, ERC1820ImplementerUpgradeable {
function __ERC777SenderRecipientMock_init() internal initializer {
__Context_init_unchained();
__ERC1820Implementer_init_unchained();
__ERC777SenderRecipientMock_init_unchained();
}
function __ERC777SenderRecipientMock_init_unchained() internal initializer {
_erc1820 = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
}
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;
IERC1820RegistryUpgradeable private _erc1820;
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();
}
IERC777Upgradeable token = IERC777Upgradeable(_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();
}
IERC777Upgradeable token = IERC777Upgradeable(_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(IERC777Upgradeable 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(IERC777Upgradeable token, uint256 amount, bytes memory data) public {
token.burn(amount, data);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/structs/EnumerableMapUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract EnumerableMapMockUpgradeable is Initializable {
function __EnumerableMapMock_init() internal initializer {
__EnumerableMapMock_init_unchained();
}
function __EnumerableMapMock_init_unchained() internal initializer {
}
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
event OperationResult(bool result);
EnumerableMapUpgradeable.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);
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
// Bytes32Set
contract EnumerableBytes32SetMockUpgradeable is Initializable {
function __EnumerableBytes32SetMock_init() internal initializer {
__EnumerableBytes32SetMock_init_unchained();
}
function __EnumerableBytes32SetMock_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set;
event OperationResult(bool result);
EnumerableSetUpgradeable.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);
}
uint256[48] private __gap;
}
// AddressSet
contract EnumerableAddressSetMockUpgradeable is Initializable {
function __EnumerableAddressSetMock_init() internal initializer {
__EnumerableAddressSetMock_init_unchained();
}
function __EnumerableAddressSetMock_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
event OperationResult(bool result);
EnumerableSetUpgradeable.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);
}
uint256[48] private __gap;
}
// UintSet
contract EnumerableUintSetMockUpgradeable is Initializable {
function __EnumerableUintSetMock_init() internal initializer {
__EnumerableUintSetMock_init_unchained();
}
function __EnumerableUintSetMock_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
event OperationResult(bool result);
EnumerableSetUpgradeable.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);
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
contract EtherReceiverMockUpgradeable is Initializable {
function __EtherReceiverMock_init() internal initializer {
__EtherReceiverMock_init_unchained();
}
function __EtherReceiverMock_init_unchained() internal initializer {
}
bool private _acceptEther;
function setAcceptEther(bool acceptEther) public {
_acceptEther = acceptEther;
}
receive () external payable {
if (!_acceptEther) {
revert();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/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");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/math/MathUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract MathMockUpgradeable is Initializable {
function __MathMock_init() internal initializer {
__MathMock_init_unchained();
}
function __MathMock_init_unchained() internal initializer {
}
function max(uint256 a, uint256 b) public pure returns (uint256) {
return MathUpgradeable.max(a, b);
}
function min(uint256 a, uint256 b) public pure returns (uint256) {
return MathUpgradeable.min(a, b);
}
function average(uint256 a, uint256 b) public pure returns (uint256) {
return MathUpgradeable.average(a, b);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/cryptography/MerkleProofUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract MerkleProofWrapperUpgradeable is Initializable {
function __MerkleProofWrapper_init() internal initializer {
__MerkleProofWrapper_init_unchained();
}
function __MerkleProofWrapper_init_unchained() internal initializer {
}
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) public pure returns (bool) {
return MerkleProofUpgradeable.verify(proof, root, leaf);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./MulticallTokenMockUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract MulticallTestUpgradeable is Initializable {
function __MulticallTest_init() internal initializer {
__MulticallTest_init_unchained();
}
function __MulticallTest_init_unchained() internal initializer {
}
function testReturnValues(MulticallTokenMockUpgradeable multicallToken, address[] calldata recipients, uint256[] calldata amounts) external {
bytes[] memory calls = new bytes[](recipients.length);
for (uint i = 0; i < recipients.length; i++) {
calls[i] = abi.encodeWithSignature("transfer(address,uint256)", recipients[i], amounts[i]);
}
bytes[] memory results = multicallToken.multicall(calls);
for (uint i = 0; i < results.length; i++) {
require(abi.decode(results[i], (bool)));
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/MulticallUpgradeable.sol";
import "./ERC20MockUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract MulticallTokenMockUpgradeable is Initializable, ERC20MockUpgradeable, MulticallUpgradeable {
function __MulticallTokenMock_init(uint256 initialBalance) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained("MulticallToken", "BCT");
__ERC20Mock_init_unchained("MulticallToken", "BCT", msg.sender, initialBalance);
__Multicall_init_unchained();
__MulticallTokenMock_init_unchained(initialBalance);
}
function __MulticallTokenMock_init_unchained(uint256 initialBalance) internal initializer {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
// Sample contracts showing upgradeability with multiple inheritance.
// Child contract inherits from Father and Mother contracts, and Father extends from Gramps.
//
// Human
// / \
// | Gramps
// | |
// Mother Father
// | |
// -- Child --
/**
* Sample base intializable contract that is a human
*/
contract SampleHuman is Initializable {
bool public isHuman;
function initialize() public initializer {
isHuman = true;
}
}
/**
* Sample base intializable contract that defines a field mother
*/
contract SampleMother is Initializable, SampleHuman {
uint256 public mother;
function initialize(uint256 value) public initializer virtual {
SampleHuman.initialize();
mother = value;
}
}
/**
* Sample base intializable contract that defines a field gramps
*/
contract SampleGramps is Initializable, SampleHuman {
string public gramps;
function initialize(string memory value) public initializer virtual {
SampleHuman.initialize();
gramps = value;
}
}
/**
* Sample base intializable contract that defines a field father and extends from gramps
*/
contract SampleFather is Initializable, SampleGramps {
uint256 public father;
function initialize(string memory _gramps, uint256 _father) public initializer {
SampleGramps.initialize(_gramps);
father = _father;
}
}
/**
* Child extends from mother, father (gramps)
*/
contract SampleChild is Initializable, SampleMother, SampleFather {
uint256 public child;
function initialize(uint256 _mother, string memory _gramps, uint256 _father, uint256 _child) public initializer {
SampleMother.initialize(_mother);
SampleFather.initialize(_gramps, _father);
child = _child;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../access/OwnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract OwnableMockUpgradeable is Initializable, OwnableUpgradeable { function __OwnableMock_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__OwnableMock_init_unchained();
}
function __OwnableMock_init_unchained() internal initializer {
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../security/PausableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract PausableMockUpgradeable is Initializable, PausableUpgradeable {
bool public drasticMeasureTaken;
uint256 public count;
function __PausableMock_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__PausableMock_init_unchained();
}
function __PausableMock_init_unchained() internal initializer {
drasticMeasureTaken = false;
count = 0;
}
function normalProcess() external whenNotPaused {
count++;
}
function drasticMeasure() external whenPaused {
drasticMeasureTaken = true;
}
function pause() external {
_pause();
}
function unpause() external {
_unpause();
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../security/PullPaymentUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
// mock class using PullPayment
contract PullPaymentMockUpgradeable is Initializable, PullPaymentUpgradeable {
function __PullPaymentMock_init() internal initializer {
__PullPayment_init_unchained();
__PullPaymentMock_init_unchained();
}
function __PullPaymentMock_init_unchained() internal initializer { }
// test helper function to call asyncTransfer
function callTransfer(address dest, uint256 amount) public {
_asyncTransfer(dest, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ReentrancyAttackUpgradeable is Initializable, ContextUpgradeable {
function __ReentrancyAttack_init() internal initializer {
__Context_init_unchained();
__ReentrancyAttack_init_unchained();
}
function __ReentrancyAttack_init_unchained() internal initializer {
}
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = _msgSender().call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../security/ReentrancyGuardUpgradeable.sol";
import "./ReentrancyAttackUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract ReentrancyMockUpgradeable is Initializable, ReentrancyGuardUpgradeable {
uint256 public counter;
function __ReentrancyMock_init() internal initializer {
__ReentrancyGuard_init_unchained();
__ReentrancyMock_init_unchained();
}
function __ReentrancyMock_init_unchained() internal initializer {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countAndCall(ReentrancyAttackUpgradeable attacker) public nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function _count() private {
counter += 1;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
contract Implementation1 is Initializable {
uint internal _value;
function initialize() public initializer {
}
function setValue(uint _number) public {
_value = _number;
}
}
contract Implementation2 is Initializable {
uint internal _value;
function initialize() public initializer {
}
function setValue(uint _number) public {
_value = _number;
}
function getValue() public view returns (uint) {
return _value;
}
}
contract Implementation3 is Initializable {
uint internal _value;
function initialize() public initializer {
}
function setValue(uint _number) public {
_value = _number;
}
function getValue(uint _number) public view returns (uint) {
return _value + _number;
}
}
contract Implementation4 is Initializable {
uint internal _value;
function initialize() public initializer {
}
function setValue(uint _number) public {
_value = _number;
}
function getValue() public view returns (uint) {
return _value;
}
// solhint-disable-next-line payable-fallback
fallback() external {
_value = 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/math/SafeCastUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
contract SafeCastMockUpgradeable is Initializable {
function __SafeCastMock_init() internal initializer {
__SafeCastMock_init_unchained();
}
function __SafeCastMock_init_unchained() internal initializer {
}
using SafeCastUpgradeable for uint;
using SafeCastUpgradeable for int;
function toUint256(int a) public pure returns (uint256) {
return a.toUint256();
}
function toInt256(uint a) public pure returns (int256) {
return a.toInt256();
}
function toUint128(uint a) public pure returns (uint128) {
return a.toUint128();
}
function toUint64(uint a) public pure returns (uint64) {
return a.toUint64();
}
function toUint32(uint a) public pure returns (uint32) {
return a.toUint32();
}
function toUint16(uint a) public pure returns (uint16) {
return a.toUint16();
}
function toUint8(uint a) public pure returns (uint8) {
return a.toUint8();
}
function toInt128(int a) public pure returns (int128) {
return a.toInt128();
}
function toInt64(int a) public pure returns (int64) {
return a.toInt64();
}
function toInt32(int a) public pure returns (int32) {
return a.toInt32();
}
function toInt16(int a) public pure returns (int16) {
return a.toInt16();
}
function toInt8(int a) public pure returns (int8) {
return a.toInt8();
}
uint256[50] private __gap;
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment