Repository: 0xNazgul/fuzzydefi
Branch: main
Commit: 89553188217c
Files: 196
Total size: 1.4 MB
Directory structure:
gitextract_drv2awpe/
├── CONTRIBUTING.md
├── LICENSE
├── PROPERTIES.md
├── README.md
├── package.json
└── protocols/
├── compound-v2/
│ ├── .gitignore
│ ├── .gitmodules
│ ├── LICENSE
│ ├── README.md
│ ├── foundry.toml
│ ├── package.json
│ ├── remappings.txt
│ ├── script/
│ │ └── Counter.s.sol
│ ├── src/
│ │ ├── BaseJumpRateModelV2.sol
│ │ ├── CDaiDelegate.sol
│ │ ├── CErc20.sol
│ │ ├── CErc20Delegate.sol
│ │ ├── CErc20Delegator.sol
│ │ ├── CErc20Immutable.sol
│ │ ├── CEther.sol
│ │ ├── CToken.sol
│ │ ├── CTokenInterfaces.sol
│ │ ├── Comptroller.sol
│ │ ├── ComptrollerG7.sol
│ │ ├── ComptrollerInterface.sol
│ │ ├── ComptrollerStorage.sol
│ │ ├── DAIInterestRateModelV3.sol
│ │ ├── EIP20Interface.sol
│ │ ├── EIP20NonStandardInterface.sol
│ │ ├── ErrorReporter.sol
│ │ ├── ExponentialNoError.sol
│ │ ├── Governance/
│ │ │ ├── Comp.sol
│ │ │ ├── GovernorAlpha.sol
│ │ │ ├── GovernorBravoDelegate.sol
│ │ │ ├── GovernorBravoDelegateG1.sol
│ │ │ ├── GovernorBravoDelegateG2.sol
│ │ │ ├── GovernorBravoDelegator.sol
│ │ │ └── GovernorBravoInterfaces.sol
│ │ ├── InterestRateModel.sol
│ │ ├── JumpRateModel.sol
│ │ ├── JumpRateModelV2.sol
│ │ ├── Lens/
│ │ │ └── CompoundLens.sol
│ │ ├── Maximillion.sol
│ │ ├── PriceOracle.sol
│ │ ├── Reservoir.sol
│ │ ├── SafeMath.sol
│ │ ├── SimplePriceOracle.sol
│ │ ├── Timelock.sol
│ │ ├── Unitroller.sol
│ │ └── WhitePaperInterestRateModel.sol
│ └── test/
│ ├── core.t.sol
│ └── mocks/
│ └── ERC20.sol
├── olympus-v1/
│ ├── .gitignore
│ ├── .gitmodules
│ ├── LICENSE
│ ├── README.md
│ ├── foundry.toml
│ ├── package.json
│ ├── remappings.txt
│ ├── script/
│ │ └── Counter.s.sol
│ ├── src/
│ │ ├── BondDepository.sol
│ │ ├── CVXBondDepository.sol
│ │ ├── OlympusERC20.sol
│ │ ├── RedeemHelper.sol
│ │ ├── RiskFreeValueOfNonReserve.sol
│ │ ├── Staking.sol
│ │ ├── StakingDistributor.sol
│ │ ├── StakingHelper.sol
│ │ ├── StakingWarmup.sol
│ │ ├── StandardBondingCalculator.sol
│ │ ├── Treasury.sol
│ │ ├── mocks/
│ │ │ ├── DAI.sol
│ │ │ ├── Frax.sol
│ │ │ ├── MockBondDepository.sol
│ │ │ └── MockTreasury.sol
│ │ ├── sOlympusERC20.sol
│ │ ├── wETHBondDepository.sol
│ │ └── wOHM.sol
│ └── test/
│ ├── IUniswapV2Pair.sol
│ └── core.t.sol
├── tombfinance/
│ ├── .gitignore
│ ├── .gitmodules
│ ├── README.md
│ ├── foundry.toml
│ ├── remappings.txt
│ ├── script/
│ │ └── Counter.s.sol
│ ├── src/
│ │ ├── Distributor.sol
│ │ ├── DummyToken.sol
│ │ ├── Masonry.sol
│ │ ├── Migrations.sol
│ │ ├── Oracle.sol
│ │ ├── SimpleERCFund.sol
│ │ ├── TBond.sol
│ │ ├── TShare.sol
│ │ ├── TaxOffice.sol
│ │ ├── TaxOfficeV2.sol
│ │ ├── TaxOracle.sol
│ │ ├── Timelock.sol
│ │ ├── Tomb.sol
│ │ ├── Treasury.sol
│ │ ├── distribution/
│ │ │ ├── TShareRewardPool.sol
│ │ │ ├── TombGenesisRewardPool.sol
│ │ │ └── TombRewardPool.sol
│ │ ├── interfaces/
│ │ │ ├── IBasisAsset.sol
│ │ │ ├── IDecimals.sol
│ │ │ ├── IDistributor.sol
│ │ │ ├── IERC20.sol
│ │ │ ├── IMasonry.sol
│ │ │ ├── IOracle.sol
│ │ │ ├── IShare.sol
│ │ │ ├── ISimpleERCFund.sol
│ │ │ ├── ITShareRewardPool.sol
│ │ │ ├── ITaxable.sol
│ │ │ ├── ITreasury.sol
│ │ │ ├── IUniswapV2Callee.sol
│ │ │ ├── IUniswapV2ERC20.sol
│ │ │ ├── IUniswapV2Factory.sol
│ │ │ ├── IUniswapV2Pair.sol
│ │ │ ├── IUniswapV2Router.sol
│ │ │ └── IWrappedFtm.sol
│ │ ├── lib/
│ │ │ ├── Babylonian.sol
│ │ │ ├── FixedPoint.sol
│ │ │ ├── Safe112.sol
│ │ │ ├── SafeMath8.sol
│ │ │ ├── UQ112x112.sol
│ │ │ ├── UniswapV2Library.sol
│ │ │ └── UniswapV2OracleLibrary.sol
│ │ ├── owner/
│ │ │ └── Operator.sol
│ │ └── utils/
│ │ ├── ContractGuard.sol
│ │ └── Epoch.sol
│ └── test/
│ ├── core.t.sol
│ ├── mocks/
│ │ ├── MockUniPair.sol
│ │ └── MockWeth.sol
│ └── v2-core/
│ ├── UniswapV2ERC20.sol
│ ├── UniswapV2Factory.sol
│ ├── UniswapV2Pair.sol
│ ├── interfaces/
│ │ ├── IUniswapV2Callee.sol
│ │ ├── IUniswapV2ERC20.sol
│ │ ├── IUniswapV2Factory.sol
│ │ └── IUniswapV2Pair.sol
│ ├── libraries/
│ │ ├── Math.sol
│ │ ├── SafeMath.sol
│ │ └── UQ112x112.sol
│ └── test/
│ └── ERC20.sol
└── uniswap-v2/
├── .gitignore
├── .gitmodules
├── README.md
├── foundry.toml
├── remappings.txt
├── script/
│ └── Counter.s.sol
├── src/
│ ├── UniswapV2ERC20.sol
│ ├── UniswapV2Factory.sol
│ ├── UniswapV2Pair.sol
│ ├── contracts/
│ │ ├── UniswapV2Migrator.sol
│ │ ├── UniswapV2Router01.sol
│ │ ├── UniswapV2Router02.sol
│ │ ├── examples/
│ │ │ ├── ExampleComputeLiquidityValue.sol
│ │ │ ├── ExampleFlashSwap.sol
│ │ │ ├── ExampleOracleSimple.sol
│ │ │ ├── ExampleSlidingWindowOracle.sol
│ │ │ ├── ExampleSwapToPrice.sol
│ │ │ └── README.md
│ │ ├── interfaces/
│ │ │ ├── IUniswapV2Migrator.sol
│ │ │ ├── IUniswapV2Router01.sol
│ │ │ ├── IUniswapV2Router02.sol
│ │ │ ├── IWETH.sol
│ │ │ └── V1/
│ │ │ ├── IUniswapV1Exchange.sol
│ │ │ └── IUniswapV1Factory.sol
│ │ ├── libraries/
│ │ │ ├── UniswapV2Library.sol
│ │ │ ├── UniswapV2LiquidityMathLibrary.sol
│ │ │ └── UniswapV2OracleLibrary.sol
│ │ └── test/
│ │ ├── DeflatingERC20.sol
│ │ ├── ERC20.sol
│ │ ├── RouterEventEmitter.sol
│ │ └── WETH9.sol
│ ├── interfaces/
│ │ ├── IERC20.sol
│ │ ├── IUniswapV2Callee.sol
│ │ ├── IUniswapV2ERC20.sol
│ │ ├── IUniswapV2Factory.sol
│ │ └── IUniswapV2Pair.sol
│ ├── libraries/
│ │ ├── AddressStringUtil.sol
│ │ ├── Babylonian.sol
│ │ ├── BitMath.sol
│ │ ├── FixedPoint.sol
│ │ ├── FullMath.sol
│ │ ├── Math.sol
│ │ ├── PairNamer.sol
│ │ ├── SafeERC20Namer.sol
│ │ ├── SafeMath.sol
│ │ ├── TransferHelper.sol
│ │ └── UQ112x112.sol
│ └── test/
│ ├── ERC20.sol
│ └── core.t.sol
└── test/
├── core.t.sol
└── mocks/
├── MockToken.sol
└── MockWETH.sol
================================================
FILE CONTENTS
================================================
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Fuzzy DeFi
First, thanks for your interest in contributing to this repository! I welcome and appreciate all contributions, including bug reports, feature suggestions, tutorials/blog posts, and code improvements.
If you're unsure where to start, I recommend taking a look at our [issue tracker](https://github.com/0xNazgul/FuzzyDeFi/issues). If you find an issue or proposal that you feel you can do, assign yourself to it.
## Bug reports and feature suggestions
Bug reports and feature suggestions can be submitted to our issue tracker. For bug reports, adding as much information as you can will help me in debugging and resolving the issue quickly.
## Questions
Questions can be submitted to the issue tracker or message me on twitter [@0xNazgul](https://twitter.com/0xNazgul).
## Code
This repository uses the pull request contribution model. Please create an account on Github if you don't have one already, fork this repository, and submit your contributions via pull requests. For more documentation, look [here](https://guides.github.com/activities/forking/).
Some pull request guidelines:
- Create a new branch from the [`main`](https://github.com/0xNazgul/FuzzyDeFi/tree/main) branch. If you are submitting a new feature, prefix the new branch name with `dev` (for example, `dev-add-properties-for-erc20-transfers`). If your submission is a bug fix, prefix the new branch name with `fix` (for example, `fix-typo-in-readme`). Please be descriptive in the branch name, avoid confusing or unclear names such as `mypatch2` or `bugfix`.
- Minimize irrelevant changes (formatting, whitespace, etc) to code that would otherwise not be touched by this patch. Save formatting or style corrections for a separate pull request that does not make any semantic changes.
- When possible, large changes should be split up into smaller focused pull requests.
- Fill out the pull request description with a summary of what your patch does, key changes that have been made, and any further points of discussion, if applicable. If your pull request solves an open issue, add "Fixes #xxx" at the end.
- Title your pull request with a brief description of what it's changing. "Fixes #123" is a good comment to add to the description, but makes for an unclear title on its own.
- If your are unsure about something, don't hesitate to ask!
## Adding a new protocol or invariant to another protocol
When adding a new protocol make sure to follow the [Directory Structure](#directory-structure), [Test File Structure](#test-file-structure) and [Properties Structure](#properties-structure). Explicitly note the required setup in a `README.md` file. I don't require you to add your own protocol notes in that same `README.md` file if you don't want to or if you just didn't.
When adding a new invariant make sure to follow the [Test File Structure](#test-file-structure) (specifically the testFuzz function format) and [Properties Structure](#properties-structure).
## Directory Structure
Below is a rough outline of the directory structure:
```text
.
├── protocols # Parent folder for contracts
│ ├── uniswap-v2 # Properties for Uniswap-v2 contracts
│ │ ├── lib # Required dependencies
│ │ ├── script # Scripts if any, mostly empty
│ │ ├── src # All slightly modified Project contracts
│ │ ├── test # Location of test files
│ │ │ ├── mocks # Any other mocks you may need
│ │ │ └── core.t.sol # Core test file with all properties
│ │ └── ... # Other testing specific files
│ ├── Olympus DAO # Properties for Olympus DAO contracts
│ │ └── ... # Same format
│ └── Other protocols
└── ...
```
Please follow this structure in your collaborations.
## Test File Structure
Below is a rough outline of the test file structure:
```Solidity
// SPDX-License-Identifier: UNLICENSED
// Adjust pragma version as needed
pragma solidity >=0.6.0;
// Test Helpers
import "forge-std/Test.sol";
// Import protocol files as needed
// Name should remain CoreTest
contract CoreTest is Test {
uint256 MAX = type(uint256).max;
function setUp() public {
// Add your own signature name if you want
vm.label(address(this), "THE_FUZZANATOR");
// Setup protocol contracts as needed
}
// Used to make sure contracts are deploying correctly
function testON() public {}
/* INVARIANTS: FUNCTION_NAME should:
* Invariant 1
* Invariant 2
* ...
*/
function testFuzz_FUNCTION_NAME() public {
// PRECONDITIONS:
// Anything that needs to be done prior to the action.
// Values that need to be fetched and stored into memory before the action
uint256 amount = _between(_amount, 1, MAX);
// ACTION:
// Calling the function to be fuzzed
try Contract.FUNCTION_NAME() {
// POSTCONDTIONS:
// Values that need to be fetched again after the action
// assert invariant conditions hold
assertEq(a, b, "A IS EQUAL TO B CHECK");
// Catch any overflow. Depending on what is being tested comment out assert(false) or assert properly
} catch {/*assert(false)*/ }// overflow
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzing framework
// This is also a guarantee bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
}
```
Please follow this structure in your collaborations.
## Properties Structure
Below is a rough outline of the properties file structure:
| ID | Name | Invariant tested |
| --- | --- | --- |
BLA-001 | [testFuzz_FUNCTIONNAME]() | FUNCTIONNAME should:
- Invariant 1
- Invariant 2
- ...
BLA-002 | [testFuzz_FUNCTIONNAME2]() | FUNCTIONNAME2 should: - Invariant 1
- Invariant 2
- ...
... | ... | ...
Please follow this structure in your collaborations.
## Protocol Notes
These are mostly for myself to get a stronger understanding of how the protocol works. If you want add more useful information or maybe I misunderstood something. Feel free to submit an issue or a PR updating those readme files.
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: PROPERTIES.md
================================================
# Introduction
Here is a list of the property tests for the top five forked protocols. For each property, there is a permalink to the file implementing it in the repository and a small description of the invariant tested.
This may not be a complete list and there may be some more invariants to test. I focused more on functions that transferred funds or of major state updates. Also note that there are still some invariants listed here that needs to be implemented. Within each project folder `README.md` one can find what is left under `Invariants TODO` section.
## Table of contents
- [Introduction](#introduction)
- [Table of contents](#table-of-contents)
- [Uniswap v2](#uniswap-v2)
- [Olympus DAO](#olympus-dao)
- [Compound v2](#compound-v2)
- [Tomb Finance](#tomb-finance)
## Uniswap v2
| ID | Name | Invariant tested |
| --- | --- | --- |
UNI-001 | [testFuzz_AddLiq](/protocols/uniswap-v2/src/test/core.t.sol#L88) | Adding liquidity to a pair should: - Increase reserves
- Increase address to balance
- Increase totalSupply
- Increase k
UNI-002 | [testFuzz_ETHAddLiq](/protocols/uniswap-v2/src/test/core.t.sol#L124) | Same as adding liquidity
UNI-003 | [testFuzz_RemoveLiq](/protocols/uniswap-v2/src/test/core.t.sol#L161) | Removing liquidity from a pair should: - Decrease reserves
- Decrease address to balance
- Decrease totalSupply
- Decrease K
UNI-004 | [testFuzz_ETHRemoveLiq](/protocols/uniswap-v2/src/test/core.t.sol#L199) | Same as removing liquidity
UNI-005 | [testFuzz_removeLiqWithPermit](/protocols/uniswap-v2/src/test/core.t.sol#L237) | Same as removing liquidity
UNI-006 | [testFuzz_removeLiquidityETHWithPermit](/protocols/uniswap-v2/src/test/core.t.sol#L124) | Same as removing liquidity
UNI-007 | [testFuzz_removeLiqETHSupportingFeeOnTransferTokens](/protocols/uniswap-v2/src/test/core.t.sol#L415) | Same as removing liquidity
UNI-008 | [testFuzz_removeLiqETHWithPermitSupportingFeeOnTransferTokens](/protocols/uniswap-v2/src/test/core.t.sol#L453) | Same as removing liquidity
UNI-009 | [testFuzz_swapExactTokensForTokens](/protocols/uniswap-v2/src/test/core.t.sol#L541) | Swapping within a pair should: - Decrease balance of user for token 2
- Increase balance of user for token 1
- Decrease/leave k unchanged
UNI-010 | [testFuzz_swapExactETHForTokens](/protocols/uniswap-v2/src/test/core.t.sol#L582) | Same as Swap
UNI-011 | [testFuzz_swapTokensForExactETH](/protocols/uniswap-v2/src/test/core.t.sol#L625) | Same as Swap
UNI-012 | [testFuzz_swapExactTokensForETH](/protocols/uniswap-v2/src/test/core.t.sol#L668) | Same as Swap
UNI-013 | [testFuzz_swapETHForExactTokens](/protocols/uniswap-v2/src/test/core.t.sol#L711) | Same as Swap
UNI-014 | [testFuzz_swapExactTokensForTokensSupportingFeeOnTransferTokens](/protocols/uniswap-v2/src/test/core.t.sol#L754) | Same as Swap
UNI-015 | [testFuzz_swapExactETHForTokensSupportingFeeOnTransferTokens](/protocols/uniswap-v2/src/test/core.t.sol#L796) | Same as Swap
UNI-016 | [testFuzz_swapExactTokensForETHSupportingFeeOnTransferTokens](/protocols/uniswap-v2/src/test/core.t.sol#L842) | Same as Swap
## Olympus DAO
| ID | Name | Invariant tested |
| --- | --- | --- |
OLY-001 | [testFuzz_deposit](/protocols/olympus-v1/test/core.t.sol#L163) | Depositing into the BondDepo should:- Increase user Bond Payout
- Updates users last block to latest
- Updates Bond Price
- Increase Total Debt
- Increase Treasury Total Reserves
- Updates control variable accordingly
- Updates rate accordingly
OLY-002 | [testFuzz_redeemNoStaking](/protocols/olympus-v1/test/core.t.sol#L204) | Redeeming without staking from BondDepo should:- Decrease user payout
- Decrease user vesting
- Update user lastBlock
- Increase user OHM Balance
OLY-003 | [testFuzz_redeemWith](/protocols/olympus-v1/test/core.t.sol#L256) | Redeeming with staking from BondDepo should:- Decrease user payout
- Decrease user vesting
- Update user lastBlock
- Increase staking OHM Balance
- Increase staking warmup sOHM Balance
- Increase user staking deposit
- Increase user gons
- Increase user expiry
- Update user lock to false
OLY-004 | [testFuzz_redeemRebase](/protocols/olympus-v1/test/core.t.sol#L305) | Redeeming from BondDepo should:- Updates distribute
- Increases number
- Increases endBlock
OLY-005 | [testFuzz_unstake](/protocols/olympus-v1/test/core.t.sol#L335) | Unstaking should:- Increase user OHM balance
- Decrease user sOHM balance
- Increase Staking sOHM balance
- Decrease Staking OHM balance
## Compound v2
| ID | Name | Invariant tested |
| --- | --- | --- |
COM-001 | [testFuzz_mint](/protocols/compound-v2/test/core.t.sol#L126) | Calling mint Should: - Increase cToken TotalSupply
- Increase User cToken Balance
- Decrease User underlying Balance
- Update Supply Index in Comptroller
- Update Comp Supplier Index in Comptroller
- Update supplier compAccrued in Comptroller
- Update Supply block Number in Comptroller
- Update cToken accrualBlockNumber
- Update cToken borrowIndex
- Update cToken totalBorrows
- Update cToken totalReserves
COM-002 | [testFuzz_redeem](/protocols/compound-v2/test/core.t.sol#L178) | Calling redeem Should:- Decrease cToken TotalSupply
- Decrease User cToken Balance
- Increase User underlying Balance
- Update Supply Index in Comptroller
- Update Comp Supplier Index in Comptroller
- Update supplier compAccrued in Comptroller
- Update Supply block Number in Comptroller
- Update cToken accrualBlockNumber
- Update cToken borrowIndex
- Update cToken totalBorrows
- Update cToken totalReserves
COM-003 | [testFuzz_borrow](/protocols/compound-v2/test/core.t.sol#L239) | Calling borrow Should:- Update borrow index in Comptroller
- Update borrow block in Comptroller
- Update borrower compAccrued in Comptroller
- Update compBorrowerIndex in Comptroller
- Add user to market in Comptroller
- Add cToken to users accountAssets in Comptroller
- Increase accountBorrows principal
- Update accountBorrows interestIndex
- Increase totalBorrows
- Increase User underlying Balance
COM-004 | [testFuzz_repayBorrow](/protocols/compound-v2/test/core.t.sol#L295) | Calling repayBorrow Should:- Update borrow index in Comptroller
- Update borrow block in Comptroller
- Update borrower compAccrued in Comptroller
- Update compBorrowerIndex in Comptroller
- Add user to market in Comptroller
- Add cToken to users accountAssets in Comptroller
- Increase accountBorrows principal
- Update accountBorrows interestIndex
- Increase totalBorrows
- Increase User underlying Balance
COM-005 | [testFuzz_liquidateBorrow](/protocols/compound-v2/test/core.t.sol#L416) | Calling liquidateBorrow Should:- Update cToken accrualBlockNumber
- Update cToken borrowIndex
- Update cToken totalBorrows
- Increase totalReserves
- Decrease cToken totalSupply
- Decrease borrower accountTokens
- Increase liquidator accountTokens
COM-006 | [testFuzz_repayBorrowBehalf](/protocols/compound-v2/test/core.t.sol#L356) | Calling repayBorrowBehalf Should:- Update borrow index in Comptroller
- Update borrow block in Comptroller
- Update borrower compAccrued in Comptroller
- Update compBorrowerIndex in Comptroller
- Add user to market in Comptroller
- Add cToken to users accountAssets in Comptroller
- Increase accountBorrows principal
- Update accountBorrows interestIndex
- Increase totalBorrows
- Increase User underlying Balance
COM-007 | [testFuzz_sweepToken](/protocols/compound-v2/test/core.t.sol#L474) | Calling sweepToken Should:- Decrease ctoken random token balance
- Increase Admin random token balance
COM-008 | [testFuzz_addReserves](/protocols/compound-v2/test/core.t.sol#L504) | Calling addReserves Should:- Update cToken accrualBlockNumber
- Update cToken borrowIndex
- Update cToken totalBorrows
- Update cToken totalReserves (after accrueInterest)
- Decease User balance
- Increase ctoken underlying balance
COM-009 | [testFuzz_transfer](/protocols/compound-v2/test/core.t.sol#L537) | Calling transfer Should:- Decrease from address accountTokens
- Increase to address accountTokens
COM-010 | [testFuzz_transferFrom](/protocols/compound-v2/test/core.t.sol#L566) | Calling transferFrom Should:- Decrease from address accountTokens
- Increase to address accountTokens
## Tomb Finance
| ID | Name | Invariant tested |
| --- | --- | --- |
TMF-001 | [testFuzz_tombMint](/protocols/tombfinance/test/core.t.sol#L182) | Tomb mint should: - Increase User Balance
- Increase Total Supply
TMF-002 | [testFuzz_tombBurn](/protocols/tombfinance/test/core.t.sol#L203) | Tomb burn should:- Decrease User Balance
- Decrease Total Supply
TMF-003 | [testFuzz_tombBurnFrom](/protocols/tombfinance/test/core.t.sol#L228) | Tomb burnFrom should:- Decrease User Balance
- Decrease Total Supply
TMF-004 | [testFuzz_tombTransferFrom](/protocols/tombfinance/test/core.t.sol#L254) | Tomb transferFrom without `autoCalculateTax & currentTaxRate == 0` should:- Decrease from User Balance
- Increase to User Balance
- Total Supply should remain the same
TMF-005 | [testFuzz_tombTaxTransferFrom](/protocols/tombfinance/test/core.t.sol#L284) | Tomb transferFrom with autoCalculateTax should:- Decrease from User Balance
- Increase to User Balance
- Decrease Total Supply
TMF-006 | [testFuzz_tBondMint](/protocols/tombfinance/test/core.t.sol#L316) | TBond mint should:- Increase User Balance
- Increase Total Supply
TMF-007 | [testFuzz_tBondBurn](/protocols/tombfinance/test/core.t.sol#L337) | TBond burn should:- Decrease User Balance
- Decrease Total Supply
TMF-008 | [testFuzz_tBondBurnFrom](/protocols/tombfinance/test/core.t.sol#L362) | TBond burnFrom should:- Decrease User Balance
- Decrease Total Supply
TMF-009 | [testFuzz_tombGenesisRewardPoolDeposit](/protocols/tombfinance/test/core.t.sol#L389) | Depositing into TombGenesisRewardPool Should: - Update pool reward variables
- Decrease User bal of token
- Update User rewardDebt
- Increase user bal amount
TMF-010 | [testFuzz_tombGenesisRewardPoolWithdraw](/protocols/tombfinance/test/core.t.sol#L430) | Withdrawing from TombGenesisRewardPool Should: - Update pool reward variables
- Increase User bal of token
- Update User rewardDebt
- Decrease user bal amount
TMF-011 | [testFuzz_tombGenesisRewardPoolEmergencyWithdraw](/protocols/tombfinance/test/core.t.sol#L372) | Emergency withdrawing from TombGenesisRewardPool Should: - Increase User bal of token
- Decrease User rewardDebt
- Decrease user bal amount
TMF-012 | [testFuzz_tombGenesisRewardPooGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L498) | TombGenesisRewardPool Governance recover Should: - Decrease contract bal of token
- Increase to User bal of token
TMF-013 | [testFuzz_tombRewardPoolDeposit]() | Depositing into TombRewardPool Should: - Update pool reward variables
- Decrease User bal of token
- Increase User rewardDebt
- Increase user bal amount
TMF-014 | [testFuzz_tombRewardPoolWithdraw](/protocols/tombfinance/test/core.t.sol#L541) | Withdrawing from TombRewardPool Should: - Update pool reward variables
- Increase User bal of token
- Update User rewardDebt
- Decrease user bal amount
TMF-015 | [testFuzz_tombRewardPoolEmergencyWithdraw](/protocols/tombfinance/test/core.t.sol#L582) | Emergency withdrawing from TombRewardPool Should: - Increase User bal of token
- Decrease User rewardDebt
- Decrease user bal amount
TMF-016 | [testFuzz_tombRewardPoolGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L650) | TombRewardPool Governance recover Should: - Decrease contract bal of token
- Increase to User bal of token
TMF-017 | [testFuzz_tShareRewardPoolDeposit](/protocols/tombfinance/test/core.t.sol#L694) | Depositing into TShareRewardPool Should: - Update pool reward variables
- Decrease User bal of token
- Increase User rewardDebt
- Increase user bal amount
TMF-018 | [testFuzz_tShareRewardPoolWithdraw](/protocols/tombfinance/test/core.t.sol#L735) | Withdrawing from TShareRewardPool Should: - Update pool reward variables
- Increase User bal of token
- Update User rewardDebt
- Decrease user bal amount
TMF-019 | [testFuzz_tShareRewardPoolEmergencyWithdraw](/protocols/tombfinance/test/core.t.sol#L777) | Emergency withdrawing from TShareRewardPool Should: - Increase User bal of token
- Decrease User rewardDebt
- Decrease user bal amount
TMF-020 | [testFuzz_testFuzztShareRewardPoolGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L803) | TShareRewardPool Governance recover Should: - Decrease contract bal of token
- Increase to User bal of token
TMF-021 | [testFuzz_masonryStake](/protocols/tombfinance/test/core.t.sol#L845) | Staking into Masonry Should: - Increase totalSupply
- Increase User staked bal
- Decrease User tBond amount
TMF-022 | [testFuzz_masonryWithdraw](/protocols/tombfinance/test/core.t.sol#L879) | Depositing into Masonry Should: - Decrease totalSupply
- Decrease User staked bal
- Increase User tBond amount
TMF-023 | [testFuzz_masonryClaimReward](/protocols/tombfinance/test/core.t.sol#L919) | Claiming reward from Masonry Should: - Decrease User Reward
- Increase tomb bal
- Update User epochTimerStart
TMF-024 | [testFuzz_masonryExit](/protocols/tombfinance/test/core.t.sol#L967) | Exiting from Masonry Should: - Decrease totalSupply
- Decrease User staked bal
- Increase User tBond amount
TMF-025 | [testFuzz_masonryAllocateSeigniorage](/protocols/tombfinance/test/core.t.sol#L1007) | Masonry Allocate Seigniorage Should: - Update nextRPS
- Update time
- Decrease from User tomb bal
- Increase contracts tomb bal
TMF-026 | [testFuzz_masonryGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L1013) | Masonry Governance recover Should: - Decrease contract bal of token
- Increase to User bal of token
TMF-027 | [testFuzz_treasuryBuyBonds](/protocols/tombfinance/test/core.t.sol#L1037) | Buying bonds from the Treasury Should: - Decrease User tomb bal
- Increase User tBond bal
- Decrease epochSupplyContractionLeft
TMF-028 | [testFuzz_treasuryRedeemBonds](/protocols/tombfinance/test/core.t.sol#L1079) | Redeeming bonds from the Treasury Should: - Decrease User tBond bal
- Increase User tomb bal
- Decrease epochSupplyContractionLeft
TMF-029 | [testFuzz_treasuryAllocateSeigniorage](/protocols/tombfinance/test/core.t.sol#L1120) | Treasury Allocate Seigniorage Should: - Update previousEpochTombPrice
- If `_savedForBond > 0`, increase contract tomb bal
- If `_savedForMasonry > 0 && daoFundSharedPercent > 0` increase daoFund tomb bal
- If `_savedForMasonry > 0 && devFundSharedPercent > 0` increase devFund tomb bal
- Update masonry's allowance
TMF-030 | [testFuzz_treasuryGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L1126) | Treasury Governance recover Should: - Decrease contract bal of token
- Increase to User bal of token
TMF-031 | [testFuzz_tShareClaimRewards](/protocols/tombfinance/test/core.t.sol#L1149) | tShare Claim rewards Should: - Increase totalSupply
- If `_pending > 0 && communityFund != address(0)` increase communityFund tShare bal
- If `_pending > 0 && devFund != address(0)` increase devFund tShare bal
TMF-032 | [testFuzz_tShareBurn](/protocols/tombfinance/test/core.t.sol#L1191) | TShare Burn Should: - Decrease User Balance
- Decrease Total Supply
TMF-033 | [testFuzz_tShareGovernanceRecoverUnsupported](/protocols/tombfinance/test/core.t.sol#L1216) | Governance recover from TShare Should: - Decrease contract bal of token
- Increase to User bal of token
================================================
FILE: README.md
================================================
# Fuzzy DeFi
## Properties
This repository contains code properties for the current top four forked protocols:
1. [Uniswap v2](/protocols/uniswap-v2/README.md) An AMM powered by the constant product formula, [properties](/PROPERTIES.md#L15).
2. [Olympus DAO](/protocols/olympus-v1/README.md) A protocol-owned Treasury serving the market gap between stablecoins and volatile assets, [properties](/PROPERTIES.md#L36).
3. [Compound v2](/protocols/compound-v2/README.md#L46) An algorithmic, autonomous interest rate protocol, [properties](/PROPERTIES.md#L).
4. [Tomb Finance](/protocols/tombfinance/README.md) An algorithmic token pegged to `FTM`, [properties](/PROPERTIES.md#L60).
The goals of these properties are to:
* Detect vulnerabilities
* Ensure adherence to the original protocols properties
* Provide educational guidance for writing invariants
## Testing
1. Install [Foundry](https://book.getfoundry.sh/getting-started/installation)
2. Follow the protocols corresponding `README` setup.
## Contributing to this repo?
You can read more about the contribution guidelines and directory structure in the [CONTRIBUTING](/CONTRIBUTING.md) file.
## Trophies
I have not used it in the wild and did this mostly to build my fuzzing skills. If you use this and find any bugs congrats!!!
Create an issue with "Trophy" as your title and we can add it to a list with your proper credits!
## No Guarantees
There are no guarantees with using this project to secure your protocol! There is still a lot to improve with this repo and not everything is fully tested nor is it a silver bullet!
## License
Modified code forked from there respective companies are licensed under there respective licenses in accordance with the original licenses.
All other files within this repository are licensed under the AGPL License unless stated otherwise.
================================================
FILE: package.json
================================================
{
"name": "fuzzy-defi",
"version": "0.0.2",
"description": "Pre-built security properties for commonly forked DeFi protocols",
"repository": {
"type": "git",
"url": "git+https://github.com/0xNazgul/FuzzyDeFi.git"
},
"author": "0xNazgul",
"license": "MIT",
"bugs": {
"url": "https://github.com/0xNazgul/FuzzyDeFi/issues"
},
"homepage": "https://github.com/0xNazgul/FuzzyDeFi#readme"
}
================================================
FILE: protocols/compound-v2/.gitignore
================================================
cache
out
================================================
FILE: protocols/compound-v2/.gitmodules
================================================
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
branch = v1.7.1
================================================
FILE: protocols/compound-v2/LICENSE
================================================
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: protocols/compound-v2/README.md
================================================
# Setup
1. `forge install`
2. `forge test --mc TestCore`
## Integration
1. Follow setup
2. Add test helpers functions:
| Contract | Function |
| --- | --- |
[CErc20.sol](./src/CErc20.sol) | [getCashPriorpub()](./src/CErc20.sol#L153)
3. Remove test helpers from contract before deploying
* I'm not responsible for what happens if you leave them in
# **Notes on Compound v2**
Compound was created on the bases of being a decentralized system for borrowing of token without flaws of existing approaches:
* Centralized exchanges
* Peer to peer protocols that have high costs and added frictions onto users
* Borrowing mechanisms were limited
* Assets having negative yield without natural interest rates to offset them.
It's meant to establish money markets (pools of tokens) with derived interest rates based on supply and demand for the token.
* Suppliers earn a floating interest rate without dealing with maturity, interest rate or collateral with a peer
* borrowers pay the floating interest rate without dealing with a peer
### **Supplying**:
Compound aggregates the supply of each user:
* When a user supplies a token it becomes a resource
* Offers liquidity
* Can withdraw at any time without loan maturity
Balances accrue interest based on the supply interest rate of the asset. When a user updates there balance, accrued interest is converted into principal and paid. This gives users with long-term investments a chance to gain additional returns.
### **Borrowing**:
Users can borrow using collateralized lines of credit. There are no specific terms and they only have to specify the wanted assets amount. The cost of such is determined by the floating interest rate set by the market.
* Each account must have a balance that covers the outstanding borrowed amount (collateral ratio).
* This can be brought below the ratio by borrowing or withdrawing
* This can be increased when users repay borrowed asset in whole or part at any time
* Balances held even being used as collateral still accrue interest
Users whose `(supplied assets / outstanding borrowing) < collateral ratio` leave their collateral and borrowed assets up for purchase at `(current market price - liquidation discount)`.
* Incentivizes arbitrageurs to reduce borrower's exposure and lower protocol's risk.
* Any user with the borrowed asset can liquidate in whole or part. Exchanging their asset for the borrower's collateral.
The main use of this is to be able to hold new assets without selling or rearranging a portfolio giving users abilities of:
* Not having to wait for order fills or off-chain behavior. Allowing dApps to borrow tokens to use.
* Traders can finance new ICO investments by borrowing and using their existing portfolio as collateral
* Traders can short token by borrowing it sending it to an exchange and sell the token
### **Interest Rate Model**:
The protocol achieves an efficient interest rate equilibrium for each market based on supply and demand of individual assets. This utilization ratio U unifies supply and demand into a single variable:
* `U = Borrows / (Cash + Borrows)`
Interest rates should increase as a function of demand:
* When demand is low rates should be low
* When demand is high rates should be high
This curve is codified through governance and updated by the chief economist. It is expressed as a function of utilization:
* `Borrowing interest Rate = 10% + U * 30%`
The total amount of interest earned by suppliers must be < total interest product by borrowers. Supply interest rate is a function of borrowing interest rate including a spread S representing the economic profit of the protocol:
* `Supply Interest Rate = Borrowing Interest Rate * U * (1 - S)`
### **cTokens**:
This is a EIP-20 compliant contract that keeps track of balances supplied to the protocol. Users can mint cTokens to earn interest from the cTokens exchange rate that increases in value relative to the asset. Users can also use the cTokens as collateral.
* All mints, redeems, borrow, repays a borrow, liquidates a borrow or transfers are done via the cToken.
* Two types of cTokens CErc20 (wraps the underlying ERC-20 asset)and CEther (wraps ether)
### **Comptroller**:
Comptroller is the risk management contract that determines the amount of collateral a user must have to maintain or if they can be liquidated. When a user interacts with a cToken the comptroller is asked to approve/deny it.
It also maps user balances to prices (price oracle) to risk weight for making the determinations. Users can list which assets they would like to include in their risk scoring.
### **Governance**:
The protocol is governed by COMP holders and has three components:
1. COMP token
2. Governance module by Governor Bravo
3. Timelock
These give COMP holders the ability to propose, vote and implement changes. Proposals can modify anything in the protocol. Holders can delegate to any address of their choice. Delegation has its limits where an address must have at least 25,000 COMP to create a proposal or any address can lock 100 COMP to create an Autonomous Proposal. This allows other users to delegate to it to crate a proposal after the 25,000 COMP is reached.
The proposal process is as follows:
* 2 day review period
* Voting weights are recorded and voting begins
* Voting last 3 days
* If a majority and at least 400,000 votes are cast for the proposal it is queued in the Timelock
* It can than be implemented 2 days later
* Total about one week
Comp itself is an ERC-20 token that has voting rights.
### **Open Price Feed**:
Accounts price data for the protocol and is used by the comptroller as a source of truth for prices. Compound uses a price feed to verify the reported prices are withing bounds of TWAP of the pair on Uniswap v2 (sanity check or Anchor price).
Chainlink price feeds submit prices for each cToken through an individual validatorProxy. This is the only valid reporter for the underlying asset price.
Open Price Feed has two main contracts:
1. ValidatorProxy which queries Uniswap v2 to check if the new price is within the TWAP anchor. If valid it updates the asset price and discards the price data elsewise
2. UiswapAnchoredView only stores prices withing the bound of the TWAP and are signed by a reporter. Handles upscaling prices into the comptroller formant.
Allows multiple views to use the same underlying price data and verify the prices in their own way.
* Stablecoins are fixed at $1. SAI is fixed at 0.005285 ETH.
* Compound multisig has the ability to switch market's primary oracle from Chainlink price feeds to uniswap v2 during a failover.
### **Extra Links**:
[Whitpaper](https://github.com/compound-finance/compound-money-market/blob/master/docs/CompoundWhitepaper.pdf)
[Protocol High level](https://github.com/compound-finance/compound-protocol/blob/master/docs/CompoundProtocol.pdf)
[Documents](https://docs.compound.finance/v2/)
### **Audit Links**:
[audits](https://docs.compound.finance/v2/security/)
================================================
FILE: protocols/compound-v2/foundry.toml
================================================
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
[fuzz]
runs = 10000
# See more config options https://github.com/foundry-rs/foundry/tree/master/config
================================================
FILE: protocols/compound-v2/package.json
================================================
{
"name": "compound-protocol",
"version": "0.2.1",
"description": "The Compound Money Market",
"main": "index.js",
"repository": "git@github.com:compound-finance/compound-protocol.git",
"author": "Compound Finance",
"license": "UNLICENSED"
}
================================================
FILE: protocols/compound-v2/remappings.txt
================================================
forge-std/=lib/forge-std/src/
@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts
@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/openzeppelin-contracts/contracts
@compound/=src/
@rari-capital/solmate/=lib/solmate/
================================================
FILE: protocols/compound-v2/script/Counter.s.sol
================================================
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Script.sol";
contract CounterScript is Script {
function setUp() public {}
function run() public {
vm.broadcast();
}
}
================================================
FILE: protocols/compound-v2/src/BaseJumpRateModelV2.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./InterestRateModel.sol";
/**
* @title Logic for Compound's JumpRateModel Contract V2.
* @author Compound (modified by Dharma Labs, refactored by Arr00)
* @notice Version 2 modifies Version 1 by enabling updateable parameters.
*/
abstract contract BaseJumpRateModelV2 is InterestRateModel {
event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink);
uint256 private constant BASE = 1e18;
/**
* @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly
*/
address public owner;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint public constant blocksPerYear = 2102400;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint public baseRatePerBlock;
/**
* @notice The multiplierPerBlock after hitting a specified utilization point
*/
uint public jumpMultiplierPerBlock;
/**
* @notice The utilization point at which the jump multiplier is applied
*/
uint public kink;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
*/
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) internal {
owner = owner_;
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
/**
* @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) virtual external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, BASE]
*/
function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
return borrows * BASE / (cash + borrows - reserves);
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by BASE)
*/
function getBorrowRateInternal(uint cash, uint borrows, uint reserves) internal view returns (uint) {
uint util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return ((util * multiplierPerBlock) / BASE) + baseRatePerBlock;
} else {
uint normalRate = ((kink * multiplierPerBlock) / BASE) + baseRatePerBlock;
uint excessUtil = util - kink;
return ((excessUtil * jumpMultiplierPerBlock) / BASE) + normalRate;
}
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by BASE)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) virtual override public view returns (uint) {
uint oneMinusReserveFactor = BASE - reserveFactorMantissa;
uint borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint rateToPool = borrowRate * oneMinusReserveFactor / BASE;
return utilizationRate(cash, borrows, reserves) * rateToPool / BASE;
}
/**
* @notice Internal function to update the parameters of the interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) internal {
baseRatePerBlock = baseRatePerYear / blocksPerYear;
multiplierPerBlock = (multiplierPerYear * BASE) / (blocksPerYear * kink_);
jumpMultiplierPerBlock = jumpMultiplierPerYear / blocksPerYear;
kink = kink_;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);
}
}
================================================
FILE: protocols/compound-v2/src/CDaiDelegate.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CErc20Delegate.sol";
/**
* @title Compound's CDai Contract
* @notice CToken which wraps Multi-Collateral DAI
* @author Compound
*/
contract CDaiDelegate is CErc20Delegate {
/**
* @notice DAI adapter address
*/
address public daiJoinAddress;
/**
* @notice DAI Savings Rate (DSR) pot address
*/
address public potAddress;
/**
* @notice DAI vat address
*/
address public vatAddress;
/**
* @notice Delegate interface to become the implementation
* @param data The encoded arguments for becoming
*/
function _becomeImplementation(bytes memory data) override public {
require(msg.sender == admin, "only the admin may initialize the implementation");
(address daiJoinAddress_, address potAddress_) = abi.decode(data, (address, address));
return _becomeImplementation(daiJoinAddress_, potAddress_);
}
/**
* @notice Explicit interface to become the implementation
* @param daiJoinAddress_ DAI adapter address
* @param potAddress_ DAI Savings Rate (DSR) pot address
*/
function _becomeImplementation(address daiJoinAddress_, address potAddress_) internal {
// Get dai and vat and sanity check the underlying
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress_);
PotLike pot = PotLike(potAddress_);
GemLike dai = daiJoin.dai();
VatLike vat = daiJoin.vat();
require(address(dai) == underlying, "DAI must be the same as underlying");
// Remember the relevant addresses
daiJoinAddress = daiJoinAddress_;
potAddress = potAddress_;
vatAddress = address(vat);
// Approve moving our DAI into the vat through daiJoin
dai.approve(daiJoinAddress, type(uint).max);
// Approve the pot to transfer our funds within the vat
vat.hope(potAddress);
vat.hope(daiJoinAddress);
// Accumulate DSR interest -- must do this in order to doTransferIn
pot.drip();
// Transfer all cash in (doTransferIn does this regardless of amount)
doTransferIn(address(this), 0);
}
/**
* @notice Delegate interface to resign the implementation
*/
function _resignImplementation() override public {
require(msg.sender == admin, "only the admin may abandon the implementation");
// Transfer all cash out of the DSR - note that this relies on self-transfer
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
PotLike pot = PotLike(potAddress);
VatLike vat = VatLike(vatAddress);
// Accumulate interest
pot.drip();
// Calculate the total amount in the pot, and move it out
uint pie = pot.pie(address(this));
pot.exit(pie);
// Checks the actual balance of DAI in the vat after the pot exit
uint bal = vat.dai(address(this));
// Remove our whole balance
daiJoin.exit(address(this), bal / RAY);
}
/*** CToken Overrides ***/
/**
* @notice Accrues DSR then applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() override public returns (uint) {
// Accumulate DSR interest
PotLike(potAddress).drip();
// Accumulate CToken interest
return super.accrueInterest();
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() override internal view returns (uint) {
PotLike pot = PotLike(potAddress);
uint pie = pot.pie(address(this));
return mul(pot.chi(), pie) / RAY;
}
/**
* @notice Transfer the underlying to this contract and sweep into DSR pot
* @param from Address to transfer funds from
* @param amount Amount of underlying to transfer
* @return The actual amount that is transferred
*/
function doTransferIn(address from, uint amount) override internal returns (uint) {
// Read from storage once
address underlying_ = underlying;
// Perform the EIP-20 transfer in
EIP20Interface token = EIP20Interface(underlying_);
require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return");
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
GemLike dai = GemLike(underlying_);
PotLike pot = PotLike(potAddress);
VatLike vat = VatLike(vatAddress);
// Convert all our DAI to internal DAI in the vat
daiJoin.join(address(this), dai.balanceOf(address(this)));
// Checks the actual balance of DAI in the vat after the join
uint bal = vat.dai(address(this));
// Calculate the percentage increase to th pot for the entire vat, and move it in
// Note: We may leave a tiny bit of DAI in the vat...but we do the whole thing every time
uint pie = bal / pot.chi();
pot.join(pie);
return amount;
}
/**
* @notice Transfer the underlying from this contract, after sweeping out of DSR pot
* @param to Address to transfer funds to
* @param amount Amount of underlying to transfer
*/
function doTransferOut(address payable to, uint amount) override internal {
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
PotLike pot = PotLike(potAddress);
// Calculate the percentage decrease from the pot, and move that much out
// Note: Use a slightly larger pie size to ensure that we get at least amount in the vat
uint pie = add(mul(amount, RAY) / pot.chi(), 1);
pot.exit(pie);
daiJoin.exit(to, amount);
}
/*** Maker Internals ***/
uint256 constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
}
/*** Maker Interfaces ***/
interface PotLike {
function chi() external view returns (uint);
function pie(address) external view returns (uint);
function drip() external returns (uint);
function join(uint) external;
function exit(uint) external;
}
interface GemLike {
function approve(address, uint) external;
function balanceOf(address) external view returns (uint);
function transferFrom(address, address, uint) external returns (bool);
}
interface VatLike {
function dai(address) external view returns (uint);
function hope(address) external;
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint) external payable;
function exit(address, uint) external;
}
================================================
FILE: protocols/compound-v2/src/CErc20.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
interface CompLike {
function delegate(address delegatee) external;
}
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) override external returns (uint) {
mintInternal(mintAmount);
return NO_ERROR;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) override external returns (uint) {
redeemInternal(redeemTokens);
return NO_ERROR;
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) override external returns (uint) {
redeemUnderlyingInternal(redeemAmount);
return NO_ERROR;
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) override external returns (uint) {
borrowInternal(borrowAmount);
return NO_ERROR;
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) override external returns (uint) {
repayBorrowInternal(repayAmount);
return NO_ERROR;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) override external returns (uint) {
repayBorrowBehalfInternal(borrower, repayAmount);
return NO_ERROR;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) override external returns (uint) {
liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return NO_ERROR;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) override external {
require(msg.sender == admin, "CErc20::sweepToken: only admin can sweep tokens");
require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.transfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) override external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() virtual override internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
// test Helper
function getCashPriorpub() public view returns(uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) virtual override internal returns (uint) {
// Read from storage once
address underlying_ = underlying;
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying_);
uint balanceBefore = EIP20Interface(underlying_).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying_).balanceOf(address(this));
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) virtual override internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of override external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/**
* @notice Admin call to delegate the votes of the COMP-like underlying
* @param compLikeDelegatee The address to delegate votes to
* @dev CTokens whose underlying are not CompLike should revert here
*/
function _delegateCompLikeTo(address compLikeDelegatee) external {
require(msg.sender == admin, "only the admin may set the comp-like delegate");
CompLike(underlying).delegate(compLikeDelegatee);
}
}
================================================
FILE: protocols/compound-v2/src/CErc20Delegate.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CErc20.sol";
/**
* @title Compound's CErc20Delegate Contract
* @notice CTokens which wrap an EIP-20 underlying and are delegated to
* @author Compound
*/
contract CErc20Delegate is CErc20, CDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) virtual override public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual override public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
================================================
FILE: protocols/compound-v2/src/CErc20Delegator.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CTokenInterfaces.sol";
/**
* @title Compound's CErc20Delegator Contract
* @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation
* @author Compound
*/
contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address implementation_,
bytes memory becomeImplementationData) {
// Creator of the contract is admin during initialization
admin = payable(msg.sender);
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)",
underlying_,
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_));
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
// Set the proper admin now that initialization is done
admin = admin_;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData)override public {
require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256)", mintAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeem(uint256)", redeemTokens));
return abi.decode(data, (uint));
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeemUnderlying(uint256)", redeemAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrow(uint256)", borrowAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrow(uint256)", repayAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrowBehalf(address,uint256)", borrower, repayAmount));
return abi.decode(data, (uint));
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("liquidateBorrow(address,uint256,address)", borrower, repayAmount, cTokenCollateral));
return abi.decode(data, (uint));
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) override external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("transfer(address,uint256)", dst, amount));
return abi.decode(data, (bool));
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) override external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("transferFrom(address,address,uint256)", src, dst, amount));
return abi.decode(data, (bool));
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) override external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("approve(address,uint256)", spender, amount));
return abi.decode(data, (bool));
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) override external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("allowance(address,address)", owner, spender));
return abi.decode(data, (uint));
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) override external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOf(address)", owner));
return abi.decode(data, (uint));
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("balanceOfUnderlying(address)", owner));
return abi.decode(data, (uint));
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) override external view returns (uint, uint, uint, uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getAccountSnapshot(address)", account));
return abi.decode(data, (uint, uint, uint, uint));
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() override external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()"));
return abi.decode(data, (uint));
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() override external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("supplyRatePerBlock()"));
return abi.decode(data, (uint));
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("totalBorrowsCurrent()"));
return abi.decode(data, (uint));
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrowBalanceCurrent(address)", account));
return abi.decode(data, (uint));
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) override public view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowBalanceStored(address)", account));
return abi.decode(data, (uint));
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() override public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("exchangeRateCurrent()"));
return abi.decode(data, (uint));
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() override public view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateStored()"));
return abi.decode(data, (uint));
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() override external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getCash()"));
return abi.decode(data, (uint));
}
/**
* @notice Applies accrued interest to total borrows and reserves.
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() override public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("accrueInterest()"));
return abi.decode(data, (uint));
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("seize(address,address,uint256)", liquidator, borrower, seizeTokens));
return abi.decode(data, (uint));
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) override external {
delegateToImplementation(abi.encodeWithSignature("sweepToken(address)", token));
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setPendingAdmin(address)", newPendingAdmin));
return abi.decode(data, (uint));
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) override public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setComptroller(address)", newComptroller));
return abi.decode(data, (uint));
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa));
return abi.decode(data, (uint));
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_acceptAdmin()"));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and adds reserves by transferring from admin
* @param addAmount Amount of reserves to add
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_addReserves(uint256)", addAmount));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_reduceReserves(uint256)", reduceAmount));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) override public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setInterestRateModel(address)", newInterestRateModel));
return abi.decode(data, (uint));
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return abi.decode(returnData, (bytes));
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
fallback() external payable {
require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
================================================
FILE: protocols/compound-v2/src/CErc20Immutable.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CErc20.sol";
/**
* @title Compound's CErc20Immutable Contract
* @notice CTokens which wrap an EIP-20 underlying and are immutable
* @author Compound
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) {
// Creator of the contract is admin during initialization
admin = payable(msg.sender);
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
================================================
FILE: protocols/compound-v2/src/CEther.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
/**
* @title Compound's CEther Contract
* @notice CToken which wraps Ether
* @author Compound
*/
contract CEther is CToken {
/**
* @notice Construct a new CEther money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) {
// Creator of the contract is admin during initialization
admin = payable(msg.sender);
initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Reverts upon any failure
*/
function mint() external payable {
mintInternal(msg.value);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
redeemInternal(redeemTokens);
return NO_ERROR;
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
redeemUnderlyingInternal(redeemAmount);
return NO_ERROR;
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
borrowInternal(borrowAmount);
return NO_ERROR;
}
/**
* @notice Sender repays their own borrow
* @dev Reverts upon any failure
*/
function repayBorrow() external payable {
repayBorrowInternal(msg.value);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @dev Reverts upon any failure
* @param borrower the account with the debt being payed off
*/
function repayBorrowBehalf(address borrower) external payable {
repayBorrowBehalfInternal(borrower, msg.value);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @dev Reverts upon any failure
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
*/
function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable {
liquidateBorrowInternal(borrower, msg.value, cTokenCollateral);
}
/**
* @notice The sender adds to reserves.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves() external payable returns (uint) {
return _addReservesInternal(msg.value);
}
/**
* @notice Send Ether to CEther to mint
*/
receive() external payable {
mintInternal(msg.value);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of Ether, before this message
* @dev This excludes the value of the current message, if any
* @return The quantity of Ether owned by this contract
*/
function getCashPrior() override internal view returns (uint) {
return address(this).balance - msg.value;
}
/**
* @notice Perform the actual transfer in, which is a no-op
* @param from Address sending the Ether
* @param amount Amount of Ether being sent
* @return The actual amount of Ether transferred
*/
function doTransferIn(address from, uint amount) override internal returns (uint) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount;
}
function doTransferOut(address payable to, uint amount) virtual override internal {
/* Send the Ether, with minimal gas and revert on failure */
to.transfer(amount);
}
}
================================================
FILE: protocols/compound-v2/src/CToken.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
import "./ExponentialNoError.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
abstract contract CToken is CTokenInterface, ExponentialNoError, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
admin = payable(address(msg.sender));
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == NO_ERROR, "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == NO_ERROR, "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return 0 if the transfer succeeded, else revert
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
revert TransferComptrollerRejection(allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
revert TransferNotAllowed();
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint).max;
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = startingAllowance - tokens;
uint srcTokensNew = accountTokens[src] - tokens;
uint dstTokensNew = accountTokens[dst] + tokens;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != type(uint).max) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return NO_ERROR;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == NO_ERROR;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) override external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == NO_ERROR;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (uint256.max means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) override external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) override external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) override external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) override external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) override external view returns (uint, uint, uint, uint) {
return (
NO_ERROR,
accountTokens[account],
borrowBalanceStoredInternal(account),
exchangeRateStoredInternal()
);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() virtual internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() override external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() override external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() override external nonReentrant returns (uint) {
accrueInterest();
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) override external nonReentrant returns (uint) {
accrueInterest();
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) override public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = borrowSnapshot.principal * borrowIndex;
return principalTimesIndex / borrowSnapshot.interestIndex;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() override public nonReentrant returns (uint) {
accrueInterest();
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() override public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() virtual internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves;
uint exchangeRate = cashPlusBorrowsMinusReserves * expScale / _totalSupply;
return exchangeRate;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() override external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() virtual override public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return NO_ERROR;
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
uint blockDelta = currentBlockNumber - accrualBlockNumberPrior;
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = interestAccumulated + borrowsPrior;
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return NO_ERROR;
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
*/
function mintInternal(uint mintAmount) internal nonReentrant {
accrueInterest();
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
mintFresh(msg.sender, mintAmount);
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
*/
function mintFresh(address minter, uint mintAmount) internal {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
revert MintComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert MintFreshnessCheck();
}
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
uint actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
uint mintTokens = div_(actualMintAmount, exchangeRate);
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
* And write them into storage
*/
totalSupply = totalSupply + mintTokens;
accountTokens[minter] = accountTokens[minter] + mintTokens;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, actualMintAmount, mintTokens);
emit Transfer(address(this), minter, mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
*/
function redeemInternal(uint redeemTokens) internal nonReentrant {
accrueInterest();
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(msg.sender), redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant {
accrueInterest();
// redeemFresh emits redeem-specific logs on errors, so we don't need to
redeemFresh(payable(msg.sender), 0, redeemAmount);
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
/* exchangeRate = invoke Exchange Rate Stored() */
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal() });
uint redeemTokens;
uint redeemAmount;
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
redeemTokens = redeemTokensIn;
redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
redeemTokens = div_(redeemAmountIn, exchangeRate);
redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, redeemTokens);
if (allowed != 0) {
revert RedeemComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RedeemFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < redeemAmount) {
revert RedeemTransferOutNotPossible();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing reduced supply before external transfer.
*/
totalSupply = totalSupply - redeemTokens;
accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens;
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, redeemAmount);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), redeemTokens);
emit Redeem(redeemer, redeemAmount, redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, redeemAmount, redeemTokens);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowInternal(uint borrowAmount) internal nonReentrant {
accrueInterest();
// borrowFresh emits borrow-specific logs on errors, so we don't need to
borrowFresh(payable(msg.sender), borrowAmount);
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
revert BorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert BorrowFreshnessCheck();
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
revert BorrowCashNotAvailable();
}
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowNew = accountBorrow + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
uint accountBorrowsNew = accountBorrowsPrev + borrowAmount;
uint totalBorrowsNew = totalBorrows + borrowAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We write the previously calculated values into storage.
* Note: Avoid token reentrancy attacks by writing increased borrow before external transfer.
`*/
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant {
accrueInterest();
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay, or -1 for the full outstanding amount
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant {
accrueInterest();
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
repayBorrowFresh(msg.sender, borrower, repayAmount);
}
// Testing function
function getAccountBorrows(address borrower) public view returns(uint principal, uint interestIndex) {
principal = accountBorrows[borrower].principal;
interestIndex = accountBorrows[borrower].interestIndex;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of underlying tokens being returned, or -1 for the full outstanding amount
* @return (uint) the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
revert RepayBorrowComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert RepayBorrowFreshnessCheck();
}
/* We fetch the amount the borrower owes, with accumulated interest */
uint accountBorrowsPrev = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
uint repayAmountFinal = repayAmount == type(uint).max ? accountBorrowsPrev : repayAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
uint actualRepayAmount = doTransferIn(payer, repayAmountFinal);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
uint accountBorrowsNew = accountBorrowsPrev - actualRepayAmount;
uint totalBorrowsNew = totalBorrows - actualRepayAmount;
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew);
return actualRepayAmount;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant {
accrueInterest();
uint error = cTokenCollateral.accrueInterest();
if (error != NO_ERROR) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
revert LiquidateAccrueCollateralInterestFailed(error);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
revert LiquidateComptrollerRejection(allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
revert LiquidateFreshnessCheck();
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
revert LiquidateCollateralFreshnessCheck();
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateLiquidatorIsBorrower();
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
revert LiquidateCloseAmountIsZero();
}
/* Fail if repayAmount = -1 */
if (repayAmount == type(uint).max) {
revert LiquidateCloseAmountIsUintMax();
}
/* Fail if repayBorrow fails */
uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == NO_ERROR, "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
if (address(cTokenCollateral) == address(this)) {
seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
require(cTokenCollateral.seize(liquidator, borrower, seizeTokens) == NO_ERROR, "token seizure failed");
}
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) override external nonReentrant returns (uint) {
seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
return NO_ERROR;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
revert LiquidateSeizeComptrollerRejection(allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
revert LiquidateSeizeLiquidatorIsBorrower();
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
uint protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));
uint liquidatorSeizeTokens = seizeTokens - protocolSeizeTokens;
Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});
uint protocolSeizeAmount = mul_ScalarTruncate(exchangeRate, protocolSeizeTokens);
uint totalReservesNew = totalReserves + protocolSeizeAmount;
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the calculated values into storage */
totalReserves = totalReservesNew;
totalSupply = totalSupply - protocolSeizeTokens;
accountTokens[borrower] = accountTokens[borrower] - seizeTokens;
accountTokens[liquidator] = accountTokens[liquidator] + liquidatorSeizeTokens;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, liquidatorSeizeTokens);
emit Transfer(borrower, address(this), protocolSeizeTokens);
emit ReservesAdded(address(this), protocolSeizeAmount, totalReservesNew);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) override external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
revert SetPendingAdminOwnerCheck();
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return NO_ERROR;
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() override external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
revert AcceptAdminPendingAdminCheck();
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = payable(address(0));
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return NO_ERROR;
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) override public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
revert SetComptrollerOwnerCheck();
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return NO_ERROR;
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) override external nonReentrant returns (uint) {
accrueInterest();
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
revert SetReserveFactorAdminCheck();
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetReserveFactorFreshCheck();
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
revert SetReserveFactorBoundsCheck();
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return NO_ERROR;
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
accrueInterest();
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
_addReservesFresh(addAmount);
return NO_ERROR;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert AddReservesFactorFreshCheck(actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (NO_ERROR, actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) override external nonReentrant returns (uint) {
accrueInterest();
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
revert ReduceReservesAdminCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert ReduceReservesFreshCheck();
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
revert ReduceReservesCashNotAvailable();
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
revert ReduceReservesCashValidation();
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return NO_ERROR;
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) override public returns (uint) {
accrueInterest();
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
revert SetInterestRateModelOwnerCheck();
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
revert SetInterestRateModelFreshCheck();
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return NO_ERROR;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() virtual internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) virtual internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure rather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) virtual internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
================================================
FILE: protocols/compound-v2/src/CTokenInterfaces.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
import "./ErrorReporter.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
// Maximum borrow rate that can ever be applied (.0005% / block)
uint internal constant borrowRateMaxMantissa = 0.0005e16;
// Maximum fraction of interest that can be set aside for reserves
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
// Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
// Official record of token balances for each account
mapping (address => uint) internal accountTokens;
// Approved token transfer amounts on behalf of others
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
// Mapping of account addresses to outstanding borrow balances
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Share of seized collateral that is added to reserves
*/
uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8%
}
abstract contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/*** User Interface ***/
function transfer(address dst, uint amount) virtual external returns (bool);
function transferFrom(address src, address dst, uint amount) virtual external returns (bool);
function approve(address spender, uint amount) virtual external returns (bool);
function allowance(address owner, address spender) virtual external view returns (uint);
function balanceOf(address owner) virtual external view returns (uint);
function balanceOfUnderlying(address owner) virtual external returns (uint);
function getAccountSnapshot(address account) virtual external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() virtual external view returns (uint);
function supplyRatePerBlock() virtual external view returns (uint);
function totalBorrowsCurrent() virtual external returns (uint);
function borrowBalanceCurrent(address account) virtual external returns (uint);
function borrowBalanceStored(address account) virtual external view returns (uint);
function exchangeRateCurrent() virtual external returns (uint);
function exchangeRateStored() virtual external view returns (uint);
function getCash() virtual external view returns (uint);
function accrueInterest() virtual external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) virtual external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) virtual external returns (uint);
function _acceptAdmin() virtual external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) virtual external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) virtual external returns (uint);
function _reduceReserves(uint reduceAmount) virtual external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) virtual external returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
abstract contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) virtual external returns (uint);
function redeem(uint redeemTokens) virtual external returns (uint);
function redeemUnderlying(uint redeemAmount) virtual external returns (uint);
function borrow(uint borrowAmount) virtual external returns (uint);
function repayBorrow(uint repayAmount) virtual external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) virtual external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) virtual external returns (uint);
function sweepToken(EIP20NonStandardInterface token) virtual external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) virtual external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) virtual external;
}
abstract contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) virtual external;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() virtual external;
}
================================================
FILE: protocols/compound-v2/src/Comptroller.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/Comp.sol";
/**
* @title Compound's Comptroller Contract
* @author Compound
*/
contract Comptroller is ComptrollerV7Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when a new borrow-side COMP speed is calculated for a market
event CompBorrowSpeedUpdated(CToken indexed cToken, uint newSpeed);
/// @notice Emitted when a new supply-side COMP speed is calculated for a market
event CompSupplySpeedUpdated(CToken indexed cToken, uint newSpeed);
/// @notice Emitted when a new COMP speed is set for a contributor
event ContributorCompSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when COMP is granted by admin
event CompGranted(address recipient, uint amount);
/// @notice Emitted when COMP accrued for a user has been manually adjusted.
event CompAccruedAdjusted(address indexed user, uint oldCompAccrued, uint newCompAccrued);
/// @notice Emitted when COMP receivable for a user has been updated.
event CompReceivableUpdated(address indexed user, uint oldCompReceivable, uint newCompReceivable);
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) override public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) override external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) override external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) override external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) override external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) override external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) override external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) override external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) override external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
/* allow accounts to be liquidated if the market is deprecated */
if (isDeprecated(CToken(cTokenBorrowed))) {
require(borrowBalance >= repayAmount, "Can not repay more than the total borrow");
} else {
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) override external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
distributeSupplierComp(cTokenCollateral, borrower);
distributeSupplierComp(cTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) override external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, src);
distributeSupplierComp(cToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) override external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(address(0)), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(address(0)), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) override external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
// Note that isComped is not in active use anymore
Market storage newMarket = markets[address(cToken)];
newMarket.isListed = true;
newMarket.isComped = false;
newMarket.collateralFactorMantissa = 0;
_addMarketInternal(address(cToken));
_initializeMarket(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
function _initializeMarket(address cToken) internal {
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
CompMarketState storage supplyState = compSupplyState[cToken];
CompMarketState storage borrowState = compBorrowState[cToken];
/*
* Update market state indices
*/
if (supplyState.index == 0) {
// Initialize supply state index with default value
supplyState.index = compInitialIndex;
}
if (borrowState.index == 0) {
// Initialize borrow state index with default value
borrowState.index = compInitialIndex;
}
/*
* Update market state block numbers
*/
supplyState.block = borrowState.block = blockNumber;
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/// @notice Delete this function after proposal 65 is executed
function fixBadAccruals(address[] calldata affectedUsers, uint[] calldata amounts) external {
require(msg.sender == admin, "Only admin can call this function"); // Only the timelock can call this function
require(!proposal65FixExecuted, "Already executed this one-off function"); // Require that this function is only called once
require(affectedUsers.length == amounts.length, "Invalid input");
// Loop variables
address user;
uint currentAccrual;
uint amountToSubtract;
uint newAccrual;
// Iterate through all affected users
for (uint i = 0; i < affectedUsers.length; ++i) {
user = affectedUsers[i];
currentAccrual = compAccrued[user];
amountToSubtract = amounts[i];
// The case where the user has claimed and received an incorrect amount of COMP.
// The user has less currently accrued than the amount they incorrectly received.
if (amountToSubtract > currentAccrual) {
// Amount of COMP the user owes the protocol
uint accountReceivable = amountToSubtract - currentAccrual; // Underflow safe since amountToSubtract > currentAccrual
uint oldReceivable = compReceivable[user];
uint newReceivable = add_(oldReceivable, accountReceivable);
// Accounting: record the COMP debt for the user
compReceivable[user] = newReceivable;
emit CompReceivableUpdated(user, oldReceivable, newReceivable);
amountToSubtract = currentAccrual;
}
if (amountToSubtract > 0) {
// Subtract the bad accrual amount from what they have accrued.
// Users will keep whatever they have correctly accrued.
compAccrued[user] = newAccrual = sub_(currentAccrual, amountToSubtract);
emit CompAccruedAdjusted(user, currentAccrual, newAccrual);
}
}
proposal65FixExecuted = true; // Makes it so that this function cannot be called again
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Comp Distribution ***/
/**
* @notice Set COMP speed for a single market
* @param cToken The market whose COMP speed to update
* @param supplySpeed New supply-side COMP speed for market
* @param borrowSpeed New borrow-side COMP speed for market
*/
function setCompSpeedInternal(CToken cToken, uint supplySpeed, uint borrowSpeed) internal {
Market storage market = markets[address(cToken)];
require(market.isListed, "comp market is not listed");
if (compSupplySpeeds[address(cToken)] != supplySpeed) {
// Supply speed updated so let's update supply state to ensure that
// 1. COMP accrued properly for the old speed, and
// 2. COMP accrued at the new speed starts after this block.
updateCompSupplyIndex(address(cToken));
// Update speed and emit event
compSupplySpeeds[address(cToken)] = supplySpeed;
emit CompSupplySpeedUpdated(cToken, supplySpeed);
}
if (compBorrowSpeeds[address(cToken)] != borrowSpeed) {
// Borrow speed updated so let's update borrow state to ensure that
// 1. COMP accrued properly for the old speed, and
// 2. COMP accrued at the new speed starts after this block.
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
// Update speed and emit event
compBorrowSpeeds[address(cToken)] = borrowSpeed;
emit CompBorrowSpeedUpdated(cToken, borrowSpeed);
}
}
/**
* @notice Accrue COMP to the market by updating the supply index
* @param cToken The market whose supply index to update
* @dev Index is a cumulative sum of the COMP per cToken accrued.
*/
function updateCompSupplyIndex(address cToken) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplySpeed = compSupplySpeeds[cToken];
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
uint deltaBlocks = sub_(uint(blockNumber), uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = CToken(cToken).totalSupply();
uint compAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0});
supplyState.index = safe224(add_(Double({mantissa: supplyState.index}), ratio).mantissa, "new index exceeds 224 bits");
supplyState.block = blockNumber;
} else if (deltaBlocks > 0) {
supplyState.block = blockNumber;
}
}
/**
* @notice Accrue COMP to the market by updating the borrow index
* @param cToken The market whose borrow index to update
* @dev Index is a cumulative sum of the COMP per cToken accrued.
*/
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compBorrowSpeeds[cToken];
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
uint deltaBlocks = sub_(uint(blockNumber), uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0});
borrowState.index = safe224(add_(Double({mantissa: borrowState.index}), ratio).mantissa, "new index exceeds 224 bits");
borrowState.block = blockNumber;
} else if (deltaBlocks > 0) {
borrowState.block = blockNumber;
}
}
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier) internal {
// TODO: Don't distribute supplier COMP if the user is not in the supplier market.
// This check should be as gas efficient as possible as distributeSupplierComp is called in many places.
// - We really don't want to call an external contract as that's quite expensive.
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplyIndex = supplyState.index;
uint supplierIndex = compSupplierIndex[cToken][supplier];
// Update supplier's index to the current index since we are distributing accrued COMP
compSupplierIndex[cToken][supplier] = supplyIndex;
if (supplierIndex == 0 && supplyIndex >= compInitialIndex) {
// Covers the case where users supplied tokens before the market's supply state index was set.
// Rewards the user with COMP accrued from the start of when supplier rewards were first
// set for the market.
supplierIndex = compInitialIndex;
}
// Calculate change in the cumulative sum of the COMP per cToken accrued
Double memory deltaIndex = Double({mantissa: sub_(supplyIndex, supplierIndex)});
uint supplierTokens = CToken(cToken).balanceOf(supplier);
// Calculate COMP accrued: cTokenAmount * accruedPerCToken
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = supplierAccrued;
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex) internal {
// TODO: Don't distribute supplier COMP if the user is not in the borrower market.
// This check should be as gas efficient as possible as distributeBorrowerComp is called in many places.
// - We really don't want to call an external contract as that's quite expensive.
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowIndex = borrowState.index;
uint borrowerIndex = compBorrowerIndex[cToken][borrower];
// Update borrowers's index to the current index since we are distributing accrued COMP
compBorrowerIndex[cToken][borrower] = borrowIndex;
if (borrowerIndex == 0 && borrowIndex >= compInitialIndex) {
// Covers the case where users borrowed tokens before the market's borrow state index was set.
// Rewards the user with COMP accrued from the start of when borrower rewards were first
// set for the market.
borrowerIndex = compInitialIndex;
}
// Calculate change in the cumulative sum of the COMP per borrowed unit accrued
Double memory deltaIndex = Double({mantissa: sub_(borrowIndex, borrowerIndex)});
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
// Calculate COMP accrued: cTokenAmount * accruedPerBorrowedUnit
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex);
}
/**
* @notice Calculate additional accrued COMP for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint compSpeed = compContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && compSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, compSpeed);
uint contributorAccrued = add_(compAccrued[contributor], newAccrued);
compAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
return claimComp(holder, allMarkets);
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim COMP for
* @param cTokens The list of markets to claim COMP in
*/
function claimComp(address holder, CToken[] memory cTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimComp(holders, cTokens, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex);
}
}
if (suppliers == true) {
updateCompSupplyIndex(address(cToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j]);
}
}
}
for (uint j = 0; j < holders.length; j++) {
compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]);
}
}
/**
* @notice Transfer COMP to the user
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param amount The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function grantCompInternal(address user, uint amount) internal returns (uint) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (amount > 0 && amount <= compRemaining) {
comp.transfer(user, amount);
return 0;
}
return amount;
}
/*** Comp Distribution Admin ***/
/**
* @notice Transfer COMP to the recipient
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer COMP to
* @param amount The amount of COMP to (possibly) transfer
*/
function _grantComp(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant comp");
uint amountLeft = grantCompInternal(recipient, amount);
require(amountLeft == 0, "insufficient comp for grant");
emit CompGranted(recipient, amount);
}
/**
* @notice Set COMP borrow and supply speeds for the specified markets.
* @param cTokens The markets whose COMP speed to update.
* @param supplySpeeds New supply-side COMP speed for the corresponding market.
* @param borrowSpeeds New borrow-side COMP speed for the corresponding market.
*/
function _setCompSpeeds(CToken[] memory cTokens, uint[] memory supplySpeeds, uint[] memory borrowSpeeds) public {
require(adminOrInitializing(), "only admin can set comp speed");
uint numTokens = cTokens.length;
require(numTokens == supplySpeeds.length && numTokens == borrowSpeeds.length, "Comptroller::_setCompSpeeds invalid input");
for (uint i = 0; i < numTokens; ++i) {
setCompSpeedInternal(cTokens[i], supplySpeeds[i], borrowSpeeds[i]);
}
}
/**
* @notice Set COMP speed for a single contributor
* @param contributor The contributor whose COMP speed to update
* @param compSpeed New COMP speed for contributor
*/
function _setContributorCompSpeed(address contributor, uint compSpeed) public {
require(adminOrInitializing(), "only admin can set comp speed");
// note that COMP speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (compSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
compContributorSpeeds[contributor] = compSpeed;
emit ContributorCompSpeedUpdated(contributor, compSpeed);
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
/**
* @notice Returns true if the given cToken market has been deprecated
* @dev All borrows in a deprecated cToken market can be immediately liquidated
* @param cToken The market to check if deprecated
*/
function isDeprecated(CToken cToken) public view returns (bool) {
return
markets[address(cToken)].collateralFactorMantissa == 0 &&
borrowGuardianPaused[address(cToken)] == true &&
cToken.reserveFactorMantissa() == 1e18
;
}
function getBlockNumber() virtual public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCompAddress() virtual public view returns (address) {
return 0xc00e94Cb662C3520282E6f5717214004A7f26888;//todo???
}
}
================================================
FILE: protocols/compound-v2/src/ComptrollerG7.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/Comp.sol";
/**
* @title Compound's Comptroller Contract
* @author Compound
*/
contract ComptrollerG7 is ComptrollerV5Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when a new COMP speed is calculated for a market
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed);
/// @notice Emitted when a new COMP speed is set for a contributor
event ContributorCompSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when COMP is granted by admin
event CompGranted(address recipient, uint amount);
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) override public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) override external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) override external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) override external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) override external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) override external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) override external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) override external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) override external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) override external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
distributeSupplierComp(cTokenCollateral, borrower);
distributeSupplierComp(cTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) override external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) override external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, src);
distributeSupplierComp(cToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) override external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(address(0)), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(address(0)), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) override external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
// Note that isComped is not in active use anymore
Market storage market = markets[address(cToken)];
market.isListed = true;
market.isComped = false;
market.collateralFactorMantissa = 0;
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Comp Distribution ***/
/**
* @notice Set COMP speed for a single market
* @param cToken The market whose COMP speed to update
* @param compSpeed New COMP speed for market
*/
function setCompSpeedInternal(CToken cToken, uint compSpeed) internal {
uint currentCompSpeed = compSpeeds[address(cToken)];
if (currentCompSpeed != 0) {
// note that COMP speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompSupplyIndex(address(cToken));
updateCompBorrowIndex(address(cToken), borrowIndex);
} else if (compSpeed != 0) {
// Add the COMP market
Market storage market = markets[address(cToken)];
require(market.isListed == true, "comp market is not listed");
if (compSupplyState[address(cToken)].index == 0 && compSupplyState[address(cToken)].block == 0) {
compSupplyState[address(cToken)] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (compBorrowState[address(cToken)].index == 0 && compBorrowState[address(cToken)].block == 0) {
compBorrowState[address(cToken)] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentCompSpeed != compSpeed) {
compSpeeds[address(cToken)] = compSpeed;
emit CompSpeedUpdated(cToken, compSpeed);
}
}
/**
* @notice Accrue COMP to the market by updating the supply index
* @param cToken The market whose supply index to update
*/
function updateCompSupplyIndex(address cToken) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplySpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = CToken(cToken).totalSupply();
uint compAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
compSupplyState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue COMP to the market by updating the borrow index
* @param cToken The market whose borrow index to update
*/
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
compBorrowState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = supplierAccrued;
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]});
compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued COMP for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint compSpeed = compContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && compSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, compSpeed);
uint contributorAccrued = add_(compAccrued[contributor], newAccrued);
compAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
return claimComp(holder, allMarkets);
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim COMP for
* @param cTokens The list of markets to claim COMP in
*/
function claimComp(address holder, CToken[] memory cTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimComp(holders, cTokens, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex);
compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateCompSupplyIndex(address(cToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j]);
compAccrued[holders[j]] = grantCompInternal(holders[j], compAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer COMP to the user
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param amount The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function grantCompInternal(address user, uint amount) internal returns (uint) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (amount > 0 && amount <= compRemaining) {
comp.transfer(user, amount);
return 0;
}
return amount;
}
/*** Comp Distribution Admin ***/
/**
* @notice Transfer COMP to the recipient
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer COMP to
* @param amount The amount of COMP to (possibly) transfer
*/
function _grantComp(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant comp");
uint amountLeft = grantCompInternal(recipient, amount);
require(amountLeft == 0, "insufficient comp for grant");
emit CompGranted(recipient, amount);
}
/**
* @notice Set COMP speed for a single market
* @param cToken The market whose COMP speed to update
* @param compSpeed New COMP speed for market
*/
function _setCompSpeed(CToken cToken, uint compSpeed) public {
require(adminOrInitializing(), "only admin can set comp speed");
setCompSpeedInternal(cToken, compSpeed);
}
/**
* @notice Set COMP speed for a single contributor
* @param contributor The contributor whose COMP speed to update
* @param compSpeed New COMP speed for contributor
*/
function _setContributorCompSpeed(address contributor, uint compSpeed) public {
require(adminOrInitializing(), "only admin can set comp speed");
// note that COMP speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (compSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
compContributorSpeeds[contributor] = compSpeed;
emit ContributorCompSpeedUpdated(contributor, compSpeed);
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCompAddress() public view returns (address) {
return 0xc00e94Cb662C3520282E6f5717214004A7f26888;
}
}
================================================
FILE: protocols/compound-v2/src/ComptrollerInterface.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
abstract contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) virtual external returns (uint[] memory);
function exitMarket(address cToken) virtual external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) virtual external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) virtual external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) virtual external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) virtual external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) virtual external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) virtual external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) virtual external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) virtual external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) virtual external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) virtual external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) virtual external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) virtual external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) virtual external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) virtual external view returns (uint, uint);
}
================================================
FILE: protocols/compound-v2/src/ComptrollerStorage.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
import "./PriceOracle.sol";
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct CompMarketState {
// The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes COMP, per block
uint public compRate;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public compSpeeds;
/// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP market borrow state for each market
mapping(address => CompMarketState) public compBorrowState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compSupplierIndex;
/// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint) public compAccrued;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract ComptrollerV5Storage is ComptrollerV4Storage {
/// @notice The portion of COMP that each contributor receives per block
mapping(address => uint) public compContributorSpeeds;
/// @notice Last block at which a contributor's COMP rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract ComptrollerV6Storage is ComptrollerV5Storage {
/// @notice The rate at which comp is distributed to the corresponding borrow market (per block)
mapping(address => uint) public compBorrowSpeeds;
/// @notice The rate at which comp is distributed to the corresponding supply market (per block)
mapping(address => uint) public compSupplySpeeds;
}
contract ComptrollerV7Storage is ComptrollerV6Storage {
/// @notice Flag indicating whether the function to fix COMP accruals has been executed (RE: proposal 62 bug)
bool public proposal65FixExecuted;
/// @notice Accounting storage mapping account addresses to how much COMP they owe the protocol.
mapping(address => uint) public compReceivable;
}
================================================
FILE: protocols/compound-v2/src/DAIInterestRateModelV3.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./JumpRateModelV2.sol";
/**
* @title Compound's DAIInterestRateModel Contract (version 3)
* @author Compound (modified by Dharma Labs)
* @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper.
* Version 3 modifies the interest rate model in Version 2 by increasing the initial "gap" or slope of
* the model prior to the "kink" from 2% to 4%, and enabling updateable parameters.
*/
contract DAIInterestRateModelV3 is JumpRateModelV2 {
uint256 private constant BASE = 1e18;
uint256 private constant RAY_BASE = 1e27;
uint256 private constant RAY_TO_BASE_SCALE = 1e9;
uint256 private constant SECONDS_PER_BLOCK = 15;
/**
* @notice The additional margin per block separating the base borrow rate from the roof.
*/
uint public gapPerBlock;
/**
* @notice The assumed (1 - reserve factor) used to calculate the minimum borrow rate (reserve factor = 0.05)
*/
uint public constant assumedOneMinusReserveFactorMantissa = 0.95e18;
PotLike pot;
JugLike jug;
/**
* @notice Construct an interest rate model
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param pot_ The address of the Dai pot (where DSR is earned)
* @param jug_ The address of the Dai jug (where SF is kept)
* @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
*/
constructor(uint jumpMultiplierPerYear, uint kink_, address pot_, address jug_, address owner_) JumpRateModelV2(0, 0, jumpMultiplierPerYear, kink_, owner_) public {
gapPerBlock = 4e16 / blocksPerYear;
pot = PotLike(pot_);
jug = JugLike(jug_);
poke();
}
/**
* @notice External function to update the parameters of the interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE). For DAI, this is calculated from DSR and SF. Input not used.
* @param gapPerYear The Additional margin per year separating the base borrow rate from the roof. (scaled by BASE)
* @param jumpMultiplierPerYear The jumpMultiplierPerYear after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) override external {
require(msg.sender == owner, "only the owner may call this function.");
gapPerBlock = gapPerYear / blocksPerYear;
updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_);
poke();
}
/**
* @notice Calculates the current supply interest rate per block including the Dai savings rate
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by BASE)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) override(BaseJumpRateModelV2, InterestRateModel) public view returns (uint) {
uint protocolRate = super.getSupplyRate(cash, borrows, reserves, reserveFactorMantissa);
uint underlying = cash + borrows - reserves;
if (underlying == 0) {
return protocolRate;
} else {
uint cashRate = cash * dsrPerBlock() / underlying;
return cashRate + protocolRate;
}
}
/**
* @notice Calculates the Dai savings rate per block
* @return The Dai savings rate per block (as a percentage, and scaled by BASE)
*/
function dsrPerBlock() public view returns (uint) {
return (pot.dsr() - RAY_BASE) // scaled RAY_BASE aka RAY, and includes an extra "ONE" before subtraction
/ RAY_TO_BASE_SCALE // descale to BASE
* SECONDS_PER_BLOCK; // seconds per block
}
/**
* @notice Resets the baseRate and multiplier per block based on the stability fee and Dai savings rate
*/
function poke() public {
(uint duty, ) = jug.ilks("ETH-A");
uint stabilityFeePerBlock = (duty + jug.base() - RAY_BASE) / RAY_TO_BASE_SCALE * SECONDS_PER_BLOCK;
// We ensure the minimum borrow rate >= DSR / (1 - reserve factor)
baseRatePerBlock = dsrPerBlock() * BASE / assumedOneMinusReserveFactorMantissa;
// The roof borrow rate is max(base rate, stability fee) + gap, from which we derive the slope
if (baseRatePerBlock < stabilityFeePerBlock) {
multiplierPerBlock = (stabilityFeePerBlock - baseRatePerBlock + gapPerBlock) * BASE / kink;
} else {
multiplierPerBlock = gapPerBlock * BASE / kink;
}
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);
}
}
/*** Maker Interfaces ***/
interface PotLike {
function chi() external view returns (uint);
function dsr() external view returns (uint);
function rho() external view returns (uint);
function pie(address) external view returns (uint);
function drip() external returns (uint);
function join(uint) external;
function exit(uint) external;
}
contract JugLike {
// --- Data ---
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public base;
}
================================================
FILE: protocols/compound-v2/src/EIP20Interface.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
================================================
FILE: protocols/compound-v2/src/EIP20NonStandardInterface.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
================================================
FILE: protocols/compound-v2/src/ErrorReporter.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
uint public constant NO_ERROR = 0; // support legacy return codes
error TransferComptrollerRejection(uint256 errorCode);
error TransferNotAllowed();
error TransferNotEnough();
error TransferTooMuch();
error MintComptrollerRejection(uint256 errorCode);
error MintFreshnessCheck();
error RedeemComptrollerRejection(uint256 errorCode);
error RedeemFreshnessCheck();
error RedeemTransferOutNotPossible();
error BorrowComptrollerRejection(uint256 errorCode);
error BorrowFreshnessCheck();
error BorrowCashNotAvailable();
error RepayBorrowComptrollerRejection(uint256 errorCode);
error RepayBorrowFreshnessCheck();
error LiquidateComptrollerRejection(uint256 errorCode);
error LiquidateFreshnessCheck();
error LiquidateCollateralFreshnessCheck();
error LiquidateAccrueBorrowInterestFailed(uint256 errorCode);
error LiquidateAccrueCollateralInterestFailed(uint256 errorCode);
error LiquidateLiquidatorIsBorrower();
error LiquidateCloseAmountIsZero();
error LiquidateCloseAmountIsUintMax();
error LiquidateRepayBorrowFreshFailed(uint256 errorCode);
error LiquidateSeizeComptrollerRejection(uint256 errorCode);
error LiquidateSeizeLiquidatorIsBorrower();
error AcceptAdminPendingAdminCheck();
error SetComptrollerOwnerCheck();
error SetPendingAdminOwnerCheck();
error SetReserveFactorAdminCheck();
error SetReserveFactorFreshCheck();
error SetReserveFactorBoundsCheck();
error AddReservesFactorFreshCheck(uint256 actualAddAmount);
error ReduceReservesAdminCheck();
error ReduceReservesFreshCheck();
error ReduceReservesCashNotAvailable();
error ReduceReservesCashValidation();
error SetInterestRateModelOwnerCheck();
error SetInterestRateModelFreshCheck();
}
================================================
FILE: protocols/compound-v2/src/ExponentialNoError.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return a + b;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return a * b;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
================================================
FILE: protocols/compound-v2/src/Governance/Comp.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
================================================
FILE: protocols/compound-v2/src/Governance/GovernorAlpha.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "Compound Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 400000e18; } // 400,000 = 4% of Comp
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Comp
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() virtual public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address comp_, address guardian_) public {
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
uint proposalId = proposalCount;
Proposal storage newProposal = proposals[proposalId];
// This should never happen but add a check in case.
require(newProposal.id == 0, "GovernorAlpha::propose: ProposalID collsion");
newProposal.id = proposalId;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
================================================
FILE: protocols/compound-v2/src/Governance/GovernorBravoDelegate.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegate is GovernorBravoDelegateStorageV2, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "Compound Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 1000e18; // 1,000 Comp
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 10; // 10 actions
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator constructor
* @param timelock_ The address of the Timelock
* @param comp_ The address of the COMP token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) virtual public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(msg.sender == admin, "GovernorBravo::initialize: admin only");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
// Reject proposals before initiating as Governor
require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active");
// Allow addresses above proposal threshold and whitelisted addresses to propose
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold || isWhitelisted(msg.sender), "GovernorBravo::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
uint newProposalID = proposalCount;
Proposal storage newProposal = proposals[newProposalID];
// This should never happen but add a check in case.
require(newProposal.id == 0, "GovernorBravo::propose: ProposalID collsion");
newProposal.id = newProposalID;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.abstainVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
// Proposer can cancel
if(msg.sender != proposal.proposer) {
// Whitelisted proposers can't be canceled for falling below proposal threshold
if(isWhitelisted(proposal.proposer)) {
require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold) && msg.sender == whitelistGuardian, "GovernorBravo::cancel: whitelisted proposer");
}
else {
require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold), "GovernorBravo::cancel: proposer above threshold");
}
}
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return targets of the proposal actions
* @return values of the proposal actions
* @return signatures of the proposal actions
* @return calldatas of the proposal actions
*/
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice View function which returns if an account is whitelisted
* @param account Account to check white list status of
* @return If the account is whitelisted
*/
function isWhitelisted(address account) public view returns (bool) {
return (whitelistAccountExpirations[account] > block.timestamp);
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function _setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Admin function for setting the whitelist expiration as a timestamp for an account. Whitelist status allows accounts to propose without meeting threshold
* @param account Account address to set whitelist expiration for
* @param expiration Expiration for account whitelist status as timestamp (if now < expiration, whitelisted)
*/
function _setWhitelistAccountExpiration(address account, uint expiration) external {
require(msg.sender == admin || msg.sender == whitelistGuardian, "GovernorBravo::_setWhitelistAccountExpiration: admin only");
whitelistAccountExpirations[account] = expiration;
emit WhitelistAccountExpirationSet(account, expiration);
}
/**
* @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses
* @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian)
*/
function _setWhitelistGuardian(address account) external {
require(msg.sender == admin, "GovernorBravo::_setWhitelistGuardian: admin only");
address oldGuardian = whitelistGuardian;
whitelistGuardian = account;
emit WhitelistGuardianSet(oldGuardian, whitelistGuardian);
}
/**
* @notice Initiate the GovernorBravo contract
* @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count
* @param governorAlpha The address for the Governor to continue the proposal id count from
*/
function _initiate(address governorAlpha) external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = GovernorAlpha(governorAlpha).proposalCount();
initialProposalId = proposalCount;
timelock.acceptAdmin();
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainIdInternal() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
================================================
FILE: protocols/compound-v2/src/Governance/GovernorBravoDelegateG1.sol
================================================
pragma solidity ^0.8.10;
pragma experimental ABIEncoderV2;
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "Compound Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 10; // 10 actions
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator constructor
* @param timelock_ The address of the Timelock
* @param comp_ The address of the COMP token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(msg.sender == admin, "GovernorBravo::initialize: admin only");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
// Reject proposals before initiating as Governor
require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active");
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
// This should never happen but add a check in case.
require(newProposal.id == 0, "GovernorBravo::propose: ProposalID collsion");
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.abstainVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == proposal.proposer || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold, "GovernorBravo::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return targets of the proposal actions
* @return values of the proposal actions
* @return signatures of the proposal actions
* @return calldatas of the proposal actions
*/
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function _setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Initiate the GovernorBravo contract
* @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count
* @param governorAlpha The address for the Governor to continue the proposal id count from
*/
function _initiate(address governorAlpha) external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = GovernorAlpha(governorAlpha).proposalCount();
initialProposalId = proposalCount;
timelock.acceptAdmin();
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainIdInternal() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
================================================
FILE: protocols/compound-v2/src/Governance/GovernorBravoDelegateG2.sol
================================================
/*pragma solidity >=0.5.16;
pragma experimental ABIEncoderV2;
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegate is GovernorBravoDelegateStorageV2, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "Compound Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 10; // 10 actions
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator contructor
* @param timelock_ The address of the Timelock
* @param comp_ The address of the COMP token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
/* function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(msg.sender == admin, "GovernorBravo::initialize: admin only");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
/* function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
// Reject proposals before initiating as Governor
require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active");
// Allow addresses above proposal threshold and whitelisted addresses to propose
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold || isWhitelisted(msg.sender), "GovernorBravo::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
/* function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
/* function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
/* function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
// Proposer can cancel
if(msg.sender != proposal.proposer) {
// Whitelisted proposers can't be canceled for falling below proposal threshold
if(isWhitelisted(proposal.proposer)) {
require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold) && msg.sender == whitelistGuardian, "GovernorBravo::cancel: whitelisted proposer");
}
else {
require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold), "GovernorBravo::cancel: proposer above threshold");
}
}
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return Targets, values, signatures, and calldatas of the proposal actions
*/
/* function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
/* function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
/* function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
/* function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
/* function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
/* function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
/* function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice View function which returns if an account is whitelisted
* @param account Account to check white list status of
* @return If the account is whitelisted
*/
/* function isWhitelisted(address account) public view returns (bool) {
return (whitelistAccountExpirations[account] > now);
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
/* function _setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
/* function _setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
/* function _setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Admin function for setting the whitelist expiration as a timestamp for an account. Whitelist status allows accounts to propose without meeting threshold
* @param account Account address to set whitelist expiration for
* @param expiration Expiration for account whitelist status as timestamp (if now < expiration, whitelisted)
*/
/* function _setWhitelistAccountExpiration(address account, uint expiration) external {
require(msg.sender == admin || msg.sender == whitelistGuardian, "GovernorBravo::_setWhitelistAccountExpiration: admin only");
whitelistAccountExpirations[account] = expiration;
emit WhitelistAccountExpirationSet(account, expiration);
}
/**
* @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses
* @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian)
*/
/* function _setWhitelistGuardian(address account) external {
require(msg.sender == admin, "GovernorBravo::_setWhitelistGuardian: admin only");
address oldGuardian = whitelistGuardian;
whitelistGuardian = account;
emit WhitelistGuardianSet(oldGuardian, whitelistGuardian);
}
/**
* @notice Initiate the GovernorBravo contract
* @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count
* @param governorAlpha The address for the Governor to continue the proposal id count from
*/
/* function _initiate(address governorAlpha) external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = GovernorAlpha(governorAlpha).proposalCount();
initialProposalId = proposalCount;
timelock.acceptAdmin();
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
/* function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
/* function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainIdInternal() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
*/
================================================
FILE: protocols/compound-v2/src/Governance/GovernorBravoDelegator.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegator is GovernorBravoDelegatorStorage, GovernorBravoEvents {
constructor(
address timelock_,
address comp_,
address admin_,
address implementation_,
uint votingPeriod_,
uint votingDelay_,
uint proposalThreshold_) public {
// Admin set to msg.sender for initialization
admin = msg.sender;
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,uint256,uint256,uint256)",
timelock_,
comp_,
votingPeriod_,
votingDelay_,
proposalThreshold_));
_setImplementation(implementation_);
admin = admin_;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
*/
function _setImplementation(address implementation_) public {
require(msg.sender == admin, "GovernorBravoDelegator::_setImplementation: admin only");
require(implementation_ != address(0), "GovernorBravoDelegator::_setImplementation: invalid implementation address");
address oldImplementation = implementation;
implementation = implementation_;
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
*/
function delegateTo(address callee, bytes memory data) internal {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback () external payable {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
================================================
FILE: protocols/compound-v2/src/Governance/GovernorBravoInterfaces.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
contract GovernorBravoEvents {
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
/// @param voter The address which casted a vote
/// @param proposalId The proposal id which was voted on
/// @param support Support value for the vote. 0=against, 1=for, 2=abstain
/// @param votes Number of votes which were cast by the voter
/// @param reason The reason given for the vote by the voter
event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
/// @notice An event emitted when the voting delay is set
event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay);
/// @notice An event emitted when the voting period is set
event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod);
/// @notice Emitted when implementation is changed
event NewImplementation(address oldImplementation, address newImplementation);
/// @notice Emitted when proposal threshold is set
event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
/// @notice Emitted when whitelist account expiration is set
event WhitelistAccountExpirationSet(address account, uint expiration);
/// @notice Emitted when the whitelistGuardian is set
event WhitelistGuardianSet(address oldGuardian, address newGuardian);
}
contract GovernorBravoDelegatorStorage {
/// @notice Administrator for this contract
address public admin;
/// @notice Pending administrator for this contract
address public pendingAdmin;
/// @notice Active brains of Governor
address public implementation;
}
/**
* @title Storage for Governor Bravo Delegate
* @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new
* contract which implements GovernorBravoDelegateStorageV1 and following the naming convention
* GovernorBravoDelegateStorageVX.
*/
contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage {
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The number of votes required in order for a voter to become a proposer
uint public proposalThreshold;
/// @notice Initial proposal id set at become
uint public initialProposalId;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Current number of votes for abstaining for this proposal
uint abstainVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal or abstains
uint8 support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
}
contract GovernorBravoDelegateStorageV2 is GovernorBravoDelegateStorageV1 {
/// @notice Stores the expiration of account whitelist status as a timestamp
mapping (address => uint) public whitelistAccountExpirations;
/// @notice Address which manages whitelisted proposals and whitelist accounts
address public whitelistGuardian;
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
interface GovernorAlpha {
/// @notice The total number of proposals
function proposalCount() external returns (uint);
}
================================================
FILE: protocols/compound-v2/src/InterestRateModel.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
abstract contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) virtual external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) virtual external view returns (uint);
}
================================================
FILE: protocols/compound-v2/src/JumpRateModel.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./InterestRateModel.sol";
/**
* @title Compound's JumpRateModel Contract
* @author Compound
*/
contract JumpRateModel is InterestRateModel {
event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink);
uint256 private constant BASE = 1e18;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint public constant blocksPerYear = 2102400;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint public baseRatePerBlock;
/**
* @notice The multiplierPerBlock after hitting a specified utilization point
*/
uint public jumpMultiplierPerBlock;
/**
* @notice The utilization point at which the jump multiplier is applied
*/
uint public kink;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) public {
baseRatePerBlock = baseRatePerYear / blocksPerYear;
multiplierPerBlock = multiplierPerYear / blocksPerYear;
jumpMultiplierPerBlock = jumpMultiplierPerYear / blocksPerYear;
kink = kink_;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, BASE]
*/
function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
return borrows * BASE / (cash + borrows - reserves);
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by BASE)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) override public view returns (uint) {
uint util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return (util * multiplierPerBlock / BASE) + baseRatePerBlock;
} else {
uint normalRate = (kink * multiplierPerBlock / BASE) + baseRatePerBlock;
uint excessUtil = util - kink;
return (excessUtil * jumpMultiplierPerBlock/ BASE) + normalRate;
}
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by BASE)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) override public view returns (uint) {
uint oneMinusReserveFactor = BASE - reserveFactorMantissa;
uint borrowRate = getBorrowRate(cash, borrows, reserves);
uint rateToPool = borrowRate * oneMinusReserveFactor / BASE;
return utilizationRate(cash, borrows, reserves) * rateToPool / BASE;
}
}
================================================
FILE: protocols/compound-v2/src/JumpRateModelV2.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./BaseJumpRateModelV2.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's JumpRateModel Contract V2 for V2 cTokens
* @author Arr00
* @notice Supports only for V2 cTokens
*/
contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 {
/**
* @notice Calculates the current borrow rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) override external view returns (uint) {
return getBorrowRateInternal(cash, borrows, reserves);
}
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_)
BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {}
}
================================================
FILE: protocols/compound-v2/src/Lens/CompoundLens.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "../CErc20.sol";
import "../CToken.sol";
import "../PriceOracle.sol";
import "../EIP20Interface.sol";
import "../Governance/GovernorAlpha.sol";
import "../Governance/Comp.sol";
interface ComptrollerLensInterface {
function markets(address) external view returns (bool, uint);
function oracle() external view returns (PriceOracle);
function getAccountLiquidity(address) external view returns (uint, uint, uint);
function getAssetsIn(address) external view returns (CToken[] memory);
function claimComp(address) external;
function compAccrued(address) external view returns (uint);
function compSpeeds(address) external view returns (uint);
function compSupplySpeeds(address) external view returns (uint);
function compBorrowSpeeds(address) external view returns (uint);
function borrowCaps(address) external view returns (uint);
}
interface GovernorBravoInterface {
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
struct Proposal {
uint id;
address proposer;
uint eta;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas);
function proposals(uint proposalId) external view returns (Proposal memory);
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory);
}
contract CompoundLens {
struct CTokenMetadata {
address cToken;
uint exchangeRateCurrent;
uint supplyRatePerBlock;
uint borrowRatePerBlock;
uint reserveFactorMantissa;
uint totalBorrows;
uint totalReserves;
uint totalSupply;
uint totalCash;
bool isListed;
uint collateralFactorMantissa;
address underlyingAssetAddress;
uint cTokenDecimals;
uint underlyingDecimals;
uint compSupplySpeed;
uint compBorrowSpeed;
uint borrowCap;
}
function getCompSpeeds(ComptrollerLensInterface comptroller, CToken cToken) internal returns (uint, uint) {
// Getting comp speeds is gnarly due to not every network having the
// split comp speeds from Proposal 62 and other networks don't even
// have comp speeds.
uint compSupplySpeed = 0;
(bool compSupplySpeedSuccess, bytes memory compSupplySpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSupplySpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSupplySpeedSuccess) {
compSupplySpeed = abi.decode(compSupplySpeedReturnData, (uint));
}
uint compBorrowSpeed = 0;
(bool compBorrowSpeedSuccess, bytes memory compBorrowSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compBorrowSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compBorrowSpeedSuccess) {
compBorrowSpeed = abi.decode(compBorrowSpeedReturnData, (uint));
}
// If the split comp speeds call doesn't work, try the oldest non-spit version.
if (!compSupplySpeedSuccess || !compBorrowSpeedSuccess) {
(bool compSpeedSuccess, bytes memory compSpeedReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.compSpeeds.selector,
abi.encode(address(cToken))
)
);
if (compSpeedSuccess) {
compSupplySpeed = compBorrowSpeed = abi.decode(compSpeedReturnData, (uint));
}
}
return (compSupplySpeed, compBorrowSpeed);
}
function cTokenMetadata(CToken cToken) public returns (CTokenMetadata memory) {
uint exchangeRateCurrent = cToken.exchangeRateCurrent();
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
(bool isListed, uint collateralFactorMantissa) = comptroller.markets(address(cToken));
address underlyingAssetAddress;
uint underlyingDecimals;
if (compareStrings(cToken.symbol(), "cETH")) {
underlyingAssetAddress = address(0);
underlyingDecimals = 18;
} else {
CErc20 cErc20 = CErc20(address(cToken));
underlyingAssetAddress = cErc20.underlying();
underlyingDecimals = EIP20Interface(cErc20.underlying()).decimals();
}
(uint compSupplySpeed, uint compBorrowSpeed) = getCompSpeeds(comptroller, cToken);
uint borrowCap = 0;
(bool borrowCapSuccess, bytes memory borrowCapReturnData) =
address(comptroller).call(
abi.encodePacked(
comptroller.borrowCaps.selector,
abi.encode(address(cToken))
)
);
if (borrowCapSuccess) {
borrowCap = abi.decode(borrowCapReturnData, (uint));
}
return CTokenMetadata({
cToken: address(cToken),
exchangeRateCurrent: exchangeRateCurrent,
supplyRatePerBlock: cToken.supplyRatePerBlock(),
borrowRatePerBlock: cToken.borrowRatePerBlock(),
reserveFactorMantissa: cToken.reserveFactorMantissa(),
totalBorrows: cToken.totalBorrows(),
totalReserves: cToken.totalReserves(),
totalSupply: cToken.totalSupply(),
totalCash: cToken.getCash(),
isListed: isListed,
collateralFactorMantissa: collateralFactorMantissa,
underlyingAssetAddress: underlyingAssetAddress,
cTokenDecimals: cToken.decimals(),
underlyingDecimals: underlyingDecimals,
compSupplySpeed: compSupplySpeed,
compBorrowSpeed: compBorrowSpeed,
borrowCap: borrowCap
});
}
function cTokenMetadataAll(CToken[] calldata cTokens) external returns (CTokenMetadata[] memory) {
uint cTokenCount = cTokens.length;
CTokenMetadata[] memory res = new CTokenMetadata[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenMetadata(cTokens[i]);
}
return res;
}
struct CTokenBalances {
address cToken;
uint balanceOf;
uint borrowBalanceCurrent;
uint balanceOfUnderlying;
uint tokenBalance;
uint tokenAllowance;
}
function cTokenBalances(CToken cToken, address payable account) public returns (CTokenBalances memory) {
uint balanceOf = cToken.balanceOf(account);
uint borrowBalanceCurrent = cToken.borrowBalanceCurrent(account);
uint balanceOfUnderlying = cToken.balanceOfUnderlying(account);
uint tokenBalance;
uint tokenAllowance;
if (compareStrings(cToken.symbol(), "cETH")) {
tokenBalance = account.balance;
tokenAllowance = account.balance;
} else {
CErc20 cErc20 = CErc20(address(cToken));
EIP20Interface underlying = EIP20Interface(cErc20.underlying());
tokenBalance = underlying.balanceOf(account);
tokenAllowance = underlying.allowance(account, address(cToken));
}
return CTokenBalances({
cToken: address(cToken),
balanceOf: balanceOf,
borrowBalanceCurrent: borrowBalanceCurrent,
balanceOfUnderlying: balanceOfUnderlying,
tokenBalance: tokenBalance,
tokenAllowance: tokenAllowance
});
}
function cTokenBalancesAll(CToken[] calldata cTokens, address payable account) external returns (CTokenBalances[] memory) {
uint cTokenCount = cTokens.length;
CTokenBalances[] memory res = new CTokenBalances[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenBalances(cTokens[i], account);
}
return res;
}
struct CTokenUnderlyingPrice {
address cToken;
uint underlyingPrice;
}
function cTokenUnderlyingPrice(CToken cToken) public returns (CTokenUnderlyingPrice memory) {
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
PriceOracle priceOracle = comptroller.oracle();
return CTokenUnderlyingPrice({
cToken: address(cToken),
underlyingPrice: priceOracle.getUnderlyingPrice(cToken)
});
}
function cTokenUnderlyingPriceAll(CToken[] calldata cTokens) external returns (CTokenUnderlyingPrice[] memory) {
uint cTokenCount = cTokens.length;
CTokenUnderlyingPrice[] memory res = new CTokenUnderlyingPrice[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenUnderlyingPrice(cTokens[i]);
}
return res;
}
struct AccountLimits {
CToken[] markets;
uint liquidity;
uint shortfall;
}
function getAccountLimits(ComptrollerLensInterface comptroller, address account) public returns (AccountLimits memory) {
(uint errorCode, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(account);
require(errorCode == 0);
return AccountLimits({
markets: comptroller.getAssetsIn(account),
liquidity: liquidity,
shortfall: shortfall
});
}
struct GovReceipt {
uint proposalId;
bool hasVoted;
bool support;
uint96 votes;
}
function getGovReceipts(GovernorAlpha governor, address voter, uint[] memory proposalIds) public view returns (GovReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovReceipt[] memory res = new GovReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorAlpha.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovBravoReceipt {
uint proposalId;
bool hasVoted;
uint8 support;
uint96 votes;
}
function getGovBravoReceipts(GovernorBravoInterface governor, address voter, uint[] memory proposalIds) public view returns (GovBravoReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovBravoReceipt[] memory res = new GovBravoReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorBravoInterface.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovBravoReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
}
function setProposal(GovProposal memory res, GovernorAlpha governor, uint proposalId) internal view {
(
,
address proposer,
uint eta,
uint startBlock,
uint endBlock,
uint forVotes,
uint againstVotes,
bool canceled,
bool executed
) = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = proposer;
res.eta = eta;
res.startBlock = startBlock;
res.endBlock = endBlock;
res.forVotes = forVotes;
res.againstVotes = againstVotes;
res.canceled = canceled;
res.executed = executed;
}
function getGovProposals(GovernorAlpha governor, uint[] calldata proposalIds) external view returns (GovProposal[] memory) {
GovProposal[] memory res = new GovProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
setProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct GovBravoProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function setBravoProposal(GovBravoProposal memory res, GovernorBravoInterface governor, uint proposalId) internal view {
GovernorBravoInterface.Proposal memory p = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = p.proposer;
res.eta = p.eta;
res.startBlock = p.startBlock;
res.endBlock = p.endBlock;
res.forVotes = p.forVotes;
res.againstVotes = p.againstVotes;
res.abstainVotes = p.abstainVotes;
res.canceled = p.canceled;
res.executed = p.executed;
}
function getGovBravoProposals(GovernorBravoInterface governor, uint[] calldata proposalIds) external view returns (GovBravoProposal[] memory) {
GovBravoProposal[] memory res = new GovBravoProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovBravoProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
setBravoProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct CompBalanceMetadata {
uint balance;
uint votes;
address delegate;
}
function getCompBalanceMetadata(Comp comp, address account) external view returns (CompBalanceMetadata memory) {
return CompBalanceMetadata({
balance: comp.balanceOf(account),
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account)
});
}
struct CompBalanceMetadataExt {
uint balance;
uint votes;
address delegate;
uint allocated;
}
function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory) {
uint balance = comp.balanceOf(account);
comptroller.claimComp(account);
uint newBalance = comp.balanceOf(account);
uint accrued = comptroller.compAccrued(account);
uint total = add(accrued, newBalance, "sum comp total");
uint allocated = sub(total, balance, "sub allocated");
return CompBalanceMetadataExt({
balance: balance,
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account),
allocated: allocated
});
}
struct CompVotes {
uint blockNumber;
uint votes;
}
function getCompVotes(Comp comp, address account, uint32[] calldata blockNumbers) external view returns (CompVotes[] memory) {
CompVotes[] memory res = new CompVotes[](blockNumbers.length);
for (uint i = 0; i < blockNumbers.length; i++) {
res[i] = CompVotes({
blockNumber: uint256(blockNumbers[i]),
votes: uint256(comp.getPriorVotes(account, blockNumbers[i]))
});
}
return res;
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
}
================================================
FILE: protocols/compound-v2/src/Maximillion.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CEther.sol";
/**
* @title Compound's Maximillion Contract
* @author Compound
*/
contract Maximillion {
/**
* @notice The default cEther market to repay in
*/
CEther public cEther;
/**
* @notice Construct a Maximillion to repay max in a CEther market
*/
constructor(CEther cEther_) public {
cEther = cEther_;
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in the cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
*/
function repayBehalf(address borrower) public payable {
repayBehalfExplicit(borrower, cEther);
}
/**
* @notice msg.sender sends Ether to repay an account's borrow in a cEther market
* @dev The provided Ether is applied towards the borrow balance, any excess is refunded
* @param borrower The address of the borrower account to repay on behalf of
* @param cEther_ The address of the cEther contract to repay in
*/
function repayBehalfExplicit(address borrower, CEther cEther_) public payable {
uint received = msg.value;
uint borrows = cEther_.borrowBalanceCurrent(borrower);
if (received > borrows) {
cEther_.repayBorrowBehalf{value: borrows}(borrower);
payable(msg.sender).transfer(received - borrows);
} else {
cEther_.repayBorrowBehalf{value: received}(borrower);
}
}
}
================================================
FILE: protocols/compound-v2/src/PriceOracle.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./CToken.sol";
abstract contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) virtual external view returns (uint);
}
================================================
FILE: protocols/compound-v2/src/Reservoir.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
/**
* @title Reservoir Contract
* @notice Distributes a token to a different contract at a fixed rate.
* @dev This contract must be poked via the `drip()` function every so often.
* @author Compound
*/
contract Reservoir {
/// @notice The block number when the Reservoir started (immutable)
uint public dripStart;
/// @notice Tokens per block that to drip to target (immutable)
uint public dripRate;
/// @notice Reference to token to drip (immutable)
EIP20Interface public token;
/// @notice Target to receive dripped tokens (immutable)
address public target;
/// @notice Amount that has already been dripped
uint public dripped;
/**
* @notice Constructs a Reservoir
* @param dripRate_ Numer of tokens per block to drip
* @param token_ The token to drip
* @param target_ The recipient of dripped tokens
*/
constructor(uint dripRate_, EIP20Interface token_, address target_) public {
dripStart = block.number;
dripRate = dripRate_;
token = token_;
target = target_;
dripped = 0;
}
/**
* @notice Drips the maximum amount of tokens to match the drip rate since inception
* @dev Note: this will only drip up to the amount of tokens available.
* @return The amount of tokens dripped in this call
*/
function drip() public returns (uint) {
// First, read storage into memory
EIP20Interface token_ = token;
uint reservoirBalance_ = token_.balanceOf(address(this)); // TODO: Verify this is a static call
uint dripRate_ = dripRate;
uint dripStart_ = dripStart;
uint dripped_ = dripped;
address target_ = target;
uint blockNumber_ = block.number;
// Next, calculate intermediate values
uint dripTotal_ = mul(dripRate_, blockNumber_ - dripStart_, "dripTotal overflow");
uint deltaDrip_ = sub(dripTotal_, dripped_, "deltaDrip underflow");
uint toDrip_ = min(reservoirBalance_, deltaDrip_);
uint drippedNext_ = add(dripped_, toDrip_, "tautological");
// Finally, write new `dripped` value and transfer tokens to target
dripped = drippedNext_;
token_.transfer(target_, toDrip_);
return toDrip_;
}
/* Internal helper functions for safe math */
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c;
unchecked { c = a + b; }
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c;
unchecked { c = a * b; }
require(c / a == b, errorMessage);
return c;
}
function min(uint a, uint b) internal pure returns (uint) {
if (a <= b) {
return a;
} else {
return b;
}
}
}
import "./EIP20Interface.sol";
================================================
FILE: protocols/compound-v2/src/SafeMath.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c;
unchecked { c = a + b; }
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c;
unchecked { c = a + b; }
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c;
unchecked { c = a * b; }
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c;
unchecked { c = a * b; }
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
================================================
FILE: protocols/compound-v2/src/SimplePriceOracle.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./PriceOracle.sol";
import "./CErc20.sol";
contract SimplePriceOracle is PriceOracle {
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function _getUnderlyingAddress(CToken cToken) private view returns (address) {
address asset;
if (compareStrings(cToken.symbol(), "cETH")) {
asset = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
} else {
asset = address(CErc20(address(cToken)).underlying());
}
return asset;
}
function getUnderlyingPrice(CToken cToken) public override view returns (uint) {
return prices[_getUnderlyingAddress(cToken)];
}
function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public {
address asset = _getUnderlyingAddress(cToken);
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
================================================
FILE: protocols/compound-v2/src/Timelock.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./SafeMath.sol";
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 2 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
fallback() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
================================================
FILE: protocols/compound-v2/src/Unitroller.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
/**
* @title ComptrollerCore
* @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
* CTokens should reference this contract as their comptroller.
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback() payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
================================================
FILE: protocols/compound-v2/src/WhitePaperInterestRateModel.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "./InterestRateModel.sol";
/**
* @title Compound's WhitePaperInterestRateModel Contract
* @author Compound
* @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper
*/
contract WhitePaperInterestRateModel is InterestRateModel {
event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock);
uint256 private constant BASE = 1e18;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint public constant blocksPerYear = 2102400;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint public baseRatePerBlock;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by BASE)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by BASE)
*/
constructor(uint baseRatePerYear, uint multiplierPerYear) public {
baseRatePerBlock = baseRatePerYear / blocksPerYear;
multiplierPerBlock = multiplierPerYear / blocksPerYear;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, BASE]
*/
function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
return borrows * BASE / (cash + borrows - reserves);
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by BASE)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) override public view returns (uint) {
uint ur = utilizationRate(cash, borrows, reserves);
return (ur * multiplierPerBlock / BASE) + baseRatePerBlock;
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by BASE)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) override public view returns (uint) {
uint oneMinusReserveFactor = BASE - reserveFactorMantissa;
uint borrowRate = getBorrowRate(cash, borrows, reserves);
uint rateToPool = borrowRate * oneMinusReserveFactor / BASE;
return utilizationRate(cash, borrows, reserves) * rateToPool / BASE;
}
}
================================================
FILE: protocols/compound-v2/test/core.t.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.10;
// Test Helpers
import "forge-std/Test.sol";
// Comptroller, Unitroller
import "@compound/Comptroller.sol";
import "@compound/Unitroller.sol";
// Goverance
import "@compound/Governance/Comp.sol";
//import "@compound/Governance/GovernorAlpha.sol";
import "@compound/Governance/GovernorBravoDelegate.sol";
import "@compound/Governance/GovernorBravoDelegator.sol";
import "@compound/Timelock.sol";
// Lens
import {CompoundLens} from "@compound/Lens/CompoundLens.sol";
// Interest Models
import "@compound/WhitePaperInterestRateModel.sol";
import {JumpRateModelV2} from "@compound/JumpRateModelV2.sol";
// CToken, Underlying, Price Oracle
import "@compound/CErc20.sol";
import "./mocks/ERC20.sol";
import "@compound/SimplePriceOracle.sol";
contract TestCore is Test {
uint256 MAX = type(uint256).max;
address RANDO = address(0x8008);
// Comptroller, Unitroller, Lens
Comptroller testComptroller;
Unitroller testUnitroller;
CompoundLens testCompLens;
// Goverance
Comp comp;
// GovernorAlpha testGovAlpha;
GovernorBravoDelegator testGovBravoDelegator;
GovernorBravoDelegate testGovBravoDelegate;
Timelock testTimelock;
// Interest Model, CToken, Underlying, Price Oracle
WhitePaperInterestRateModel wpirm;
JumpRateModelV2 jrm2;
CErc20 ctoken;
ERC20 underlying;
ERC20 randoToken;
SimplePriceOracle testOracle;
function setUp() public {
vm.label(address(this), "THE_FUZZANATOR");
vm.label(address(RANDO), "RANDO");
// Deploy Comptroller, Unitroller, Lens
testUnitroller = new Unitroller();
vm.label(address(testUnitroller), "UNITROLLER");
testComptroller = new Comptroller();
testComptroller._setBorrowCapGuardian(address(this));
testComptroller._setPauseGuardian(address(this));
vm.label(address(testComptroller), "COMPTROLLER");
testCompLens = new CompoundLens();
vm.label(address(testCompLens), "COMPOUND LENS");
// Deploy Governance contracts
comp = new Comp(address(this));
vm.label(address(comp), "COMP");
testTimelock = new Timelock(address(this), 2 days);
vm.label(address(testTimelock), "TIMELOCK");
/*testGovAlpha = new GovernorAlpha(address(timelock), address(comp), address(this));
vm.label(address(testGovAlpha), "GOVERNOR ALPHA");*/
testGovBravoDelegate = new GovernorBravoDelegate();
vm.label(address(testGovBravoDelegate), "GOVERNOR BRAVO HARNESS");
// Also deploys and initializes GovernorBravoDelegate.sol should find a way to assign that to something
testGovBravoDelegator = new GovernorBravoDelegator(address(testTimelock), address(comp), address(this), address(testGovBravoDelegate), 17280, 1, 100000000000000000000000);
vm.label(address(testGovBravoDelegator), "GOVERNOR BRAVO DELEGATOR");
// Deploy Interest Model, CToken, Underlying, Price Oracle
wpirm = new WhitePaperInterestRateModel(50000, 50000);
vm.label(address(wpirm), "INTERSET RATE MODEL");
jrm2 = new JumpRateModelV2(2102400, 2102400, 2102400, 1, address(this));
vm.label(address(jrm2), "INTERSET RATE MODEL");
underlying = new StandardToken(0, "UNDERLYING", 18, "UNDERLYING");
vm.label(address(underlying), "UNDERLYING");
randoToken = new StandardToken(0, "RANDO", 18, "RANDO");
vm.label(address(randoToken), "UNDERLYING");
ctoken = new CErc20();
ctoken.initialize(address(underlying), ComptrollerInterface(address(testComptroller)), InterestRateModel(address(wpirm)), 50000, "CTOKEN", "CTOKEN", 18);
vm.label(address(ctoken), "CTOKEN");
testOracle = new SimplePriceOracle();
vm.label(address(testOracle), "ORACLE");
testComptroller._setPriceOracle(PriceOracle(testOracle));
testComptroller._supportMarket(CToken(ctoken));
}
function testON() public {}
/* INVARIANTS: cToken mint should:
* Increase cToken TotalSupply
* Increase User cToken Balance
* Decrease User underlying Balance
* Update Supply Index in Comptroller
* Update Comp Supplier Index in Comptroller
* Update supplier compAccrued in Comptroller
* Update Supply block Number in Comptroller
* Update cToken accrualBlockNumber
* Update cToken borrowIndex
* Update cToken totalBorrows
* Update cToken totalReserves
*/
function testFuzz_mint(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if(!setUnderlying) {
initUnderlying(amount);
underlying.approve(address(ctoken), amount);
}
uint totalSupplyBefore = ctoken.totalSupply();
uint userCTokenBalanceBefore = ctoken.balanceOf(address(this));
uint userUnderlyingBalanceBefore = underlying.balanceOf(address(this));
(uint224 indexBefore, ) = testComptroller.compSupplyState(address(ctoken));
uint compAccruedBefore = testComptroller.compAccrued(address(this));
uint compSupplierIndexBefore = testComptroller.compSupplierIndex(address(ctoken), address(this));
(bool isListed, , ) = testComptroller.markets(address(ctoken));
if (!isListed) {
assert(false);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(userUnderlyingBalanceBefore + ctoken.getCashPriorpub());
// ACTION:
try ctoken.mint(amount) {
// POSTCONDTIONS:
uint totalSupplyAfter = ctoken.totalSupply();
uint userCTokenBalanceAfter = ctoken.balanceOf(address(this));
uint userUnderlyingBalanceAfter = underlying.balanceOf(address(this));
assertGt(userCTokenBalanceAfter, userCTokenBalanceBefore, "USER CTOKEN BALANCE CHECK");
assertLt(userUnderlyingBalanceAfter, userUnderlyingBalanceBefore, "USER UNDERLYING BALANCE CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTALSUPPLY CHECK");
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
this.mintHelper(indexBefore, compAccruedBefore, compSupplierIndexBefore);
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: redeem should:
* Decrease cToken TotalSupply
* Decrease User cToken Balance
* Increase User underlying Balance
* Update Supply Index in Comptroller
* Update Comp Supplier Index in Comptroller
* Update supplier compAccrued in Comptroller
* Update Supply block Number in Comptroller
* Update cToken accrualBlockNumber
* Update cToken borrowIndex
* Update cToken totalBorrows
* Update cToken totalReserves
*/
function testFuzz_redeem(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userUnderlyingBalanceBefore = underlying.balanceOf(address(this));
if(!setUnderlying) {
// I do this because of the first deposit bug and only want happy paths
if (amount < 1000) {
uint newAmount = amount + (1000 - amount);
initUnderlying(newAmount);
underlying.approve(address(ctoken), newAmount);
try ctoken.mint(newAmount) {} catch {/*assert(false);*/}// overflow
}
initUnderlying(amount);
underlying.approve(address(ctoken), amount);
}
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
uint totalSupplyBefore = ctoken.totalSupply();
uint userCTokenBalanceBefore = ctoken.balanceOf(address(this));
(uint224 indexBefore, ) = testComptroller.compSupplyState(address(ctoken));
uint compAccruedBefore = testComptroller.compAccrued(address(this));
uint compSupplierIndexBefore = testComptroller.compSupplierIndex(address(ctoken), address(this));
(bool isListed, , ) = testComptroller.markets(address(ctoken));
if (!isListed) {
assert(false);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) =this.accrueIntrestHelper(userUnderlyingBalanceBefore + ctoken.getCashPriorpub());
// ACTION:
try ctoken.redeem(amount) {
// POSTCONDTIONS:
uint totalSupplyAfter = ctoken.totalSupply();
uint userCTokenBalanceAfter = ctoken.balanceOf(address(this));
uint userUnderlyingBalanceAfter = underlying.balanceOf(address(this));
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
this.redeemHelper(indexBefore, compAccruedBefore, compSupplierIndexBefore);
assertLt(userCTokenBalanceAfter, userCTokenBalanceBefore, "USER CTOKEN BALANCE CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTALSUPPLY CHECK");
assertGe(userUnderlyingBalanceAfter, userUnderlyingBalanceBefore, "USER UNDERLYING BALANCE CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: borrow should:
* Update borrow index in Comptroller
* Update borrow block in Comptroller
* Update borrower compAccrued in Comptroller
* Update compBorrowerIndex in Comptroller
* Add user to market in Comptroller
* Add cToken to users accountAssets in Comptroller
* Increase accountBorrows principal
* Update accountBorrows interestIndex
* Increase totalBorrows
* Increase User underlying Balance
*/
function testFuzz_borrow(uint _amount, uint _price) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint256 price = _between(_price, 1, MAX);
uint userUnderlyingBalanceBefore = underlying.balanceOf(address(this));
(uint224 indexBefore, ) = testComptroller.compBorrowState(address(ctoken));
uint compAccruedBefore = testComptroller.compAccrued(address(this));
uint compBorrowIndexBefore = testComptroller.compBorrowerIndex(address(ctoken), address(this));
(bool isListed, , ) = testComptroller.markets(address(ctoken));
(uint userPrincipalBefore, uint userInterestIndexBefore) = ctoken.getAccountBorrows(address(this));
uint totalBorrowsBefore = ctoken.totalBorrows();
if(!setUnderlying) {
try underlying.mint(address(ctoken), amount) {} catch {/*assert(false);*/}// overflow
initUnderlying(amount);
testOracle.setDirectPrice(address(underlying), price);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
}
if (!isListed) {
assert(false);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(userUnderlyingBalanceBefore + ctoken.getCashPriorpub());
// ACTION:
try ctoken.borrow(amount) {
// POSTCONDTIONS:
(uint224 indexAfter, uint32 block) = testComptroller.compBorrowState(address(ctoken));
uint compBorrowIndexAfter = testComptroller.compBorrowerIndex(address(ctoken), address(this));
uint compAccruedAfter = testComptroller.compAccrued(address(this));
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
this.borrowHelper(totalBorrowsBefore, userPrincipalBefore, userInterestIndexBefore);
assertGe(indexAfter, indexBefore, "BORROW INDEX CHECK");
assertGe(compBorrowIndexAfter, compBorrowIndexBefore, "COMP BORROW INDEX CHECK");
assertGe(compAccruedAfter, compAccruedBefore, "BORROW COMP ACCRUED CHECK");
assertEq(block, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: repayBorrow should:
* Update borrow index in Comptroller
* Update borrow block in Comptroller
* Update borrower compAccrued in Comptroller
* Update compBorrowerIndex in Comptroller
* Add user to market in Comptroller
* Add cToken to users accountAssets in Comptroller
* Increase accountBorrows principal
* Update accountBorrows interestIndex
* Increase totalBorrows
* Increase User underlying Balance
*/
function testFuzz_repayBorrow(uint _amount, uint _price) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint256 price = _between(_price, 1, MAX);
uint userUnderlyingBalanceBefore = underlying.balanceOf(address(this));
if(!setUnderlying) {
initUnderlying(amount);
testOracle.setDirectPrice(address(underlying), price);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
try underlying.mint(address(this), amount) {} catch {/*assert(false);*/}// overflow
underlying.approve(address(ctoken), amount);
}
(bool isListed, , ) = testComptroller.markets(address(ctoken));
if (!isListed) {
assert(false);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(userUnderlyingBalanceBefore + ctoken.getCashPriorpub());
try ctoken.borrow(amount) {} catch {/*assert(false);*/}// overflow
(uint224 indexBefore, ) = testComptroller.compBorrowState(address(ctoken));
uint compAccruedBefore = testComptroller.compAccrued(address(this));
uint compBorrowIndexBefore = testComptroller.compBorrowerIndex(address(ctoken), address(this));
(uint userPrincipalBefore, uint userInterestIndexBefore) = ctoken.getAccountBorrows(address(this));
uint totalBorrowsBefore = ctoken.totalBorrows();
// ACTION:
try ctoken.repayBorrow(amount) {
// POSTCONDTIONS:
(uint224 indexAfter, uint32 block) = testComptroller.compBorrowState(address(ctoken));
uint compBorrowIndexAfter = testComptroller.compBorrowerIndex(address(ctoken), address(this));
uint compAccruedAfter = testComptroller.compAccrued(address(this));
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
this.repayBorrowHelper(totalBorrowsBefore, userPrincipalBefore, userInterestIndexBefore);
assertGe(indexAfter, indexBefore, "BORROW INDEX CHECK");
assertGe(compBorrowIndexAfter, compBorrowIndexBefore, "COMP BORROW INDEX CHECK");
assertGe(compAccruedAfter, compAccruedBefore, "BORROW COMP ACCRUED CHECK");
assertEq(block, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: RepayBorrowBehalf should:
* Update borrow index in Comptroller
* Update borrow block in Comptroller
* Update borrower compAccrued in Comptroller
* Update compBorrowerIndex in Comptroller
* Add user to market in Comptroller
* Add cToken to users accountAssets in Comptroller
* Increase accountBorrows principal
* Update accountBorrows interestIndex
* Increase totalBorrows
* Increase User underlying Balance
*/
function testFuzz_RepayBorrowBehalf(uint _amount, uint _price) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint256 price = _between(_price, 1, MAX);
uint userUnderlyingBalanceBefore = underlying.balanceOf(address(this));
if(!setUnderlying) {
initUnderlying(amount);
testOracle.setDirectPrice(address(underlying), price);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
try underlying.mint(address(this), amount) {} catch {/*assert(false);*/}// overflow
underlying.approve(address(ctoken), amount);
}
(bool isListed, , ) = testComptroller.markets(address(ctoken));
if (!isListed) {
assert(false);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(userUnderlyingBalanceBefore + ctoken.getCashPriorpub());
try ctoken.borrow(amount) {} catch {/*assert(false);*/}// overflow
(uint224 indexBefore, ) = testComptroller.compBorrowState(address(ctoken));
uint compAccruedBefore = testComptroller.compAccrued(address(this));
uint compBorrowIndexBefore = testComptroller.compBorrowerIndex(address(ctoken), address(this));
(uint userPrincipalBefore, uint userInterestIndexBefore) = ctoken.getAccountBorrows(address(this));
uint totalBorrowsBefore = ctoken.totalBorrows();
// ACTION:
// borrower address can be adjusted but does more or less the same
// Would just need to update the varibles here to adjust for the changed address
try ctoken.repayBorrowBehalf(address(this), amount) {
// POSTCONDTIONS:
(uint224 indexAfter, uint32 block) = testComptroller.compBorrowState(address(ctoken));
uint compBorrowIndexAfter = testComptroller.compBorrowerIndex(address(ctoken), address(this));
uint compAccruedAfter = testComptroller.compAccrued(address(this));
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
this.repayBorrowHelper(totalBorrowsBefore, userPrincipalBefore, userInterestIndexBefore);
assertGe(indexAfter, indexBefore, "BORROW INDEX CHECK");
assertGe(compBorrowIndexAfter, compBorrowIndexBefore, "COMP BORROW INDEX CHECK");
assertGe(compAccruedAfter, compAccruedBefore, "BORROW COMP ACCRUED CHECK");
assertEq(block, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: liquidateBorrow should:
* Update cToken accrualBlockNumber
* Update cToken borrowIndex
* Update cToken totalBorrows
* Increase totalReserves
* Decrease cToken totalSupply
* Decrease borrower accountTokens
* Increase liquidator accountTokens
*/
function testFuzz_liquidateBorrow(uint _amount, uint _price) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint256 price = _between(_price, 1, MAX);
if(!setUnderlying) {
initUnderlying(amount);
testOracle.setDirectPrice(address(underlying), price);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
try underlying.mint(address(RANDO), amount) {} catch {/*assert(false);*/}// overflow
vm.startPrank(RANDO);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
try ctoken.borrow(amount) {} catch {/*assert(false);*/}// overflow
try testComptroller.liquidateCalculateSeizeTokens(address(ctoken), address(ctoken), amount) returns(uint error, uint seizeTokens) {
if (seizeTokens == 0 || error > 0) {
testOracle.setDirectPrice(address(underlying), price / 2);
}
} catch {/*assert(false);*/}// overflow
vm.stopPrank();
}
(bool isListed, , ) = testComptroller.markets(address(ctoken));
if (!isListed) {
assert(false);
}
uint totalReservesBefore = ctoken.totalReserves();
uint totalSupplyBefore = ctoken.totalSupply();
uint borrowerBalBefore = ctoken.balanceOf(RANDO);
uint liquidatorBalBefore = ctoken.balanceOf(address(this));
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(borrowerBalBefore + ctoken.getCashPriorpub());
try ctoken.liquidateBorrow(RANDO, amount, CTokenInterface(address(ctoken))) {
uint totalReservesAfter = ctoken.totalReserves();
uint totalSupplyAfter = ctoken.totalSupply();
uint borrowerBalAfter = ctoken.balanceOf(RANDO);
uint liquidatorBalAfter = ctoken.balanceOf(address(this));
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
assertGt(totalReservesAfter, totalReservesBefore, "TOTAL RESERVES CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(borrowerBalAfter, borrowerBalBefore, "BORROWER BALANCE CHECK");
assertGt(liquidatorBalAfter, liquidatorBalBefore, "LIQUIDATOR BALANCE CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: sweepToken should:
* Decrease ctoken random token balance
* Increase Admin random token balance
*/
function testFuzz_sweepToken(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if(!setToken) {
initToken(amount);
}
uint adminBalBefore = randoToken.balanceOf(address(this));
uint ctokenContractBalBefore = randoToken.balanceOf(address(ctoken));
// ACTION:
try ctoken.sweepToken(EIP20NonStandardInterface(address(randoToken))) {
// POSTCONDTIONS:
uint ctokenContractBalAfter = randoToken.balanceOf(address(ctoken));
uint adminBalAfter = randoToken.balanceOf(address(this));
assertGt(adminBalAfter, adminBalBefore, "ADMIN TOKEN BALANCE CHECK");
assertLt(ctokenContractBalAfter, ctokenContractBalBefore, "CONTRACT TOKEN BALANCE CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: addReserves should:
* Update cToken accrualBlockNumber
* Update cToken borrowIndex
* Update cToken totalBorrows
* Update cToken totalReserves (after accrueInterest)
* Decease User balance
* Increase ctoken underlying balance
*/
function testFuzz_addReserves(uint _amount) public {
// PERECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if(!setUnderlying) {
this.initUnderlying(amount);
underlying.approve(address(ctoken), amount);
}
(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) = this.accrueIntrestHelper(ctoken.getCashPriorpub());
uint userBalBefore = underlying.balanceOf(address(this));
uint ctokenBalBefore = underlying.balanceOf(address(ctoken));
uint totalReservesBefore = ctoken.totalReserves();
// ACTION:
try ctoken._addReserves(amount) {
// POSTCONDITIONS:
uint userBalAfter = underlying.balanceOf(address(this));
uint ctokenBalAfter = underlying.balanceOf(address(ctoken));
uint totalReservesAfter = ctoken.totalReserves();
this.accrualHelper(borrowIndexAfter, totalBorrowsAfter, totalReservesAfter);
assertLe(userBalAfter, userBalBefore, "USER BAL CHECK");
assertGt(ctokenBalAfter, ctokenBalBefore, "CTOKEN BAL CHECK");
assertGt(totalReservesAfter, totalReservesBefore, "TOTAL RESERVES CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: transfer should:
* Decrease from address accountTokens
* Increase to address accountTokens
*/
function testFuzz_transfer(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if(!setUnderlying) {
initUnderlying(amount);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
}
uint userBalBefore = ctoken.balanceOf(address(this));
uint otherUserBalBefore = ctoken.balanceOf(RANDO);
// ACTION:
try ctoken.transfer(RANDO, amount) {
// POSTCONDTIONS:
uint userBalAfter = ctoken.balanceOf(address(this));
uint otherUserBalAfter = ctoken.balanceOf(RANDO);
assertGt(otherUserBalAfter, otherUserBalBefore, "OTHER USER BALANCE CHECK");
assertLt(userBalAfter, userBalBefore, "USER BALANCE CHECK");
} catch {/*assert(false);*/}// overflow
}
/* INVARIANTS: transfer should:
* Decrease from address accountTokens
* Increase to address accountTokens
* Decrease transferAllowances if != type(uint).max
*/
function testFuzz_transferFrom(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if(!setUnderlying) {
initUnderlying(amount);
underlying.approve(address(ctoken), amount);
try ctoken.mint(amount) {} catch {/*assert(false);*/}// overflow
}
uint userBalBefore = ctoken.balanceOf(address(this));
uint otherUserBalBefore = ctoken.balanceOf(RANDO);
ctoken.approve(RANDO, amount);
uint otherUserAllowanceBefore = ctoken.allowance(address(this), RANDO);
// ACTION:
vm.startPrank(RANDO);
try ctoken.transferFrom(address(this), RANDO, amount) {
// POSTCONDTIONS:
uint userBalAfter = ctoken.balanceOf(address(this));
uint otherUserBalAfter = ctoken.balanceOf(RANDO);
uint otherUserAllowanceAfter = ctoken.allowance(address(this), RANDO);
if (otherUserAllowanceBefore == MAX) {
assertEq(otherUserAllowanceAfter, MAX, "USER ALLOWANCE CHECK");
} else {
assertLt(otherUserAllowanceAfter, otherUserAllowanceBefore, "USER ALLOWANCE CHECK");
}
assertGt(otherUserBalAfter, otherUserBalBefore, "OTHER USER BALANCE CHECK");
assertLt(userBalAfter, userBalBefore, "USER BALANCE CHECK");
} catch {/*assert(false);*/}// overflow
}
// Helper functions
function accrualHelper(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter) public {
uint accrualBlockNumberAfter = ctoken.accrualBlockNumber();
uint borrowIndex = ctoken.borrowIndex();
uint totalBorrows = ctoken.totalBorrows();
uint totalReserves = ctoken.totalReserves();
assertEq(accrualBlockNumberAfter, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
assertEq(borrowIndex, borrowIndexAfter, "BORROW INDEX CHECK");
assertGe(totalBorrows, totalBorrowsAfter, "TOTAL BORROWS CHECK");
assertEq(totalReserves, totalReservesAfter, "TOTAL RESERVES CHECK");
}
function mintHelper(uint indexBefore, uint compAccruedBefore, uint compSupplierIndexBefore) public {
(uint224 indexAfter, uint32 block) = testComptroller.compSupplyState(address(ctoken));
uint compSupplierIndexAfter = testComptroller.compSupplierIndex(address(ctoken), address(this));
uint compAccruedAfter = testComptroller.compAccrued(address(this));
assertGe(indexAfter, indexBefore, "SUPPLY INDEX CHECK");
assertGe(compSupplierIndexAfter, compSupplierIndexBefore, "COMP SUPPLIER INDEX CHECK");
assertGe(compAccruedAfter, compAccruedBefore, "SUPPLIER COMP ACCRUED CHECK");
assertEq(block, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
}
function redeemHelper(uint indexBefore, uint compAccruedBefore, uint compSupplierIndexBefore) public {
(uint224 indexAfter, uint32 block) = testComptroller.compSupplyState(address(ctoken));
uint compSupplierIndexAfter = testComptroller.compSupplierIndex(address(ctoken), address(this));
uint compAccruedAfter = testComptroller.compAccrued(address(this));
assertGe(indexAfter, indexBefore, "SUPPLY INDEX CHECK");
assertGe(compSupplierIndexAfter, compSupplierIndexBefore, "COMP SUPPLIER INDEX CHECK");
assertLe(compAccruedAfter, compAccruedBefore, "SUPPLIER COMP ACCRUED CHECK");
assertEq(block, uint32(testComptroller.getBlockNumber()), "BLOCK CHECK");
}
function borrowHelper(uint totalBorrowsBefore, uint userPrincipalBefore, uint userInterestIndexBefore) public {
(uint userPrincipalAfter, uint userInterestIndexAfter) = ctoken.getAccountBorrows(address(this));
uint totalBorrowsAfter = ctoken.totalBorrows();
assertGt(totalBorrowsAfter, totalBorrowsBefore, "TOTAL BORROWS CHECK");
assertGe(userPrincipalAfter, userPrincipalBefore, "USER PRINCIPAL CHECK");
assertGe(userInterestIndexAfter, userInterestIndexBefore, "USER INTEREST INDEX CHECK");
}
function repayBorrowHelper(uint totalBorrowsBefore, uint userPrincipalBefore, uint userInterestIndexBefore) public {
(uint userPrincipalAfter, uint userInterestIndexAfter) = ctoken.getAccountBorrows(address(this));
uint totalBorrowsAfter = ctoken.totalBorrows();
assertLt(totalBorrowsAfter, totalBorrowsBefore, "TOTAL BORROWS CHECK");
assertLe(userPrincipalAfter, userPrincipalBefore, "USER PRINCIPAL CHECK");
assertLe(userInterestIndexAfter, userInterestIndexBefore, "USER INTEREST INDEX CHECK");
}
function accrueIntrestHelper(uint userUnderlyingBalanceBefore) public returns(uint borrowIndexAfter, uint totalBorrowsAfter, uint totalReservesAfter){
// Taken from cToken and reworked to function here
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = wpirm.getBorrowRate(userUnderlyingBalanceBefore, ctoken.totalBorrows(), ctoken.totalReserves());
// 0.0005e16 is the borrowRateMaxMantissa in CTokenInterFaces.sol
require(borrowRateMantissa <= 0.0005e16, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
uint accrualBlockNumberPrior = ctoken.accrualBlockNumber();
uint blockDelta = block.number - accrualBlockNumberPrior;
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, ctoken.totalBorrows());
totalBorrowsAfter = interestAccumulated + ctoken.totalBorrows();
totalReservesAfter = mul_ScalarTruncateAddUInt(Exp({mantissa: ctoken.reserveFactorMantissa()}), interestAccumulated, ctoken.totalReserves());
borrowIndexAfter = mul_ScalarTruncateAddUInt(simpleInterestFactor, ctoken.borrowIndex(), ctoken.borrowIndex());
}
// Helper functions to mint tokens when necessary
bool setUnderlying;
function initUnderlying(uint256 amount) public {
try underlying.mint(address(this), amount) {} catch {/*assert(false);*/}// overflow
setUnderlying = true;
}
// Helper functions to mint tokens when necessary
bool setToken;
function initToken(uint256 amount) public {
try randoToken.mint(address(ctoken), amount) {} catch {/*assert(false);*/}// overflow
setToken = true;
}
// Mantissa helper
struct Exp {
uint mantissa;
}
// Math Helpers taken from ExponentialNoError.sol to be used here
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
// 1e18 is the expScale in ExponentialNoError.sol
return exp.mantissa / 1e18;
}
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / 1e18});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / 1e18;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return a * b;
}
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return a + b;
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzying framework
// This is also a guarante bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
}
================================================
FILE: protocols/compound-v2/test/mocks/ERC20.sol
================================================
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
import "../../src/SafeMath.sol";
//Taken form compound-v2 tests/contracts
interface ERC20Base {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function totalSupply() external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function balanceOf(address who) external view returns (uint256);
}
abstract contract ERC20 is ERC20Base {
function transfer(address to, uint256 value) virtual external returns (bool);
function transferFrom(address from, address to, uint256 value) virtual external returns (bool);
function mint(address to, uint256 amount) virtual external returns(bool);
}
abstract contract ERC20NS is ERC20Base {
function transfer(address to, uint256 value) virtual external;
function transferFrom(address from, address to, uint256 value) virtual external;
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
* See https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 override public totalSupply;
mapping (address => mapping (address => uint256)) override public allowance;
mapping(address => uint256) override public balanceOf;
constructor(uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol) {
totalSupply = _initialAmount;
balanceOf[msg.sender] = _initialAmount;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _decimalUnits;
}
function transfer(address dst, uint256 amount) virtual override external returns (bool) {
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(msg.sender, dst, amount);
return true;
}
function transferFrom(address src, address dst, uint256 amount) virtual override external returns (bool) {
allowance[src][msg.sender] = allowance[src][msg.sender].sub(amount, "Insufficient allowance");
balanceOf[src] = balanceOf[src].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(src, dst, amount);
return true;
}
function approve(address _spender, uint256 amount) virtual override external returns (bool) {
allowance[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
// Added this to use in tests
function mint(address _to, uint256 _amount) virtual override external returns (bool) {
_mint(_to, _amount);
return true;
}
function _mint(address to, uint256 value) internal{
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
}
/**
* @title Non-Standard ERC20 token
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
contract NonStandardToken is ERC20NS {
using SafeMath for uint256;
string public name;
uint8 public decimals;
string public symbol;
uint256 override public totalSupply;
mapping (address => mapping (address => uint256)) override public allowance;
mapping(address => uint256) override public balanceOf;
constructor(uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol) {
totalSupply = _initialAmount;
balanceOf[msg.sender] = _initialAmount;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _decimalUnits;
}
function transfer(address dst, uint256 amount) override external {
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(msg.sender, dst, amount);
}
function transferFrom(address src, address dst, uint256 amount) override external {
allowance[src][msg.sender] = allowance[src][msg.sender].sub(amount, "Insufficient allowance");
balanceOf[src] = balanceOf[src].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(src, dst, amount);
}
function approve(address _spender, uint256 amount) override external returns (bool) {
allowance[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
}
contract ERC20Harness is StandardToken {
using SafeMath for uint256;
// To support testing, we can specify addresses for which transferFrom should fail and return false
mapping (address => bool) public failTransferFromAddresses;
// To support testing, we allow the contract to always fail `transfer`.
mapping (address => bool) public failTransferToAddresses;
constructor(uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol)
StandardToken(_initialAmount, _tokenName, _decimalUnits, _tokenSymbol) {}
function harnessSetFailTransferFromAddress(address src, bool _fail) public {
failTransferFromAddresses[src] = _fail;
}
function harnessSetFailTransferToAddress(address dst, bool _fail) public {
failTransferToAddresses[dst] = _fail;
}
function harnessSetBalance(address _account, uint _amount) public {
balanceOf[_account] = _amount;
}
function transfer(address dst, uint256 amount) override external returns (bool success) {
// Added for testing purposes
if (failTransferToAddresses[dst]) {
return false;
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(msg.sender, dst, amount);
return true;
}
function transferFrom(address src, address dst, uint256 amount) override external returns (bool success) {
// Added for testing purposes
if (failTransferFromAddresses[src]) {
return false;
}
allowance[src][msg.sender] = allowance[src][msg.sender].sub(amount, "Insufficient allowance");
balanceOf[src] = balanceOf[src].sub(amount, "Insufficient balance");
balanceOf[dst] = balanceOf[dst].add(amount, "Balance overflow");
emit Transfer(src, dst, amount);
return true;
}
}
================================================
FILE: protocols/olympus-v1/.gitignore
================================================
cache
out
================================================
FILE: protocols/olympus-v1/.gitmodules
================================================
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
branch = v1.7.1
[submodule "lib/openzeppelin-contracts"]
path = lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
branch = v5.0.0
[submodule "lib/solmate"]
path = lib/solmate
url = https://github.com/transmissions11/solmate
================================================
FILE: protocols/olympus-v1/LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: protocols/olympus-v1/README.md
================================================
# Setup
1. `forge install`
2. `forge test --mc TestCore`
## Integration
1. Follow setup
2. No test helpers needed
# **Notes on OlympusDAO v1**
Olympus at a high level is an autonomous and dynamic monetary policy with market operations supported by the protocol-owned Olympus Treasury. It serves the market gap between stablecoins and volatile assets. Users will interact with the bond depository where there is a reserve and liquidity bond. One can then buy a bond and redeem OHM. The bond depository always sends assets to the treasury. It is meant to calculate value of the token/LP bonded. It can also mint new OHM for the staking contract to be distributed to stakers. This depends on the amount of reserves no backing any OHM. Excess reserves can be withdraw (yield strategies and allocators) to then create extra revenue.
## **Tokens**
### **OHM**
* Reserve currency with 9 decimals
* Only minted by the vault (treasury)
### **sOHM**
* Staked OHM
* Rebases every epoch (2,220 blocks)
* Can rely on block numbers on Ethereum
* Other chain forks rely on block timestamp
* gons are stakers balance and their external balance is the `gon / gonsPerFragment`
* This is for gas efficiency for it is expensive to adjust a staker's balance every rebase
* rebasing adjusts the gonsPerFragment
* less gonsPerFragment == greater balance
* rebases the given profit generated for a given epoch (increasing totalSupply)
* Reducing gonsPerFragment as totalSupply increases
* This makes sOHM not follow standard and must be done by all transfering functions
* Each time taking the external balance and converting it to the gon value and adjusting balances from there
### **wsOHM**
Wrapped OHM which is later replaced with gOHM in v2. It doesn't rebase and it's value is based on its underlying sOHM rebases.
### **Bonds**
Bonds are handled by the Bond Depository where users can deposit their assets. The assets are moved to the treasury, calculate the amount of OHM to pay out minus fees. It creates a bond and vests for 5 days where it can then be redeemed for OHM as time reaches.
* Each deposit, debt decays by the amount of debt being vested.
* Debt: amount of OHM owed to bonders no yet vested
* Vested OHM is not considered debt
* There is a debt ceiling for every bond
* total bond debt after debt decay cannot exceed the ceiling
* If debt ceiling is never reached the bond price is calculated for the actual bond price
* This price in USD is only used for event emission
* The real price is based on bond control variable and bond depository's debt ratio
* higher bond control variable & debt ratio == higher price
* There is a minimum to the bond price
* In cents and without the decimals
* There is a Maximum provided by the user via frontend (not contract)
* debt ratio == bond depository current debt / total supply of OHM
* Reserve asset is "1 to 1" to OHM
* However it can trade below or above
* For LP tokens being the Bonded asset the StandardBondingCalculator to calculate the asset value.
* Total value of the pool and is then multiplied by the fraction of LP tokens deposited as a % of total LP token supply
* The total value is 2 times the square root of the LP token’s K value because1
1. x * y = k (Uniswap V2 formula)
2. assuming the LP token is OHM-DAI, and Olympus sees OHM/DAI as 1:1
3. with x = y, x * y = k becomes x^2 = k, x = sqrt(k)
4. y is also equal to sqrt(k) because x = y.
5. so x + y (the value of OHM + DAI) becomes 2 * sqrt(k).
* LP token's value is accounted with this.
* RFV of OHM-DAI is marked down because the LP token consists of OHM and it has a circular dependency
* Payout amount is in OHM is `(deposited asset value / bond price)`
* A fee is charged on this payout amount and is minted for the DAO.
* Remaining asset value goes to the treasury.
* Profit here means the asset is not used to back newly minted OHM and is distributed to stakers during rebase or allocated to an yield strategy
* The bond record is stored for when the user later claims their vested payout
* Vesting resets the clock no matter what
* Even if they have a previous payout meaning it's not optimal to bond and vest at the same time
* Adjust is called after whenever the bond control variable can be updated depending on:
* Block time buffer between each adjustment
* Adjustment rate is nonzero
* If these are true then the bond control variable increases/decreases
* If it hits the target the rate becomes zero and will remain such until the policy team changes it
* Redeemable OHM depends on the blocks elapsed since the last redeem or the beginning of vesting
* Redeemed amount is subtracted from the bond's payout and the the redeem block is updated
* Redeemer can use these tokens for staking or take them
* The stake function transfers the vested OHM to itself and updates the redeemer's details and finishes by transfering sOHM to the warmup contract
* Governor sets the warmup period so that redeemers can receive their sOHM at the end of the period
* If there is no warmup period than they receive it that block
* The claim function is also called and uses the stakingHelper contract
### **Rebasing**
Rebasing happens every 2,200 blocks that is triggered during staking or by anyone by calling the rebase function.
* The amount of sOHM to distribute equal to the difference of the staking contract's OHM balance and sOHM's circulating supply (excludes the sOHM balance)
* The amount of OHM minted from the treasury to the staking contract is set by the policy team and is rate.
* This should not exceed the treasury's excess reserves and there is a require statement for such
* After each distribution the rate is adjusted
### **Treasury**
* Approved depositors can deposit assets directly to mint OHM without vesting needed to acquire the initial supply of OHM to create a liquidity pool
* Approved spenders can withdraw reserve assets by burning OHM (liquidated)
* Approved yield strategies can manage the reserves to move assets to their own contract
* Approved addresses can borrow excess treasury reserves (same as approve but maybe for off-chain tracking )
### **Reserve currencies**:
* Deep liquidity: reserve currencies are highly liquid and easily exchangeable for other assets or products
* unit of account: other assets are denominated in the currency
* Preserve purchasing power: provides holders a stable low volatility asset that grow at a steady rate over the med-to-long term.
### **Extra Links**:
[Dissecting OlympusDAO](https://0xkowloon.substack.com/p/dissecting-the-olympus-protocol)
[OlympusDAO Docs](https://docs.olympusdao.finance/main/overview/intro)
[Primer on Bonding](https://olympusdao.medium.com/a-primer-on-oly-bonds-9763f125c124)
[3,3 Game Theory](https://olympusdao.medium.com/the-game-theory-of-olympus-e4c5f19a77df)
[Empty Set Dollar](https://olympusdao.medium.com/comparison-of-olympus-credits-and-the-empty-set-dollar-590146dcdf8b)
### **Audit Links**:
[PeckShield](https://github.com/peckshield/publications/blob/master/audit_reports/PeckShield-Audit-Report-OlympusDAO-v1.0.pdf)
================================================
FILE: protocols/olympus-v1/foundry.toml
================================================
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
[fuzz]
runs = 10000
# See more config options https://github.com/foundry-rs/foundry/tree/master/config
================================================
FILE: protocols/olympus-v1/package.json
================================================
{
"name": "olympus-contracts",
"version": "1.0.0",
"description": "Smart Contracts for Olympus",
"directories": {
"test": "test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/OlympusDAO/olympus-contracts.git"
},
"author": "",
"bugs": {
"url": "https://github.com/OlympusDAO/olympus-contracts/issues"
},
"homepage": "https://github.com/OlympusDAO/olympus-contracts#readme"
}
================================================
FILE: protocols/olympus-v1/remappings.txt
================================================
forge-std/=lib/forge-std/src/
@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts
@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/openzeppelin-contracts/contracts
@olympus/=src/
@rari-capital/solmate/=lib/solmate/
================================================
FILE: protocols/olympus-v1/script/Counter.s.sol
================================================
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Script.sol";
contract CounterScript is Script {
function setUp() public {}
function run() public {
vm.broadcast();
}
}
================================================
FILE: protocols/olympus-v1/src/BondDepository.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyPolicy() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( bool );
function valueOf( address _token, uint _amount ) external view returns ( uint value_ );
}
interface IBondCalculator {
function valuation( address _LP, uint _amount ) external view returns ( uint );
function markdown( address _LP ) external view returns ( uint );
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
}
interface IStakingHelper {
function stake( uint _amount, address _recipient ) external;
}
contract OlympusBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable OHM; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints OHM when receives principle
address public immutable DAO; // receives profit share from bond
bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different
address public immutable bondCalculator; // calculates value of LP tokens
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principle value
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint payout; // OHM remaining to be paid
uint vesting; // Blocks left to vest
uint lastBlock; // Last interaction
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor (
address _OHM,
address _principle,
address _treasury,
address _DAO,
address _bondCalculator
) {
require( _OHM != address(0) );
OHM = _OHM;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
// bondCalculator should be address(0) if not LP bond
bondCalculator = _bondCalculator;
isLiquidityBond = ( _bondCalculator != address(0) );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _fee uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, FEE, DEBT }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 10000, "Vesting must be longer than 36 hours" );
terms.vestingTerm = _input;
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.FEE ) { // 2
require( _input <= 10000, "DAO fee cannot exceed payout" );
terms.fee = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking( address _staking, bool _helper ) external onlyPolicy() {
require( _staking != address(0) );
if ( _helper ) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOf( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 OHM ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint fee = payout.mul( terms.fee ).div( 10000 );
uint profit = value.sub( payout ).sub( fee );
/**
principle is transferred in
approved and
deposited into the treasury, returning (_amount - profit) OHM
*/
IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( principle ).approve( address( treasury ), _amount );
ITreasury( treasury ).deposit( _amount, principle, profit );
if ( fee != 0 ) { // fee is transferred to dao
IERC20( OHM ).safeTransfer( DAO, fee );
}
// total debt is increased
totalDebt = totalDebt.add( value );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( OHM ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
if ( useHelper ) { // use if staking warmup is 0
IERC20( OHM ).approve( stakingHelper, _amount );
IStakingHelper( stakingHelper ).stake( _amount, _recipient );
} else {
IERC20( OHM ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient );
}
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( OHM ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
if( isLiquidityBond ) {
price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 );
} else {
price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 );
}
}
/**
* @notice calculate current ratio of debt to OHM supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( OHM ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms for reserve or liquidity bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
if ( isLiquidityBond ) {
return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
} else {
return debtRatio();
}
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint blocksSinceLast = block.number.sub( bond.lastBlock );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of OHM available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != OHM );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
================================================
FILE: protocols/olympus-v1/src/CVXBondDepository.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyPolicy() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( bool );
function valueOf( address _token, uint _amount ) external view returns ( uint value_ );
function mintRewards( address _recipient, uint _amount ) external;
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
}
interface IStakingHelper {
function stake( uint _amount, address _recipient ) external;
}
contract OlympusCVXBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable OHM; // token given as payment for bond
address public immutable principal; // token used to create bond
address public immutable treasury; // mints OHM when receives principal
address public immutable DAO; // receives profit share from bond
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principal value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint payout; // OHM remaining to be paid
uint vesting; // Blocks left to vest
uint lastBlock; // Last interaction
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor (
address _OHM,
address _principal,
address _treasury,
address _DAO
) {
require( _OHM != address(0) );
OHM = _OHM;
require( _principal != address(0) );
principal = _principal;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
require( currentDebt() == 0, "Debt must be 0 for initialization" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 10000, "Vesting must be longer than 36 hours" );
terms.vestingTerm = _input;
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking( address _staking, bool _helper ) external onlyPolicy() {
require( _staking != address(0) );
if ( _helper ) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOf( principal, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 OHM ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principal ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: nativePrice
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), nativePrice );
emit BondPriceChanged( _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( OHM ).safeTransfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
if ( useHelper ) { // use if staking warmup is 0
IERC20( OHM ).approve( stakingHelper, _amount );
IStakingHelper( stakingHelper ).stake( _amount, _recipient );
} else {
IERC20( OHM ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient );
}
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( OHM ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice calculate current ratio of debt to OHM supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( OHM ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint blocksSinceLast = block.number.sub( bond.lastBlock );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of OHM available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principal or OHM) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != OHM );
require( _token != principal );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
================================================
FILE: protocols/olympus-v1/src/OlympusERC20.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
function _getValues( Set storage set_ ) private view returns ( bytes32[] storage ) {
return set_._values;
}
// TODO needs insert function that maintains order.
// TODO needs NatSpec documentation comment.
/**
* Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index
*/
function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) {
require( set_._values.length > index_ );
require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." );
bytes32 existingValue_ = _at( set_, index_ );
set_._values[index_] = valueToInsert_;
return _add( set_, existingValue_);
}
struct Bytes4Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes4Set storage set, bytes4 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Bytes4Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes4Set storage set, uint256 index) internal view returns ( bytes4 ) {
return bytes4( _at( set._inner, index ) );
}
function getValues( Bytes4Set storage set_ ) internal view returns ( bytes4[] memory ) {
bytes4[] memory bytes4Array_;
for( uint256 iteration_ = 0; _length( set_._inner ) > iteration_; iteration_++ ) {
bytes4Array_[iteration_] = bytes4( _at( set_._inner, iteration_ ) );
}
return bytes4Array_;
}
function insert( Bytes4Set storage set_, uint256 index_, bytes4 valueToInsert_ ) internal returns ( bool ) {
return _insert( set_._inner, index_, valueToInsert_ );
}
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns ( bytes32 ) {
return _at(set._inner, index);
}
function getValues( Bytes32Set storage set_ ) internal view returns ( bytes4[] memory ) {
bytes4[] memory bytes4Array_;
for( uint256 iteration_ = 0; _length( set_._inner ) >= iteration_; iteration_++ ){
bytes4Array_[iteration_] = bytes4( at( set_, iteration_ ) );
}
return bytes4Array_;
}
function insert( Bytes32Set storage set_, uint256 index_, bytes32 valueToInsert_ ) internal returns ( bool ) {
return _insert( set_._inner, index_, valueToInsert_ );
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
/**
* TODO Might require explicit conversion of bytes32[] to address[].
* Might require iteration.
*/
function getValues( AddressSet storage set_ ) internal view returns ( address[] memory ) {
address[] memory addressArray;
for( uint256 iteration_ = 0; _length(set_._inner) >= iteration_; iteration_++ ){
addressArray[iteration_] = at( set_, iteration_ );
}
return addressArray;
}
function insert(AddressSet storage set_, uint256 index_, address valueToInsert_ ) internal returns ( bool ) {
return _insert( set_._inner, index_, bytes32(uint256(valueToInsert_)) );
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
struct UInt256Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UInt256Set storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UInt256Set storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UInt256Set storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UInt256Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UInt256Set storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
// Present in ERC777
mapping (address => uint256) internal _balances;
// Present in ERC777
mapping (address => mapping (address => uint256)) internal _allowances;
// Present in ERC777
uint256 internal _totalSupply;
// Present in ERC777
string internal _name;
// Present in ERC777
string internal _symbol;
// Present in ERC777
uint8 internal _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account_, uint256 amount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, amount_);
_totalSupply = _totalSupply.add(amount_);
_balances[account_] = _balances[account_].add(amount_);
emit Transfer(address( this ), account_, amount_);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
interface IOwnable {
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership( address newOwner_ ) external;
}
contract Ownable is IOwnable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipTransferred( address(0), _owner );
}
function owner() public view override returns (address) {
return _owner;
}
modifier onlyOwner() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceOwnership() public virtual override onlyOwner() {
emit OwnershipTransferred( _owner, address(0) );
_owner = address(0);
}
function transferOwnership( address newOwner_ ) public virtual override onlyOwner() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred( _owner, newOwner_ );
_owner = newOwner_;
}
}
contract VaultOwned is Ownable {
address internal _vault;
function setVault( address vault_ ) external onlyOwner() returns ( bool ) {
_vault = vault_;
return true;
}
function vault() public view returns (address) {
return _vault;
}
modifier onlyVault() {
require( _vault == msg.sender, "VaultOwned: caller is not the Vault" );
_;
}
}
contract OlympusERC20Token is ERC20Permit, VaultOwned {
using SafeMath for uint256;
constructor() ERC20("Olympus", "OHM", 9) {
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
function mockMint(address account_, uint256 amount_) external {
_mint(account_, amount_);
}
function burn(uint256 amount) public virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) public virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) public virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(
amount_,
"ERC20: burn amount exceeds allowance"
);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
================================================
FILE: protocols/olympus-v1/src/RedeemHelper.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyPolicy() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
interface IBond {
function redeem( address _recipient, bool _stake ) external returns ( uint );
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ );
}
contract RedeemHelper is Ownable {
address[] public bonds;
function redeemAll( address _recipient, bool _stake ) external {
for( uint i = 0; i < bonds.length; i++ ) {
if ( bonds[i] != address(0) ) {
if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) {
IBond( bonds[i] ).redeem( _recipient, _stake );
}
}
}
}
function addBondContract( address _bond ) external onlyPolicy() {
require( _bond != address(0) );
bonds.push( _bond );
}
function removeBondContract( uint _index ) external onlyPolicy() {
bonds[ _index ] = address(0);
}
}
================================================
FILE: protocols/olympus-v1/src/RiskFreeValueOfNonReserve.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
contract RiskFreeValueOfNonReserve {
function valuation(address token_, uint amount_) external view returns( uint _value ) {}
}
================================================
FILE: protocols/olympus-v1/src/Staking.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyManager() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
interface IsOHM {
function rebase( uint256 ohmProfit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function gonsForBalance( uint amount ) external view returns ( uint );
function balanceForGons( uint gons ) external view returns ( uint );
function index() external view returns ( uint );
}
interface IWarmup {
function retrieve( address staker_, uint amount_ ) external;
}
interface IDistributor {
function distribute() external returns ( bool );
}
contract OlympusStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public immutable OHM;
address public immutable sOHM;
struct Epoch {
uint length;
uint number;
uint endBlock;
uint distribute;
}
Epoch public epoch;
address public distributor;
address public locker;
uint public totalBonus;
address public warmupContract;
uint public warmupPeriod;
constructor (
address _OHM,
address _sOHM,
uint _epochLength,
uint _firstEpochNumber,
uint _firstEpochBlock
) {
require( _OHM != address(0) );
OHM = _OHM;
require( _sOHM != address(0) );
sOHM = _sOHM;
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endBlock: _firstEpochBlock,
distribute: 0
});
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
mapping( address => Claim ) public warmupInfo;
/**
@notice stake OHM to enter warmup
@param _amount uint
@return bool
*/
function stake( uint _amount, address _recipient ) external returns ( bool ) {
rebase();
IERC20( OHM ).safeTransferFrom( msg.sender, address(this), _amount );
Claim memory info = warmupInfo[ _recipient ];
require( !info.lock, "Deposits for account are locked" );
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add( _amount ),
gons: info.gons.add( IsOHM( sOHM ).gonsForBalance( _amount ) ),
expiry: epoch.number.add( warmupPeriod ),
lock: false
});
IERC20( sOHM ).safeTransfer( warmupContract, _amount );
return true;
}
/**
@notice retrieve sOHM from warmup
@param _recipient address
*/
function claim ( address _recipient ) public {
Claim memory info = warmupInfo[ _recipient ];
if ( epoch.number >= info.expiry && info.expiry != 0 ) {
delete warmupInfo[ _recipient ];
IWarmup( warmupContract ).retrieve( _recipient, IsOHM( sOHM ).balanceForGons( info.gons ) );
}
}
/**
@notice forfeit sOHM in warmup and retrieve OHM
*/
function forfeit() external {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
IWarmup( warmupContract ).retrieve( address(this), IsOHM( sOHM ).balanceForGons( info.gons ) );
IERC20( OHM ).safeTransfer( msg.sender, info.deposit );
}
/**
@notice prevent new deposits to address (protection from malicious activity)
*/
function toggleDepositLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
/**
@notice redeem sOHM for OHM
@param _amount uint
@param _trigger bool
*/
function unstake( uint _amount, bool _trigger ) external {
if ( _trigger ) {
rebase();
}
IERC20( sOHM ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( OHM ).safeTransfer( msg.sender, _amount );
}
/**
@notice returns the sOHM index, which tracks rebase growth
@return uint
*/
function index() public view returns ( uint ) {
return IsOHM( sOHM ).index();
}
/**
@notice trigger rebase if epoch over
*/
function rebase() public {
if( epoch.endBlock <= block.number ) {
IsOHM( sOHM ).rebase( epoch.distribute, epoch.number );
epoch.endBlock = epoch.endBlock.add( epoch.length );
epoch.number++;
if ( distributor != address(0) ) {
IDistributor( distributor ).distribute();
}
uint balance = contractBalance();
uint staked = IsOHM( sOHM ).circulatingSupply();
if( balance <= staked ) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub( staked );
}
}
}
/**
@notice returns contract OHM holdings, including bonuses provided
@return uint
*/
function contractBalance() public view returns ( uint ) {
return IERC20( OHM ).balanceOf( address(this) ).add( totalBonus );
}
/**
@notice provide bonus to locked staking contract
@param _amount uint
*/
function giveLockBonus( uint _amount ) external {
require( msg.sender == locker );
totalBonus = totalBonus.add( _amount );
IERC20( sOHM ).safeTransfer( locker, _amount );
}
/**
@notice reclaim bonus from locked staking contract
@param _amount uint
*/
function returnLockBonus( uint _amount ) external {
require( msg.sender == locker );
totalBonus = totalBonus.sub( _amount );
IERC20( sOHM ).safeTransferFrom( locker, address(this), _amount );
}
enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
/**
@notice sets the contract address for LP staking
@param _contract address
*/
function setContract( CONTRACTS _contract, address _address ) external onlyManager() {
if( _contract == CONTRACTS.DISTRIBUTOR ) { // 0
distributor = _address;
} else if ( _contract == CONTRACTS.WARMUP ) { // 1
require( warmupContract == address( 0 ), "Warmup cannot be set more than once" );
warmupContract = _address;
} else if ( _contract == CONTRACTS.LOCKER ) { // 2
require( locker == address(0), "Locker cannot be set more than once" );
locker = _address;
}
}
/**
* @notice set warmup period for new stakers
* @param _warmupPeriod uint
*/
function setWarmup( uint _warmupPeriod ) external onlyManager() {
warmupPeriod = _warmupPeriod;
}
}
================================================
FILE: protocols/olympus-v1/src/StakingDistributor.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IPolicy {
function policy() external view returns (address);
function renouncePolicy() external;
function pushPolicy( address newPolicy_ ) external;
function pullPolicy() external;
}
contract Policy is IPolicy {
address internal _policy;
address internal _newPolicy;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
_policy = msg.sender;
emit OwnershipTransferred( address(0), _policy );
}
function policy() public view override returns (address) {
return _policy;
}
modifier onlyPolicy() {
require( _policy == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renouncePolicy() public virtual override onlyPolicy() {
emit OwnershipTransferred( _policy, address(0) );
_policy = address(0);
}
function pushPolicy( address newPolicy_ ) public virtual override onlyPolicy() {
require( newPolicy_ != address(0), "Ownable: new owner is the zero address");
_newPolicy = newPolicy_;
}
function pullPolicy() public virtual override {
require( msg.sender == _newPolicy );
emit OwnershipTransferred( _policy, _newPolicy );
_policy = _newPolicy;
}
}
interface ITreasury {
function mintRewards( address _recipient, uint _amount ) external;
}
contract Distributor is Policy {
using SafeMath for uint;
using SafeERC20 for IERC20;
/* ====== VARIABLES ====== */
address public immutable OHM;
address public immutable treasury;
uint public immutable epochLength;
uint public nextEpochBlock;
mapping( uint => Adjust ) public adjustments;
/* ====== STRUCTS ====== */
struct Info {
uint rate; // in ten-thousandths ( 5000 = 0.5% )
address recipient;
}
Info[] public info;
struct Adjust {
bool add;
uint rate;
uint target;
}
/* ====== CONSTRUCTOR ====== */
constructor( address _treasury, address _ohm, uint _epochLength, uint _nextEpochBlock ) {
require( _treasury != address(0) );
treasury = _treasury;
require( _ohm != address(0) );
OHM = _ohm;
epochLength = _epochLength;
nextEpochBlock = _nextEpochBlock;
}
/* ====== PUBLIC FUNCTIONS ====== */
/**
@notice send epoch reward to staking contract
*/
function distribute() external returns ( bool ) {
if ( nextEpochBlock <= block.number ) {
nextEpochBlock = nextEpochBlock.add( epochLength ); // set next epoch block
// distribute rewards to each recipient
for ( uint i = 0; i < info.length; i++ ) {
if ( info[ i ].rate > 0 ) {
ITreasury( treasury ).mintRewards( // mint and send from treasury
info[ i ].recipient,
nextRewardAt( info[ i ].rate )
);
adjust( i ); // check for adjustment
}
}
return true;
} else {
return false;
}
}
/* ====== INTERNAL FUNCTIONS ====== */
/**
@notice increment reward rate for collector
*/
function adjust( uint _index ) internal {
Adjust memory adjustment = adjustments[ _index ];
if ( adjustment.rate != 0 ) {
if ( adjustment.add ) { // if rate should increase
info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate
if ( info[ _index ].rate >= adjustment.target ) { // if target met
adjustments[ _index ].rate = 0; // turn off adjustment
}
} else { // if rate should decrease
info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate
if ( info[ _index ].rate <= adjustment.target ) { // if target met
adjustments[ _index ].rate = 0; // turn off adjustment
}
}
}
}
/* ====== VIEW FUNCTIONS ====== */
/**
@notice view function for next reward at given rate
@param _rate uint
@return uint
*/
function nextRewardAt( uint _rate ) public view returns ( uint ) {
return IERC20( OHM ).totalSupply().mul( _rate ).div( 1000000 );
}
/**
@notice view function for next reward for specified address
@param _recipient address
@return uint
*/
function nextRewardFor( address _recipient ) public view returns ( uint ) {
uint reward;
for ( uint i = 0; i < info.length; i++ ) {
if ( info[ i ].recipient == _recipient ) {
reward = nextRewardAt( info[ i ].rate );
}
}
return reward;
}
/* ====== POLICY FUNCTIONS ====== */
/**
@notice adds recipient for distributions
@param _recipient address
@param _rewardRate uint
*/
function addRecipient( address _recipient, uint _rewardRate ) external onlyPolicy() {
require( _recipient != address(0) );
info.push( Info({
recipient: _recipient,
rate: _rewardRate
}));
}
/**
@notice removes recipient for distributions
@param _index uint
@param _recipient address
*/
function removeRecipient( uint _index, address _recipient ) external onlyPolicy() {
require( _recipient == info[ _index ].recipient );
info[ _index ].recipient = address(0);
info[ _index ].rate = 0;
}
/**
@notice set adjustment info for a collector's reward rate
@param _index uint
@param _add bool
@param _rate uint
@param _target uint
*/
function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyPolicy() {
adjustments[ _index ] = Adjust({
add: _add,
rate: _rate,
target: _target
});
}
}
================================================
FILE: protocols/olympus-v1/src/StakingHelper.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IERC20 {
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim( address _recipient ) external;
}
contract StakingHelper {
address public immutable staking;
address public immutable OHM;
constructor ( address _staking, address _OHM ) {
require( _staking != address(0) );
staking = _staking;
require( _OHM != address(0) );
OHM = _OHM;
}
function stake( uint _amount ) external {
IERC20( OHM ).transferFrom( msg.sender, address(this), _amount );
IERC20( OHM ).approve( staking, _amount );
IStaking( staking ).stake( _amount, msg.sender );
IStaking( staking ).claim( msg.sender );
}
}
================================================
FILE: protocols/olympus-v1/src/StakingWarmup.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IERC20 {
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StakingWarmup {
address public immutable staking;
address public immutable sOHM;
constructor ( address _staking, address _sOHM ) {
require( _staking != address(0) );
staking = _staking;
require( _sOHM != address(0) );
sOHM = _sOHM;
}
function retrieve( address _staker, uint _amount ) external {
require( msg.sender == staking );
IERC20( sOHM ).transfer( _staker, _amount );
}
}
================================================
FILE: protocols/olympus-v1/src/StandardBondingCalculator.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library Babylonian {
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
interface IERC20 {
function decimals() external view returns (uint8);
}
interface IUniswapV2ERC20 {
function totalSupply() external view returns (uint);
}
interface IUniswapV2Pair is IUniswapV2ERC20 {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns ( address );
function token1() external view returns ( address );
}
interface IBondingCalculator {
function valuation( address pair_, uint amount_ ) external view returns ( uint _value );
}
contract OlympusBondingCalculator is IBondingCalculator {
using FixedPoint for *;
using SafeMath for uint;
using SafeMath for uint112;
address public immutable OHM;
constructor( address _OHM ) {
require( _OHM != address(0) );
OHM = _OHM;
}
/* function getKValue( address _pair ) public view returns( uint k_ ) {
uint token0 = IERC20( IUniswapV2Pair( _pair ).token0() ).decimals();
uint token1 = IERC20( IUniswapV2Pair( _pair ).token1() ).decimals();
uint decimals = token0.add( token1 ).sub( IERC20( _pair ).decimals() );
(uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
k_ = reserve0.mul(reserve1).div( 10 ** decimals );
}
function getTotalValue( address _pair ) public view returns ( uint _value ) {
_value = getKValue( _pair ).sqrrt().mul(2);
}*/
function getKValue( address _pair ) public view returns( uint k_ ) {
uint token0 = 9; // OHM
uint token1 = 18; // DAI
uint pair = 18;
uint decimals = token0.add( token1 ).sub( pair );
k_ = reserve.mul(reserve1).div( 10 ** decimals );
}
// Mocked getTotalValue
function getTotalValue( address _pair ) public view returns ( uint _value ) {
_value = getKValue( _pair ).sqrrt().mul(2);
}
function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) {
uint totalValue = getTotalValue( _pair );
uint totalSupply = IUniswapV2Pair( _pair ).totalSupply();
_value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 );
}
/* function markdown( address _pair ) external view returns ( uint ) {
( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
uint reserve;
if ( IUniswapV2Pair( _pair ).token0() == OHM ) {
reserve = reserve1;
} else {
reserve = reserve0;
}
return reserve.mul( 2 * ( 10 ** IERC20( OHM ).decimals() ) ).div( getTotalValue( _pair ) );
}*/
uint reserve; // will always be OHM reserve
uint reserve1;
// Makes a random reserve
function updateReserve(uint pairReserve) public {
reserve = pairReserve;
reserve1 = pairReserve + 10000000000000000000000;
}
//45463917690286269240430
//4365363797267
//10000000000000000000000
// Mocked markdown
function markdown( address _pair ) external view returns ( uint ) {
return reserve.mul( 2 * ( 10 ** IERC20( OHM ).decimals() ) ).div( getTotalValue( _pair ) );
}
}
================================================
FILE: protocols/olympus-v1/src/Treasury.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyManager() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IERC20Mintable {
function mint( uint256 amount_ ) external;
function mint( address account_, uint256 ammount_ ) external;
}
interface IOHMERC20 {
function burnFrom(address account_, uint256 amount_) external;
}
interface IBondCalculator {
function valuation( address pair_, uint amount_ ) external view returns ( uint _value );
}
contract OlympusTreasury is Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
event Deposit( address indexed token, uint amount, uint value );
event Withdrawal( address indexed token, uint amount, uint value );
event CreateDebt( address indexed debtor, address indexed token, uint amount, uint value );
event RepayDebt( address indexed debtor, address indexed token, uint amount, uint value );
event ReservesManaged( address indexed token, uint amount );
event ReservesUpdated( uint indexed totalReserves );
event ReservesAudited( uint indexed totalReserves );
event RewardsMinted( address indexed caller, address indexed recipient, uint amount );
event ChangeQueued( MANAGING indexed managing, address queued );
event ChangeActivated( MANAGING indexed managing, address activated, bool result );
enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SOHM }
address public immutable OHM;
uint public immutable blocksNeededForQueue;
address[] public reserveTokens; // Push only, beware false-positives.
mapping( address => bool ) public isReserveToken;
mapping( address => uint ) public reserveTokenQueue; // Delays changes to mapping.
address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveDepositor;
mapping( address => uint ) public reserveDepositorQueue; // Delays changes to mapping.
address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveSpender;
mapping( address => uint ) public reserveSpenderQueue; // Delays changes to mapping.
address[] public liquidityTokens; // Push only, beware false-positives.
mapping( address => bool ) public isLiquidityToken;
mapping( address => uint ) public LiquidityTokenQueue; // Delays changes to mapping.
address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isLiquidityDepositor;
mapping( address => uint ) public LiquidityDepositorQueue; // Delays changes to mapping.
mapping( address => address ) public bondCalculator; // bond calculator for liquidity token
address[] public reserveManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isReserveManager;
mapping( address => uint ) public ReserveManagerQueue; // Delays changes to mapping.
address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isLiquidityManager;
mapping( address => uint ) public LiquidityManagerQueue; // Delays changes to mapping.
address[] public debtors; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isDebtor;
mapping( address => uint ) public debtorQueue; // Delays changes to mapping.
mapping( address => uint ) public debtorBalance;
address[] public rewardManagers; // Push only, beware false-positives. Only for viewing.
mapping( address => bool ) public isRewardManager;
mapping( address => uint ) public rewardManagerQueue; // Delays changes to mapping.
address public sOHM;
uint public sOHMQueue; // Delays change to sOHM address
uint public totalReserves; // Risk-free value of all assets
uint public totalDebt;
constructor (
address _OHM,
address _DAI,
address _Frax,
address _OHMDAI,
uint _blocksNeededForQueue
) {
require( _OHM != address(0) );
OHM = _OHM;
isReserveToken[ _DAI ] = true;
reserveTokens.push( _DAI );
isReserveToken[ _Frax] = true;
reserveTokens.push( _Frax );
isLiquidityToken[ _OHMDAI ] = true;
liquidityTokens.push( _OHMDAI );
blocksNeededForQueue = _blocksNeededForQueue;
}
/**
@notice allow approved address to deposit an asset for OHM
@param _amount uint
@param _token address
@param _profit uint
@return send_ uint
*/
function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {
require( isReserveToken[ _token ] || isLiquidityToken[ _token ], "Not accepted" );
IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );
if ( isReserveToken[ _token ] ) {
require( isReserveDepositor[ msg.sender ], "Not approved" );
} else {
require( isLiquidityDepositor[ msg.sender ], "Not approved" );
}
uint value = valueOf(_token, _amount);
// mint OHM needed and store amount of rewards for distribution
send_ = value.sub( _profit );
IERC20Mintable( OHM ).mint( msg.sender, send_ );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit Deposit( _token, _amount, value );
}
/**
@notice allow approved address to burn OHM for reserves
@param _amount uint
@param _token address
*/
function withdraw( uint _amount, address _token ) external {
require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions
require( isReserveSpender[ msg.sender ] == true, "Not approved" );
uint value = valueOf( _token, _amount );
IOHMERC20( OHM ).burnFrom( msg.sender, value );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20( _token ).safeTransfer( msg.sender, _amount );
emit Withdrawal( _token, _amount, value );
}
/**
@notice allow approved address to borrow reserves
@param _amount uint
@param _token address
*/
function incurDebt( uint _amount, address _token ) external {
require( isDebtor[ msg.sender ], "Not approved" );
require( isReserveToken[ _token ], "Not accepted" );
uint value = valueOf( _token, _amount );
uint maximumDebt = IERC20( sOHM ).balanceOf( msg.sender ); // Can only borrow against sOHM held
uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] );
require( value <= availableDebt, "Exceeds debt limit" );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value );
totalDebt = totalDebt.add( value );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20( _token ).transfer( msg.sender, _amount );
emit CreateDebt( msg.sender, _token, _amount, value );
}
/**
@notice allow approved address to repay borrowed reserves with reserves
@param _amount uint
@param _token address
*/
function repayDebtWithReserve( uint _amount, address _token ) external {
require( isDebtor[ msg.sender ], "Not approved" );
require( isReserveToken[ _token ], "Not accepted" );
IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );
uint value = valueOf( _token, _amount );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( value );
totalDebt = totalDebt.sub( value );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit RepayDebt( msg.sender, _token, _amount, value );
}
/**
@notice allow approved address to repay borrowed reserves with OHM
@param _amount uint
*/
function repayDebtWithOHM( uint _amount ) external {
require( isDebtor[ msg.sender ], "Not approved" );
IOHMERC20( OHM ).burnFrom( msg.sender, _amount );
debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );
totalDebt = totalDebt.sub( _amount );
emit RepayDebt( msg.sender, OHM, _amount, _amount );
}
/**
@notice allow approved address to withdraw assets
@param _token address
@param _amount uint
*/
function manage( address _token, uint _amount ) external {
if( isLiquidityToken[ _token ] ) {
require( isLiquidityManager[ msg.sender ], "Not approved" );
} else {
require( isReserveManager[ msg.sender ], "Not approved" );
}
uint value = valueOf(_token, _amount);
require( value <= excessReserves(), "Insufficient reserves" );
totalReserves = totalReserves.sub( value );
emit ReservesUpdated( totalReserves );
IERC20( _token ).safeTransfer( msg.sender, _amount );
emit ReservesManaged( _token, _amount );
}
/**
@notice send epoch reward to staking contract
*/
function mintRewards( address _recipient, uint _amount ) external {
require( isRewardManager[ msg.sender ], "Not approved" );
require( _amount <= excessReserves(), "Insufficient reserves" );
IERC20Mintable( OHM ).mint( _recipient, _amount );
emit RewardsMinted( msg.sender, _recipient, _amount );
}
/**
@notice returns excess reserves not backing tokens
@return uint
*/
function excessReserves() public view returns ( uint ) {
return totalReserves.sub( IERC20( OHM ).totalSupply().sub( totalDebt ) );
}
/**
@notice takes inventory of all tracked assets
@notice always consolidate to recognized reserves before audit
*/
function auditReserves() external onlyManager() {
uint reserves;
for( uint i = 0; i < reserveTokens.length; i++ ) {
reserves = reserves.add (
valueOf( reserveTokens[ i ], IERC20( reserveTokens[ i ] ).balanceOf( address(this) ) )
);
}
for( uint i = 0; i < liquidityTokens.length; i++ ) {
reserves = reserves.add (
valueOf( liquidityTokens[ i ], IERC20( liquidityTokens[ i ] ).balanceOf( address(this) ) )
);
}
totalReserves = reserves;
emit ReservesUpdated( reserves );
emit ReservesAudited( reserves );
}
/**
@notice returns OHM valuation of asset
@param _token address
@param _amount uint
@return value_ uint
*/
function valueOf( address _token, uint _amount ) public view returns ( uint value_ ) {
if ( isReserveToken[ _token ] ) {
// convert amount to match OHM decimals
value_ = _amount.mul( 10 ** IERC20( OHM ).decimals() ).div( 10 ** IERC20( _token ).decimals() );
} else if ( isLiquidityToken[ _token ] ) {
value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount );
}
}
/**
@notice queue address to change boolean in mapping
@param _managing MANAGING
@param _address address
@return bool
*/
function queue( MANAGING _managing, address _address ) external onlyManager() returns ( bool ) {
require( _address != address(0) );
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
reserveDepositorQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
reserveSpenderQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
reserveTokenQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
ReserveManagerQueue[ _address ] = block.number.add( blocksNeededForQueue.mul( 2 ) );
} else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4
LiquidityDepositorQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5
LiquidityTokenQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6
LiquidityManagerQueue[ _address ] = block.number.add( blocksNeededForQueue.mul( 2 ) );
} else if ( _managing == MANAGING.DEBTOR ) { // 7
debtorQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.REWARDMANAGER ) { // 8
rewardManagerQueue[ _address ] = block.number.add( blocksNeededForQueue );
} else if ( _managing == MANAGING.SOHM ) { // 9
sOHMQueue = block.number.add( blocksNeededForQueue );
} else return false;
emit ChangeQueued( _managing, _address );
return true;
}
/**
@notice verify queue then set boolean in mapping
@param _managing MANAGING
@param _address address
@param _calculator address
@return bool
*/
function toggle( MANAGING _managing, address _address, address _calculator ) external onlyManager() returns ( bool ) {
require( _address != address(0) );
bool result;
if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0
if ( requirements( reserveDepositorQueue, isReserveDepositor, _address ) ) {
reserveDepositorQueue[ _address ] = 0;
if( !listContains( reserveDepositors, _address ) ) {
reserveDepositors.push( _address );
}
}
result = !isReserveDepositor[ _address ];
isReserveDepositor[ _address ] = result;
} else if ( _managing == MANAGING.RESERVESPENDER ) { // 1
if ( requirements( reserveSpenderQueue, isReserveSpender, _address ) ) {
reserveSpenderQueue[ _address ] = 0;
if( !listContains( reserveSpenders, _address ) ) {
reserveSpenders.push( _address );
}
}
result = !isReserveSpender[ _address ];
isReserveSpender[ _address ] = result;
} else if ( _managing == MANAGING.RESERVETOKEN ) { // 2
if ( requirements( reserveTokenQueue, isReserveToken, _address ) ) {
reserveTokenQueue[ _address ] = 0;
if( !listContains( reserveTokens, _address ) ) {
reserveTokens.push( _address );
}
}
result = !isReserveToken[ _address ];
isReserveToken[ _address ] = result;
} else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3
if ( requirements( ReserveManagerQueue, isReserveManager, _address ) ) {
reserveManagers.push( _address );
ReserveManagerQueue[ _address ] = 0;
if( !listContains( reserveManagers, _address ) ) {
reserveManagers.push( _address );
}
}
result = !isReserveManager[ _address ];
isReserveManager[ _address ] = result;
} else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4
if ( requirements( LiquidityDepositorQueue, isLiquidityDepositor, _address ) ) {
liquidityDepositors.push( _address );
LiquidityDepositorQueue[ _address ] = 0;
if( !listContains( liquidityDepositors, _address ) ) {
liquidityDepositors.push( _address );
}
}
result = !isLiquidityDepositor[ _address ];
isLiquidityDepositor[ _address ] = result;
} else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5
if ( requirements( LiquidityTokenQueue, isLiquidityToken, _address ) ) {
LiquidityTokenQueue[ _address ] = 0;
if( !listContains( liquidityTokens, _address ) ) {
liquidityTokens.push( _address );
}
}
result = !isLiquidityToken[ _address ];
isLiquidityToken[ _address ] = result;
bondCalculator[ _address ] = _calculator;
} else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6
if ( requirements( LiquidityManagerQueue, isLiquidityManager, _address ) ) {
LiquidityManagerQueue[ _address ] = 0;
if( !listContains( liquidityManagers, _address ) ) {
liquidityManagers.push( _address );
}
}
result = !isLiquidityManager[ _address ];
isLiquidityManager[ _address ] = result;
} else if ( _managing == MANAGING.DEBTOR ) { // 7
if ( requirements( debtorQueue, isDebtor, _address ) ) {
debtorQueue[ _address ] = 0;
if( !listContains( debtors, _address ) ) {
debtors.push( _address );
}
}
result = !isDebtor[ _address ];
isDebtor[ _address ] = result;
} else if ( _managing == MANAGING.REWARDMANAGER ) { // 8
if ( requirements( rewardManagerQueue, isRewardManager, _address ) ) {
rewardManagerQueue[ _address ] = 0;
if( !listContains( rewardManagers, _address ) ) {
rewardManagers.push( _address );
}
}
result = !isRewardManager[ _address ];
isRewardManager[ _address ] = result;
} else if ( _managing == MANAGING.SOHM ) { // 9
sOHMQueue = 0;
sOHM = _address;
result = true;
} else return false;
emit ChangeActivated( _managing, _address, result );
return true;
}
/**
@notice checks requirements and returns altered structs
@param queue_ mapping( address => uint )
@param status_ mapping( address => bool )
@param _address address
@return bool
*/
function requirements(
mapping( address => uint ) storage queue_,
mapping( address => bool ) storage status_,
address _address
) internal view returns ( bool ) {
if ( !status_[ _address ] ) {
require( queue_[ _address ] != 0, "Must queue" );
require( queue_[ _address ] <= block.number, "Queue not expired" );
return true;
} return false;
}
/**
@notice checks array to ensure against duplicate
@param _list address[]
@param _token address
@return bool
*/
function listContains( address[] storage _list, address _token ) internal view returns ( bool ) {
for( uint i = 0; i < _list.length; i++ ) {
if( _list[ i ] == _token ) {
return true;
}
}
return false;
}
}
================================================
FILE: protocols/olympus-v1/src/mocks/DAI.sol
================================================
pragma solidity 0.7.5;
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
// assembly {
// // log an 'anonymous' event with a constant 6 words of calldata
// // and four indexed topics: selector, caller, arg1 and arg2
// let mark := msize() // end of memory ensures zero
// mstore(0x40, add(mark, 288)) // update free memory pointer
// mstore(mark, 0x20) // bytes type data offset
// mstore(add(mark, 0x20), 224) // bytes size (padded)
// calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
// log4(mark, 288, // calldata
// shl(224, shr(224, calldataload(0))), // msg.sig
// caller(), // msg.sender
// calldataload(4), // arg1
// calldataload(36) // arg2
// )
// }
}
}
interface IDAI {
// --- Auth ---
function wards() external returns ( uint256 );
function rely(address guy) external;
function deny(address guy) external;
// --- Token ---
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function mint(address usr, uint wad) external;
function burn(address usr, uint wad) external;
function approve(address usr, uint wad) external returns (bool);
// --- Alias ---
function push(address usr, uint wad) external;
function pull(address usr, uint wad) external;
function move(address src, address dst, uint wad) external;
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
// Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
/* pragma solidity 0.5.12; */
/* import "./lib.sol"; */
contract DAI is LibNote {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
// --- Auth ---
mapping (address => uint) public wards;
function rely(address guy) external note auth { wards[guy] = 1; }
function deny(address guy) external note auth { wards[guy] = 0; }
modifier auth {
require(wards[msg.sender] == 1, "Dai/not-authorized");
_;
}
// --- ERC20 Data ---
string public constant name = "Dai Stablecoin";
string public constant symbol = "DAI";
string public constant version = "1";
uint8 public constant decimals = 18;
uint256 public totalSupply;
uint public dailyDAILimit;
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) private allowances;
mapping (address => uint) public nonces;
mapping (address => uint) public lastMintRestart;
mapping (address => uint) public daiMintedToday;
// event Approval(address indexed src, address indexed guy, uint wad);
// event Transfer(address indexed src, address indexed dst, uint wad);
// --- Math ---
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
constructor(uint256 chainId_) {
wards[msg.sender] = 1;
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId_,
address(this)
));
dailyDAILimit = 10000000000000000000000;
}
function allowance( address account_, address sender_ ) external view returns ( uint ) {
return _allowance( account_, sender_ );
}
function _allowance( address account_, address sender_ ) internal view returns ( uint ) {
return allowances[account_][sender_];
}
// --- Token ---
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad) public returns (bool) {
require(balanceOf[src] >= wad, "Dai/insufficient-balance");
if (src != msg.sender && _allowance( src, msg.sender ) != uint(-1)) {
require(_allowance( src, msg.sender ) >= wad, "Dai/insufficient-allowance");
allowances[src][msg.sender] = sub(_allowance( src, msg.sender ), wad);
}
balanceOf[src] = sub(balanceOf[src], wad);
balanceOf[dst] = add(balanceOf[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function addAuth(address usr) external auth {
wards[usr] = 1;
}
function adjustDailyDAILimit(uint _limit) external auth {
dailyDAILimit = _limit;
}
function mint(address usr, uint wad) external {
if(wards[msg.sender] == 0) {
require(add(wad, daiMintedToday[msg.sender]) <= dailyDAILimit || sub(block.number, lastMintRestart[msg.sender]) >= 6500 && wad <= dailyDAILimit, "Over daily DAI Limit");
if( sub(block.number, lastMintRestart[msg.sender]) >= 6500 ) {
daiMintedToday[msg.sender] = wad;
lastMintRestart[msg.sender] = block.number;
} else {
daiMintedToday[msg.sender] = add(daiMintedToday[msg.sender], wad);
}
}
balanceOf[usr] = add(balanceOf[usr], wad);
totalSupply = add(totalSupply, wad);
emit Transfer(address(0), usr, wad);
}
function burn(address usr, uint wad) external {
require(balanceOf[usr] >= wad, "Dai/insufficient-balance");
if (usr != msg.sender && _allowance( usr, msg.sender ) != uint(-1)) {
require(_allowance( usr, msg.sender ) >= wad, "Dai/insufficient-allowance");
allowances[usr][msg.sender] = sub(_allowance( usr, msg.sender ), wad);
}
balanceOf[usr] = sub(balanceOf[usr], wad);
totalSupply = sub(totalSupply, wad);
emit Transfer(usr, address(0), wad);
}
function _approve(address usr, uint wad) internal returns (bool) {
allowances[msg.sender][usr] = wad;
emit Approval(msg.sender, usr, wad);
return true;
}
function approve(address usr_, uint wad_ ) external returns (bool) {
return _approve( usr_, wad_ ) ;
}
// --- Alias ---
function push(address usr, uint wad) external {
transferFrom(msg.sender, usr, wad);
}
function pull(address usr, uint wad) external {
transferFrom(usr, msg.sender, wad);
}
function move(address src, address dst, uint wad) external {
transferFrom(src, dst, wad);
}
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry,
bool allowed, uint8 v, bytes32 r, bytes32 s) external
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "Dai/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
require(expiry == 0 || block.timestamp <= expiry, "Dai/permit-expired");
require(nonce == nonces[holder]++, "Dai/invalid-nonce");
uint wad = allowed ? uint(-1) : 0;
allowances[holder][spender] = wad;
emit Approval(holder, spender, wad);
}
}
================================================
FILE: protocols/olympus-v1/src/mocks/Frax.sol
================================================
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.5;
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
// assembly {
// // log an 'anonymous' event with a constant 6 words of calldata
// // and four indexed topics: selector, caller, arg1 and arg2
// let mark := msize() // end of memory ensures zero
// mstore(0x40, add(mark, 288)) // update free memory pointer
// mstore(mark, 0x20) // bytes type data offset
// mstore(add(mark, 0x20), 224) // bytes size (padded)
// calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
// log4(mark, 288, // calldata
// shl(224, shr(224, calldataload(0))), // msg.sig
// caller(), // msg.sender
// calldataload(4), // arg1
// calldataload(36) // arg2
// )
// }
}
}
interface IFRAX {
// --- Auth ---
function wards() external returns ( uint256 );
function rely(address guy) external;
function deny(address guy) external;
// --- Token ---
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function mint(address usr, uint wad) external;
function burn(address usr, uint wad) external;
function approve(address usr, uint wad) external returns (bool);
// --- Alias ---
function push(address usr, uint wad) external;
function pull(address usr, uint wad) external;
function move(address src, address dst, uint wad) external;
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
contract FRAX is LibNote {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
// --- Auth ---
mapping (address => uint) public wards;
function rely(address guy) external note auth { wards[guy] = 1; }
function deny(address guy) external note auth { wards[guy] = 0; }
modifier auth {
require(wards[msg.sender] == 1, "Frax/not-authorized");
_;
}
// --- ERC20 Data ---
string public constant name = "FRAX TOKEN";
string public constant symbol = "FRAX";
string public constant version = "1";
uint8 public constant decimals = 18;
uint256 public totalSupply;
uint public dailyFraxLimit;
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) private allowances;
mapping (address => uint) public nonces;
mapping (address => uint) public lastMintRestart;
mapping (address => uint) public fraxMintedToday;
// event Approval(address indexed src, address indexed guy, uint wad);
// event Transfer(address indexed src, address indexed dst, uint wad);
// --- Math ---
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
constructor(uint256 chainId_) {
wards[msg.sender] = 1;
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId_,
address(this)
));
dailyFraxLimit = 10000000000000000000000;
}
function allowance( address account_, address sender_ ) external view returns ( uint ) {
return _allowance( account_, sender_ );
}
function _allowance( address account_, address sender_ ) internal view returns ( uint ) {
return allowances[account_][sender_];
}
// --- Token ---
function transfer(address dst, uint wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad) public returns (bool) {
require(balanceOf[src] >= wad, "Frax/insufficient-balance");
if (src != msg.sender && _allowance( src, msg.sender ) != uint(-1)) {
require(_allowance( src, msg.sender ) >= wad, "Frax/insufficient-allowance");
allowances[src][msg.sender] = sub(_allowance( src, msg.sender ), wad);
}
balanceOf[src] = sub(balanceOf[src], wad);
balanceOf[dst] = add(balanceOf[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function addAuth(address usr) external auth {
wards[usr] = 1;
}
function adjustDailyFraxLimit(uint _limit) external auth {
dailyFraxLimit = _limit;
}
function mint(address usr, uint wad) external {
if(wards[msg.sender] == 0) {
require(add(wad, fraxMintedToday[msg.sender]) <= dailyFraxLimit || sub(block.number, lastMintRestart[msg.sender]) >= 6500 && wad <= dailyFraxLimit, "Over daily Frax Limit");
if( sub(block.number, lastMintRestart[msg.sender]) >= 6500 ) {
fraxMintedToday[msg.sender] = wad;
lastMintRestart[msg.sender] = block.number;
} else {
fraxMintedToday[msg.sender] = add(fraxMintedToday[msg.sender], wad);
}
}
balanceOf[usr] = add(balanceOf[usr], wad);
totalSupply = add(totalSupply, wad);
emit Transfer(address(0), usr, wad);
}
function burn(address usr, uint wad) external {
require(balanceOf[usr] >= wad, "Frax/insufficient-balance");
if (usr != msg.sender && _allowance( usr, msg.sender ) != uint(-1)) {
require(_allowance( usr, msg.sender ) >= wad, "Frax/insufficient-allowance");
allowances[usr][msg.sender] = sub(_allowance( usr, msg.sender ), wad);
}
balanceOf[usr] = sub(balanceOf[usr], wad);
totalSupply = sub(totalSupply, wad);
emit Transfer(usr, address(0), wad);
}
function _approve(address usr, uint wad) internal returns (bool) {
allowances[msg.sender][usr] = wad;
emit Approval(msg.sender, usr, wad);
return true;
}
function approve(address usr_, uint wad_ ) external returns (bool) {
return _approve( usr_, wad_ ) ;
}
// --- Alias ---
function push(address usr, uint wad) external {
transferFrom(msg.sender, usr, wad);
}
function pull(address usr, uint wad) external {
transferFrom(usr, msg.sender, wad);
}
function move(address src, address dst, uint wad) external {
transferFrom(src, dst, wad);
}
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry,
bool allowed, uint8 v, bytes32 r, bytes32 s) external
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed))
));
require(holder != address(0), "Frax/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Frax/invalid-permit");
require(expiry == 0 || block.timestamp <= expiry, "Frax/permit-expired");
require(nonce == nonces[holder]++, "Frax/invalid-nonce");
uint wad = allowed ? uint(-1) : 0;
allowances[holder][spender] = wad;
emit Approval(holder, spender, wad);
}
}
================================================
FILE: protocols/olympus-v1/src/mocks/MockBondDepository.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(
address indexed previousOwner,
address indexed newOwner
);
event OwnershipPulled(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyPolicy {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_)
public
virtual
override
onlyPolicy
{
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint256 c) {
if (a > 3) {
c = a;
uint256 b = add(div(a, 2), 1);
while (b < c) {
c = b;
b = div(add(div(a, b), b), 2);
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address)
internal
pure
returns (string memory)
{
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = "0";
_addr[1] = "x";
for (uint256 i = 0; i < 20; i++) {
_addr[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 private constant ERC20TOKEN_ERC1820_INTERFACE_ID =
keccak256("ERC20Token");
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(this), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address(this), account_, ammount_);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from_,
address to_,
uint256 amount_
) internal virtual {}
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
_nonces[owner].current(),
deadline
)
);
bytes32 _hash = keccak256(
abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)
);
address signer = ecrecover(_hash, v, r, s);
require(
signer != address(0) && signer == owner,
"ZeroSwapPermit: Invalid signature"
);
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y)
private
pure
returns (uint256 l, uint256 h)
{
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, "FullMath::mulDiv: overflow");
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 =
0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self)
internal
pure
returns (uint256)
{
return uint256(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator)
internal
pure
returns (uq112x112 memory)
{
require(denominator > 0, "FixedPoint::fraction: division by zero");
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
}
}
}
interface ITreasury {
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external returns (bool);
function valueOfToken(address _token, uint256 _amount)
external
view
returns (uint256 value_);
}
interface IBondCalculator {
function valuation(address _LP, uint256 _amount)
external
view
returns (uint256);
function markdown(address _LP) external view returns (uint256);
}
interface IStaking {
function stake(uint256 _amount, address _recipient) external returns (bool);
}
interface IStakingHelper {
function stake(uint256 _amount, address _recipient) external;
}
contract MockOlympusBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/* ======== EVENTS ======== */
event BondCreated(
uint256 deposit,
uint256 indexed payout,
uint256 indexed expires,
uint256 indexed priceInUSD
);
event BondRedeemed(
address indexed recipient,
uint256 payout,
uint256 remaining
);
event BondPriceChanged(
uint256 indexed priceInUSD,
uint256 indexed internalPrice,
uint256 indexed debtRatio
);
event ControlVariableAdjustment(
uint256 initialBCV,
uint256 newBCV,
uint256 adjustment,
bool addition
);
/* ======== STATE VARIABLES ======== */
address public immutable OHM; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints OHM when receives principle
address public immutable DAO; // receives profit share from bond
bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different
address public immutable bondCalculator; // calculates value of LP tokens
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping(address => Bond) public bondInfo; // stores bond information for depositors
uint256 public totalDebt; // total value of outstanding bonds; used for pricing
uint256 public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint256 controlVariable; // scaling variable for price
uint256 vestingTerm; // in blocks
uint256 minimumPrice; // vs principle value
uint256 maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint256 fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint256 maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint256 payout; // OHM remaining to be paid
uint256 vesting; // Blocks left to vest
uint256 lastBlock; // Last interaction
uint256 pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint256 rate; // increment
uint256 target; // BCV when adjustment finished
uint256 buffer; // minimum length (in blocks) between adjustments
uint256 lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor(
address _OHM,
address _principle,
address _treasury,
address _DAO,
address _bondCalculator
) {
require(_OHM != address(0));
OHM = _OHM;
require(_principle != address(0));
principle = _principle;
require(_treasury != address(0));
treasury = _treasury;
require(_DAO != address(0));
DAO = _DAO;
// bondCalculator should be address(0) if not LP bond
bondCalculator = _bondCalculator;
isLiquidityBond = (_bondCalculator != address(0));
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _fee uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint256 _controlVariable,
uint256 _vestingTerm,
uint256 _minimumPrice,
uint256 _maxPayout,
uint256 _fee,
uint256 _maxDebt,
uint256 _initialDebt
) external onlyPolicy {
require(terms.controlVariable == 0, "Bonds must be initialized from 0");
terms = Terms({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER {
VESTING,
PAYOUT,
FEE,
DEBT
}
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms(PARAMETER _parameter, uint256 _input)
external
onlyPolicy
{
if (_parameter == PARAMETER.VESTING) {
// 0
require(_input >= 10000, "Vesting must be longer than 36 hours");
terms.vestingTerm = _input;
} else if (_parameter == PARAMETER.PAYOUT) {
// 1
require(_input <= 1000, "Payout cannot be above 1 percent");
terms.maxPayout = _input;
} else if (_parameter == PARAMETER.FEE) {
// 2
require(_input <= 10000, "DAO fee cannot exceed payout");
terms.fee = _input;
} else if (_parameter == PARAMETER.DEBT) {
// 3
terms.maxDebt = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment(
bool _addition,
uint256 _increment,
uint256 _target,
uint256 _buffer
) external onlyPolicy {
require(
_increment <= terms.controlVariable.mul(25).div(1000),
"Increment too large"
);
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking(address _staking, bool _helper) external onlyPolicy {
require(_staking != address(0));
if (_helper) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint256 _amount,
uint256 _maxPrice,
address _depositor
) external returns (uint256) {
require(_depositor != address(0), "Invalid address");
decayDebt();
require(totalDebt <= terms.maxDebt, "Max capacity reached");
uint256 priceInUSD = bondPriceInUSD(); // Stored in bond info
uint256 nativePrice = _bondPrice();
require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection
uint256 value = ITreasury(treasury).valueOfToken(principle, _amount);
uint256 payout = payoutFor(value); // payout to bonder is computed
require(payout >= 10000000, "Bond too small"); // must be > 0.01 OHM ( underflow protection )
require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint256 fee = payout.mul(terms.fee).div(10000);
uint256 profit = value.sub(payout).sub(fee);
/**
principle is transferred in
approved and
deposited into the treasury, returning (_amount - profit) OHM
*/
IERC20(principle).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(principle).approve(address(treasury), _amount);
ITreasury(treasury).deposit(_amount, principle, profit);
if (fee != 0) {
// fee is transferred to dao
IERC20(OHM).safeTransfer(DAO, fee);
}
// total debt is increased
totalDebt = totalDebt.add(value);
// depositor info is stored
bondInfo[_depositor] = Bond({
payout: bondInfo[_depositor].payout.add(payout),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated(
_amount,
payout,
block.number.add(terms.vestingTerm),
priceInUSD
);
emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio());
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem(address _recipient, bool _stake) external returns (uint256) {
Bond memory info = bondInfo[_recipient];
uint256 percentVested = percentVestedFor(_recipient); // (blocks since last interaction / vesting term remaining)
if (percentVested >= 10000) {
// if fully vested
delete bondInfo[_recipient]; // delete user info
emit BondRedeemed(_recipient, info.payout, 0); // emit bond data
return stakeOrSend(_recipient, _stake, info.payout); // pay user everything due
} else {
// if unfinished
// calculate payout vested
uint256 payout = info.payout.mul(percentVested).div(10000);
// store updated deposit info
bondInfo[_recipient] = Bond({
payout: info.payout.sub(payout),
vesting: info.vesting.sub(block.number.sub(info.lastBlock)),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed(_recipient, payout, bondInfo[_recipient].payout);
return stakeOrSend(_recipient, _stake, payout);
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend(
address _recipient,
bool _stake,
uint256 _amount
) internal returns (uint256) {
if (!_stake) {
// if user does not want to stake
IERC20(OHM).transfer(_recipient, _amount); // send payout
} else {
// if user wants to stake
if (useHelper) {
// use if staking warmup is 0
IERC20(OHM).approve(stakingHelper, _amount);
IStakingHelper(stakingHelper).stake(_amount, _recipient);
} else {
IERC20(OHM).approve(staking, _amount);
IStaking(staking).stake(_amount, _recipient);
}
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint256 blockCanAdjust = adjustment.lastBlock.add(adjustment.buffer);
if (adjustment.rate != 0 && block.number >= blockCanAdjust) {
uint256 initial = terms.controlVariable;
if (adjustment.add) {
terms.controlVariable = terms.controlVariable.add(adjustment.rate);
if (terms.controlVariable >= adjustment.target) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub(adjustment.rate);
if (terms.controlVariable <= adjustment.target) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment(
initial,
terms.controlVariable,
adjustment.rate,
adjustment.add
);
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub(debtDecay());
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns (uint256) {
return IERC20(OHM).totalSupply().mul(terms.maxPayout).div(100000);
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor(uint256 _value) public view returns (uint256) {
return FixedPoint.fraction(_value, bondPrice()).decode112with18().div(1e16);
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).add(1000000000).div(1e7);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).add(1000000000).div(1e7);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
} else if (terms.minimumPrice != 0) {
terms.minimumPrice = 0;
}
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns (uint256 price_) {
if (isLiquidityBond) {
price_ = bondPrice()
.mul(IBondCalculator(bondCalculator).markdown(principle))
.div(100);
} else {
price_ = bondPrice().mul(10**IERC20(principle).decimals()).div(100);
}
}
/**
* @notice calculate current ratio of debt to OHM supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns (uint256 debtRatio_) {
uint256 supply = IERC20(OHM).totalSupply();
debtRatio_ = FixedPoint
.fraction(currentDebt().mul(1e9), supply)
.decode112with18()
.div(1e18);
}
/**
* @notice debt ratio in same terms for reserve or liquidity bonds
* @return uint
*/
function standardizedDebtRatio() external view returns (uint256) {
if (isLiquidityBond) {
return
debtRatio()
.mul(IBondCalculator(bondCalculator).markdown(principle))
.div(1e9);
} else {
return debtRatio();
}
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns (uint256) {
return totalDebt.sub(debtDecay());
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns (uint256 decay_) {
uint256 blocksSinceLast = block.number.sub(lastDecay);
decay_ = totalDebt.mul(blocksSinceLast).div(terms.vestingTerm);
if (decay_ > totalDebt) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor(address _depositor)
public
view
returns (uint256 percentVested_)
{
Bond memory bond = bondInfo[_depositor];
uint256 blocksSinceLast = block.number.sub(bond.lastBlock);
uint256 vesting = bond.vesting;
if (vesting > 0) {
percentVested_ = blocksSinceLast.mul(10000).div(vesting);
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of OHM available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor(address _depositor)
external
view
returns (uint256 pendingPayout_)
{
uint256 percentVested = percentVestedFor(_depositor);
uint256 payout = bondInfo[_depositor].payout;
if (percentVested >= 10000) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul(percentVested).div(10000);
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO
* @return bool
*/
function recoverLostToken(address _token) external returns (bool) {
require(_token != OHM);
require(_token != principle);
IERC20(_token).safeTransfer(DAO, IERC20(_token).balanceOf(address(this)));
return true;
}
}
================================================
FILE: protocols/olympus-v1/src/mocks/MockTreasury.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(
address indexed previousOwner,
address indexed newOwner
);
event OwnershipPulled(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_)
public
virtual
override
onlyManager
{
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
interface IERC20Mintable {
function mint(uint256 amount_) external;
function mint(address account_, uint256 ammount_) external;
}
interface IOHMERC20 {
function burnFrom(address account_, uint256 amount_) external;
}
interface IBondCalculator {
function valuation(address pair_, uint256 amount_)
external
view
returns (uint256 _value);
}
contract MockOlympusTreasury is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Deposit(address indexed token, uint256 amount, uint256 value);
event Withdrawal(address indexed token, uint256 amount, uint256 value);
event CreateDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event RepayDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event ReservesManaged(address indexed token, uint256 amount);
event ReservesUpdated(uint256 indexed totalReserves);
event ReservesAudited(uint256 indexed totalReserves);
event RewardsMinted(
address indexed caller,
address indexed recipient,
uint256 amount
);
event ChangeQueued(MANAGING indexed managing, address queued);
event ChangeActivated(
MANAGING indexed managing,
address activated,
bool result
);
enum MANAGING {
RESERVEDEPOSITOR,
RESERVESPENDER,
RESERVETOKEN,
RESERVEMANAGER,
LIQUIDITYDEPOSITOR,
LIQUIDITYTOKEN,
LIQUIDITYMANAGER,
DEBTOR,
REWARDMANAGER,
SOHM
}
address public immutable OHM;
uint256 public immutable blocksNeededForQueue;
address[] public reserveTokens; // Push only, beware false-positives.
mapping(address => bool) public isReserveToken;
mapping(address => uint256) public reserveTokenQueue; // Delays changes to mapping.
address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isReserveDepositor;
mapping(address => uint256) public reserveDepositorQueue; // Delays changes to mapping.
address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isReserveSpender;
mapping(address => uint256) public reserveSpenderQueue; // Delays changes to mapping.
address[] public liquidityTokens; // Push only, beware false-positives.
mapping(address => bool) public isLiquidityToken;
mapping(address => uint256) public LiquidityTokenQueue; // Delays changes to mapping.
address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isLiquidityDepositor;
mapping(address => uint256) public LiquidityDepositorQueue; // Delays changes to mapping.
mapping(address => address) public bondCalculator; // bond calculator for liquidity token
address[] public reserveManagers; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isReserveManager;
mapping(address => uint256) public ReserveManagerQueue; // Delays changes to mapping.
address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isLiquidityManager;
mapping(address => uint256) public LiquidityManagerQueue; // Delays changes to mapping.
address[] public debtors; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isDebtor;
mapping(address => uint256) public debtorQueue; // Delays changes to mapping.
mapping(address => uint256) public debtorBalance;
address[] public rewardManagers; // Push only, beware false-positives. Only for viewing.
mapping(address => bool) public isRewardManager;
mapping(address => uint256) public rewardManagerQueue; // Delays changes to mapping.
address public sOHM;
uint256 public sOHMQueue; // Delays change to sOHM address
uint256 public totalReserves; // Risk-free value of all assets
uint256 public totalDebt;
constructor(
address _OHM,
address _DAI,
address _Frax,
//address _OHMDAI,
uint256 _blocksNeededForQueue
) {
require(_OHM != address(0));
OHM = _OHM;
isReserveToken[_DAI] = true;
reserveTokens.push(_DAI);
isReserveToken[_Frax] = true;
reserveTokens.push(_Frax);
// isLiquidityToken[ _OHMDAI ] = true;
// liquidityTokens.push( _OHMDAI );
blocksNeededForQueue = _blocksNeededForQueue;
}
/**
@notice allow approved address to deposit an asset for OHM
@param _amount uint
@param _token address
@param _profit uint
@return send_ uint
*/
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external returns (uint256 send_) {
require(isReserveToken[_token] || isLiquidityToken[_token], "Not accepted");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
if (isReserveToken[_token]) {
require(isReserveDepositor[msg.sender], "Not approved");
} else {
require(isLiquidityDepositor[msg.sender], "Not approved");
}
uint256 value = valueOfToken(_token, _amount);
(_token, _amount);
// mint OHM needed and store amount of rewards for distribution
send_ = value.sub(_profit);
IERC20Mintable(OHM).mint(msg.sender, send_);
totalReserves = totalReserves.add(value);
emit ReservesUpdated(totalReserves);
emit Deposit(_token, _amount, value);
}
/**
@notice allow approved address to burn OHM for reserves
@param _amount uint
@param _token address
*/
function withdraw(uint256 _amount, address _token) external {
require(isReserveToken[_token], "Not accepted"); // Only reserves can be used for redemptions
require(isReserveSpender[msg.sender] == true, "Not approved");
uint256 value = valueOfToken(_token, _amount);
IOHMERC20(OHM).burnFrom(msg.sender, value);
totalReserves = totalReserves.sub(value);
emit ReservesUpdated(totalReserves);
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Withdrawal(_token, _amount, value);
}
/**
@notice allow approved address to borrow reserves
@param _amount uint
@param _token address
*/
function incurDebt(uint256 _amount, address _token) external {
require(isDebtor[msg.sender], "Not approved");
require(isReserveToken[_token], "Not accepted");
uint256 value = valueOfToken(_token, _amount);
uint256 maximumDebt = IERC20(sOHM).balanceOf(msg.sender); // Can only borrow against sOHM held
uint256 availableDebt = maximumDebt.sub(debtorBalance[msg.sender]);
require(value <= availableDebt, "Exceeds debt limit");
debtorBalance[msg.sender] = debtorBalance[msg.sender].add(value);
totalDebt = totalDebt.add(value);
totalReserves = totalReserves.sub(value);
emit ReservesUpdated(totalReserves);
IERC20(_token).transfer(msg.sender, _amount);
emit CreateDebt(msg.sender, _token, _amount, value);
}
/**
@notice allow approved address to repay borrowed reserves with reserves
@param _amount uint
@param _token address
*/
function repayDebtWithReserve(uint256 _amount, address _token) external {
require(isDebtor[msg.sender], "Not approved");
require(isReserveToken[_token], "Not accepted");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 value = valueOfToken(_token, _amount);
debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(value);
totalDebt = totalDebt.sub(value);
totalReserves = totalReserves.add(value);
emit ReservesUpdated(totalReserves);
emit RepayDebt(msg.sender, _token, _amount, value);
}
/**
@notice allow approved address to repay borrowed reserves with OHM
@param _amount uint
*/
function repayDebtWithOHM(uint256 _amount) external {
require(isDebtor[msg.sender], "Not approved");
IOHMERC20(OHM).burnFrom(msg.sender, _amount);
debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(_amount);
totalDebt = totalDebt.sub(_amount);
emit RepayDebt(msg.sender, OHM, _amount, _amount);
}
/**
@notice allow approved address to withdraw assets
@param _token address
@param _amount uint
*/
function manage(address _token, uint256 _amount) external {
if (isLiquidityToken[_token]) {
require(isLiquidityManager[msg.sender], "Not approved");
} else {
require(isReserveManager[msg.sender], "Not approved");
}
uint256 value = valueOfToken(_token, _amount);
(_token, _amount);
require(value <= excessReserves(), "Insufficient reserves");
totalReserves = totalReserves.sub(value);
emit ReservesUpdated(totalReserves);
IERC20(_token).safeTransfer(msg.sender, _amount);
emit ReservesManaged(_token, _amount);
}
/**
@notice send epoch reward to staking contract
*/
function mintRewards(address _recipient, uint256 _amount) external {
require(isRewardManager[msg.sender], "Not approved");
require(_amount <= excessReserves(), "Insufficient reserves");
IERC20Mintable(OHM).mint(_recipient, _amount);
emit RewardsMinted(msg.sender, _recipient, _amount);
}
/**
@notice returns excess reserves not backing tokens
@return uint
*/
function excessReserves() public view returns (uint256) {
return totalReserves.sub(IERC20(OHM).totalSupply().sub(totalDebt));
}
/**
@notice takes inventory of all tracked assets
@notice always consolidate to recognized reserves before audit
*/
function auditReserves() external onlyManager {
uint256 reserves;
for (uint256 i = 0; i < reserveTokens.length; i++) {
reserves = reserves.add(
valueOfToken(
reserveTokens[i],
IERC20(reserveTokens[i]).balanceOf(address(this))
)
);
}
for (uint256 i = 0; i < liquidityTokens.length; i++) {
reserves = reserves.add(
valueOfToken(
liquidityTokens[i],
IERC20(liquidityTokens[i]).balanceOf(address(this))
)
);
}
totalReserves = reserves;
emit ReservesUpdated(reserves);
emit ReservesAudited(reserves);
}
/**
@notice returns OHM valuation of asset
@param _token address
@param _amount uint
@return value_ uint
*/
function valueOfToken(address _token, uint256 _amount)
public
view
returns (uint256 value_)
{
if (isReserveToken[_token]) {
// convert amount to match OHM decimals
value_ = _amount.mul(10**IERC20(OHM).decimals()).div(
10**IERC20(_token).decimals()
);
} else if (isLiquidityToken[_token]) {
value_ = IBondCalculator(bondCalculator[_token]).valuation(
_token,
_amount
);
}
}
/**
@notice queue address to change boolean in mapping
@param _managing MANAGING
@param _address address
@return bool
*/
function queue(MANAGING _managing, address _address)
external
onlyManager
returns (bool)
{
require(_address != address(0));
if (_managing == MANAGING.RESERVEDEPOSITOR) {
// 0
reserveDepositorQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.RESERVESPENDER) {
// 1
reserveSpenderQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.RESERVETOKEN) {
// 2
reserveTokenQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.RESERVEMANAGER) {
// 3
ReserveManagerQueue[_address] = block.number.add(
blocksNeededForQueue.mul(2)
);
} else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {
// 4
LiquidityDepositorQueue[_address] = block.number.add(
blocksNeededForQueue
);
} else if (_managing == MANAGING.LIQUIDITYTOKEN) {
// 5
LiquidityTokenQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.LIQUIDITYMANAGER) {
// 6
LiquidityManagerQueue[_address] = block.number.add(
blocksNeededForQueue.mul(2)
);
} else if (_managing == MANAGING.DEBTOR) {
// 7
debtorQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.REWARDMANAGER) {
// 8
rewardManagerQueue[_address] = block.number.add(blocksNeededForQueue);
} else if (_managing == MANAGING.SOHM) {
// 9
sOHMQueue = block.number.add(blocksNeededForQueue);
} else return false;
emit ChangeQueued(_managing, _address);
return true;
}
/**
@notice verify queue then set boolean in mapping
@param _managing MANAGING
@param _address address
@param _calculator address
@return bool
*/
function toggle(
MANAGING _managing,
address _address,
address _calculator
) external onlyManager returns (bool) {
require(_address != address(0));
bool result;
if (_managing == MANAGING.RESERVEDEPOSITOR) {
// 0
if (requirements(reserveDepositorQueue, isReserveDepositor, _address)) {
reserveDepositorQueue[_address] = 0;
if (!listContains(reserveDepositors, _address)) {
reserveDepositors.push(_address);
}
}
result = !isReserveDepositor[_address];
isReserveDepositor[_address] = result;
} else if (_managing == MANAGING.RESERVESPENDER) {
// 1
if (requirements(reserveSpenderQueue, isReserveSpender, _address)) {
reserveSpenderQueue[_address] = 0;
if (!listContains(reserveSpenders, _address)) {
reserveSpenders.push(_address);
}
}
result = !isReserveSpender[_address];
isReserveSpender[_address] = result;
} else if (_managing == MANAGING.RESERVETOKEN) {
// 2
if (requirements(reserveTokenQueue, isReserveToken, _address)) {
reserveTokenQueue[_address] = 0;
if (!listContains(reserveTokens, _address)) {
reserveTokens.push(_address);
}
}
result = !isReserveToken[_address];
isReserveToken[_address] = result;
} else if (_managing == MANAGING.RESERVEMANAGER) {
// 3
if (requirements(ReserveManagerQueue, isReserveManager, _address)) {
reserveManagers.push(_address);
ReserveManagerQueue[_address] = 0;
if (!listContains(reserveManagers, _address)) {
reserveManagers.push(_address);
}
}
result = !isReserveManager[_address];
isReserveManager[_address] = result;
} else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {
// 4
if (
requirements(LiquidityDepositorQueue, isLiquidityDepositor, _address)
) {
liquidityDepositors.push(_address);
LiquidityDepositorQueue[_address] = 0;
if (!listContains(liquidityDepositors, _address)) {
liquidityDepositors.push(_address);
}
}
result = !isLiquidityDepositor[_address];
isLiquidityDepositor[_address] = result;
} else if (_managing == MANAGING.LIQUIDITYTOKEN) {
// 5
if (requirements(LiquidityTokenQueue, isLiquidityToken, _address)) {
LiquidityTokenQueue[_address] = 0;
if (!listContains(liquidityTokens, _address)) {
liquidityTokens.push(_address);
}
}
result = !isLiquidityToken[_address];
isLiquidityToken[_address] = result;
bondCalculator[_address] = _calculator;
} else if (_managing == MANAGING.LIQUIDITYMANAGER) {
// 6
if (requirements(LiquidityManagerQueue, isLiquidityManager, _address)) {
LiquidityManagerQueue[_address] = 0;
if (!listContains(liquidityManagers, _address)) {
liquidityManagers.push(_address);
}
}
result = !isLiquidityManager[_address];
isLiquidityManager[_address] = result;
} else if (_managing == MANAGING.DEBTOR) {
// 7
if (requirements(debtorQueue, isDebtor, _address)) {
debtorQueue[_address] = 0;
if (!listContains(debtors, _address)) {
debtors.push(_address);
}
}
result = !isDebtor[_address];
isDebtor[_address] = result;
} else if (_managing == MANAGING.REWARDMANAGER) {
// 8
if (requirements(rewardManagerQueue, isRewardManager, _address)) {
rewardManagerQueue[_address] = 0;
if (!listContains(rewardManagers, _address)) {
rewardManagers.push(_address);
}
}
result = !isRewardManager[_address];
isRewardManager[_address] = result;
} else if (_managing == MANAGING.SOHM) {
// 9
sOHMQueue = 0;
sOHM = _address;
result = true;
} else return false;
emit ChangeActivated(_managing, _address, result);
return true;
}
/**
@notice checks requirements and returns altered structs
@param queue_ mapping( address => uint )
@param status_ mapping( address => bool )
@param _address address
@return bool
*/
function requirements(
mapping(address => uint256) storage queue_,
mapping(address => bool) storage status_,
address _address
) internal view returns (bool) {
if (!status_[_address]) {
require(queue_[_address] != 0, "Must queue");
require(queue_[_address] <= block.number, "Queue not expired");
return true;
}
return false;
}
/**
@notice checks array to ensure against duplicate
@param _list address[]
@param _token address
@return bool
*/
function listContains(address[] storage _list, address _token)
internal
view
returns (bool)
{
for (uint256 i = 0; i < _list.length; i++) {
if (_list[i] == _token) {
return true;
}
}
return false;
}
}
================================================
FILE: protocols/olympus-v1/src/sOlympusERC20.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
/*
* Expects percentage to be trailed by 00,
*/
function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) {
return div( mul( total_, percentage_ ), 1000 );
}
/*
* Expects percentage to be trailed by 00,
*/
function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) {
return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) );
}
function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) {
return div( mul(part_, 100) , total_ );
}
/**
* Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) {
return sqrrt( mul( multiplier_, payment_ ) );
}
function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) {
return mul( multiplier_, supply_ );
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
// function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
// require(address(this).balance >= value, "Address: insufficient balance for call");
// return _functionCallWithValue(target, data, value, errorMessage);
// }
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract ERC20
is
IERC20
{
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
// Present in ERC777
mapping (address => uint256) internal _balances;
// Present in ERC777
mapping (address => mapping (address => uint256)) internal _allowances;
// Present in ERC777
uint256 internal _totalSupply;
// Present in ERC777
string internal _name;
// Present in ERC777
string internal _symbol;
// Present in ERC777
uint8 internal _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
/**
* @dev Returns the name of the token.
*/
// Present in ERC777
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
// Present in ERC777
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// Present in ERC777
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
// Present in ERC777
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
// Present in ERC777
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
// Overrideen in ERC777
// Confirm that this behavior changes
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
// Present in ERC777
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
// Present in ERC777
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
// Present in ERC777
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
// Present in ERC777
function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
function mockMint(address account_, uint256 ammount_) public virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
// Present in ERC777
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
// Present in ERC777
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
// Considering deprication to reduce size of bytecode as changing _decimals to internal acheived the same functionality.
// function _setupDecimals(uint8 decimals_) internal {
// _decimals = decimals_;
// }
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
// Present in ERC777
function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
interface IERC2612Permit {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
));
}
/**
* @dev See {IERC2612Permit-permit}.
*
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
/**
* @dev See {IERC2612Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyManager() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
contract sOlympus is ERC20Permit, Ownable {
using SafeMath for uint256;
modifier onlyStakingContract() {
require( msg.sender == stakingContract );
_;
}
address public stakingContract;
address public initializer;
event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply );
event LogRebase( uint256 indexed epoch, uint256 rebase, uint256 index );
event LogStakingContractUpdated( address stakingContract );
struct Rebase {
uint epoch;
uint rebase; // 18 decimals
uint totalStakedBefore;
uint totalStakedAfter;
uint amountRebased;
uint index;
uint blockNumberOccured;
}
Rebase[] public rebases;
uint public INDEX;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
mapping ( address => mapping ( address => uint256 ) ) private _allowedValue;
constructor() ERC20("Staked Olympus", "sOHM", 9) ERC20Permit() {
initializer = msg.sender;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
}
function initialize( address stakingContract_ ) external returns ( bool ) {
require( msg.sender == initializer );
require( stakingContract_ != address(0) );
stakingContract = stakingContract_;
_gonBalances[ stakingContract ] = TOTAL_GONS;
emit Transfer( address(0x0), stakingContract, _totalSupply );
emit LogStakingContractUpdated( stakingContract_ );
initializer = address(0);
return true;
}
function setIndex( uint _INDEX ) external onlyManager() returns ( bool ) {
require( INDEX == 0 );
INDEX = gonsForBalance( _INDEX );
return true;
}
/**
@notice increases sOHM supply to increase staking balances relative to profit_
@param profit_ uint256
@return uint256
*/
function rebase( uint256 profit_, uint epoch_ ) public onlyStakingContract() returns ( uint256 ) {
uint256 rebaseAmount;
uint256 circulatingSupply_ = circulatingSupply();
if ( profit_ == 0 ) {
emit LogSupply( epoch_, block.timestamp, _totalSupply );
emit LogRebase( epoch_, 0, index() );
return _totalSupply;
} else if ( circulatingSupply_ > 0 ){
rebaseAmount = profit_.mul( _totalSupply ).div( circulatingSupply_ );
} else {
rebaseAmount = profit_;
}
_totalSupply = _totalSupply.add( rebaseAmount );
if ( _totalSupply > MAX_SUPPLY ) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div( _totalSupply );
_storeRebase( circulatingSupply_, profit_, epoch_ );
return _totalSupply;
}
/**
@notice emits event with data about rebase
@param previousCirculating_ uint
@param profit_ uint
@param epoch_ uint
@return bool
*/
function _storeRebase( uint previousCirculating_, uint profit_, uint epoch_ ) internal returns ( bool ) {
uint rebasePercent = profit_.mul( 1e18 ).div( previousCirculating_ );
rebases.push( Rebase ( {
epoch: epoch_,
rebase: rebasePercent, // 18 decimals
totalStakedBefore: previousCirculating_,
totalStakedAfter: circulatingSupply(),
amountRebased: profit_,
index: index(),
blockNumberOccured: block.number
}));
emit LogSupply( epoch_, block.timestamp, _totalSupply );
emit LogRebase( epoch_, rebasePercent, index() );
return true;
}
function balanceOf( address who ) public view override returns ( uint256 ) {
return _gonBalances[ who ].div( _gonsPerFragment );
}
function gonsForBalance( uint amount ) public view returns ( uint ) {
return amount.mul( _gonsPerFragment );
}
function balanceForGons( uint gons ) public view returns ( uint ) {
return gons.div( _gonsPerFragment );
}
// Staking contract holds excess sOHM
function circulatingSupply() public view returns ( uint ) {
return _totalSupply.sub( balanceOf( stakingContract ) );
}
function index() public view returns ( uint ) {
return balanceForGons( INDEX );
}
function transfer( address to, uint256 value ) public override returns (bool) {
uint256 gonValue = gonsForBalance(value);
_gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub( gonValue );
_gonBalances[ to ] = _gonBalances[ to ].add( gonValue );
emit Transfer( msg.sender, to, value );
return true;
}
function allowance( address owner_, address spender ) public view override returns ( uint256 ) {
return _allowedValue[ owner_ ][ spender ];
}
function transferFrom( address from, address to, uint256 value ) public override returns ( bool ) {
_allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub( value );
emit Approval( from, msg.sender, _allowedValue[ from ][ msg.sender ] );
uint256 gonValue = gonsForBalance( value );
_gonBalances[ from ] = _gonBalances[from].sub( gonValue );
_gonBalances[ to ] = _gonBalances[to].add( gonValue );
emit Transfer( from, to, value );
return true;
}
function approve( address spender, uint256 value ) public override returns (bool) {
_allowedValue[ msg.sender ][ spender ] = value;
emit Approval( msg.sender, spender, value );
return true;
}
// What gets called in a permit
function _approve( address owner, address spender, uint256 value ) internal override virtual {
_allowedValue[owner][spender] = value;
emit Approval( owner, spender, value );
}
function increaseAllowance( address spender, uint256 addedValue ) public override returns (bool) {
_allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add( addedValue );
emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] );
return true;
}
function decreaseAllowance( address spender, uint256 subtractedValue ) public override returns (bool) {
uint256 oldValue = _allowedValue[ msg.sender ][ spender ];
if (subtractedValue >= oldValue) {
_allowedValue[ msg.sender ][ spender ] = 0;
} else {
_allowedValue[ msg.sender ][ spender ] = oldValue.sub( subtractedValue );
}
emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] );
return true;
}
}
================================================
FILE: protocols/olympus-v1/src/wETHBondDepository.sol
================================================
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement( address newOwner_ ) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed( address(0), _owner );
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy() {
require( _owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed( _owner, address(0) );
_owner = address(0);
}
function pushManagement( address newOwner_ ) public virtual override onlyPolicy() {
require( newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed( _owner, newOwner_ );
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require( msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled( _owner, _newOwner );
_owner = _newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract ERC20 is IERC20 {
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
}
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external returns ( bool );
function valueOf( address _token, uint _amount ) external view returns ( uint value_ );
function mintRewards( address _recipient, uint _amount ) external;
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
}
interface IStakingHelper {
function stake( uint _amount, address _recipient ) external;
}
contract OlympusBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable OHM; // token given as payment for bond
address public immutable principle; // token used to create bond
address public immutable treasury; // mints OHM when receives principle
address public immutable DAO; // receives profit share from bond
AggregatorV3Interface internal priceFeed;
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
mapping( address => Bond ) public bondInfo; // stores bond information for depositors
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15)
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
// Info for bond holder
struct Bond {
uint payout; // OHM remaining to be paid
uint vesting; // Blocks left to vest
uint lastBlock; // Last interaction
uint pricePaid; // In DAI, for front end viewing
}
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor (
address _OHM,
address _principle,
address _treasury,
address _DAO,
address _feed
) {
require( _OHM != address(0) );
OHM = _OHM;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
require( _feed != address(0) );
priceFeed = AggregatorV3Interface( _feed );
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
require( currentDebt() == 0, "Debt must be 0 for initialization" );
terms = Terms ({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER { VESTING, PAYOUT, DEBT }
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
if ( _parameter == PARAMETER.VESTING ) { // 0
require( _input >= 10000, "Vesting must be longer than 36 hours" );
terms.vestingTerm = _input;
} else if ( _parameter == PARAMETER.PAYOUT ) { // 1
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
} else if ( _parameter == PARAMETER.DEBT ) { // 3
terms.maxDebt = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking( address _staking, bool _helper ) external onlyPolicy() {
require( _staking != address(0) );
if ( _helper ) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection
uint value = ITreasury( treasury ).valueOf( principle, _amount );
uint payout = payoutFor( value ); // payout to bonder is computed
require( payout >= 10000000, "Bond too small" ); // must be > 0.01 OHM ( underflow protection )
require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
/**
asset carries risk and is not minted against
asset transfered to treasury and rewards minted as payout
*/
IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount );
ITreasury( treasury ).mintRewards( address(this), payout );
// total debt is increased
totalDebt = totalDebt.add( value );
// depositor info is stored
bondInfo[ _depositor ] = Bond({
payout: bondInfo[ _depositor ].payout.add( payout ),
vesting: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
}
/**
* @notice redeem bond for user
* @param _recipient address
* @param _stake bool
* @return uint
*/
function redeem( address _recipient, bool _stake ) external returns ( uint ) {
Bond memory info = bondInfo[ _recipient ];
uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)
if ( percentVested >= 10000 ) { // if fully vested
delete bondInfo[ _recipient ]; // delete user info
emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint payout = info.payout.mul( percentVested ).div( 10000 );
// store updated deposit info
bondInfo[ _recipient ] = Bond({
payout: info.payout.sub( payout ),
vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
lastBlock: block.number,
pricePaid: info.pricePaid
});
emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
return stakeOrSend( _recipient, _stake, payout );
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
* @notice allow user to stake payout automatically
* @param _stake bool
* @param _amount uint
* @return uint
*/
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) {
if ( !_stake ) { // if user does not want to stake
IERC20( OHM ).transfer( _recipient, _amount ); // send payout
} else { // if user wants to stake
if ( useHelper ) { // use if staking warmup is 0
IERC20( OHM ).approve( stakingHelper, _amount );
IStakingHelper( stakingHelper ).stake( _amount, _recipient );
} else {
IERC20( OHM ).approve( staking, _amount );
IStaking( staking ).stake( _amount, _recipient );
}
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
uint initial = terms.controlVariable;
if ( adjustment.add ) {
terms.controlVariable = terms.controlVariable.add( adjustment.rate );
if ( terms.controlVariable >= adjustment.target ) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
if ( terms.controlVariable <= adjustment.target ) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt.sub( debtDecay() );
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns ( uint ) {
return IERC20( OHM ).totalSupply().mul( terms.maxPayout ).div( 100000 );
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor( uint _value ) public view returns ( uint ) {
return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 );
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns ( uint price_ ) {
price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 );
if ( price_ < terms.minimumPrice ) {
price_ = terms.minimumPrice;
} else if ( terms.minimumPrice != 0 ) {
terms.minimumPrice = 0;
}
}
/**
* @notice get asset price from chainlink
*/
function assetPrice() public view returns (int) {
( , int price, , , ) = priceFeed.latestRoundData();
return price;
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns ( uint price_ ) {
price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 );
}
/**
* @notice calculate current ratio of debt to OHM supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns ( uint debtRatio_ ) {
uint supply = IERC20( OHM ).totalSupply();
debtRatio_ = FixedPoint.fraction(
currentDebt().mul( 1e9 ),
supply
).decode112with18().div( 1e18 );
}
/**
* @notice debt ratio in same terms as reserve bonds
* @return uint
*/
function standardizedDebtRatio() external view returns ( uint ) {
return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns ( uint decay_ ) {
uint blocksSinceLast = block.number.sub( lastDecay );
decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
if ( decay_ > totalDebt ) {
decay_ = totalDebt;
}
}
/**
* @notice calculate how far into vesting a depositor is
* @param _depositor address
* @return percentVested_ uint
*/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
Bond memory bond = bondInfo[ _depositor ];
uint blocksSinceLast = block.number.sub( bond.lastBlock );
uint vesting = bond.vesting;
if ( vesting > 0 ) {
percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
} else {
percentVested_ = 0;
}
}
/**
* @notice calculate amount of OHM available for claim by depositor
* @param _depositor address
* @return pendingPayout_ uint
*/
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
uint percentVested = percentVestedFor( _depositor );
uint payout = bondInfo[ _depositor ].payout;
if ( percentVested >= 10000 ) {
pendingPayout_ = payout;
} else {
pendingPayout_ = payout.mul( percentVested ).div( 10000 );
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO
* @return bool
*/
function recoverLostToken( address _token ) external returns ( bool ) {
require( _token != OHM );
require( _token != principle );
IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
return true;
}
}
================================================
FILE: protocols/olympus-v1/src/wOHM.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
function unstake( uint _amount, address _recipient ) external returns ( bool );
function index() external view returns ( uint );
}
contract wOHM is ERC20 {
using SafeERC20 for ERC20;
using Address for address;
using SafeMath for uint;
address public immutable staking;
address public immutable OHM;
address public immutable sOHM;
constructor( address _staking, address _OHM, address _sOHM ) ERC20( 'Wrapped sOHM', 'wsOHM' ) {
require( _staking != address(0) );
staking = _staking;
require( _OHM != address(0) );
OHM = _OHM;
require( _sOHM != address(0) );
sOHM = _sOHM;
}
/**
@notice stakes OHM and wraps sOHM
@param _amount uint
@return uint
*/
function wrapFromOHM( uint _amount ) external returns ( uint ) {
IERC20( OHM ).transferFrom( msg.sender, address(this), _amount );
IERC20( OHM ).approve( staking, _amount ); // stake OHM for sOHM
IStaking( staking ).stake( _amount, address(this) );
uint value = wOHMValue( _amount );
_mint( msg.sender, value );
return value;
}
/**
@notice unwrap sOHM and unstake OHM
@param _amount uint
@return uint
*/
function unwrapToOHM( uint _amount ) external returns ( uint ) {
_burn( msg.sender, _amount );
uint value = sOHMValue( _amount );
IERC20( sOHM ).approve( staking, value ); // unstake sOHM for OHM
IStaking( staking ).unstake( value, address(this) );
IERC20( OHM ).transfer( msg.sender, value );
return value;
}
/**
@notice wrap sOHM
@param _amount uint
@return uint
*/
function wrapFromsOHM( uint _amount ) external returns ( uint ) {
IERC20( sOHM ).transferFrom( msg.sender, address(this), _amount );
uint value = wOHMValue( _amount );
_mint( msg.sender, value );
return value;
}
/**
@notice unwrap sOHM
@param _amount uint
@return uint
*/
function unwrapTosOHM( uint _amount ) external returns ( uint ) {
_burn( msg.sender, _amount );
uint value = sOHMValue( _amount );
IERC20( sOHM ).transfer( msg.sender, value );
return value;
}
/**
@notice converts wOHM amount to sOHM
@param _amount uint
@return uint
*/
function sOHMValue( uint _amount ) public view returns ( uint ) {
return _amount.mul( IStaking( staking ).index() ).div( 10 ** decimals() );
}
/**
@notice converts sOHM amount to wOHM
@param _amount uint
@return uint
*/
function wOHMValue( uint _amount ) public view returns ( uint ) {
return _amount.mul( 10 ** decimals() ).div( IStaking( staking ).index() );
}
}
================================================
FILE: protocols/olympus-v1/test/IUniswapV2Pair.sol
================================================
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
================================================
FILE: protocols/olympus-v1/test/core.t.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// Test Helpers
import "forge-std/Test.sol";
// Ohm tokens, Mock Tokens
import {OlympusERC20Token} from "@olympus/OlympusERC20.sol";
import {sOlympus} from "@olympus/sOlympusERC20.sol";
import {wOHM} from "@olympus/wOHM.sol";
import {DAI} from "@olympus/mocks/DAI.sol";
import {FRAX} from "@olympus/mocks/Frax.sol";
// Staking, Distributor, Staking Helper, Staking Warmup
import {OlympusStaking} from "@olympus/Staking.sol";
import {Distributor} from "@olympus/StakingDistributor.sol";
import {StakingHelper} from "@olympus/StakingHelper.sol";
import {StakingWarmup} from "@olympus/StakingWarmup.sol";
// Treasury
import {OlympusTreasury} from "@olympus/Treasury.sol";
// Bond Depository, CVX Depository, Bond Calculator
import {OlympusBondDepository, SafeMath} from "@olympus/BondDepository.sol";
import {OlympusCVXBondDepository} from "@olympus/CVXBondDepository.sol";
import {OlympusBondingCalculator} from "@olympus/StandardBondingCalculator.sol";
contract TestCore is Test {
using SafeMath for uint;
uint256 MAX = type(uint256).max;
uint256 RMIN = 10**3; // min Uniswap reserve
uint256 RMAX = 4365363797267; // Current reserve at time of fuzzing
uint256 INITDAI = 10000000008400000000000000;
// Ohm tokens, Mock Tokens
OlympusERC20Token ohm;
sOlympus sohm;
wOHM wsohm;
DAI dai;
DAI ohmdai;
FRAX frax;
// Staking, Distributor, Staking Helper, Staking Warmup
OlympusStaking testStaking;
Distributor testStakingDistr;
StakingHelper testStakingHelper;
StakingWarmup testStakingWarmup;
// Treasury
OlympusTreasury testTreasury;
// Bond Depository, CVX Depository, Bond Calculator
//OlympusBondDepository
OlympusBondDepository testBondDepo;
OlympusCVXBondDepository testCVXbondDepo;
OlympusBondingCalculator testBondCalculator;
function setUp() public {
vm.label(address(this), "THE_FUZZANATOR");
// Deploy tokens
ohm = new OlympusERC20Token();
vm.label(address(ohm), "OHM");
sohm = new sOlympus();
vm.label(address(sohm), "SOHM");
frax = new FRAX(9);
vm.label(address(frax), "FRAX");
dai = new DAI(9);
vm.label(address(dai), "DAI");
ohmdai = new DAI(9);
vm.label(address(ohmdai), "OHMDAI");
testStaking = new OlympusStaking(address(ohm), address(sohm), 2200, 338, block.timestamp);
vm.label(address(testStaking), "STAKING");
wsohm = new wOHM(address(testStaking), address(ohm), address(sohm));
vm.label(address(wsohm), "WOHM");
testTreasury = new OlympusTreasury(address(ohm), address(dai), address(frax), address(ohmdai), 0);
vm.label(address(testTreasury), "TREASURY");
testStakingDistr = new Distributor(address(testTreasury), address(ohm), 2200, block.timestamp);
vm.label(address(testStakingDistr), "STAKING_DISTRIBUTOR");
testStakingHelper = new StakingHelper(address(testStaking), address(ohm));
vm.label(address(testStakingHelper), "STAKING_HELPER");
testStakingWarmup = new StakingWarmup(address(testStaking), address(sohm));
vm.label(address(testStakingWarmup), "STAKING_WARMUP");
// Bond Depository
//OlympusBondDepository
testBondCalculator = new OlympusBondingCalculator(address(ohm));
vm.label(address(testBondCalculator), "BONDING_CALCULATOR");
testBondDepo = new OlympusBondDepository(address(ohm), address(dai), address(testTreasury), address(this), address(testBondCalculator));
vm.label(address(testBondDepo), "BOND_DEPO");
testBondDepo.initializeBondTerms(369, 33110, 50000, 50, 10000, 1000000000000000, 0);
testBondDepo.setStaking(address(testStaking), false);
testBondDepo.setStaking(address(testStakingHelper), true);
sohm.initialize(address(testStaking));
sohm.setIndex(7675210820);
//enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
testStaking.setContract(OlympusStaking.CONTRACTS.DISTRIBUTOR, address(testStakingDistr));
testStaking.setContract(OlympusStaking.CONTRACTS.WARMUP, address(testStakingWarmup));
ohm.setVault(address(testTreasury));
testStakingDistr.addRecipient(address(testStaking), 3000);
//enum MANAGING { RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SOHM }
testTreasury.queue(OlympusTreasury.MANAGING.REWARDMANAGER, address(testStakingDistr));
testTreasury.toggle(OlympusTreasury.MANAGING.REWARDMANAGER, address(testStakingDistr), address(0));
testTreasury.queue(OlympusTreasury.MANAGING.RESERVEDEPOSITOR, address(this));
testTreasury.toggle(OlympusTreasury.MANAGING.RESERVEDEPOSITOR, address(this), address(0));
testTreasury.queue(OlympusTreasury.MANAGING.RESERVEDEPOSITOR, address(testBondDepo));
testTreasury.toggle(OlympusTreasury.MANAGING.RESERVEDEPOSITOR, address(testBondDepo), address(0));
testTreasury.queue(OlympusTreasury.MANAGING.LIQUIDITYDEPOSITOR, address(this));
testTreasury.toggle(OlympusTreasury.MANAGING.LIQUIDITYDEPOSITOR, address(this), address(0));
testCVXbondDepo = new OlympusCVXBondDepository(address(ohm), address(this), address(this), address(testBondCalculator));
vm.label(address(testCVXbondDepo), "CVX_BOND_DEPO");
//testCVXbondDepo.initializeBondTerms(369, 33110, 50000, 50, 10000, 1000000000000000);
dai.approve(address(testTreasury), MAX);
dai.approve(address(testBondDepo), MAX);
ohm.approve(address(testStaking), MAX);
ohm.approve(address(testStakingHelper), MAX);
testBondCalculator.updateReserve(4365363797267);
dai.mint(address(this), INITDAI);
testTreasury.deposit(9000000000000000000000000, address(dai), 8400000000000000);
testStakingHelper.stake(100000000000);
testBondDepo.deposit(1000000000000000000000, 60000, address(this));
testBondDepo.setAdjustment(true, 1, 1000, 10);
}
/* INVARIANTS: Depositing into the bondDepo should:
* Increase user Bond Payout
* Updates users last block to latest
* Updates Bond Price
* Increase Total Debt
* Increase Treasury Total Reserves
* Updates control variable accordingly
* Updates rate accordingly
*/
function testFuzz_deposit(uint256 amount, uint maxPrice, uint timeSkip, uint pairReserve) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, (MAX - INITDAI));
uint _pairReserve = _between(pairReserve, RMIN, RMAX);
testBondCalculator.updateReserve(_pairReserve);
if (!set) {
init(_amount, _between(timeSkip, 1, (33110 * 2)));
}
uint totalReservesBefore = testTreasury.totalReserves();
uint totalDebtBefore = testBondDepo.totalDebt();
(uint payoutBefore, , , ) = testBondDepo.bondInfo(address(this));
(, uint rateBefore, uint target, uint buffer, uint lastBlock) = testBondDepo.adjustment();
(uint controlVariableBefore, , , , , ) = testBondDepo.terms();
this.depositHelper(_amount, maxPrice);
// ACTION:
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
// POSTCONDITIONS:
uint totalDebtAfter = testBondDepo.totalDebt();
(uint payoutAfter, , uint lastBlockAfter, ) = testBondDepo.bondInfo(address(this));
uint totalReservesAfter = testTreasury.totalReserves();
this.adjustmentHelper(controlVariableBefore, rateBefore, target, buffer, lastBlock);
assertGt(payoutAfter, payoutBefore, "PAYOUT CHECK");
assertEq(lastBlockAfter, block.number, "LAST BLOCK CHECK");
assertGt(totalDebtAfter, totalDebtBefore, "TOTAL DEBT CHECK");
assertGt(totalReservesAfter, totalReservesBefore, "TOTAL RESERVES CHECK");
} catch {/*assert(false)*/ }// overflow
}
// redeem without staking
/* INVARIANTS: Redeeming from BondDepo should:
* Decrease user payout
* Decrease user vesting
* Update user lastBlock
* Increase user OHM Balance
*/
function testFuzz_redeemNoStaking(uint amount, uint maxPrice, uint timeSkip) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, (MAX - INITDAI));
if (!setR) {
initR(_amount);
}
this.depositHelper(_amount, maxPrice);
uint userBalBefore = ohm.balanceOf(address(this));
// ACTIONS:
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
(uint payoutBefore, uint vestingBefore , uint lastBlockBefore , ) = testBondDepo.bondInfo(address(this));
skip(_between(timeSkip, 1, (33110 * 2)));
uint percentVested = testBondDepo.percentVestedFor(address(this));
if (percentVested >= 10000) {
try testBondDepo.redeem(address(this), false) {
uint userBalAfter = ohm.balanceOf(address(this));
// no need to check all of bond info since it is deleted
(uint payoutAfter, , , ) = testBondDepo.bondInfo(address(this));
// POSTCONDITIONS:
assertEq(payoutAfter, 0, "BOND INFO CHECK");
assertGt(userBalAfter, userBalBefore, "USER BALANCE CHECK");
} catch {/*assert(false)*/} // overflow
} else {
try testBondDepo.redeem(address(this), false) {
(uint payoutAfter, uint vestingAfter , , ) = testBondDepo.bondInfo(address(this));
uint userBalAfter = ohm.balanceOf(address(this));
// POSTCONDITIONS:
assertLe(payoutAfter, payoutBefore, "PAYOUT CHECK");
assertLe(vestingAfter, vestingBefore, "VESTING CHECK");
assertEq(block.number, lastBlockBefore, "LASTBLOCK CHECK");
assertGe(userBalAfter, userBalBefore, "USER BALANCE CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
// redeem with staking (Both with (TODO: without staking helper))
/* INVARIANTS: Redeeming from BondDepo should:
* Decrease user payout
* Decrease user vesting
* Update user lastBlock
* Increase staking OHM Balance
* Increase staking warmup sOHM Balance
* Increase user staking deposit
* Increase user gons
* Increase user expiry
* Update user lock to false
*/
function testFuzz_redeemWith(uint amount, uint maxPrice, uint timeSkip) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, (MAX - INITDAI));
if (!setR) {
initR(_amount);
}
this.depositHelper(_amount, maxPrice);
uint stakingBalBefore = ohm.balanceOf(address(testStaking));
uint stakingWarmupBalBefore = sohm.balanceOf(address(testStakingWarmup));
(uint depositBefore, uint gonsBefore, uint expiryBefore, ) = testStaking.warmupInfo(address(this));
// ACTIONS:
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
(uint payoutBefore, uint vestingBefore , uint lastBlockBefore , ) = testBondDepo.bondInfo(address(this));
skip(_between(timeSkip, 1, (33110 * 2)));
uint percentVested = testBondDepo.percentVestedFor(address(this));
if (percentVested >= 10000) {
try testBondDepo.redeem(address(this), true) {
// no need to check all of bond info since it is deleted
(uint payoutAfter, , , ) = testBondDepo.bondInfo(address(this));
// POSTCONDITIONS:
this.redeemWithHelper(depositBefore, gonsBefore, expiryBefore, stakingBalBefore, stakingWarmupBalBefore);
assertEq(payoutAfter, 0, "BOND INFO CHECK");
} catch {/*assert(false)*/} // overflow
} else {
try testBondDepo.redeem(address(this), true) {
(uint payoutAfter, uint vestingAfter , , ) = testBondDepo.bondInfo(address(this));
// POSTCONDITIONS:
this.redeemWithHelper(depositBefore, gonsBefore, expiryBefore, stakingBalBefore, stakingWarmupBalBefore);
assertLe(payoutAfter, payoutBefore, "PAYOUT CHECK");
assertLe(vestingAfter, vestingBefore, "VESTING CHECK");
assertEq(block.number, lastBlockBefore, "LASTBLOCK CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
// Redeem without staking and there is a rebase
/* INVARIANTS: Redeeming from BondDepo should:
* Updates distribute
* Increases number
* Increases endBlock
*/
function testFuzz_redeemRebase(uint amount, uint maxPrice, uint timeSkip) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, (MAX - INITDAI));
if (!setR) {
initR(_amount);
}
this.depositHelper(_amount, maxPrice);
// ACTIONS:
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
skip(_between(timeSkip, 1, (33110 * 2)));
(,uint numberBefore, uint endBlockBefore, ) = testStaking.epoch();
if (endBlockBefore <= block.number) {
try testBondDepo.redeem(address(this), true) {
// POSTCONDITIONS:
this.redeemWithEpochHelper(numberBefore, endBlockBefore);
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
// Unstaking without _trigger because it's invariants are tested
/* INVARIANTS: unstaking should:
* Increase user OHM balance
* Decrease user sOHM balance
* Increase Staking sOHM balance
* Decrease Staking OHM balance
*/
function testFuzz_unstake(uint amount) public {
// PRECONDTIONS:
uint _amount = _between(amount, 1, (MAX - INITDAI));
if (!setU) {
initR(_amount);
}
uint userSOHMBalBefore = sohm.balanceOf(address(this));
uint userOHMBalBefore = ohm.balanceOf(address(this));
uint stakingSOHMBalBefore = sohm.balanceOf(address(testStaking));
uint stakingOHMBalBefore = ohm.balanceOf(address(testStaking));
// ACTION:
try testStaking.unstake(_amount, false) {
// POSTCONDTIONS:
uint userSOHMBalAfter = sohm.balanceOf(address(this));
uint userOHMBalAfter = ohm.balanceOf(address(this));
uint stakingSOHMBalAfter = sohm.balanceOf(address(testStaking));
uint stakingOHMBalAfter = ohm.balanceOf(address(testStaking));
assertGt(userOHMBalAfter, userOHMBalBefore, "USER OHM CHECK");
assertLt(userSOHMBalAfter, userSOHMBalBefore, "USER SOHM CHECK");
assertGt(stakingSOHMBalAfter, stakingSOHMBalBefore, "STAKING SOHM CHECK");
assertLt(stakingOHMBalAfter, stakingOHMBalBefore, "STAKING OHM CHECK");
} catch {/*assert(false)*/} // overflow
}
// Helper functions
function redeemWithEpochHelper(uint numberBefore, uint endBlockBefore) public {
(, uint numberAfter, uint endBlockAfter, uint distributeAfter) = testStaking.epoch();
assertGt(numberAfter, numberBefore, "NUMBER CHECK");
assertGt(endBlockAfter, endBlockBefore, "ENDBLOCK CHECK");
//TODO: Test without distributor
uint balance = testStaking.contractBalance();
uint staked = sohm.circulatingSupply();
if( balance <= staked ) {
assertEq(distributeAfter, 0, "DISTRIBUTE CHECK");
} else {
assertEq(distributeAfter, balance.sub( staked ), "DISTRIBUTE CHECK");
}
}
function redeemWithHelper(uint depositBefore, uint gonsBefore, uint expiryBefore, uint stakingBalBefore, uint stakingWarmupBalBefore) public {
(uint depositAfter, uint gonsAfter, uint expiryAfter, bool lockAfter) = testStaking.warmupInfo(address(this));
uint stakingWarmupBalAfter = sohm.balanceOf(address(testStakingWarmup));
uint stakingBalAfter = ohm.balanceOf(address(testStaking));
assertGt(stakingBalAfter, stakingBalBefore, "STAKING BALANCE CHECK");
assertGt(depositAfter, depositBefore, "DEPOSIT CHECK");
assertGt(gonsAfter, gonsBefore, "GONS CHECK");
assertGt(expiryAfter, expiryBefore, "EXPIRY CHECK");
assertEq(lockAfter, false, "LOCK CHECK");
assertGe(stakingWarmupBalAfter, stakingWarmupBalBefore, "STAKING WARMUP BALANCE CHECK");
}
function adjustmentHelper(uint controlVariableBefore, uint rateBefore, uint target, uint buffer, uint lastBlock) public {
(bool add, uint rateAfter, , , ) = testBondDepo.adjustment();
(uint controlVariableAfter, , , , , ) = testBondDepo.terms();
if (rateBefore != 0 && block.number >= lastBlock.add(buffer)) {
if (add) {
assertGt(controlVariableAfter, controlVariableBefore, "CONTROL VARIABLE CHECK");
if (controlVariableBefore >= target) {
assertEq(rateAfter, 0, "RATE CHECK");
}
assertEq(rateAfter, rateBefore, "RATE CHECK");
} else {
assertLt(controlVariableAfter, controlVariableBefore, "CONTROL VARIABLE CHECK");
if (controlVariableBefore <= target) {
assertEq(rateAfter, 0, "RATE CHECK");
}
assertEq(rateAfter, rateBefore, "RATE CHECK");
}
}
}
function depositHelper(uint _amount, uint maxPrice) public {
uint totalDebtBeforeWithDecay = (testBondDepo.totalDebt().sub(testBondDepo.debtDecay()));
(uint _controlVariable, , uint _minimumPrice, , , uint _maxDebt) = testBondDepo.terms();
uint _nativePrice = this.bondPrice(_controlVariable, _minimumPrice);
uint _value;
try testTreasury.valueOf(address(dai), _amount) returns (uint value) {
_value = value;
} catch {/*assert(false)*/} // overflow
uint _payout;
try testBondDepo.payoutFor(_value) returns (uint payout) {
_payout = payout;
} catch {/*assert(false)*/} // overflow
uint maxpout = testBondDepo.maxPayout();
// Unhappy paths :(
if ( totalDebtBeforeWithDecay > _maxDebt) {
vm.expectRevert(bytes("Max capacity reached"));
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
} catch {/*assert(false)*/} // overflow
} else if (maxPrice < _nativePrice) {
vm.expectRevert(bytes("Slippage limit: more than max price"));
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
} catch {/*assert(false)*/} // overflow
} else if (_payout < 10000000) {
vm.expectRevert(bytes("Bond too small"));
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
}catch {/*assert(false)*/} // overflow
} else if (_payout > maxpout) {
vm.expectRevert(bytes("Bond too large"));
try testBondDepo.deposit(_amount, maxPrice, address(this)) {
} catch {/*assert(false)*/} // overflow
}
}
function bondPrice(uint controlVariable, uint minimumPrice) public returns ( uint price_ ) {
price_ = controlVariable.mul( testBondDepo.debtRatio() ).add( 1000000000 ).div( 1e7 );
if ( price_ < minimumPrice ) {
price_ = minimumPrice;
} else if ( minimumPrice != 0 ) {
minimumPrice = 0;
}
}
bool set;
function init(uint amount, uint timeSkip) public {
dai.mint(address(this), amount);
skip(timeSkip);
set = true;
}
bool setR;
function initR(uint amount) public {
dai.mint(address(this), amount);
setR = true;
}
bool setU;
function initU(uint amount) public {
ohm.mockMint(address(testStaking), amount);
sohm.mockMint(address(address(this)), amount);
setU = true;
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzying framework
// This is also a guarante bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
}
================================================
FILE: protocols/tombfinance/.gitignore
================================================
cache
out
================================================
FILE: protocols/tombfinance/.gitmodules
================================================
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
branch = v1.7.1
[submodule "lib/openzeppelin-contracts"]
path = lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
branch = release-v3.4
================================================
FILE: protocols/tombfinance/README.md
================================================
# **Setup**
# Setup
1. `forge install`
2. `forge test --mc TestCore`
## Integration
1. Follow setup
2. Add test helpers functions:
| Contract | Function |
| --- | --- |
[Masonry.sol](./src/Masonry.sol) | [earning()](./src/Masonry.sol#L210)
[Oracle.sol](./src/Oracle.sol) | [setPrice()](./src/Oracle.sol#L85)
[Treasury.sol](./src/Treasury.sol) | [setepochSupplyContractionLeft()](./src/Treasury.sol#L287)
[Treasury.sol](./src/Treasury.sol) | [moveEpoch()](./src/Treasury.sol#L551)
[TShare.sol](./src/TShare.sol) | [mint()](./src/TShare.sol#L124)
3. Remove test helpers from contracts before deploying
* I'm not responsible for what happens if you leave them in
# **Notes on Tomb Finance**
Tomb is a protocol that serves `TOMB` as an algorithmic token pegged to `FTM`. It's underlying mechanics are to adjust `TOMB`'s supply by moving the price up or down relative to `FTM`'s price. Inspired by [Basis](https://www.basis.io/) and currently consists of three tokens, `TOMB`, `TSHARE` and `TBOND`. `TOMB`
## **TOMB Token**:
Main token that is algorithmic stablecoin pegged to `FTM`. When it's price is about 1 `FTM` (adjusted to a TWAP over 6 hour periods) this is the expansion phase/inflation phase. To bring the price down more `TOMB` is minted at a percentage of supply.
* 18% is sent to the DAO (for buybacks when price is below peg)
* 2% for development/marketing fund
* 80% is distributed into the Masonry for users to receive `TOMB` for staking `TSHARE`
Every time `TOMB` is sold and creating LPs that are resent to the DAO or instantly burned will have a tax by the Gatekeeper system.
## **TSHARE Token**:
`TSHARE` is used to pair with `FTM` and provides liquidity to Cemetery to earn `TSHARE` rewards. It's other use is to stake in the Masonry. Every 6 hours during the expansion phase `TOMB` is paid out to `TSHARE` stakers in the masonry. Lock times are of 36 hours and 18 hours for claiming rewards.
Holders also have voting rights on proposals to improve the protocol. There is a maximum total supply of 70_000 distributed as:
1. DAO Allocation: 500 `TSHARE` vested linearly 12 months
2. Team Allocation: 5_000 `TSHARE` vested linearly over 12 months
3. Remaining 59_500 `TSHARE` are allocated for incentivizing Liquidity Providers in two shares pools for 12 months
## **TBONDS Token**:
During reduction phase/deflationary phase or when `TOMB` price falls below 1 `FTM`. Users can burn supply themselves and profit when the price goes back above the peg. In doing so the user receives `TBOND` tokens. Users can then redeem their `TBOND`s for `TOMB` with a bonus multiplier starting once the price is above 1.
* Available for purchase in the Pit R (bonus multiplier) can be calculated in the formula as shown below:
* `R=1+[(TOMB(twapprice)−1)∗coeff)]`
* Where coeff = 0.7
### **Masonry**:
* Epoch duration: 6 hours
* Deposits / Withdrawal of `TSHARE` into/from Masonry will lock:
* `TSHARE` for 6 epochs and
* `TOMB` rewards for 3 epochs
* `TOMB` rewards claim will lock staked `TSHARE` for 6 epochs and the next `TOMB` rewards can only be claimed 3 epochs later
* Distribution of `TOMB` during Expansion
* 80% as Reward for Boardroom `TSHARE` Stakers
* 18% goes to DAO fund
* 2% goes to DEV fund
* Epoch Expansion: Current expansion cap base on `TOMB` supply, if there are bonds to be redeemed:
* 65% of minted `TOMB` goes to treasury until its sufficiently full to meet bond redemption.
* If there is no debt it will follow max capped expansion rate
### **Cemetery**:
* Stake your LP to earn `TSHARE` tokens
* Shares Pools (Shares Reward) available for 12 months:
* `TOMB-FTM LP`: 35500 Shares
* `TSHARE-FTM LP`: 24000 Shares
### **Extra Links**:
[Tomb Docs](https://docs.tomb.com/)
[Tomb overview](https://tombfinance.medium.com/what-is-tomb-finance-82e8b3db2c09)
### **Audit Links**:
[Rekt artical](https://rekt.news/tomb-finance-rekt/)
[Post Mortem](https://tombfinance.medium.com/tomb-finance-post-mortem-480fa68375b2)
[Post Mortem pt2](https://tombfinance.medium.com/the-postmortem-revival-of-tomb-finance-past-present-and-future-f78cd19d48bd)
[TombSwap](https://tombfinance.medium.com/tombswap-has-arrived-aa9816b455a1)
================================================
FILE: protocols/tombfinance/foundry.toml
================================================
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
[fuzz]
runs = 100
# See more config options https://github.com/foundry-rs/foundry/tree/master/config
================================================
FILE: protocols/tombfinance/remappings.txt
================================================
forge-std/=lib/forge-std/src/
@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts
@solmate/=lib/solmate/src/
@solmock/=lib/solmate/src/test/utils/mocks/
@tomb/=src/
@uni/=test/v2-core/
================================================
FILE: protocols/tombfinance/script/Counter.s.sol
================================================
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Script.sol";
contract CounterScript is Script {
function setUp() public {}
function run() public {
vm.broadcast();
}
}
================================================
FILE: protocols/tombfinance/src/Distributor.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./interfaces/IDistributor.sol";
contract Distributor {
IDistributor[] public distributors;
constructor(IDistributor[] memory _distributors) public {
distributors = _distributors;
}
function distribute() public {
for (uint256 i = 0; i < distributors.length; i++) {
distributors[i].distribute();
}
}
}
================================================
FILE: protocols/tombfinance/src/DummyToken.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "./owner/Operator.sol";
contract DummyToken is ERC20Burnable, Operator {
uint8 private __decimals;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20(_name, _symbol) public {
__decimals = _decimals;
}
function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) {
_mint(recipient_, amount_);
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override onlyOperator {
super.burnFrom(account, amount);
}
}
================================================
FILE: protocols/tombfinance/src/Masonry.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./utils/ContractGuard.sol";
import "./interfaces/IBasisAsset.sol";
import "./interfaces/ITreasury.sol";
contract ShareWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public share;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
share.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
uint256 masonShare = _balances[msg.sender];
require(masonShare >= amount, "Masonry: withdraw request greater than staked amount");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = masonShare.sub(amount);
share.safeTransfer(msg.sender, amount);
}
}
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract Masonry is ShareWrapper, ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== DATA STRUCTURES ========== */
struct Masonseat {
uint256 lastSnapshotIndex;
uint256 rewardEarned;
uint256 epochTimerStart;
}
struct MasonrySnapshot {
uint256 time;
uint256 rewardReceived;
uint256 rewardPerShare;
}
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
IERC20 public tomb;
ITreasury public treasury;
mapping(address => Masonseat) public masons;
MasonrySnapshot[] public masonryHistory;
uint256 public withdrawLockupEpochs;
uint256 public rewardLockupEpochs;
/* ========== EVENTS ========== */
event Initialized(address indexed executor, uint256 at);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(address indexed user, uint256 reward);
/* ========== Modifiers =============== */
modifier onlyOperator() {
require(operator == msg.sender, "Masonry: caller is not the operator");
_;
}
modifier masonExists {
require(balanceOf(msg.sender) > 0, "Masonry: The mason does not exist");
_;
}
modifier updateReward(address mason) {
if (mason != address(0)) {
Masonseat memory seat = masons[mason];
seat.rewardEarned = earned(mason);
seat.lastSnapshotIndex = latestSnapshotIndex();
masons[mason] = seat;
}
_;
}
modifier notInitialized {
require(!initialized, "Masonry: already initialized");
_;
}
/* ========== GOVERNANCE ========== */
function initialize(
IERC20 _tomb,
IERC20 _share,
ITreasury _treasury
) public notInitialized {
tomb = _tomb;
share = _share;
treasury = _treasury;
MasonrySnapshot memory genesisSnapshot = MasonrySnapshot({time : block.number, rewardReceived : 0, rewardPerShare : 0});
masonryHistory.push(genesisSnapshot);
withdrawLockupEpochs = 6; // Lock for 6 epochs (36h) before release withdraw
rewardLockupEpochs = 3; // Lock for 3 epochs (18h) before release claimReward
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator {
require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week
withdrawLockupEpochs = _withdrawLockupEpochs;
rewardLockupEpochs = _rewardLockupEpochs;
}
/* ========== VIEW FUNCTIONS ========== */
// =========== Snapshot getters
function latestSnapshotIndex() public view returns (uint256) {
return masonryHistory.length.sub(1);
}
function getLatestSnapshot() internal view returns (MasonrySnapshot memory) {
return masonryHistory[latestSnapshotIndex()];
}
function getLastSnapshotIndexOf(address mason) public view returns (uint256) {
return masons[mason].lastSnapshotIndex;
}
function getLastSnapshotOf(address mason) internal view returns (MasonrySnapshot memory) {
return masonryHistory[getLastSnapshotIndexOf(mason)];
}
function canWithdraw(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch();
}
function canClaimReward(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch();
}
function epoch() external view returns (uint256) {
return treasury.epoch();
}
function nextEpochPoint() external view returns (uint256) {
return treasury.nextEpochPoint();
}
function getTombPrice() external view returns (uint256) {
return treasury.getTombPrice();
}
// =========== Mason getters
function rewardPerShare() public view returns (uint256) {
return getLatestSnapshot().rewardPerShare;
}
function earned(address mason) public view returns (uint256) {
uint256 latestRPS = getLatestSnapshot().rewardPerShare;
uint256 storedRPS = getLastSnapshotOf(mason).rewardPerShare;
return balanceOf(mason).mul(latestRPS.sub(storedRPS)).div(1e18).add(masons[mason].rewardEarned);
}
// Test function to skip checks
function earning(uint amount, address mason) public {
Masonseat memory seat = masons[mason];
seat.rewardEarned = amount;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount) public override onlyOneBlock updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot stake 0");
super.stake(amount);
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override onlyOneBlock masonExists updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot withdraw 0");
require(masons[msg.sender].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch(), "Masonry: still in withdraw lockup");
claimReward();
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
}
function claimReward() public updateReward(msg.sender) {
uint256 reward = masons[msg.sender].rewardEarned;
if (reward > 0) {
require(masons[msg.sender].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch(), "Masonry: still in reward lockup");
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
masons[msg.sender].rewardEarned = 0;
tomb.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function allocateSeigniorage(uint256 amount) external onlyOneBlock onlyOperator {
require(amount > 0, "Masonry: Cannot allocate 0");
require(totalSupply() > 0, "Masonry: Cannot allocate when totalSupply is 0");
// Create & add new snapshot
uint256 prevRPS = getLatestSnapshot().rewardPerShare;
uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply()));
MasonrySnapshot memory newSnapshot = MasonrySnapshot({
time: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
masonryHistory.push(newSnapshot);
tomb.safeTransferFrom(msg.sender, address(this), amount);
emit RewardAdded(msg.sender, amount);
}
function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(tomb), "tomb");
require(address(_token) != address(share), "share");
_token.safeTransfer(_to, _amount);
}
}
================================================
FILE: protocols/tombfinance/src/Migrations.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
}
================================================
FILE: protocols/tombfinance/src/Oracle.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./lib/Babylonian.sol";
import "./lib/FixedPoint.sol";
import "./lib/UniswapV2OracleLibrary.sol";
import "./utils/Epoch.sol";
import "./interfaces/IUniswapV2Pair.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
// fixed window oracle that recomputes the average price for the entire period once every period
// note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract Oracle is Epoch {
using FixedPoint for *;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// uniswap
address public token0;
address public token1;
IUniswapV2Pair public pair;
// oracle
uint32 public blockTimestampLast;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
/* ========== CONSTRUCTOR ========== */
constructor(
IUniswapV2Pair _pair,
uint256 _period,
uint256 _startTime
) public Epoch(_period, _startTime, 0) {
pair = _pair;
token0 = pair.token0();
token1 = pair.token1();
price0CumulativeLast = pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, "Oracle: NO_RESERVES"); // ensure that there's liquidity in the pair
}
/* ========== MUTABLE FUNCTIONS ========== */
/** @dev Updates 1-day EMA price from Uniswap. */
function update() external checkEpoch {
(uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed == 0) {
// prevent divided by zero
return;
}
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
emit Updated(price0Cumulative, price1Cumulative);
}
// Test helper
function setPrice(uint _amount) public {
price0Average = FixedPoint.uq112x112(uint224(_amount / 2));
price1Average = FixedPoint.uq112x112(uint224(_amount / 2));
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address _token, uint256 _amountIn) external view returns (uint144 amountOut) {
if (_token == token0) {
amountOut = price0Average.mul(_amountIn).decode144();
} else {
require(_token == token1, "Oracle: INVALID_TOKEN");
amountOut = price1Average.mul(_amountIn).decode144();
}
}
function twap(address _token, uint256 _amountIn) external view returns (uint144 _amountOut) {
(uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (_token == token0) {
_amountOut = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)).mul(_amountIn).decode144();
} else if (_token == token1) {
_amountOut = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)).mul(_amountIn).decode144();
}
}
event Updated(uint256 price0CumulativeLast, uint256 price1CumulativeLast);
}
================================================
FILE: protocols/tombfinance/src/SimpleERCFund.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './owner/Operator.sol';
import './interfaces/ISimpleERCFund.sol';
contract SimpleERCFund is ISimpleERCFund, Operator {
using SafeERC20 for IERC20;
function deposit(
address token,
uint256 amount,
string memory reason
) public override {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, now, reason);
}
function withdraw(
address token,
uint256 amount,
address to,
string memory reason
) public override onlyOperator {
IERC20(token).safeTransfer(to, amount);
emit Withdrawal(msg.sender, to, now, reason);
}
event Deposit(address indexed from, uint256 indexed at, string reason);
event Withdrawal(
address indexed from,
address indexed to,
uint256 indexed at,
string reason
);
}
================================================
FILE: protocols/tombfinance/src/TBond.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "./owner/Operator.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract TBond is ERC20Burnable, Operator {
/**
* @notice Constructs the TOMB Bond ERC-20 contract.
*/
constructor() public ERC20("TBOND", "TBOND") {}
/**
* @notice Operator mints basis bonds to a recipient
* @param recipient_ The address of recipient
* @param amount_ The amount of basis bonds to mint to
* @return whether the process has been done
*/
function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) {
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override onlyOperator {
super.burnFrom(account, amount);
}
}
================================================
FILE: protocols/tombfinance/src/TShare.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "./owner/Operator.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract TShare is ERC20Burnable, Operator {
using SafeMath for uint256;
// TOTAL MAX SUPPLY = 70,000 tSHAREs
uint256 public constant FARMING_POOL_REWARD_ALLOCATION = 59500 ether;
uint256 public constant COMMUNITY_FUND_POOL_ALLOCATION = 5500 ether;
uint256 public constant DEV_FUND_POOL_ALLOCATION = 5000 ether;
uint256 public constant VESTING_DURATION = 365 days;
uint256 public startTime;
uint256 public endTime;
uint256 public communityFundRewardRate;
uint256 public devFundRewardRate;
address public communityFund;
address public devFund;
uint256 public communityFundLastClaimed;
uint256 public devFundLastClaimed;
bool public rewardPoolDistributed = false;
constructor(uint256 _startTime, address _communityFund, address _devFund) public ERC20("TSHARE", "TSHARE") {
_mint(msg.sender, 1 ether); // mint 1 TOMB Share for initial pools deployment
startTime = _startTime;
endTime = startTime + VESTING_DURATION;
communityFundLastClaimed = startTime;
devFundLastClaimed = startTime;
communityFundRewardRate = COMMUNITY_FUND_POOL_ALLOCATION.div(VESTING_DURATION);
devFundRewardRate = DEV_FUND_POOL_ALLOCATION.div(VESTING_DURATION);
require(_devFund != address(0), "Address cannot be 0");
devFund = _devFund;
require(_communityFund != address(0), "Address cannot be 0");
communityFund = _communityFund;
}
function setTreasuryFund(address _communityFund) external {
require(msg.sender == devFund, "!dev");
communityFund = _communityFund;
}
function setDevFund(address _devFund) external {
require(msg.sender == devFund, "!dev");
require(_devFund != address(0), "zero");
devFund = _devFund;
}
function unclaimedTreasuryFund() public view returns (uint256 _pending) {
uint256 _now = block.timestamp;
if (_now > endTime) _now = endTime;
if (communityFundLastClaimed >= _now) return 0;
_pending = _now.sub(communityFundLastClaimed).mul(communityFundRewardRate);
}
function unclaimedDevFund() public view returns (uint256 _pending) {
uint256 _now = block.timestamp;
if (_now > endTime) _now = endTime;
if (devFundLastClaimed >= _now) return 0;
_pending = _now.sub(devFundLastClaimed).mul(devFundRewardRate);
}
/**
* @dev Claim pending rewards to community and dev fund
*/
function claimRewards() external {
uint256 _pending = unclaimedTreasuryFund();
if (_pending > 0 && communityFund != address(0)) {
_mint(communityFund, _pending);
communityFundLastClaimed = block.timestamp;
}
_pending = unclaimedDevFund();
if (_pending > 0 && devFund != address(0)) {
_mint(devFund, _pending);
devFundLastClaimed = block.timestamp;
}
}
/**
* @notice distribute to reward pool (only once)
*/
function distributeReward(address _farmingIncentiveFund) external onlyOperator {
require(!rewardPoolDistributed, "only can distribute once");
require(_farmingIncentiveFund != address(0), "!_farmingIncentiveFund");
rewardPoolDistributed = true;
_mint(_farmingIncentiveFund, FARMING_POOL_REWARD_ALLOCATION);
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
_token.transfer(_to, _amount);
}
// Used to test and bypass checks
function mint(address to, uint amount) public {
_mint(to, amount);
}
}
================================================
FILE: protocols/tombfinance/src/TaxOffice.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./owner/Operator.sol";
import "./interfaces/ITaxable.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract TaxOffice is Operator {
address public tomb;
constructor(address _tomb) public {
require(_tomb != address(0), "tomb address cannot be 0");
tomb = _tomb;
}
function setTaxTiersTwap(uint8 _index, uint256 _value) public onlyOperator returns (bool) {
return ITaxable(tomb).setTaxTiersTwap(_index, _value);
}
function setTaxTiersRate(uint8 _index, uint256 _value) public onlyOperator returns (bool) {
return ITaxable(tomb).setTaxTiersRate(_index, _value);
}
function enableAutoCalculateTax() public onlyOperator {
ITaxable(tomb).enableAutoCalculateTax();
}
function disableAutoCalculateTax() public onlyOperator {
ITaxable(tomb).disableAutoCalculateTax();
}
function setTaxRate(uint256 _taxRate) public onlyOperator {
ITaxable(tomb).setTaxRate(_taxRate);
}
function setBurnThreshold(uint256 _burnThreshold) public onlyOperator {
ITaxable(tomb).setBurnThreshold(_burnThreshold);
}
function setTaxCollectorAddress(address _taxCollectorAddress) public onlyOperator {
ITaxable(tomb).setTaxCollectorAddress(_taxCollectorAddress);
}
function excludeAddressFromTax(address _address) external onlyOperator returns (bool) {
return ITaxable(tomb).excludeAddress(_address);
}
function includeAddressInTax(address _address) external onlyOperator returns (bool) {
return ITaxable(tomb).includeAddress(_address);
}
function setTaxableTombOracle(address _tombOracle) external onlyOperator {
ITaxable(tomb).setTombOracle(_tombOracle);
}
function transferTaxOffice(address _newTaxOffice) external onlyOperator {
ITaxable(tomb).setTaxOffice(_newTaxOffice);
}
}
================================================
FILE: protocols/tombfinance/src/TaxOfficeV2.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./owner/Operator.sol";
import "./interfaces/ITaxable.sol";
import "./interfaces/IUniswapV2Router.sol";
import "./interfaces/IERC20.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract TaxOfficeV2 is Operator {
using SafeMath for uint256;
address public tomb = address(0x6c021Ae822BEa943b2E66552bDe1D2696a53fbB7);
address public wftm = address(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
address public uniRouter = address(0xF491e7B69E4244ad4002BC14e878a34207E38c29);
mapping(address => bool) public taxExclusionEnabled;
function setTaxTiersTwap(uint8 _index, uint256 _value) public onlyOperator returns (bool) {
return ITaxable(tomb).setTaxTiersTwap(_index, _value);
}
function setTaxTiersRate(uint8 _index, uint256 _value) public onlyOperator returns (bool) {
return ITaxable(tomb).setTaxTiersRate(_index, _value);
}
function enableAutoCalculateTax() public onlyOperator {
ITaxable(tomb).enableAutoCalculateTax();
}
function disableAutoCalculateTax() public onlyOperator {
ITaxable(tomb).disableAutoCalculateTax();
}
function setTaxRate(uint256 _taxRate) public onlyOperator {
ITaxable(tomb).setTaxRate(_taxRate);
}
function setBurnThreshold(uint256 _burnThreshold) public onlyOperator {
ITaxable(tomb).setBurnThreshold(_burnThreshold);
}
function setTaxCollectorAddress(address _taxCollectorAddress) public onlyOperator {
ITaxable(tomb).setTaxCollectorAddress(_taxCollectorAddress);
}
function excludeAddressFromTax(address _address) external onlyOperator returns (bool) {
return _excludeAddressFromTax(_address);
}
function _excludeAddressFromTax(address _address) private returns (bool) {
if (!ITaxable(tomb).isAddressExcluded(_address)) {
return ITaxable(tomb).excludeAddress(_address);
}
}
function includeAddressInTax(address _address) external onlyOperator returns (bool) {
return _includeAddressInTax(_address);
}
function _includeAddressInTax(address _address) private returns (bool) {
if (ITaxable(tomb).isAddressExcluded(_address)) {
return ITaxable(tomb).includeAddress(_address);
}
}
function taxRate() external view returns (uint256) {
return ITaxable(tomb).taxRate();
}
function addLiquidityTaxFree(
address token,
uint256 amtTomb,
uint256 amtToken,
uint256 amtTombMin,
uint256 amtTokenMin
)
external
returns (
uint256,
uint256,
uint256
)
{
require(amtTomb != 0 && amtToken != 0, "amounts can't be 0");
_excludeAddressFromTax(msg.sender);
IERC20(tomb).transferFrom(msg.sender, address(this), amtTomb);
IERC20(token).transferFrom(msg.sender, address(this), amtToken);
_approveTokenIfNeeded(tomb, uniRouter);
_approveTokenIfNeeded(token, uniRouter);
_includeAddressInTax(msg.sender);
uint256 resultAmtTomb;
uint256 resultAmtToken;
uint256 liquidity;
(resultAmtTomb, resultAmtToken, liquidity) = IUniswapV2Router(uniRouter).addLiquidity(
tomb,
token,
amtTomb,
amtToken,
amtTombMin,
amtTokenMin,
msg.sender,
block.timestamp
);
if(amtTomb.sub(resultAmtTomb) > 0) {
IERC20(tomb).transfer(msg.sender, amtTomb.sub(resultAmtTomb));
}
if(amtToken.sub(resultAmtToken) > 0) {
IERC20(token).transfer(msg.sender, amtToken.sub(resultAmtToken));
}
return (resultAmtTomb, resultAmtToken, liquidity);
}
function addLiquidityETHTaxFree(
uint256 amtTomb,
uint256 amtTombMin,
uint256 amtFtmMin
)
external
payable
returns (
uint256,
uint256,
uint256
)
{
require(amtTomb != 0 && msg.value != 0, "amounts can't be 0");
_excludeAddressFromTax(msg.sender);
IERC20(tomb).transferFrom(msg.sender, address(this), amtTomb);
_approveTokenIfNeeded(tomb, uniRouter);
_includeAddressInTax(msg.sender);
uint256 resultAmtTomb;
uint256 resultAmtFtm;
uint256 liquidity;
(resultAmtTomb, resultAmtFtm, liquidity) = IUniswapV2Router(uniRouter).addLiquidityETH{value: msg.value}(
tomb,
amtTomb,
amtTombMin,
amtFtmMin,
msg.sender,
block.timestamp
);
if(amtTomb.sub(resultAmtTomb) > 0) {
IERC20(tomb).transfer(msg.sender, amtTomb.sub(resultAmtTomb));
}
return (resultAmtTomb, resultAmtFtm, liquidity);
}
function setTaxableTombOracle(address _tombOracle) external onlyOperator {
ITaxable(tomb).setTombOracle(_tombOracle);
}
function transferTaxOffice(address _newTaxOffice) external onlyOperator {
ITaxable(tomb).setTaxOffice(_newTaxOffice);
}
function taxFreeTransferFrom(
address _sender,
address _recipient,
uint256 _amt
) external {
require(taxExclusionEnabled[msg.sender], "Address not approved for tax free transfers");
_excludeAddressFromTax(_sender);
IERC20(tomb).transferFrom(_sender, _recipient, _amt);
_includeAddressInTax(_sender);
}
function setTaxExclusionForAddress(address _address, bool _excluded) external onlyOperator {
taxExclusionEnabled[_address] = _excluded;
}
function _approveTokenIfNeeded(address _token, address _router) private {
if (IERC20(_token).allowance(address(this), _router) == 0) {
IERC20(_token).approve(_router, type(uint256).max);
}
}
}
================================================
FILE: protocols/tombfinance/src/TaxOracle.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract TombTaxOracle is Ownable {
using SafeMath for uint256;
IERC20 public tomb;
IERC20 public wftm;
address public pair;
constructor(
address _tomb,
address _wftm,
address _pair
) public {
require(_tomb != address(0), "tomb address cannot be 0");
require(_wftm != address(0), "wftm address cannot be 0");
require(_pair != address(0), "pair address cannot be 0");
tomb = IERC20(_tomb);
wftm = IERC20(_wftm);
pair = _pair;
}
function consult(address _token, uint256 _amountIn) external view returns (uint144 amountOut) {
require(_token == address(tomb), "token needs to be tomb");
uint256 tombBalance = tomb.balanceOf(pair);
uint256 wftmBalance = wftm.balanceOf(pair);
return uint144(tombBalance.div(wftmBalance));
}
function setTomb(address _tomb) external onlyOwner {
require(_tomb != address(0), "tomb address cannot be 0");
tomb = IERC20(_tomb);
}
function setWftm(address _wftm) external onlyOwner {
require(_wftm != address(0), "wftm address cannot be 0");
wftm = IERC20(_wftm);
}
function setPair(address _pair) external onlyOwner {
require(_pair != address(0), "pair address cannot be 0");
pair = _pair;
}
}
================================================
FILE: protocols/tombfinance/src/Timelock.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/*
* Copyright 2020 Compound Labs, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Timelock {
using SafeMath for uint256;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant MINIMUM_DELAY = 1 days;
uint256 public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint256 public delay;
mapping(bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint256 delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
receive() external payable {}
function setDelay(uint256 delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint256) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
================================================
FILE: protocols/tombfinance/src/Tomb.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "./lib/SafeMath8.sol";
import "./owner/Operator.sol";
import "./interfaces/IOracle.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract Tomb is ERC20Burnable, Operator {
using SafeMath8 for uint8;
using SafeMath for uint256;
// Initial distribution for the first 24h genesis pools
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 11000 ether;
// Initial distribution for the day 2-5 TOMB-WFTM LP -> TOMB pool
uint256 public constant INITIAL_TOMB_POOL_DISTRIBUTION = 140000 ether;
// Distribution for airdrops wallet
uint256 public constant INITIAL_AIRDROP_WALLET_DISTRIBUTION = 9000 ether;
// Have the rewards been distributed to the pools
bool public rewardPoolDistributed = false;
/* ================= Taxation =============== */
// Address of the Oracle
address public tombOracle;
// Address of the Tax Office
address public taxOffice;
// Current tax rate
uint256 public taxRate;
// Price threshold below which taxes will get burned
uint256 public burnThreshold = 1.10e18;
// Address of the tax collector wallet
address public taxCollectorAddress;
// Should the taxes be calculated using the tax tiers
bool public autoCalculateTax;
// Tax Tiers
uint256[] public taxTiersTwaps = [0, 5e17, 6e17, 7e17, 8e17, 9e17, 9.5e17, 1e18, 1.05e18, 1.10e18, 1.20e18, 1.30e18, 1.40e18, 1.50e18];
uint256[] public taxTiersRates = [2000, 1900, 1800, 1700, 1600, 1500, 1500, 1500, 1500, 1400, 900, 400, 200, 100];
// Sender addresses excluded from Tax
mapping(address => bool) public excludedAddresses;
event TaxOfficeTransferred(address oldAddress, address newAddress);
modifier onlyTaxOffice() {
require(taxOffice == msg.sender, "Caller is not the tax office");
_;
}
modifier onlyOperatorOrTaxOffice() {
require(isOperator() || taxOffice == msg.sender, "Caller is not the operator or the tax office");
_;
}
/**
* @notice Constructs the TOMB ERC-20 contract.
*/
constructor(uint256 _taxRate, address _taxCollectorAddress) public ERC20("TOMB", "TOMB") {
// Mints 1 TOMB to contract creator for initial pool setup
require(_taxRate < 10000, "tax equal or bigger to 100%");
require(_taxCollectorAddress != address(0), "tax collector address must be non-zero address");
excludeAddress(address(this));
_mint(msg.sender, 1 ether);
taxRate = _taxRate;
taxCollectorAddress = _taxCollectorAddress;
}
/* ============= Taxation ============= */
function getTaxTiersTwapsCount() public view returns (uint256 count) {
return taxTiersTwaps.length;
}
function getTaxTiersRatesCount() public view returns (uint256 count) {
return taxTiersRates.length;
}
function isAddressExcluded(address _address) public view returns (bool) {
return excludedAddresses[_address];
}
function setTaxTiersTwap(uint8 _index, uint256 _value) public onlyTaxOffice returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < getTaxTiersTwapsCount(), "Index has to lower than count of tax tiers");
if (_index > 0) {
require(_value > taxTiersTwaps[_index - 1]);
}
if (_index < getTaxTiersTwapsCount().sub(1)) {
require(_value < taxTiersTwaps[_index + 1]);
}
taxTiersTwaps[_index] = _value;
return true;
}
function setTaxTiersRate(uint8 _index, uint256 _value) public onlyTaxOffice returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < getTaxTiersRatesCount(), "Index has to lower than count of tax tiers");
taxTiersRates[_index] = _value;
return true;
}
function setBurnThreshold(uint256 _burnThreshold) public onlyTaxOffice returns (bool) {
burnThreshold = _burnThreshold;
}
function _getTombPrice() internal view returns (uint256 _tombPrice) {
try IOracle(tombOracle).consult(address(this), 1e18) returns (uint144 _price) {
return uint256(_price);
} catch {
revert("Tomb: failed to fetch TOMB price from Oracle");
}
}
function _updateTaxRate(uint256 _tombPrice) internal returns (uint256){
if (autoCalculateTax) {
for (uint8 tierId = uint8(getTaxTiersTwapsCount()).sub(1); tierId >= 0; --tierId) {
if (_tombPrice >= taxTiersTwaps[tierId]) {
require(taxTiersRates[tierId] < 10000, "tax equal or bigger to 100%");
taxRate = taxTiersRates[tierId];
return taxTiersRates[tierId];
}
}
}
}
function enableAutoCalculateTax() public onlyTaxOffice {
autoCalculateTax = true;
}
function disableAutoCalculateTax() public onlyTaxOffice {
autoCalculateTax = false;
}
function setTombOracle(address _tombOracle) public onlyOperatorOrTaxOffice {
require(_tombOracle != address(0), "oracle address cannot be 0 address");
tombOracle = _tombOracle;
}
function setTaxOffice(address _taxOffice) public onlyOperatorOrTaxOffice {
require(_taxOffice != address(0), "tax office address cannot be 0 address");
emit TaxOfficeTransferred(taxOffice, _taxOffice);
taxOffice = _taxOffice;
}
function setTaxCollectorAddress(address _taxCollectorAddress) public onlyTaxOffice {
require(_taxCollectorAddress != address(0), "tax collector address must be non-zero address");
taxCollectorAddress = _taxCollectorAddress;
}
function setTaxRate(uint256 _taxRate) public onlyTaxOffice {
require(!autoCalculateTax, "auto calculate tax cannot be enabled");
require(_taxRate < 10000, "tax equal or bigger to 100%");
taxRate = _taxRate;
}
function excludeAddress(address _address) public onlyOperatorOrTaxOffice returns (bool) {
require(!excludedAddresses[_address], "address can't be excluded");
excludedAddresses[_address] = true;
return true;
}
function includeAddress(address _address) public onlyOperatorOrTaxOffice returns (bool) {
require(excludedAddresses[_address], "address can't be included");
excludedAddresses[_address] = false;
return true;
}
/**
* @notice Operator mints TOMB to a recipient
* @param recipient_ The address of recipient
* @param amount_ The amount of TOMB to mint to
* @return whether the process has been done
*/
function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) {
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
}
function burn(uint256 amount) public override {
super.burn(amount);
}
function burnFrom(address account, uint256 amount) public override onlyOperator {
super.burnFrom(account, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentTaxRate = 0;
bool burnTax = false;
if (autoCalculateTax) {
uint256 currentTombPrice = _getTombPrice();
currentTaxRate = _updateTaxRate(currentTombPrice);
if (currentTombPrice < burnThreshold) {
burnTax = true;
}
}
if (currentTaxRate == 0 || excludedAddresses[sender]) {
_transfer(sender, recipient, amount);
} else {
_transferWithTax(sender, recipient, amount, burnTax);
}
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _transferWithTax(
address sender,
address recipient,
uint256 amount,
bool burnTax
) internal returns (bool) {
uint256 taxAmount = amount.mul(taxRate).div(10000);
uint256 amountAfterTax = amount.sub(taxAmount);
if(burnTax) {
// Burn tax
super.burnFrom(sender, taxAmount);
} else {
// Transfer tax to tax collector
_transfer(sender, taxCollectorAddress, taxAmount);
}
// Transfer amount after tax to recipient
_transfer(sender, recipient, amountAfterTax);
return true;
}
/**
* @notice distribute to reward pool (only once)
*/
function distributeReward(
address _genesisPool,
address _tombPool,
address _airdropWallet
) external onlyOperator {
require(!rewardPoolDistributed, "only can distribute once");
require(_genesisPool != address(0), "!_genesisPool");
require(_tombPool != address(0), "!_tombPool");
require(_airdropWallet != address(0), "!_airdropWallet");
rewardPoolDistributed = true;
_mint(_genesisPool, INITIAL_GENESIS_POOL_DISTRIBUTION);
_mint(_tombPool, INITIAL_TOMB_POOL_DISTRIBUTION);
_mint(_airdropWallet, INITIAL_AIRDROP_WALLET_DISTRIBUTION);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
_token.transfer(_to, _amount);
}
}
================================================
FILE: protocols/tombfinance/src/Treasury.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./lib/Babylonian.sol";
import "./owner/Operator.sol";
import "./utils/ContractGuard.sol";
import "./interfaces/IBasisAsset.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IMasonry.sol";
/*
______ __ _______
/_ __/___ ____ ___ / /_ / ____(_)___ ____ _____ ________
/ / / __ \/ __ `__ \/ __ \ / /_ / / __ \/ __ `/ __ \/ ___/ _ \
/ / / /_/ / / / / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/
/_/ \____/_/ /_/ /_/_.___/ /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/
http://tomb.finance
*/
contract Treasury is ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========= CONSTANT VARIABLES ======== */
uint256 public constant PERIOD = 6 hours;
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
// epoch
uint256 public startTime;
uint256 public epoch = 0;
uint256 public epochSupplyContractionLeft = 0;
// exclusions from total supply
address[] public excludedFromTotalSupply = [
address(0x9A896d3c54D7e45B558BD5fFf26bF1E8C031F93b), // TombGenesisPool
address(0xa7b9123f4b15fE0fF01F469ff5Eab2b41296dC0E), // new TombRewardPool
address(0xA7B16703470055881e7EE093e9b0bF537f29CD4d) // old TombRewardPool
];
// core components
address public tomb;
address public tbond;
address public tshare;
address public masonry;
address public tombOracle;
// price
uint256 public tombPriceOne;
uint256 public tombPriceCeiling;
uint256 public seigniorageSaved;
uint256[] public supplyTiers;
uint256[] public maxExpansionTiers;
uint256 public maxSupplyExpansionPercent;
uint256 public bondDepletionFloorPercent;
uint256 public seigniorageExpansionFloorPercent;
uint256 public maxSupplyContractionPercent;
uint256 public maxDebtRatioPercent;
// 28 first epochs (1 week) with 4.5% expansion regardless of TOMB price
uint256 public bootstrapEpochs;
uint256 public bootstrapSupplyExpansionPercent;
/* =================== Added variables =================== */
uint256 public previousEpochTombPrice;
uint256 public maxDiscountRate; // when purchasing bond
uint256 public maxPremiumRate; // when redeeming bond
uint256 public discountPercent;
uint256 public premiumThreshold;
uint256 public premiumPercent;
uint256 public mintingFactorForPayingDebt; // print extra TOMB during debt phase
address public daoFund;
uint256 public daoFundSharedPercent;
address public devFund;
uint256 public devFundSharedPercent;
/* =================== Events =================== */
event Initialized(address indexed executor, uint256 at);
event BurnedBonds(address indexed from, uint256 bondAmount);
event RedeemedBonds(address indexed from, uint256 tombAmount, uint256 bondAmount);
event BoughtBonds(address indexed from, uint256 tombAmount, uint256 bondAmount);
event TreasuryFunded(uint256 timestamp, uint256 seigniorage);
event MasonryFunded(uint256 timestamp, uint256 seigniorage);
event DaoFundFunded(uint256 timestamp, uint256 seigniorage);
event DevFundFunded(uint256 timestamp, uint256 seigniorage);
/* =================== Modifier =================== */
modifier onlyOperator() {
require(operator == msg.sender, "Treasury: caller is not the operator");
_;
}
modifier checkCondition {
require(now >= startTime, "Treasury: not started yet");
_;
}
modifier checkEpoch {
require(now >= nextEpochPoint(), "Treasury: not opened yet");
_;
epoch = epoch.add(1);
epochSupplyContractionLeft = (getTombPrice() > tombPriceCeiling) ? 0 : getTombCirculatingSupply().mul(maxSupplyContractionPercent).div(10000);
}
modifier checkOperator {
require(
IBasisAsset(tomb).operator() == address(this) &&
IBasisAsset(tbond).operator() == address(this) &&
IBasisAsset(tshare).operator() == address(this) &&
Operator(masonry).operator() == address(this),
"Treasury: need more permission"
);
_;
}
modifier notInitialized {
require(!initialized, "Treasury: already initialized");
_;
}
/* ========== VIEW FUNCTIONS ========== */
function isInitialized() public view returns (bool) {
return initialized;
}
// epoch
function nextEpochPoint() public view returns (uint256) {
return startTime.add(epoch.mul(PERIOD));
}
// oracle
function getTombPrice() public view returns (uint256 tombPrice) {
try IOracle(tombOracle).consult(tomb, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult TOMB price from the oracle");
}
}
function getTombUpdatedPrice() public view returns (uint256 _tombPrice) {
try IOracle(tombOracle).twap(tomb, 1e18) returns (uint144 price) {
return uint256(price);
} catch {
revert("Treasury: failed to consult TOMB price from the oracle");
}
}
// budget
function getReserve() public view returns (uint256) {
return seigniorageSaved;
}
function getBurnableTombLeft() public view returns (uint256 _burnableTombLeft) {
uint256 _tombPrice = getTombPrice();
if (_tombPrice <= tombPriceOne) {
uint256 _tombSupply = getTombCirculatingSupply();
uint256 _bondMaxSupply = _tombSupply.mul(maxDebtRatioPercent).div(10000);
uint256 _bondSupply = IERC20(tbond).totalSupply();
if (_bondMaxSupply > _bondSupply) {
uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply);
uint256 _maxBurnableTomb = _maxMintableBond.mul(_tombPrice).div(1e18);
_burnableTombLeft = Math.min(epochSupplyContractionLeft, _maxBurnableTomb);
}
}
}
function getRedeemableBonds() public view returns (uint256 _redeemableBonds) {
uint256 _tombPrice = getTombPrice();
if (_tombPrice > tombPriceCeiling) {
uint256 _totalTomb = IERC20(tomb).balanceOf(address(this));
uint256 _rate = getBondPremiumRate();
if (_rate > 0) {
_redeemableBonds = _totalTomb.mul(1e18).div(_rate);
}
}
}
function getBondDiscountRate() public view returns (uint256 _rate) {
uint256 _tombPrice = getTombPrice();
if (_tombPrice <= tombPriceOne) {
if (discountPercent == 0) {
// no discount
_rate = tombPriceOne;
} else {
uint256 _bondAmount = tombPriceOne.mul(1e18).div(_tombPrice); // to burn 1 TOMB
uint256 _discountAmount = _bondAmount.sub(tombPriceOne).mul(discountPercent).div(10000);
_rate = tombPriceOne.add(_discountAmount);
if (maxDiscountRate > 0 && _rate > maxDiscountRate) {
_rate = maxDiscountRate;
}
}
}
}
function getBondPremiumRate() public view returns (uint256 _rate) {
uint256 _tombPrice = getTombPrice();
if (_tombPrice > tombPriceCeiling) {
uint256 _tombPricePremiumThreshold = tombPriceOne.mul(premiumThreshold).div(100);
if (_tombPrice >= _tombPricePremiumThreshold) {
//Price > 1.10
uint256 _premiumAmount = _tombPrice.sub(tombPriceOne).mul(premiumPercent).div(10000);
_rate = tombPriceOne.add(_premiumAmount);
if (maxPremiumRate > 0 && _rate > maxPremiumRate) {
_rate = maxPremiumRate;
}
} else {
// no premium bonus
_rate = tombPriceOne;
}
}
}
/* ========== GOVERNANCE ========== */
function initialize(
address _tomb,
address _tbond,
address _tshare,
address _tombOracle,
address _masonry,
uint256 _startTime
) public notInitialized {
tomb = _tomb;
tbond = _tbond;
tshare = _tshare;
tombOracle = _tombOracle;
masonry = _masonry;
startTime = _startTime;
tombPriceOne = 10**18;
tombPriceCeiling = tombPriceOne.mul(101).div(100);
// Dynamic max expansion percent
supplyTiers = [0 ether, 500000 ether, 1000000 ether, 1500000 ether, 2000000 ether, 5000000 ether, 10000000 ether, 20000000 ether, 50000000 ether];
maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100];
maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion
bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor
seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for masonry
maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn TOMB and mint tBOND)
maxDebtRatioPercent = 3500; // Upto 35% supply of tBOND to purchase
premiumThreshold = 110;
premiumPercent = 7000;
// First 28 epochs with 4.5% expansion
bootstrapEpochs = 28;
bootstrapSupplyExpansionPercent = 450;
// set seigniorageSaved to it's balance
seigniorageSaved = IERC20(tomb).balanceOf(address(this));
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
// Test helper
function setepochSupplyContractionLeft(uint num) public {
epochSupplyContractionLeft = num;
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setMasonry(address _masonry) external onlyOperator {
masonry = _masonry;
}
function setTombOracle(address _tombOracle) external onlyOperator {
tombOracle = _tombOracle;
}
function setTombPriceCeiling(uint256 _tombPriceCeiling) external onlyOperator {
require(_tombPriceCeiling >= tombPriceOne && _tombPriceCeiling <= tombPriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2]
tombPriceCeiling = _tombPriceCeiling;
}
function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator {
require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%]
maxSupplyExpansionPercent = _maxSupplyExpansionPercent;
}
function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
if (_index > 0) {
require(_value > supplyTiers[_index - 1]);
}
if (_index < 8) {
require(_value < supplyTiers[_index + 1]);
}
supplyTiers[_index] = _value;
return true;
}
function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) {
require(_index >= 0, "Index has to be higher than 0");
require(_index < 9, "Index has to be lower than count of tiers");
require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%]
maxExpansionTiers[_index] = _value;
return true;
}
function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator {
require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%]
bondDepletionFloorPercent = _bondDepletionFloorPercent;
}
function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator {
require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%]
maxSupplyContractionPercent = _maxSupplyContractionPercent;
}
function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator {
require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%]
maxDebtRatioPercent = _maxDebtRatioPercent;
}
function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator {
require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month
require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%]
bootstrapEpochs = _bootstrapEpochs;
bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent;
}
function setExtraFunds(
address _daoFund,
uint256 _daoFundSharedPercent,
address _devFund,
uint256 _devFundSharedPercent
) external onlyOperator {
require(_daoFund != address(0), "zero");
require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30%
require(_devFund != address(0), "zero");
require(_devFundSharedPercent <= 1000, "out of range"); // <= 10%
daoFund = _daoFund;
daoFundSharedPercent = _daoFundSharedPercent;
devFund = _devFund;
devFundSharedPercent = _devFundSharedPercent;
}
function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator {
maxDiscountRate = _maxDiscountRate;
}
function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator {
maxPremiumRate = _maxPremiumRate;
}
function setDiscountPercent(uint256 _discountPercent) external onlyOperator {
require(_discountPercent <= 20000, "_discountPercent is over 200%");
discountPercent = _discountPercent;
}
function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator {
require(_premiumThreshold >= tombPriceCeiling, "_premiumThreshold exceeds tombPriceCeiling");
require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5");
premiumThreshold = _premiumThreshold;
}
function setPremiumPercent(uint256 _premiumPercent) external onlyOperator {
require(_premiumPercent <= 20000, "_premiumPercent is over 200%");
premiumPercent = _premiumPercent;
}
function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator {
require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%]
mintingFactorForPayingDebt = _mintingFactorForPayingDebt;
}
/* ========== MUTABLE FUNCTIONS ========== */
function _updateTombPrice() internal {
try IOracle(tombOracle).update() {} catch {}
}
function getTombCirculatingSupply() public view returns (uint256) {
IERC20 tombErc20 = IERC20(tomb);
uint256 totalSupply = tombErc20.totalSupply();
uint256 balanceExcluded = 0;
for (uint8 entryId = 0; entryId < excludedFromTotalSupply.length; ++entryId) {
balanceExcluded = balanceExcluded.add(tombErc20.balanceOf(excludedFromTotalSupply[entryId]));
}
return totalSupply.sub(balanceExcluded);
}
function buyBonds(uint256 _tombAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_tombAmount > 0, "Treasury: cannot purchase bonds with zero amount");
uint256 tombPrice = getTombPrice();
require(tombPrice == targetPrice, "Treasury: TOMB price moved");
require(
tombPrice < tombPriceOne, // price < $1
"Treasury: tombPrice not eligible for bond purchase"
);
require(_tombAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase");
uint256 _rate = getBondDiscountRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _bondAmount = _tombAmount.mul(_rate).div(1e18);
uint256 tombSupply = getTombCirculatingSupply();
uint256 newBondSupply = IERC20(tbond).totalSupply().add(_bondAmount);
require(newBondSupply <= tombSupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio");
IBasisAsset(tomb).burnFrom(msg.sender, _tombAmount);
IBasisAsset(tbond).mint(msg.sender, _bondAmount);
epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_tombAmount);
_updateTombPrice();
emit BoughtBonds(msg.sender, _tombAmount, _bondAmount);
}
function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator {
require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount");
uint256 tombPrice = getTombPrice();
require(tombPrice == targetPrice, "Treasury: TOMB price moved");
require(
tombPrice > tombPriceCeiling, // price > $1.01
"Treasury: tombPrice not eligible for bond purchase"
);
uint256 _rate = getBondPremiumRate();
require(_rate > 0, "Treasury: invalid bond rate");
uint256 _tombAmount = _bondAmount.mul(_rate).div(1e18);
require(IERC20(tomb).balanceOf(address(this)) >= _tombAmount, "Treasury: treasury has no more budget");
seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _tombAmount));
IBasisAsset(tbond).burnFrom(msg.sender, _bondAmount);
IERC20(tomb).safeTransfer(msg.sender, _tombAmount);
_updateTombPrice();
emit RedeemedBonds(msg.sender, _tombAmount, _bondAmount);
}
function _sendToMasonry(uint256 _amount) internal {
IBasisAsset(tomb).mint(address(this), _amount);
uint256 _daoFundSharedAmount = 0;
if (daoFundSharedPercent > 0) {
_daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000);
IERC20(tomb).transfer(daoFund, _daoFundSharedAmount);
emit DaoFundFunded(now, _daoFundSharedAmount);
}
uint256 _devFundSharedAmount = 0;
if (devFundSharedPercent > 0) {
_devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000);
IERC20(tomb).transfer(devFund, _devFundSharedAmount);
emit DevFundFunded(now, _devFundSharedAmount);
}
_amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount);
IERC20(tomb).safeApprove(masonry, 0);
IERC20(tomb).safeApprove(masonry, _amount);
IMasonry(masonry).allocateSeigniorage(_amount);
emit MasonryFunded(now, _amount);
}
function _calculateMaxSupplyExpansionPercent(uint256 _tombSupply) internal returns (uint256) {
for (uint8 tierId = 8; tierId >= 0; --tierId) {
if (_tombSupply >= supplyTiers[tierId]) {
maxSupplyExpansionPercent = maxExpansionTiers[tierId];
break;
}
}
return maxSupplyExpansionPercent;
}
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator {
_updateTombPrice();
previousEpochTombPrice = getTombPrice();
uint256 tombSupply = getTombCirculatingSupply().sub(seigniorageSaved);
if (epoch < bootstrapEpochs) {
// 28 first epochs with 4.5% expansion
_sendToMasonry(tombSupply.mul(bootstrapSupplyExpansionPercent).div(10000));
} else {
if (previousEpochTombPrice > tombPriceCeiling) {
// Expansion ($TOMB Price > 1 $FTM): there is some seigniorage to be allocated
uint256 bondSupply = IERC20(tbond).totalSupply();
uint256 _percentage = previousEpochTombPrice.sub(tombPriceOne);
uint256 _savedForBond;
uint256 _savedForMasonry;
uint256 _mse = _calculateMaxSupplyExpansionPercent(tombSupply).mul(1e14);
if (_percentage > _mse) {
_percentage = _mse;
}
if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) {
// saved enough to pay debt, mint as usual rate
_savedForMasonry = tombSupply.mul(_percentage).div(1e18);
} else {
// have not saved enough to pay debt, mint more
uint256 _seigniorage = tombSupply.mul(_percentage).div(1e18);
_savedForMasonry = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000);
_savedForBond = _seigniorage.sub(_savedForMasonry);
if (mintingFactorForPayingDebt > 0) {
_savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000);
}
}
if (_savedForMasonry > 0) {
_sendToMasonry(_savedForMasonry);
}
if (_savedForBond > 0) {
seigniorageSaved = seigniorageSaved.add(_savedForBond);
IBasisAsset(tomb).mint(address(this), _savedForBond);
emit TreasuryFunded(now, _savedForBond);
}
}
}
}
// Used for testing
function moveEpoch(uint skipNum) public {
epoch = epoch.add(skipNum);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(tomb), "tomb");
require(address(_token) != address(tbond), "bond");
require(address(_token) != address(tshare), "share");
_token.safeTransfer(_to, _amount);
}
function masonrySetOperator(address _operator) external onlyOperator {
IMasonry(masonry).setOperator(_operator);
}
function masonrySetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator {
IMasonry(masonry).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs);
}
function masonryAllocateSeigniorage(uint256 amount) external onlyOperator {
IMasonry(masonry).allocateSeigniorage(amount);
}
function masonryGovernanceRecoverUnsupported(
address _token,
uint256 _amount,
address _to
) external onlyOperator {
IMasonry(masonry).governanceRecoverUnsupported(_token, _amount, _to);
}
}
================================================
FILE: protocols/tombfinance/src/distribution/TShareRewardPool.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// Note that this pool has no minter key of tSHARE (rewards).
// Instead, the governance will call tSHARE distributeReward method and send reward to this pool at the beginning.
contract TShareRewardPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// governance
address public operator;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. tSHAREs to distribute per block.
uint256 lastRewardTime; // Last time that tSHAREs distribution occurs.
uint256 accTSharePerShare; // Accumulated tSHAREs per share, times 1e18. See below.
bool isStarted; // if lastRewardTime has passed
}
IERC20 public tshare;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The time when tSHARE mining starts.
uint256 public poolStartTime;
// The time when tSHARE mining ends.
uint256 public poolEndTime;
uint256 public tSharePerSecond = 0.00186122 ether; // 59500 tshare / (370 days * 24h * 60min * 60s)
uint256 public runningTime = 370 days; // 370 days
uint256 public constant TOTAL_REWARDS = 59500 ether;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 amount);
constructor(
address _tshare,
uint256 _poolStartTime
) public {
require(block.timestamp < _poolStartTime, "late");
if (_tshare != address(0)) tshare = IERC20(_tshare);
poolStartTime = _poolStartTime;
poolEndTime = poolStartTime + runningTime;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "TShareRewardPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "TShareRewardPool: existing pool?");
}
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
// chef is sleeping
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
} else {
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
} else {
// chef is cooking
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted =
(_lastRewardTime <= poolStartTime) ||
(_lastRewardTime <= block.timestamp);
poolInfo.push(PoolInfo({
token : _token,
allocPoint : _allocPoint,
lastRewardTime : _lastRewardTime,
accTSharePerShare : 0,
isStarted : _isStarted
}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's tSHARE allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _from to _to block.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
if (_fromTime >= _toTime) return 0;
if (_toTime >= poolEndTime) {
if (_fromTime >= poolEndTime) return 0;
if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(tSharePerSecond);
return poolEndTime.sub(_fromTime).mul(tSharePerSecond);
} else {
if (_toTime <= poolStartTime) return 0;
if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(tSharePerSecond);
return _toTime.sub(_fromTime).mul(tSharePerSecond);
}
}
// View function to see pending tSHAREs on frontend.
function pendingShare(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTSharePerShare = pool.accTSharePerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tshareReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accTSharePerShare = accTSharePerShare.add(_tshareReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accTSharePerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tshareReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accTSharePerShare = pool.accTSharePerShare.add(_tshareReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accTSharePerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTShareTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTSharePerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accTSharePerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTShareTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accTSharePerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe tshare transfer function, just in case if rounding error causes pool to not have enough tSHAREs.
function safeTShareTransfer(address _to, uint256 _amount) internal {
uint256 _tshareBal = tshare.balanceOf(address(this));
if (_tshareBal > 0) {
if (_amount > _tshareBal) {
tshare.safeTransfer(_to, _tshareBal);
} else {
tshare.safeTransfer(_to, _amount);
}
}
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
if (block.timestamp < poolEndTime + 90 days) {
// do not allow to drain core token (tSHARE or lps) if less than 90 days after pool ends
require(_token != tshare, "tshare");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
================================================
FILE: protocols/tombfinance/src/distribution/TombGenesisRewardPool.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// Note that this pool has no minter key of TOMB (rewards).
// Instead, the governance will call TOMB distributeReward method and send reward to this pool at the beginning.
contract TombGenesisRewardPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// governance
address public operator;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. TOMB to distribute.
uint256 lastRewardTime; // Last time that TOMB distribution occurs.
uint256 accTombPerShare; // Accumulated TOMB per share, times 1e18. See below.
bool isStarted; // if lastRewardBlock has passed
}
IERC20 public tomb;
address public shiba;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The time when TOMB mining starts.
uint256 public poolStartTime;
// The time when TOMB mining ends.
uint256 public poolEndTime;
// TESTNET
uint256 public tombPerSecond = 3.0555555 ether; // 11000 TOMB / (1h * 60min * 60s)
uint256 public runningTime = 24 hours; // 1 hours
uint256 public constant TOTAL_REWARDS = 11000 ether;
// END TESTNET
// MAINNET
// uint256 public tombPerSecond = 0.11574 ether; // 10000 TOMB / (24h * 60min * 60s)
// uint256 public runningTime = 1 days; // 1 days
// uint256 public constant TOTAL_REWARDS = 10000 ether;
// END MAINNET
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 amount);
constructor(
address _tomb,
address _shiba,
uint256 _poolStartTime
) public {
require(block.timestamp < _poolStartTime, "late");
if (_tomb != address(0)) tomb = IERC20(_tomb);
if (_shiba != address(0)) shiba = _shiba;
poolStartTime = _poolStartTime;
poolEndTime = poolStartTime + runningTime;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "TombGenesisPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "TombGenesisPool: existing pool?");
}
}
// Add a new token to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
// chef is sleeping
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
} else {
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
} else {
// chef is cooking
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted =
(_lastRewardTime <= poolStartTime) ||
(_lastRewardTime <= block.timestamp);
poolInfo.push(PoolInfo({
token : _token,
allocPoint : _allocPoint,
lastRewardTime : _lastRewardTime,
accTombPerShare : 0,
isStarted : _isStarted
}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's TOMB allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _from to _to block.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
if (_fromTime >= _toTime) return 0;
if (_toTime >= poolEndTime) {
if (_fromTime >= poolEndTime) return 0;
if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(tombPerSecond);
return poolEndTime.sub(_fromTime).mul(tombPerSecond);
} else {
if (_toTime <= poolStartTime) return 0;
if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(tombPerSecond);
return _toTime.sub(_fromTime).mul(tombPerSecond);
}
}
// View function to see pending TOMB on frontend.
function pendingTOMB(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTombPerShare = pool.accTombPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accTombPerShare = accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accTombPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accTombPerShare = pool.accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTombTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
if(address(pool.token) == shiba) {
user.amount = user.amount.add(_amount.mul(9900).div(10000));
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTombTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe TOMB transfer function, just in case if rounding error causes pool to not have enough TOMBs.
function safeTombTransfer(address _to, uint256 _amount) internal {
uint256 _tombBalance = tomb.balanceOf(address(this));
if (_tombBalance > 0) {
if (_amount > _tombBalance) {
tomb.safeTransfer(_to, _tombBalance);
} else {
tomb.safeTransfer(_to, _amount);
}
}
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
if (block.timestamp < poolEndTime + 90 days) {
// do not allow to drain core token (TOMB or lps) if less than 90 days after pool ends
require(_token != tomb, "tomb");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
================================================
FILE: protocols/tombfinance/src/distribution/TombRewardPool.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// Note that this pool has no minter key of TOMB (rewards).
// Instead, the governance will call TOMB distributeReward method and send reward to this pool at the beginning.
contract TombRewardPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// governance
address public operator;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. TOMBs to distribute in the pool.
uint256 lastRewardTime; // Last time that TOMBs distribution occurred.
uint256 accTombPerShare; // Accumulated TOMBs per share, times 1e18. See below.
bool isStarted; // if lastRewardTime has passed
}
IERC20 public tomb;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The time when TOMB mining starts.
uint256 public poolStartTime;
uint256[] public epochTotalRewards = [80000 ether, 60000 ether];
// Time when each epoch ends.
uint256[3] public epochEndTimes;
// Reward per second for each of 2 epochs (last item is equal to 0 - for sanity).
uint256[3] public epochTombPerSecond;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 amount);
constructor(address _tomb, uint256 _poolStartTime) public {
require(block.timestamp < _poolStartTime, "late");
if (_tomb != address(0)) tomb = IERC20(_tomb);
poolStartTime = _poolStartTime;
epochEndTimes[0] = poolStartTime + 4 days; // Day 2-5
epochEndTimes[1] = epochEndTimes[0] + 5 days; // Day 6-10
epochTombPerSecond[0] = epochTotalRewards[0].div(4 days);
epochTombPerSecond[1] = epochTotalRewards[1].div(5 days);
epochTombPerSecond[2] = 0;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "TombRewardPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "TombRewardPool: existing pool?");
}
}
// Add a new token to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
// chef is sleeping
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
} else {
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
} else {
// chef is cooking
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
poolInfo.push(PoolInfo({token: _token, allocPoint: _allocPoint, lastRewardTime: _lastRewardTime, accTombPerShare: 0, isStarted: _isStarted}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's TOMB allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _fromTime to _toTime.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 2; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochTombPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochTombPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochTombPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochTombPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochTombPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochTombPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochTombPerSecond[0]);
}
// View function to see pending TOMBs on frontend.
function pendingTOMB(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTombPerShare = pool.accTombPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accTombPerShare = accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accTombPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _tombReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accTombPerShare = pool.accTombPerShare.add(_tombReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTombTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeTombTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe tomb transfer function, just in case if rounding error causes pool to not have enough TOMBs.
function safeTombTransfer(address _to, uint256 _amount) internal {
uint256 _tombBal = tomb.balanceOf(address(this));
if (_tombBal > 0) {
if (_amount > _tombBal) {
tomb.safeTransfer(_to, _tombBal);
} else {
tomb.safeTransfer(_to, _amount);
}
}
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 amount,
address to
) external onlyOperator {
if (block.timestamp < epochEndTimes[1] + 30 days) {
// do not allow to drain token if less than 30 days after farming
require(_token != tomb, "!tomb");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
================================================
FILE: protocols/tombfinance/src/interfaces/IBasisAsset.sol
================================================
pragma solidity ^0.6.0;
interface IBasisAsset {
function mint(address recipient, uint256 amount) external returns (bool);
function burn(uint256 amount) external;
function burnFrom(address from, uint256 amount) external;
function isOperator() external returns (bool);
function operator() external view returns (address);
function transferOperator(address newOperator_) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IDecimals.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IDecimals {
function decimals() external view returns (uint8);
}
================================================
FILE: protocols/tombfinance/src/interfaces/IDistributor.sol
================================================
pragma solidity ^0.6.0;
interface IDistributor {
function distribute() external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IERC20.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
================================================
FILE: protocols/tombfinance/src/interfaces/IMasonry.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IMasonry {
function balanceOf(address _mason) external view returns (uint256);
function earned(address _mason) external view returns (uint256);
function canWithdraw(address _mason) external view returns (bool);
function canClaimReward(address _mason) external view returns (bool);
function epoch() external view returns (uint256);
function nextEpochPoint() external view returns (uint256);
function getTombPrice() external view returns (uint256);
function setOperator(address _operator) external;
function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external;
function stake(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function exit() external;
function claimReward() external;
function allocateSeigniorage(uint256 _amount) external;
function governanceRecoverUnsupported(address _token, uint256 _amount, address _to) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IOracle.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IOracle {
function update() external;
function consult(address _token, uint256 _amountIn) external view returns (uint144 amountOut);
function twap(address _token, uint256 _amountIn) external view returns (uint144 _amountOut);
}
================================================
FILE: protocols/tombfinance/src/interfaces/IShare.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IShare {
function unclaimedTreasuryFund() external view returns (uint256 _pending);
function claimRewards() external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/ISimpleERCFund.sol
================================================
pragma solidity ^0.6.0;
interface ISimpleERCFund {
function deposit(
address token,
uint256 amount,
string memory reason
) external;
function withdraw(
address token,
uint256 amount,
address to,
string memory reason
) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/ITShareRewardPool.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ITShareRewardPool {
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function pendingShare(uint256 _pid, address _user) external view returns (uint256);
function userInfo(uint _pid, address _user) external view returns (uint amount, uint rewardDebt);
}
================================================
FILE: protocols/tombfinance/src/interfaces/ITaxable.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ITaxable {
function setTaxTiersTwap(uint8 _index, uint256 _value) external returns (bool);
function setTaxTiersRate(uint8 _index, uint256 _value) external returns (bool);
function enableAutoCalculateTax() external;
function disableAutoCalculateTax() external;
function setTaxCollectorAddress(address _taxCollectorAddress) external;
function setTaxRate(uint256 _taxRate) external;
function setBurnThreshold(uint256 _burnThreshold) external;
function excludeAddress(address _address) external returns (bool);
function includeAddress(address _address) external returns (bool);
function setTombOracle(address _tombOracle) external;
function setTaxOffice(address _taxOffice) external;
function isAddressExcluded(address _address) external view returns (bool);
function taxRate() external view returns(uint256);
}
================================================
FILE: protocols/tombfinance/src/interfaces/ITreasury.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface ITreasury {
function epoch() external view returns (uint256);
function nextEpochPoint() external view returns (uint256);
function getTombPrice() external view returns (uint256);
function buyBonds(uint256 amount, uint256 targetPrice) external;
function redeemBonds(uint256 amount, uint256 targetPrice) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IUniswapV2Callee.sol
================================================
pragma solidity ^0.6.0;
interface IUniswapV2Callee {
function uniswapV2Call(
address sender,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IUniswapV2ERC20.sol
================================================
pragma solidity ^0.6.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IUniswapV2Factory.sol
================================================
pragma solidity ^0.6.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
================================================
FILE: protocols/tombfinance/src/interfaces/IUniswapV2Pair.sol
================================================
pragma solidity ^0.6.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IUniswapV2Router.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IUniswapV2Router {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
================================================
FILE: protocols/tombfinance/src/interfaces/IWrappedFtm.sol
================================================
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWrappedFtm is IERC20 {
function deposit() external payable returns (uint256);
function withdraw(uint256 amount) external returns (uint256);
}
================================================
FILE: protocols/tombfinance/src/lib/Babylonian.sol
================================================
pragma solidity ^0.6.0;
library Babylonian {
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
================================================
FILE: protocols/tombfinance/src/lib/FixedPoint.sol
================================================
pragma solidity ^0.6.0;
import "./Babylonian.sol";
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = uint256(1) << RESOLUTION;
uint256 private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z;
require(y == 0 || (z = uint256(self._x) * y) / y == uint256(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, "FixedPoint: ZERO_RECIPROCAL");
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
================================================
FILE: protocols/tombfinance/src/lib/Safe112.sol
================================================
pragma solidity ^0.6.0;
library Safe112 {
function add(uint112 a, uint112 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "Safe112: addition overflow");
return c;
}
function sub(uint112 a, uint112 b) internal pure returns (uint256) {
return sub(a, b, "Safe112: subtraction overflow");
}
function sub(
uint112 a,
uint112 b,
string memory errorMessage
) internal pure returns (uint112) {
require(b <= a, errorMessage);
uint112 c = a - b;
return c;
}
function mul(uint112 a, uint112 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "Safe112: multiplication overflow");
return c;
}
function div(uint112 a, uint112 b) internal pure returns (uint256) {
return div(a, b, "Safe112: division by zero");
}
function div(
uint112 a,
uint112 b,
string memory errorMessage
) internal pure returns (uint112) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint112 c = a / b;
return c;
}
function mod(uint112 a, uint112 b) internal pure returns (uint256) {
return mod(a, b, "Safe112: modulo by zero");
}
function mod(
uint112 a,
uint112 b,
string memory errorMessage
) internal pure returns (uint112) {
require(b != 0, errorMessage);
return a % b;
}
}
================================================
FILE: protocols/tombfinance/src/lib/SafeMath8.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath8 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
require(b <= a, errorMessage);
uint8 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint8 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint8 a, uint8 b) internal pure returns (uint8) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
require(b > 0, errorMessage);
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint8 a, uint8 b) internal pure returns (uint8) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint8 a, uint8 b, string memory errorMessage) internal pure returns (uint8) {
require(b != 0, errorMessage);
return a % b;
}
}
================================================
FILE: protocols/tombfinance/src/lib/UQ112x112.sol
================================================
pragma solidity =0.6.12;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
================================================
FILE: protocols/tombfinance/src/lib/UniswapV2Library.sol
================================================
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IUniswapV2Pair.sol";
library UniswapV2Library {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
================================================
FILE: protocols/tombfinance/src/lib/UniswapV2OracleLibrary.sol
================================================
pragma solidity ^0.6.0;
import "./FixedPoint.sol";
import "../interfaces/IUniswapV2Pair.sol";
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2**32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(address pair)
internal
view
returns (
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
)
{
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
================================================
FILE: protocols/tombfinance/src/owner/Operator.sol
================================================
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Operator is Context, Ownable {
address private _operator;
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
constructor() internal {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
}
function operator() public view returns (address) {
return _operator;
}
modifier onlyOperator() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
function isOperator() public view returns (bool) {
return _msgSender() == _operator;
}
function transferOperator(address newOperator_) public onlyOwner {
_transferOperator(newOperator_);
}
function _transferOperator(address newOperator_) internal {
require(newOperator_ != address(0), "operator: zero address given for new operator");
emit OperatorTransferred(address(0), newOperator_);
_operator = newOperator_;
}
}
================================================
FILE: protocols/tombfinance/src/utils/ContractGuard.sol
================================================
pragma solidity 0.6.12;
contract ContractGuard {
mapping(uint256 => mapping(address => bool)) private _status;
function checkSameOriginReentranted() internal view returns (bool) {
return _status[block.number][tx.origin];
}
function checkSameSenderReentranted() internal view returns (bool) {
return _status[block.number][msg.sender];
}
modifier onlyOneBlock() {
require(!checkSameOriginReentranted(), "ContractGuard: one block, one function");
require(!checkSameSenderReentranted(), "ContractGuard: one block, one function");
_;
_status[block.number][tx.origin] = true;
_status[block.number][msg.sender] = true;
}
}
================================================
FILE: protocols/tombfinance/src/utils/Epoch.sol
================================================
pragma solidity ^0.6.0;
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../owner/Operator.sol';
contract Epoch is Operator {
using SafeMath for uint256;
uint256 private period;
uint256 private startTime;
uint256 private lastEpochTime;
uint256 private epoch;
/* ========== CONSTRUCTOR ========== */
constructor(
uint256 _period,
uint256 _startTime,
uint256 _startEpoch
) public {
period = _period;
startTime = _startTime;
epoch = _startEpoch;
lastEpochTime = startTime.sub(period);
}
/* ========== Modifier ========== */
modifier checkStartTime {
require(now >= startTime, 'Epoch: not started yet');
_;
}
modifier checkEpoch {
uint256 _nextEpochPoint = nextEpochPoint();
if (now < _nextEpochPoint) {
require(msg.sender == operator(), 'Epoch: only operator allowed for pre-epoch');
_;
} else {
_;
for (;;) {
lastEpochTime = _nextEpochPoint;
++epoch;
_nextEpochPoint = nextEpochPoint();
if (now < _nextEpochPoint) break;
}
}
}
/* ========== VIEW FUNCTIONS ========== */
function getCurrentEpoch() public view returns (uint256) {
return epoch;
}
function getPeriod() public view returns (uint256) {
return period;
}
function getStartTime() public view returns (uint256) {
return startTime;
}
function getLastEpochTime() public view returns (uint256) {
return lastEpochTime;
}
function nextEpochPoint() public view returns (uint256) {
return lastEpochTime.add(period);
}
/* ========== GOVERNANCE ========== */
function setPeriod(uint256 _period) external onlyOperator {
require(_period >= 1 hours && _period <= 48 hours, '_period: out of range');
period = _period;
}
function setEpoch(uint256 _epoch) external onlyOperator {
epoch = _epoch;
}
}
================================================
FILE: protocols/tombfinance/test/core.t.sol
================================================
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
// Test Helpers
import "@tomb/interfaces/IUniswapV2Pair.sol";
import {MockUniPair} from "./mocks/MockUniPair.sol";
import "forge-std/Test.sol";
// Mock tokens
import "./mocks/MockWeth.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@tomb/DummyToken.sol";
// Protocol Tokens
import {Tomb} from "@tomb/Tomb.sol";
import {TBond} from "@tomb/TBond.sol";
import {TShare} from "@tomb/TShare.sol";
import {TaxOffice} from "@tomb/TaxOffice.sol";
// Timelock, Treasury, Oracle, Masonry
import {Timelock} from "@tomb/Timelock.sol";
import {Treasury} from "@tomb/Treasury.sol";
import "@tomb/interfaces/ITreasury.sol";
import {Oracle} from "@tomb/Oracle.sol";
import {Masonry} from "@tomb/Masonry.sol";
// Distruibution Pools, Distributor
import {TombGenesisRewardPool} from "@tomb/distribution/TombGenesisRewardPool.sol";
import {TombRewardPool} from "@tomb/distribution/TombRewardPool.sol";
import {TShareRewardPool} from "@tomb/distribution/TShareRewardPool.sol";
import {Distributor} from "@tomb/Distributor.sol";
import "@tomb/interfaces/IDistributor.sol";
contract TestCore is MockUniPair, Test {
uint256 MAX = type(uint256).max;
uint256 INITR = 100000000000000 + 1 ether; // Initial reserve of tomb minted in setup process
uint INIT = 10**4; // Just above initial reserve for Uniswap
address RANDO = address(0x8008);
address COMMUNITYFUND = address(0x8007);
address DEVFUND = address(0x8006);
// Mocks
MockWETH weth;
DummyToken shiba;
DummyToken usdt;
DummyToken usdc;
// Protocol Tokens, TaxOffice
TBond tbond;
Tomb tomb;
TShare tshare;
TaxOffice testTaxOffice;
// Distruibution Pools, Distributor
TombGenesisRewardPool testTombGenesisRewardPool;
TombRewardPool testTombRewardPool;
TShareRewardPool testTShareRewardPool;
Distributor testDistributor;
// Pair
address tombWethPair;
address usdtUsdcPair;
// Timelock, Treasury, Oracle, Masonry
Timelock testTimelock;
Treasury testTreasury;
Oracle testOracle;
Masonry testMasonry;
function setUp() public {
vm.label(address(this), "THE_FUZZANATOR");
vm.label(address(RANDO), "RANDO_USER");
// Dummy funds
vm.label(address(0x8008), "COMMUNITY_FUND");
vm.label(address(0x8007), "DEV_FUND");
// Deploy Mocks
weth = new MockWETH();
vm.label(address(weth), "WETH");
shiba = new DummyToken("SHIBA", "SHIBA", 18);
vm.label(address(shiba), "SHIBA");
usdc = new DummyToken("USDC", "USDC", 18);
vm.label(address(usdc), "USDC");
usdt = new DummyToken("USDT", "USDT", 6);
vm.label(address(usdt), "USDT");
// Deploy Protocol Tokens, TaxOffice
tomb = new Tomb(1, address(this));
vm.label(address(tomb), "TOMB");
testTaxOffice = new TaxOffice(address(tomb));
vm.label(address(testTaxOffice), "TOMB");
tomb.setTaxOffice(address(testTaxOffice));
tbond = new TBond();
vm.label(address(tbond), "TBOND");
tshare = new TShare(block.timestamp, COMMUNITYFUND, DEVFUND);
vm.label(address(tbond), "TSHARE");
// Deploy Distruibution Pools, Distributor
testTombGenesisRewardPool = new TombGenesisRewardPool(address(tomb), address(shiba), block.timestamp + 1);
vm.label(address(testTombGenesisRewardPool), "TOMB_GENESIS_POOL");
testTombRewardPool = new TombRewardPool(address(tomb), block.timestamp + 1);
vm.label(address(testTombRewardPool), "TOMB_POOL");
testTShareRewardPool = new TShareRewardPool(address(tshare), block.timestamp + 1);
vm.label(address(testTShareRewardPool), "TSHARE_POOL");
IDistributor[] memory pools = new IDistributor[](3);
pools[0] = IDistributor(address(testTombGenesisRewardPool));
pools[1] = IDistributor(address(testTombRewardPool));
pools[2] = IDistributor(address(testTShareRewardPool));
testDistributor = new Distributor(pools);
vm.label(address(testDistributor), "DISTRIBUTOR");
// Deploy mock Pairs and reserves
(address _testPair) = this.deployPair(address(tomb), address(weth));
tombWethPair = _testPair;
vm.label(address(tombWethPair), "TOMB-WETH_PAIR");
(address _testPair2) = this.deployPair(address(usdt), address(usdc));
usdtUsdcPair = _testPair2;
vm.label(address(usdtUsdcPair), "USDT-USDC_PAIR");
// Setup TOMB-WETH reserves
vm.deal(address(this), INITR);
weth.deposit{value: INITR}();
weth.transfer(address(tombWethPair), INITR);
tomb.mint(address(this), INITR);
tomb.transfer(address(tombWethPair), INITR);
IUniswapV2Pair(tombWethPair).mint(address(this));
// Setup USDT-USDC reserves
usdt.mint(address(this), INIT);
usdt.transfer(address(usdtUsdcPair), INIT);
usdc.mint(address(this), INIT);
usdc.transfer(address(usdtUsdcPair), INIT);
IUniswapV2Pair(usdtUsdcPair).mint(address(this));
// Add LP token to reward pools
testTombGenesisRewardPool.add(1, IERC20(usdtUsdcPair), false, 0);
testTombRewardPool.add(1, IERC20(usdtUsdcPair), false, 0);
testTShareRewardPool.add(1, IERC20(usdtUsdcPair), false, 0);
// Timelock, Treasury, Oracle, Masonry, TaxOffice
testTimelock = new Timelock(address(this), 1 days);
vm.label(address(testTimelock), "TIMELOCK");
testTreasury = new Treasury();
vm.label(address(testTreasury), "TREASURY");
testOracle = new Oracle(IUniswapV2Pair(address(_testPair)), 1, block.timestamp);
vm.label(address(testOracle), "ORACLE");
tomb.setTombOracle(address(testOracle));
testOracle.update();
skip(86400);
testMasonry = new Masonry();
vm.label(address(testMasonry), "MASONRY");
// Finish initialize setup
testMasonry.initialize(IERC20(address(tomb)), IERC20(address(tshare)), ITreasury(address(testTreasury)));
testTreasury.initialize(address(tomb), address(tbond), address(tshare), address(testOracle), address(testMasonry), block.timestamp);
}
function testON() public {}
/* INVARIANTS: Tomb mint should:
* Increase User Balance
* Increase Total Supply
*/
function testFuzz_TombMint(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX - INITR);
uint256 userBalBefore = tomb.balanceOf(address(this));
uint256 totalSupplyBefore = tomb.totalSupply();
// ACTION:
try tomb.mint(address(this), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tomb.balanceOf(address(this));
uint256 totalSupplyAfter = tomb.totalSupply();
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Tomb burn should:
* Decrease User Balance
* Decrease Total Supply
*/
function testFuzz_TombBurn(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX - INITR);
if (!setTomb) {
initTomb(amount);
}
uint256 userBalBefore = tomb.balanceOf(address(this));
uint256 totalSupplyBefore = tomb.totalSupply();
// ACTION:
try tomb.burn(amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tomb.balanceOf(address(this));
uint256 totalSupplyAfter = tomb.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Tomb burnfrom should:
* Decrease User Balance
* Decrease Total Supply
*/
function testFuzz_TombBurnFrom(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX - INITR);
if (!setTomb) {
initTomb(amount);
}
uint256 userBalBefore = tomb.balanceOf(address(this));
uint256 totalSupplyBefore = tomb.totalSupply();
// ACTION:
try tomb.burnFrom(address(this), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tomb.balanceOf(address(this));
uint256 totalSupplyAfter = tomb.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Tomb transferFrom without autoCalculateTax & currentTaxRate == 0 should:
* Decrease from User Balance
* Increase to User Balance
* Total Supply should remain the same
*/
function testFuzz_TombTransferFrom(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX - INITR);
if (!setTomb) {
initTomb(amount);
}
uint256 userBalBefore = tomb.balanceOf(address(this));
uint256 otherUserBalBefore = tomb.balanceOf(address(RANDO));
uint256 totalSupplyBefore = tomb.totalSupply();
// ACTION:
try tomb.transferFrom(address(this), address(RANDO), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tomb.balanceOf(address(this));
uint256 otherUserBalAfter = tomb.balanceOf(address(RANDO));
uint256 totalSupplyAfter = tomb.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertGt(otherUserBalAfter, otherUserBalBefore, "OTHER USER BAL CHECK");
assertEq(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
//TODO get consult to return > 0
/* INVARIANTS: Tomb transferFrom with autoCalculateTax should:
* Decrease from User Balance
* Increase to User Balance
* Decrease Total Supply
*/
function testFuzz_TombTaxTransferFrom(uint256 _amount) public {
// PRECONDITIONS:
testTaxOffice.enableAutoCalculateTax();
uint256 amount = _between(_amount, 1, MAX - INITR);
if (!setTomb) {
initTomb(amount);
skip(86400);
testOracle.update();
tomb.approve(address(tomb), amount);
}
uint256 userBalBefore = tomb.balanceOf(address(this));
uint256 otherUserBalBefore = tomb.balanceOf(address(RANDO));
uint256 totalSupplyBefore = tomb.totalSupply();
// ACTION:
try tomb.transferFrom(address(this), address(RANDO), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tomb.balanceOf(address(this));
uint256 otherUserBalAfter = tomb.balanceOf(address(RANDO));
uint256 totalSupplyAfter = tomb.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertGt(otherUserBalAfter, otherUserBalBefore, "OTHER USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TBond mint should:
* Increase User Balance
* Increase Total Supply
*/
function testFuzz_TBondMint(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint256 userBalBefore = tbond.balanceOf(address(this));
uint256 totalSupplyBefore = tbond.totalSupply();
// ACTION:
try tbond.mint(address(this), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tbond.balanceOf(address(this));
uint256 totalSupplyAfter = tbond.totalSupply();
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TBond burn should:
* Decrease User Balance
* Decrease Total Supply
*/
function testFuzz_TBondBurn(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTbond) {
initTbond(amount);
}
uint256 userBalBefore = tbond.balanceOf(address(this));
uint256 totalSupplyBefore = tbond.totalSupply();
// ACTION:
try tbond.burn(amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tbond.balanceOf(address(this));
uint256 totalSupplyAfter = tbond.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TBond burnfrom should:
* Decrease User Balance
* Decrease Total Supply
*/
function testFuzz_TBondBurnFrom(uint256 _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTbond) {
initTbond(amount);
}
uint256 userBalBefore = tbond.balanceOf(address(this));
uint256 totalSupplyBefore = tbond.totalSupply();
// ACTION:
try tbond.burnFrom(address(this), amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tbond.balanceOf(address(this));
uint256 totalSupplyAfter = tbond.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Depositing into TombGenesisRewardPool Should:
* Update pool reward variables
* Decrease User bal of token
* Update User rewardDebt
* Increase user bal amount
*/
function testFuzz_tombGenesisRewardPoolDeposit(uint256 _amount, uint256 skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTombGenesisRewardPool.totalAllocPoint();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTombGenesisRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTombPerShareBefore, bool isStartedBefore) = testTombGenesisRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tomb
if (tomb.balanceOf(address(testTombGenesisRewardPool)) > userAmountBefore * accTombPerShareBefore / 1e18 - userRewardDebtBefore) {
tomb.mint(address(testTombGenesisRewardPool), amount);
}
skip(skipNum);
}
// ACTION:
try testTombGenesisRewardPool.deposit(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTombGenesisRewardPool.userInfo(1, address(this));
this.genesisPoolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore, isStartedBefore, userRewardDebtAfter, false);
assertGt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Withdrawing from TombGenesisRewardPool Should:
* Update pool reward variables
* Increase User bal of token
* Update User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tombGenesisRewardPoolWithdraw(uint _amount, uint256 skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTombGenesisRewardPool.totalAllocPoint();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTombGenesisRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTombPerShareBefore, bool isStartedBefore) = testTombGenesisRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tomb
if (tomb.balanceOf(address(testTombGenesisRewardPool)) > userAmountBefore * accTombPerShareBefore / 1e18 - userRewardDebtBefore) {
tomb.mint(address(testTombGenesisRewardPool), amount);
}
skip(skipNum);
}
try testTombGenesisRewardPool.deposit(0, amount) {
// ACTION:
try testTombGenesisRewardPool.withdraw(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTombGenesisRewardPool.userInfo(1, address(this));
this.genesisPoolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore, isStartedBefore, userRewardDebtAfter, true);
assertLt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Emergency withdrawing from TombGenesisRewardPool Should:
* Increase User bal of token
* Decrease User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tombGenesisRewardPoolEmergencyWithdraw(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
}
try testTombGenesisRewardPool.deposit(0, amount) {
// ACTION:
try testTombGenesisRewardPool.emergencyWithdraw(0) {
// POSTCONDTIONS:
(uint userAmountAfter, uint userRewardDebtAfter) = testTombGenesisRewardPool.userInfo(1, address(this));
uint userTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
assertEq(userAmountAfter, 0, "USER BAL CHECK");
assertEq(userRewardDebtAfter, 0, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TombGenesisRewardPool Governance recover Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_tombGenesisRewardPooGovernanceRecoverUnsupported(uint _amount, uint256 skipNum ) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint poolEndTime = testTombGenesisRewardPool.poolEndTime();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = shiba.balanceOf(address(this));
uint userLPTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
try tomb.mint(address(testTombGenesisRewardPool), amount) {}catch {/*assert(false)*/ }// overflow
try shiba.mint(address(testTombGenesisRewardPool), amount) {}catch {/*assert(false)*/ }// overflow
skip(skipNum);
}
try testTombGenesisRewardPool.deposit(0, amount) {
// ACTION:
if (block.timestamp < poolEndTime + 90 days) {
try testTombGenesisRewardPool.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
try testTombGenesisRewardPool.governanceRecoverUnsupported(IERC20(usdtUsdcPair), amount, address(this)) {
// POSTCONDTIONS:
uint userLPTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userLPTokenBalAfter, userLPTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
try testTombGenesisRewardPool.governanceRecoverUnsupported(IERC20(tomb), amount, address(this)) {
// POSTCONDTIONS:
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Depositing into TombRewardPool Should:
* Update pool reward variables
* Decrease User bal of token
* Increase User rewardDebt
* Increase user bal amount
*/
function testFuzz_tombRewardPoolDeposit(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTombRewardPool.totalAllocPoint();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTombRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTombPerShareBefore, bool isStartedBefore) = testTombGenesisRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tomb
if (tomb.balanceOf(address(testTombRewardPool)) > userAmountBefore * accTombPerShareBefore / 1e18 - userRewardDebtBefore) {
tomb.mint(address(testTombRewardPool), amount);
}
skip(skipNum);
}
// ACTION:
try testTombRewardPool.deposit(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTombRewardPool.userInfo(1, address(this));
this.poolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore, isStartedBefore, userRewardDebtAfter, false);
assertGt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Withdrawing from TombRewardPool Should:
* Update pool reward variables
* Increase User bal of token
* Update User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tombRewardPoolWithdraw(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTombRewardPool.totalAllocPoint();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTombRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTombPerShareBefore, bool isStartedBefore) = testTombGenesisRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tomb
if (tomb.balanceOf(address(testTombRewardPool)) > userAmountBefore * accTombPerShareBefore / 1e18 - userRewardDebtBefore) {
tomb.mint(address(testTombRewardPool), amount);
}
skip(skipNum);
}
try testTombRewardPool.deposit(0, amount) {
// ACTION:
try testTombRewardPool.withdraw(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTombRewardPool.userInfo(1, address(this));
this.genesisPoolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore, isStartedBefore, userRewardDebtAfter, true);
assertLt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Emergency withdrawing from TombRewardPool Should:
* Increase User bal of token
* Decrease User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tombRewardPoolEmergencyWithdraw(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
}
try testTombRewardPool.deposit(0, amount) {
// ACTION:
try testTombRewardPool.emergencyWithdraw(0) {
// POSTCONDTIONS:
(uint userAmountAfter, uint userRewardDebtAfter) = testTombRewardPool.userInfo(1, address(this));
uint userTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
assertEq(userAmountAfter, 0, "USER BAL CHECK");
assertEq(userRewardDebtAfter, 0, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TombRewardPool Governance recover Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_tombRewardPoolGovernanceRecoverUnsupported(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint epochEndTime = testTombRewardPool.epochEndTimes(1);
uint userTombBalBefore = tomb.balanceOf(address(this));
uint userTokenBalBefore = shiba.balanceOf(address(this));
uint userLPTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
try tomb.mint(address(testTombRewardPool), amount) {}catch {/*assert(false)*/ }// overflow
try shiba.mint(address(testTombRewardPool), amount){}catch {/*assert(false)*/ }// overflow
skip(skipNum);
}
try testTombRewardPool.deposit(0, amount) {
// ACTION:
if (block.timestamp < epochEndTime + 30 days) {
try testTombRewardPool.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
try testTombRewardPool.governanceRecoverUnsupported(IERC20(usdtUsdcPair), amount, address(this)) {
// POSTCONDTIONS:
uint userLPTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userLPTokenBalAfter, userLPTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
try testTombGenesisRewardPool.governanceRecoverUnsupported(IERC20(tomb), amount, address(this)) {
// POSTCONDTIONS:
uint userTombBalAfter = tomb.balanceOf(address(this));
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Depositing into TShareRewardPool Should:
* Update pool reward variables
* Decrease User bal of token
* Increase User rewardDebt
* Increase user bal amount
*/
function testFuzz_tShareRewardPoolDeposit(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTShareRewardPool.totalAllocPoint();
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTShareRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTSharePerShareBefore, bool isStartedBefore) = testTShareRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tshare
if (tshare.balanceOf(address(testTShareRewardPool)) > userAmountBefore * accTSharePerShareBefore / 1e18 - userRewardDebtBefore) {
tshare.mint(address(testTShareRewardPool), amount);
}
skip(skipNum);
}
// ACTION:
try testTShareRewardPool.deposit(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTShareBalAfter = tshare.balanceOf(address(this));
assertGt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTShareRewardPool.userInfo(1, address(this));
this.genesisPoolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTSharePerShareBefore, isStartedBefore, userRewardDebtAfter, false);
assertGt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Withdrawing from TShareRewardPool Should:
* Update pool reward variables
* Increase User bal of token
* Update User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tShareRewardPoolWithdraw(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint totalAllocPointBefore = testTShareRewardPool.totalAllocPoint();
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
(uint userAmountBefore, uint userRewardDebtBefore) = testTShareRewardPool.userInfo(1, address(this));
(IERC20 token, uint256 allocPointBefore, uint256 lastRewardTimeBefore, uint256 accTSharePerShareBefore, bool isStartedBefore) = testTShareRewardPool.poolInfo(0);
if (!setReserves) {
initReserves(amount);
// Don't want the pool to run out of tshare
if (tshare.balanceOf(address(testTShareRewardPool)) > userAmountBefore * accTSharePerShareBefore / 1e18 - userRewardDebtBefore) {
tshare.mint(address(testTShareRewardPool), amount);
}
skip(skipNum);
}
try testTShareRewardPool.deposit(0, amount) {
// ACTION:
try testTShareRewardPool.withdraw(0, amount) {
// POSTCONDTIONS:
if (userAmountBefore > 0) {
uint userTShareBalAfter = tshare.balanceOf(address(this));
assertGt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
}
(uint userAmountAfter, uint userRewardDebtAfter) = testTShareRewardPool.userInfo(1, address(this));
this.genesisPoolUpdateHelper(totalAllocPointBefore, userTokenBalBefore, userRewardDebtBefore, token, allocPointBefore, lastRewardTimeBefore, accTSharePerShareBefore, isStartedBefore, userRewardDebtAfter, true);
assertLt(userAmountAfter, userAmountBefore, "USER BAL CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Emergency withdrawing from TShareRewardPool Should:
* Increase User bal of token
* Decrease User rewardDebt
* Decrease user bal amount
*/
function testFuzz_tShareRewardPoolEmergencyWithdraw(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
}
try testTShareRewardPool.deposit(0, amount) {
// ACTION:
try testTShareRewardPool.emergencyWithdraw(0) {
// POSTCONDTIONS:
(uint userAmountAfter, uint userRewardDebtAfter) = testTShareRewardPool.userInfo(1, address(this));
uint userTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
assertEq(userAmountAfter, 0, "USER BAL CHECK");
assertEq(userRewardDebtAfter, 0, "USER REWARD CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS:TShareRewardPool Governance recover Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_testFuzztShareRewardPoolGovernanceRecoverUnsupported(uint _amount, uint skipNum) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint poolEndTime = testTShareRewardPool.poolEndTime();
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userTokenBalBefore = shiba.balanceOf(address(this));
uint userLPTokenBalBefore = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (!setReserves) {
initReserves(amount);
try shiba.mint(address(testTShareRewardPool), amount){}catch {/*assert(false)*/ }// overflow
skip(skipNum);
}
try testTShareRewardPool.deposit(0, amount) {
// ACTION:
if (block.timestamp < poolEndTime + 90 days) {
try testTShareRewardPool.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
try testTShareRewardPool.governanceRecoverUnsupported(IERC20(usdtUsdcPair), amount, address(this)) {
// POSTCONDTIONS:
uint userLPTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
assertGt(userLPTokenBalAfter, userLPTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
try testTShareRewardPool.governanceRecoverUnsupported(IERC20(tshare), amount, address(this)) {
// POSTCONDTIONS:
uint userTShareBalAfter = tshare.balanceOf(address(this));
assertGt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Staking into Masonry Should:
* Increase totalSupply
* Increase User staked bal
* Decrease User tBond amount
* Set user epoch timer Start
*/
function testFuzz_masonryStake(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTShare) {
initTShare(amount);
vm.roll(10);
}
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userMasonryBalBefore = testMasonry.balanceOf(address(this));
uint totalSupplyBefore = testMasonry.totalSupply();
// ACTION:
try testMasonry.stake(amount) {
// POSTCONDTIONS:
uint userTShareBalAfter = tshare.balanceOf(address(this));
uint userMasonryBalAfter = testMasonry.balanceOf(address(this));
uint totalSupplyAfter = testMasonry.totalSupply();
( , , uint epochTimerStartAfter) = testMasonry.masons(address(this));
assertEq(epochTimerStartAfter, testTreasury.epoch(), "USER EPOCH TIMER CHECK");
assertLt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
assertGt(userMasonryBalAfter, userMasonryBalBefore, "USER MASONRY BAL CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "MASONRY TOTALSUPPLY BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Depositing into Masonry Should:
* Decrease totalSupply
* Decrease User staked bal
* Increase User tshare amount
*/
function testFuzz_masonryWithdraw(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTShare) {
initTShare(amount);
}
try testMasonry.stake(amount) {
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userMasonryBalBefore = testMasonry.balanceOf(address(this));
uint totalSupplyBefore = testMasonry.totalSupply();
if (!(testMasonry.canWithdraw(address(this)))) {
( , , uint epochTimerStart) = testMasonry.masons(address(this));
uint withdrawLockupEpochs = testMasonry.withdrawLockupEpochs();
uint skipNum = epochTimerStart + withdrawLockupEpochs;
testTreasury.moveEpoch(skipNum);
vm.roll(10);
}
// ACTION:
try testMasonry.withdraw(amount) {
// POSTCONDTIONS:
uint userTShareBalAfter = tshare.balanceOf(address(this));
uint userMasonryBalAfter = testMasonry.balanceOf(address(this));
uint totalSupplyAfter = testMasonry.totalSupply();
assertGt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
assertLt(userMasonryBalAfter, userMasonryBalBefore, "USER MASONRY BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "MASONRY TOTALSUPPLY BAL CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Claiming reward from Masonry Should:
* Decrease User Reward
* Increase tomb bal
* Update User epochTimerStart
* Decrease User reward Earned
*/
function testFuzz_masonryClaimReward(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTShare) {
initTShare(amount);
vm.roll(10);
}
uint userTombBalBefore = tomb.balanceOf(address(this));
uint masonryTombBalBefore = tomb.balanceOf(address(testMasonry));
try testMasonry.stake(amount) {
if (!(testMasonry.canClaimReward(address(this)))) {
( , , uint epochTimerStart) = testMasonry.masons(address(this));
uint rewardLockupEpochs = testMasonry.rewardLockupEpochs();
uint skipNum = epochTimerStart + rewardLockupEpochs;
testTreasury.moveEpoch(skipNum);
( , uint userRewardEarnedBefore, ) = testMasonry.masons(address(this));
if (userRewardEarnedBefore > 0 ) {
try testMasonry.earning(amount, address(this)) {} catch {/*assert(false)*/ }// overflow
try tomb.mint(address(testMasonry), amount) {} catch {/*assert(false)*/ }// overflow
// ACTION:
try testMasonry.claimReward() {
// POSTCONDTIONS:
uint userTombBalAfter = tomb.balanceOf(address(this));
uint masonryTombBalAfter = tomb.balanceOf(address(testMasonry));
( , uint userRewardEarnedAfter, uint epochTimerStartAfter) = testMasonry.masons(address(this));
assertEq(userRewardEarnedAfter, 0, "USER REWARD CHECK");
assertEq(epochTimerStartAfter, testTreasury.epoch(), "USER EPOCH TIMER CHECK");
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
assertLt(masonryTombBalAfter, masonryTombBalBefore, "USER TOMB BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
}
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Exiting from Masonry Should:
* Decrease totalSupply
* Decrease User staked bal
* Increase User tBond amount
*/
function testFuzz_masonryExit(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTShare) {
initTShare(amount);
}
try testMasonry.stake(amount) {
uint userTShareBalBefore = tshare.balanceOf(address(this));
uint userMasonryBalBefore = testMasonry.balanceOf(address(this));
uint totalSupplyBefore = testMasonry.totalSupply();
if (!(testMasonry.canWithdraw(address(this)))) {
( , , uint epochTimerStart) = testMasonry.masons(address(this));
uint withdrawLockupEpochs = testMasonry.withdrawLockupEpochs();
uint skipNum = epochTimerStart + withdrawLockupEpochs;
testTreasury.moveEpoch(skipNum);
vm.roll(10);
}
// ACTION:
try testMasonry.exit() {
// POSTCONDTIONS:
uint userTShareBalAfter = tshare.balanceOf(address(this));
uint userMasonryBalAfter = testMasonry.balanceOf(address(this));
uint totalSupplyAfter = testMasonry.totalSupply();
assertGt(userTShareBalAfter, userTShareBalBefore, "USER TSHARE BAL CHECK");
assertLt(userMasonryBalAfter, userMasonryBalBefore, "USER MASONRY BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "MASONRY TOTALSUPPLY BAL CHECK");
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Masonry Allocate Seigniorage
* Should: Update nextRPS
* Update time
* Decrease from User tomb bal
* Increase contracts tomb bal
*/
function testFuzz_masonryAllocateSeigniorage() public {}//TODO
/* INVARIANTS: Masonry Governance recover Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_masonryGovernanceRecoverUnsupported(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = shiba.balanceOf(address(this));
if (!setShiba) {
initShiba(address(testMasonry), amount);
}
try testMasonry.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Buying bonds from the Treasury Should:
* Decrease User tomb bal
* Decrease tomb totalSupply
* Increase User tBond bal
* Increase tBond totalSupply
* Decrease epochSupplyContractionLeft
*/
function testFuzz_treasuryBuyBonds(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTomb) {
initTomb(amount);
setOperatorsHelper();
tomb.approve(address(testTreasury), MAX);
testTreasury.setepochSupplyContractionLeft(amount);
testOracle.setPrice(1);
}
uint tombTotalSupplyBefore = tomb.totalSupply();
uint userTBondBalBefore = tbond.balanceOf(address(this));
uint tBondTotalSupplyBefore = tbond.totalSupply();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint epochSupplyContractionLeftBefore = testTreasury.epochSupplyContractionLeft();
uint targetPrice = testTreasury.getTombPrice();
try testTreasury.buyBonds(amount, targetPrice) {
// POSTCONDTIONS:
uint userTombBalAfter = tomb.balanceOf(address(this));
uint tombTotalSupplyAfter = tomb.totalSupply();
uint userTBondBalAfter = tbond.balanceOf(address(this));
uint tBondTotalSupplyAfter = tbond.totalSupply();
uint epochSupplyContractionLeftAfter = testTreasury.epochSupplyContractionLeft();
assertLt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
assertLe(tombTotalSupplyAfter, tombTotalSupplyBefore, "TOMB TOTALSUPPLY CHECK");
assertGt(userTBondBalAfter, userTBondBalBefore, "USER TBOND BAL CHECK");
assertGt(tBondTotalSupplyAfter, tBondTotalSupplyBefore, "TBOND TOTALSUPPLYS CHECK");
assertLt(epochSupplyContractionLeftAfter, epochSupplyContractionLeftBefore, "EPOCH SUPPLY CONTRACTION CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Redeeming bonds from the Treasury Should:
* Decrease User tBond bal
* Decrease tBond totalSupply
* Increase User tomb bal
* Increase tomb totalSupply
*/
function testFuzz_treasuryRedeemBonds(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
if (!setTbond) {
initTbond(amount);
try tomb.mint(address(testTreasury), amount) {} catch {/*assert(false)*/ }// overflow
setOperatorsHelper();
tbond.approve(address(testTreasury), MAX);
testOracle.setPrice(2);
}
uint tombTotalSupplyBefore = tomb.totalSupply();
uint userTBondBalBefore = tbond.balanceOf(address(this));
uint tBondTotalSupplyBefore = tbond.totalSupply();
uint userTombBalBefore = tomb.balanceOf(address(this));
uint targetPrice = testTreasury.getTombPrice();
try testTreasury.redeemBonds(amount, targetPrice) {
// POSTCONDTIONS:
uint userTombBalAfter = tomb.balanceOf(address(this));
uint tombTotalSupplyAfter = tomb.totalSupply();
uint userTBondBalAfter = tbond.balanceOf(address(this));
uint tBondTotalSupplyAfter = tbond.totalSupply();
uint epochSupplyContractionLeftAfter = testTreasury.epochSupplyContractionLeft();
assertGt(userTombBalAfter, userTombBalBefore, "USER TOMB BAL CHECK");
assertGt(tombTotalSupplyAfter, tombTotalSupplyBefore, "TOMB TOTALSUPPLY CHECK");
assertLt(userTBondBalAfter, userTBondBalBefore, "USER TBOND BAL CHECK");
assertLt(tBondTotalSupplyAfter, tBondTotalSupplyBefore, "TBOND TOTALSUPPLYS CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: reasury Allocate Seigniorage Should:
* Update previousEpochTombPrice
* If `_savedForBond > 0`, increase contract tomb bal
* If `_savedForMasonry > 0 && daoFundSharedPercent > 0` increase daoFund tomb bal
* If `_savedForMasonry > 0 && devFundSharedPercent > 0` increase devFund tomb bal
* Update masonry's allowance
*/
function testFuzz_treasuryAllocateSeigniorage() public {} //TODO
/* INVARIANTS: Treasury Governance recover Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_treasuryGovernanceRecoverUnsupported(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = shiba.balanceOf(address(this));
if (!setShiba) {
initShiba(address(testTreasury), amount);
}
try testTreasury.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: tShare Claim rewards Should:
* Increase totalSupply
* If `_pending > 0 && communityFund != address(0)` increase communityFund tShare bal
* If `_pending > 0 && devFund != address(0)` increase devFund tShare bal
* Update last claimed time
*/
function testFuzz_tShareClaimRewards(uint skipNum) public {
// PRECONDITIONS:
bool timeMove;
if (!timeMove) {
skip(skipNum);
}
uint256 communityBalBefore = tshare.balanceOf(address(COMMUNITYFUND));
uint256 devBalBefore = tshare.balanceOf(address(DEVFUND));
uint256 totalSupplyBefore = tshare.totalSupply();
uint unclaimedTreasury = tshare.unclaimedTreasuryFund();
uint unclaimedDev = tshare.unclaimedDevFund();
// ACTION:
try tshare.claimRewards() {
// POSTCONDTIONS:
if (unclaimedTreasury > 0 ) {
uint256 communityBalAfter = tshare.balanceOf(address(COMMUNITYFUND));
uint256 communityFundLastClaimed = tshare.communityFundLastClaimed();
assertGt(communityBalAfter, communityBalBefore, "COMMUNITY FUND CHECK");
assertEq(communityFundLastClaimed, block.timestamp, "COMMUNITY FUND TIME CHECK");
}
if (unclaimedDev > 0 ) {
uint256 devBalAfter = tshare.balanceOf(address(DEVFUND));
uint256 devFundLastClaimed = tshare.devFundLastClaimed();
assertGt(devBalAfter, devBalBefore, "DEV FUND CHECK");
assertEq(devFundLastClaimed, block.timestamp, "DEV FUND TIME CHECK");
}
uint256 totalSupplyAfter = tshare.totalSupply();
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: TShare Burn Should:
* Decrease User Balance
* Decrease Total Supply
*/
function testFuzz_tShareBurn(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX - INITR);
if (!setTShare) {
initTShare(amount);
}
uint256 userBalBefore = tshare.balanceOf(address(this));
uint256 totalSupplyBefore = tshare.totalSupply();
// ACTION:
try tshare.burn(amount) {
// POSTCONDTIONS:
uint256 userBalAfter = tshare.balanceOf(address(this));
uint256 totalSupplyAfter = tshare.totalSupply();
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
} catch {/*assert(false)*/ }// overflow
}
/* INVARIANTS: Governance recover from TShare Should:
* Decrease contract bal of token
* Increase to User bal of token
*/
function testFuzz_tShareGovernanceRecoverUnsupported(uint _amount) public {
// PRECONDITIONS:
uint256 amount = _between(_amount, 1, MAX);
uint userTokenBalBefore = shiba.balanceOf(address(this));
if (!setShiba) {
initShiba(address(tshare), amount);
}
try tshare.governanceRecoverUnsupported(IERC20(shiba), amount, address(this)) {
// POSTCONDTIONS:
uint userTokenBalAfter = shiba.balanceOf(address(this));
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} catch {/*assert(false)*/ }// overflow
}
// Helpers to init funds and other small setup
bool setTomb;
function initTomb(uint amount) public {
try tomb.mint(address(this), amount) {} catch {/*assert(false)*/ }// overflow
setTomb = true;
}
bool setTbond;
function initTbond(uint amount) public {
try tbond.mint(address(this), amount) {} catch {/*assert(false)*/ }// overflow
setTbond = true;
}
bool setTShare;
function initTShare(uint amount) public {
try tshare.mint(address(this), amount) {} catch {/*assert(false)*/ }// overflow
tshare.approve(address(testMasonry), amount);
setTShare = true;
}
bool setShiba;
function initShiba(address who, uint amount) public {
try shiba.mint(address(who), amount){}catch {/*assert(false)*/ }// overflow
setShiba = true;
}
bool setReserves;
function initReserves(uint amount) public {
try usdt.mint(address(this), amount) {
try usdt.transfer(address(usdtUsdcPair), amount) {} catch {/*assert(false)*/ }// overflow
try usdc.mint(address(this), amount) {
try usdc.transfer(address(usdtUsdcPair), amount) {} catch {/*assert(false)*/ }// overflow
try IUniswapV2Pair(usdtUsdcPair).mint(address(this)) {} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
} catch {/*assert(false)*/ }// overflow
setReserves = true;
}
function setOperatorsHelper() public {
tomb.transferOperator(address(testTreasury));
tbond.transferOperator(address(testTreasury));
tshare.transferOperator(address(testTreasury));
testMasonry.setOperator(address(testTreasury));
}
// Helpers to avoid stack too deep
function genesisPoolUpdateHelper(uint totalAllocPointBefore, uint userTokenBalBefore, uint userRewardDebtBefore, IERC20 token, uint allocPointBefore, uint lastRewardTimeBefore, uint accTombPerShareBefore, bool isStartedBefore, uint userRewardDebtAfter, bool withdraw) public {
( , , uint256 lastRewardTimeAfter, uint256 accTombPerShareAfter, bool isStartedAfter) = testTombGenesisRewardPool.poolInfo(0);
this.poolUpdateHelper2(userTokenBalBefore, withdraw);
if (block.timestamp <= lastRewardTimeBefore) {
this.poolUpdateHelper3(allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore);
} else {
if(IERC20(token).balanceOf(address(testTombGenesisRewardPool)) == 0) {
assertEq(lastRewardTimeAfter, block.timestamp, "LAST REWARD TIME UNCHANGED CHECK");
}
if(!isStartedBefore) {
this.poolUpdateHelper4(isStartedAfter, totalAllocPointBefore);
}
if (totalAllocPointBefore > 0) {
genesisGeneratedRewardHelper(userRewardDebtBefore, accTombPerShareBefore, userRewardDebtAfter, lastRewardTimeBefore, accTombPerShareAfter);
}
}
assertEq(lastRewardTimeAfter, block.timestamp, "LAST REWARD TIME CHECK");
}
function poolUpdateHelper(uint totalAllocPointBefore, uint userTokenBalBefore, uint userRewardDebtBefore, IERC20 token, uint allocPointBefore, uint lastRewardTimeBefore, uint accTombPerShareBefore, bool isStartedBefore, uint userRewardDebtAfter, bool withdraw) public {
( , , uint256 lastRewardTimeAfter, uint256 accTombPerShareAfter, bool isStartedAfter) = testTombGenesisRewardPool.poolInfo(0);
this.poolUpdateHelper2(userTokenBalBefore, withdraw);
if (block.timestamp <= lastRewardTimeBefore) {
this.poolUpdateHelper3(allocPointBefore, lastRewardTimeBefore, accTombPerShareBefore);
} else {
if(IERC20(token).balanceOf(address(testTombGenesisRewardPool)) == 0) {
assertEq(lastRewardTimeAfter, block.timestamp, "LAST REWARD TIME UNCHANGED CHECK");
}
if(!isStartedBefore) {
this.poolUpdateHelper4(isStartedAfter, totalAllocPointBefore);
}
if (totalAllocPointBefore > 0) {
generatedRewardHelper(lastRewardTimeBefore, accTombPerShareBefore, accTombPerShareAfter, userRewardDebtBefore, userRewardDebtAfter);
}
}
assertEq(lastRewardTimeAfter, block.timestamp, "LAST REWARD TIME CHECK");
}
function poolUpdateHelper2(uint userTokenBalBefore, bool withdraw) public {
uint userTokenBalAfter = IUniswapV2Pair(usdtUsdcPair).balanceOf(address(this));
if (withdraw) {
assertGt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
} else {
assertLt(userTokenBalAfter, userTokenBalBefore, "USER TOKEN BAL CHECK");
}
}
function poolUpdateHelper3(uint allocPointBefore, uint lastRewardTimeBefore, uint accTombPerShareBefore) public {
( , uint256 allocPointAfter, uint256 lastRewardTimeAfter, uint256 accTombPerShareAfter, ) = testTombGenesisRewardPool.poolInfo(0);
assertEq(allocPointBefore, allocPointAfter, "ALLOC POINT UNCHANGED CHECK");
assertEq(lastRewardTimeAfter, lastRewardTimeBefore, "LAST REWARD TIME UNCHANGED CHECK");
assertEq(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE UNCHANGED CHECK");
}
function poolUpdateHelper4(bool isStartedAfter, uint totalAllocPointBefore) public {
uint totalAllocPointAfter = testTombGenesisRewardPool.totalAllocPoint();
assertEq(isStartedAfter, true, "IS STARTED CHECK");
assertGt(totalAllocPointAfter, totalAllocPointBefore, "TOTAL ALLOC POINT CHECK");
}
function genesisGeneratedRewardHelper(uint userRewardDebtBefore, uint accTombPerShareBefore, uint userRewardDebtAfter, uint lastRewardTimeBefore, uint accTombPerShareAfter) public {
uint poolStartTime = testTombGenesisRewardPool.poolStartTime();
uint poolEndTime = testTombGenesisRewardPool.poolEndTime();
if(lastRewardTimeBefore >= block.timestamp){
assertEq(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE UNCHANGED CHECK");
} else if (block.timestamp >= poolEndTime) {
if (lastRewardTimeBefore >= poolEndTime) {
assertEq(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE UNCHANGED CHECK");
} else if (lastRewardTimeBefore <= poolStartTime) {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} else {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
} else {
if(block.timestamp <= poolStartTime) {
assertEq(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE UNCHANGED CHECK");
} else if (lastRewardTimeBefore <= poolStartTime){
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} else {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
}
}
function generatedRewardHelper(uint lastRewardTimeBefore, uint accTombPerShareBefore, uint accTombPerShareAfter, uint userRewardDebtBefore, uint userRewardDebtAfter) public {
uint[] memory epochEndTimes;
epochEndTimes[0] = testTombRewardPool.epochEndTimes(0);
epochEndTimes[1] = testTombRewardPool.epochEndTimes(1);
for (uint8 epochId = 2; epochId >= 1; --epochId) {
if (block.timestamp >= epochEndTimes[epochId - 1]) {
if (lastRewardTimeBefore >= epochEndTimes[epochId - 1]) {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
} else if (epochId == 1) {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (lastRewardTimeBefore >= epochEndTimes[epochId - 1]) {
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
}
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
}
assertGt(accTombPerShareAfter, accTombPerShareBefore, "ACCTOMB PER SHARE CHECK");
assertGt(userRewardDebtAfter, userRewardDebtBefore, "USER REWARD CHECK");
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzying framework
// This is also a guarante bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
}
================================================
FILE: protocols/tombfinance/test/mocks/MockUniPair.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.6.2;
// Pair factory and Pair
import "@uni/UniswapV2Factory.sol";
import "@uni/UniswapV2Pair.sol";
contract MockUniPair {
function deployPair(address _token1, address _token2) public returns(address) {
// Deploy factory and Pairs
UniswapV2Factory _testFactory = new UniswapV2Factory(address(this));
UniswapV2Pair _testPair = UniswapV2Pair(_testFactory.createPair(_token1, _token2));
return(address(_testPair));
}
/*
Helper if you ever change the pair code. Would also need to then import forge-std
function testGetInitCode() public {
bytes memory bytecode = type(UniswapV2Pair).creationCode;
emit log_bytes32(keccak256(abi.encodePacked(bytecode)));
}
*/
}
================================================
FILE: protocols/tombfinance/test/mocks/MockWeth.sol
================================================
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//updated version and fallback
pragma solidity >=0.6.0;
contract MockWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
payable(address(msg.sender)).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/UniswapV2ERC20.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.6.0;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public override constant name = 'Uniswap V2';
string public override constant symbol = 'UNI-V2';
uint8 public override constant decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
//event Approval(address indexed owner, address indexed spender, uint value);
//event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != /*uint(-1)*/ type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
function mint(address account, uint amount) external {
_mint(account,amount);
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/UniswapV2Factory.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.6.0;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/UniswapV2Pair.sol
================================================
pragma solidity ^0.6.0;
// pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is /*IUniswapV2Pair*/ UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= /*uint112(-1)*/ type(uint112).max && balance1 <= /*uint112(-1)*/ type(uint112).max, 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/interfaces/IUniswapV2Callee.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity >=0.6.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
================================================
FILE: protocols/tombfinance/test/v2-core/interfaces/IUniswapV2ERC20.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity >=0.6.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
================================================
FILE: protocols/tombfinance/test/v2-core/interfaces/IUniswapV2Factory.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity >=0.6.0;
interface IUniswapV2Factory {
//event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
================================================
FILE: protocols/tombfinance/test/v2-core/interfaces/IUniswapV2Pair.sol
================================================
pragma solidity >=0.6.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
================================================
FILE: protocols/tombfinance/test/v2-core/libraries/Math.sol
================================================
//pragma solidity =0.5.16;
pragma solidity >=0.6.0;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/libraries/SafeMath.sol
================================================
//pragma solidity =0.5.16;
pragma solidity >=0.6.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/libraries/UQ112x112.sol
================================================
//pragma solidity =0.5.16;
pragma solidity >=0.6.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
================================================
FILE: protocols/tombfinance/test/v2-core/test/ERC20.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.6.0;
import '../UniswapV2ERC20.sol';
contract ERC20 is UniswapV2ERC20 {
constructor(uint _totalSupply) public {
_mint(msg.sender, _totalSupply);
}
}
================================================
FILE: protocols/uniswap-v2/.gitignore
================================================
cache
out
================================================
FILE: protocols/uniswap-v2/.gitmodules
================================================
[submodule "lib/openzeppelin-contracts"]
path = lib/openzeppelin-contracts
url = https://github.com/OpenZeppelin/openzeppelin-contracts
branch = release-v4.5
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
branch = v1.7.1
================================================
FILE: protocols/uniswap-v2/README.md
================================================
# **Setup**
# Setup
1. `forge install OpenZeppelin/openzeppelin-contracts`
2. `forge install foundry-rs/forge-std`
3. `forge test --mc TestCore`
## Integration
1. Follow setup
2. Add test helpers functions:
| Contract | Function |
| --- | --- |
[UniswapV2ERC20.sol](./src/UniswapV2ERC20.sol) | [mint()](./src/UniswapV2ERC20.sol#L96)
3. Remove test helpers from contract before deploying
* I'm not responsible for what happens if you leave them in
# **Notes on Uniswap v2**
Uniswap v2 is an AMM but some major changes and updates to the original. It's powered by a constant product formula `x*y=Z`.
## **Pairs**:
Unlike Uniswap V1 where liquidity pools were between ETH and a single ERC20 token. It can now users can swap between any ERC20 and now uses WETH (wrapped Ether) instead of native ETH.
* Useful for liquidity providers to maintain more diverse ERC20 token positions without any exposure to ETH.
* Also improves prices because of routing through ETH for a swap between two other assets (fees & slippage on 2 separate pairs instead of one).
* If two tokens are not paired directly and don't have a common pair between them they can be swapped along a path that could exist.
## **Oracles**:
This is a new implementation that offers decentralized manipulation-resistant on-chain price feeds.
* It measures prices when they are expensive to manipulate and accumulating historical data
* Offers gas-efficient time-weighted averages of uniswap prices for any time interval
* Uniswap v1 can't be used safely as a price oracle because the price can moe significantly in a short period of time
* It measures (not store) market price at the beginning of each block (before any trades take place).
* Thus making it expensive to manipulate because it was set by the last Tx in a previous block.
* They would also have to make a bad trade at the end of the previous block and then be able to arbitrage it back in the next block
* Attackers will lose to arbitrageurs and would have to selfishly mine two blocks in a row (has not be observed to date).
* The end-of-block price is added to a single cumulative-price variable in the core contact weighted by the amount of time this price existed.
* It represents a sum of the price for every second in the entire history of the contract.
* This can be used by external contracts to track TWAPs across any time interval.
* `(priceCumulative2 - priceCumulative1) / (timestamp2 - timestamp1) = TWAP`
* Can be used for directly or as basis for moving averages (EMAs and SMAs)
* Cost of attack:
* Moving the price 5% on a 1-hour TWAP is about equal to the amount lost to arbitrage and fess for moving the price 5% every block for 1 hour.
Flash Swaps:
Similar to flash loans where a user can with no upfront capital or constraints can borrow => arbitrage => return either of the token in the pair.
## **Split into Core & Periphery**:
* Core in where one can find the Pair and Factory contracts.
* Periphery where one can find the router, oracle, migrator.
## **Changes From UNIv1-UNIv2**:

### **Extra Links**:
[Uniswap v2 Blog](https://blog.uniswap.org/uniswap-v2)
[Uniswap v2 whitepaper](https://uniswap.org/whitepaper.pdf)
[Uniswap v2 Overview](https://docs.uniswap.org/contracts/v2/overview)
[Uniswap V1 to V3](https://medium.com/auditless/uniswap-v1-to-v3-a-table-80d71d1303d2)
================================================
FILE: protocols/uniswap-v2/foundry.toml
================================================
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
[fuzz]
runs = 10000
# See more config options https://github.com/foundry-rs/foundry/tree/master/config
================================================
FILE: protocols/uniswap-v2/remappings.txt
================================================
forge-std/=lib/forge-std/src/
@openzeppelin/=lib/openzeppelin-contracts/contracts
@uniCore/=src/
@uniPer/=src/contracts
@uniswap/lib/contracts/=src/
@uniswap/v2-core/contracts/=src/
================================================
FILE: protocols/uniswap-v2/script/Counter.s.sol
================================================
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "forge-std/Script.sol";
contract CounterScript is Script {
function setUp() public {}
function run() public {
vm.broadcast();
}
}
================================================
FILE: protocols/uniswap-v2/src/UniswapV2ERC20.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
//event Approval(address indexed owner, address indexed spender, uint value);
//event Transfer(address indexed from, address indexed to, uint value);
constructor() /*public*/ {
uint chainId = block.chainid;
/*assembly {
chainId := chainid
}*/
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != /*uint(-1)*/ type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
// test helper
function mint(address account, uint amount) external {
_mint(account,amount);
}
}
================================================
FILE: protocols/uniswap-v2/src/UniswapV2Factory.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) /*public*/ {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
================================================
FILE: protocols/uniswap-v2/src/UniswapV2Pair.sol
================================================
pragma solidity ^0.8.0;
// pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is /*IUniswapV2Pair*/ UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() /*public*/ {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= /*uint112(-1)*/ type(uint112).max && balance1 <= /*uint112(-1)*/ type(uint112).max, 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/UniswapV2Migrator.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Migrator.sol';
import './interfaces/V1/IUniswapV1Factory.sol';
import './interfaces/V1/IUniswapV1Exchange.sol';
import './interfaces/IUniswapV2Router01.sol';
//import './interfaces/IERC20.sol';
import '@uniCore/interfaces/IERC20.sol';
contract UniswapV2Migrator is IUniswapV2Migrator {
IUniswapV1Factory immutable factoryV1;
IUniswapV2Router01 immutable router;
constructor(address _factoryV1, address _router) /*public*/ {
factoryV1 = IUniswapV1Factory(_factoryV1);
router = IUniswapV2Router01(_router);
}
// needs to accept ETH from any v1 exchange and the router. ideally this could be enforced, as in the router,
// but it's not possible because it requires a call to the v1 factory, which takes too much gas
receive() external payable {}
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external
override
{
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(token));
uint liquidityV1 = exchangeV1.balanceOf(msg.sender);
require(exchangeV1.transferFrom(msg.sender, address(this), liquidityV1), 'TRANSFER_FROM_FAILED');
(uint amountETHV1, uint amountTokenV1) = exchangeV1.removeLiquidity(liquidityV1, 1, 1, /*uint(-1)*/ type(uint256).max);
TransferHelper.safeApprove(token, address(router), amountTokenV1);
(uint amountTokenV2, uint amountETHV2,) = router.addLiquidityETH{value: amountETHV1}(
token,
amountTokenV1,
amountTokenMin,
amountETHMin,
to,
deadline
);
if (amountTokenV1 > amountTokenV2) {
TransferHelper.safeApprove(token, address(router), 0); // be a good blockchain citizen, reset allowance to 0
TransferHelper.safeTransfer(token, msg.sender, amountTokenV1 - amountTokenV2);
} else if (amountETHV1 > amountETHV2) {
// addLiquidityETH guarantees that all of amountETHV1 or amountTokenV1 will be used, hence this else is safe
TransferHelper.safeTransferETH(msg.sender, amountETHV1 - amountETHV2);
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/UniswapV2Router01.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './libraries/UniswapV2Library.sol';
import './interfaces/IUniswapV2Router01.sol';
//import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
import '@uniCore/interfaces/IERC20.sol';
contract UniswapV2Router01 is IUniswapV2Router01 {
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) /*public*/ {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) private returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); // refund dust eth, if any
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? /*uint(-1)*/ type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? /*uint(-1)*/ type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) private {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); // refund dust eth, if any
}
function quote(uint amountA, uint reserveA, uint reserveB) public pure override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure override returns (uint amountOut) {
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure override returns (uint amountIn) {
return UniswapV2Library.getAmountOut(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path) public view override returns (uint[] memory amounts) {
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path) public view override returns (uint[] memory amounts) {
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/UniswapV2Router02.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Router02.sol';
import './libraries/UniswapV2Library.sol';
//import './libraries/SafeMath.sol';
import '@uniCore/libraries/SafeMath.sol';
//import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
import '@uniCore/interfaces/IERC20.sol';
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) /*public*/ {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? /*uint(-1)*/ type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? /*uint(-1)*/ type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? /*uint(-1)*/ type(uint256).max : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/ExampleComputeLiquidityValue.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '../libraries/UniswapV2LiquidityMathLibrary.sol';
contract ExampleComputeLiquidityValue {
using SafeMath for uint256;
address public immutable factory;
constructor(address factory_) /*public*/ {
factory = factory_;
}
// see UniswapV2LiquidityMathLibrary#getReservesAfterArbitrage
function getReservesAfterArbitrage(
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB
) external view returns (uint256 reserveA, uint256 reserveB) {
return UniswapV2LiquidityMathLibrary.getReservesAfterArbitrage(
factory,
tokenA,
tokenB,
truePriceTokenA,
truePriceTokenB
);
}
// see UniswapV2LiquidityMathLibrary#getLiquidityValue
function getLiquidityValue(
address tokenA,
address tokenB,
uint256 liquidityAmount
) external view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
return UniswapV2LiquidityMathLibrary.getLiquidityValue(
factory,
tokenA,
tokenB,
liquidityAmount
);
}
// see UniswapV2LiquidityMathLibrary#getLiquidityValueAfterArbitrageToPrice
function getLiquidityValueAfterArbitrageToPrice(
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) external view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
return UniswapV2LiquidityMathLibrary.getLiquidityValueAfterArbitrageToPrice(
factory,
tokenA,
tokenB,
truePriceTokenA,
truePriceTokenB,
liquidityAmount
);
}
// test function to measure the gas cost of the above function
function getGasCostOfGetLiquidityValueAfterArbitrageToPrice(
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) external view returns (
uint256
) {
uint gasBefore = gasleft();
UniswapV2LiquidityMathLibrary.getLiquidityValueAfterArbitrageToPrice(
factory,
tokenA,
tokenB,
truePriceTokenA,
truePriceTokenB,
liquidityAmount
);
uint gasAfter = gasleft();
return gasBefore - gasAfter;
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/ExampleFlashSwap.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol';
import '../libraries/UniswapV2Library.sol';
import '../interfaces/V1/IUniswapV1Factory.sol';
import '../interfaces/V1/IUniswapV1Exchange.sol';
import '../interfaces/IUniswapV2Router01.sol';
//import '../interfaces/IERC20.sol';
import '../interfaces/IWETH.sol';
import '@uniCore/interfaces/IERC20.sol';
contract ExampleFlashSwap is IUniswapV2Callee {
IUniswapV1Factory immutable factoryV1;
address immutable factory;
IWETH immutable WETH;
constructor(address _factory, address _factoryV1, address router) /*public*/ {
factoryV1 = IUniswapV1Factory(_factoryV1);
factory = _factory;
WETH = IWETH(IUniswapV2Router01(router).WETH());
}
// needs to accept ETH from any V1 exchange and WETH. ideally this could be enforced, as in the router,
// but it's not possible because it requires a call to the v1 factory, which takes too much gas
receive() external payable {}
// gets tokens/WETH via a V2 flash swap, swaps for the ETH/tokens on V1, repays V2, and keeps the rest!
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external override {
address[] memory path = new address[](2);
uint amountToken;
uint amountETH;
{ // scope for token{0,1}, avoids stack too deep errors
address token0 = IUniswapV2Pair(msg.sender).token0();
address token1 = IUniswapV2Pair(msg.sender).token1();
assert(msg.sender == UniswapV2Library.pairFor(factory, token0, token1)); // ensure that msg.sender is actually a V2 pair
assert(amount0 == 0 || amount1 == 0); // this strategy is unidirectional
path[0] = amount0 == 0 ? token0 : token1;
path[1] = amount0 == 0 ? token1 : token0;
amountToken = token0 == address(WETH) ? amount1 : amount0;
amountETH = token0 == address(WETH) ? amount0 : amount1;
}
assert(path[0] == address(WETH) || path[1] == address(WETH)); // this strategy only works with a V2 WETH pair
IERC20 token = IERC20(path[0] == address(WETH) ? path[1] : path[0]);
IUniswapV1Exchange exchangeV1 = IUniswapV1Exchange(factoryV1.getExchange(address(token))); // get V1 exchange
if (amountToken > 0) {
(uint minETH) = abi.decode(data, (uint)); // slippage parameter for V1, passed in by caller
token.approve(address(exchangeV1), amountToken);
uint amountReceived = exchangeV1.tokenToEthSwapInput(amountToken, minETH, /*uint(-1)*/ type(uint256).max);
uint amountRequired = UniswapV2Library.getAmountsIn(factory, amountToken, path)[0];
assert(amountReceived > amountRequired); // fail if we didn't get enough ETH back to repay our flash loan
WETH.deposit{value: amountRequired}();
assert(WETH.transfer(msg.sender, amountRequired)); // return WETH to V2 pair
(bool success,) = sender.call{value: amountReceived - amountRequired}(new bytes(0)); // keep the rest! (ETH)
assert(success);
} else {
(uint minTokens) = abi.decode(data, (uint)); // slippage parameter for V1, passed in by caller
WETH.withdraw(amountETH);
uint amountReceived = exchangeV1.ethToTokenSwapInput{value: amountETH}(minTokens, /*uint(-1)*/ type(uint256).max);
uint amountRequired = UniswapV2Library.getAmountsIn(factory, amountETH, path)[0];
assert(amountReceived > amountRequired); // fail if we didn't get enough tokens back to repay our flash loan
assert(token.transfer(msg.sender, amountRequired)); // return tokens to V2 pair
assert(token.transfer(sender, amountReceived - amountRequired)); // keep the rest! (tokens)
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/ExampleOracleSimple.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
import '../libraries/UniswapV2OracleLibrary.sol';
import '../libraries/UniswapV2Library.sol';
// fixed window oracle that recomputes the average price for the entire period once every period
// note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract ExampleOracleSimple {
using FixedPoint for *;
uint public constant PERIOD = 24 hours;
IUniswapV2Pair immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
constructor(address factory, address tokenA, address tokenB) /*public*/ {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'ExampleOracleSimple: NO_RESERVES'); // ensure that there's liquidity in the pair
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'ExampleOracleSimple: PERIOD_NOT_ELAPSED');
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) external view returns (uint amountOut) {
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'ExampleOracleSimple: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/ExampleSlidingWindowOracle.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
//import '../libraries/SafeMath.sol';
import '@uniCore/libraries/SafeMath.sol';
import '../libraries/UniswapV2Library.sol';
import '../libraries/UniswapV2OracleLibrary.sol';
// sliding window oracle that uses observations collected over a window to provide moving price averages in the past
// `windowSize` with a precision of `windowSize / granularity`
// note this is a singleton oracle and only needs to be deployed once per desired parameters, which
// differs from the simple oracle which must be deployed once per pair.
contract ExampleSlidingWindowOracle {
using FixedPoint for *;
using SafeMath for uint;
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
address public immutable factory;
// the desired amount of time over which the moving average should be computed, e.g. 24 hours
uint public immutable windowSize;
// the number of observations stored for each pair, i.e. how many price observations are stored for the window.
// as granularity increases from 1, more frequent updates are needed, but moving averages become more precise.
// averages are computed over intervals with sizes in the range:
// [windowSize - (windowSize / granularity) * 2, windowSize]
// e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for
// the period:
// [now - [22 hours, 24 hours], now]
uint8 public immutable granularity;
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint public immutable periodSize;
// mapping from pair address to a list of price observations of that pair
mapping(address => Observation[]) public pairObservations;
constructor(address factory_, uint windowSize_, uint8 granularity_) /*public*/ {
require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY');
require(
(periodSize = windowSize_ / granularity_) * granularity_ == windowSize_,
'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE'
);
factory = factory_;
windowSize = windowSize_;
granularity = granularity_;
}
// returns the index of the observation corresponding to the given timestamp
function observationIndexOf(uint timestamp) public view returns (uint8 index) {
uint epochPeriod = timestamp / periodSize;
return uint8(epochPeriod % granularity);
}
// returns the observation from the oldest epoch (at the beginning of the window) relative to the current time
function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) {
uint8 observationIndex = observationIndexOf(block.timestamp);
// no overflow issue. if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = pairObservations[pair][firstObservationIndex];
}
// update the cumulative price for the observation at the current timestamp. each observation is updated at most
// once per epoch period.
function update(address tokenA, address tokenB) external {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
// populate the array with empty observations (first call only)
for (uint i = pairObservations[pair].length; i < granularity; i++) {
pairObservations[pair].push();
}
// get the observation for the current period
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = pairObservations[pair][observationIndex];
// we only want to commit updates once per period (i.e. windowSize / granularity)
uint timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed > periodSize) {
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
observation.timestamp = block.timestamp;
observation.price0Cumulative = price0Cumulative;
observation.price1Cumulative = price1Cumulative;
}
}
// given the cumulative prices of the start and end of a period, and the length of the period, compute the average
// price in terms of how much amount out is received for the amount in
function computeAmountOut(
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.mul(amountIn).decode144();
}
// returns the amount out corresponding to the amount in for a given token using the moving average over the time
// range [now - [windowSize, windowSize - periodSize * 2], now]
// update must have been called for the bucket corresponding to timestamp `now - windowSize`
function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {
address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut);
Observation storage firstObservation = getFirstObservationInWindow(pair);
uint timeElapsed = block.timestamp - firstObservation.timestamp;
require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION');
// should never happen.
require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED');
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
(address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut);
if (token0 == tokenIn) {
return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/ExampleSwapToPrice.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/Babylonian.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import '../libraries/UniswapV2LiquidityMathLibrary.sol';
//import '../interfaces/IERC20.sol';
import '../interfaces/IUniswapV2Router01.sol';
//import '../libraries/SafeMath.sol';
import '@uniCore/libraries/SafeMath.sol';
import '../libraries/UniswapV2Library.sol';
import '@uniCore/interfaces/IERC20.sol';
contract ExampleSwapToPrice {
using SafeMath for uint256;
IUniswapV2Router01 public immutable router;
address public immutable factory;
constructor(address factory_, IUniswapV2Router01 router_) /*public*/ {
factory = factory_;
router = router_;
}
// swaps an amount of either token such that the trade is profit-maximizing, given an external true price
// true price is expressed in the ratio of token A to token B
// caller must approve this contract to spend whichever token is intended to be swapped
function swapToPrice(
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 maxSpendTokenA,
uint256 maxSpendTokenB,
address to,
uint256 deadline
) public {
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokenA != 0 && truePriceTokenB != 0, "ExampleSwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokenA != 0 || maxSpendTokenB != 0, "ExampleSwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
(aToB, amountIn) = UniswapV2LiquidityMathLibrary.computeProfitMaximizingTrade(
truePriceTokenA, truePriceTokenB,
reserveA, reserveB
);
}
require(amountIn > 0, 'ExampleSwapToPrice: ZERO_AMOUNT_IN');
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokenA : maxSpendTokenB;
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? tokenA : tokenB;
address tokenOut = aToB ? tokenB : tokenA;
TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested
path,
to,
deadline
);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/examples/README.md
================================================
# Examples
## Disclaimer
These contracts are for demonstrative purposes only.
While these contracts have unit tests, and we generally expect them to be
correct, there are no guarantees about the correctness or security of
these contracts. We hold these contracts to a different standard of
correctness and security than other contracts in this repository.
E.g., we have explicitly excluded these contracts from the
[bug bounty](https://uniswap.org/bug-bounty/#scope).
You must do your own due diligence if you wish to use code
from these examples in your project.
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/IUniswapV2Migrator.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV2Migrator {
function migrate(address token, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external;
}
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/IUniswapV2Router01.sol
================================================
//pragma solidity >=0.6.2;
pragma solidity ^0.8.0;
interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/IUniswapV2Router02.sol
================================================
//pragma solidity >=0.6.2;
pragma solidity ^0.8.0;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/IWETH.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/V1/IUniswapV1Exchange.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV1Exchange {
function balanceOf(address owner) external view returns (uint);
function transferFrom(address from, address to, uint value) external returns (bool);
function removeLiquidity(uint, uint, uint, uint) external returns (uint, uint);
function tokenToEthSwapInput(uint, uint, uint) external returns (uint);
function ethToTokenSwapInput(uint, uint) external payable returns (uint);
}
================================================
FILE: protocols/uniswap-v2/src/contracts/interfaces/V1/IUniswapV1Factory.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV1Factory {
function getExchange(address) external view returns (address);
}
================================================
FILE: protocols/uniswap-v2/src/contracts/libraries/UniswapV2Library.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
//import "./SafeMath.sol";
import '@uniCore/libraries/SafeMath.sol';
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'1ca0726131e63169c9745e0a2f23eb3703b8d0ecde6c93790db3ffbdaafb6179' // init code hash
)))));
}
//OLD: 96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/lib/contracts/libraries/Babylonian.sol';
import '@uniswap/lib/contracts/libraries/FullMath.sol';
import '@uniCore/libraries/SafeMath.sol';
//import './SafeMath.sol';
import './UniswapV2Library.sol';
// library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value
// in terms of the underlying tokens
library UniswapV2LiquidityMathLibrary {
using SafeMath for uint256;
// computes the direction and magnitude of the profit-maximizing trade
function computeProfitMaximizingTrade(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) pure internal returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
uint256 leftSide = Babylonian.sqrt(
FullMath.mulDiv(
invariant.mul(1000),
aToB ? truePriceTokenA : truePriceTokenB,
(aToB ? truePriceTokenB : truePriceTokenA).mul(997)
)
);
uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide.sub(rightSide);
}
// gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price
function getReservesAfterArbitrage(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB
) view internal returns (uint256 reserveA, uint256 reserveB) {
// first get reserves before the swap
(reserveA, reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
require(reserveA > 0 && reserveB > 0, 'UniswapV2ArbitrageLibrary: ZERO_PAIR_RESERVES');
// then compute how much to swap to arb to the true price
(bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB);
if (amountIn == 0) {
return (reserveA, reserveB);
}
// now affect the trade to the reserves
if (aToB) {
uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveA, reserveB);
reserveA += amountIn;
reserveB -= amountOut;
} else {
uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveB, reserveA);
reserveB += amountIn;
reserveA -= amountOut;
}
}
// computes liquidity value given all the parameters of the pair
function computeLiquidityValue(
uint256 reservesA,
uint256 reservesB,
uint256 totalSupply,
uint256 liquidityAmount,
bool feeOn,
uint kLast
) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) {
if (feeOn && kLast > 0) {
uint rootK = Babylonian.sqrt(reservesA.mul(reservesB));
uint rootKLast = Babylonian.sqrt(kLast);
if (rootK > rootKLast) {
uint numerator1 = totalSupply;
uint numerator2 = rootK.sub(rootKLast);
uint denominator = rootK.mul(5).add(rootKLast);
uint feeLiquidity = FullMath.mulDiv(numerator1, numerator2, denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
return (reservesA.mul(liquidityAmount) / totalSupply, reservesB.mul(liquidityAmount) / totalSupply);
}
// get all current parameters from the pair and compute value of a liquidity amount
// **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to
// #getLiquidityValueAfterArbitrageToPrice
function getLiquidityValue(
address factory,
address tokenA,
address tokenB,
uint256 liquidityAmount
) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) {
(uint256 reservesA, uint256 reservesB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0);
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
// given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B,
// and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB
function getLiquidityValueAfterArbitrageToPrice(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) internal view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
// this also checks that totalSupply > 0
require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT');
(uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB);
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/libraries/UniswapV2OracleLibrary.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/test/DeflatingERC20.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
//import '../libraries/SafeMath.sol';
import '@uniCore/libraries/SafeMath.sol';
contract DeflatingERC20 {
using SafeMath for uint;
string public constant name = 'Deflating Test Token';
string public constant symbol = 'DTT';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor(uint _totalSupply) /*public*/ {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
//_mint(msg.sender, _totalSupply);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
uint burnAmount = value / 100;
_burn(from, burnAmount);
uint transferAmount = value.sub(burnAmount);
balanceOf[from] = balanceOf[from].sub(transferAmount);
balanceOf[to] = balanceOf[to].add(transferAmount);
emit Transfer(from, to, transferAmount);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != /*uint(-1)*/ type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/test/ERC20.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
//import '../libraries/SafeMath.sol';
import '@uniCore/libraries/SafeMath.sol';
contract ERC20 {
using SafeMath for uint;
string public constant name = 'Test Token';
string public constant symbol = 'TT';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor(uint _totalSupply) /*public*/ {
uint chainId = block.chainid;
/*assembly {
chainId := chainid()
}*/
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
_mint(msg.sender, _totalSupply);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != /*uint(-1)*/ type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/test/RouterEventEmitter.sol
================================================
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
import '../interfaces/IUniswapV2Router01.sol';
contract RouterEventEmitter {
event Amounts(uint[] amounts);
receive() external payable {}
function swapExactTokensForTokens(
address router,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapExactTokensForTokens.selector, amountIn, amountOutMin, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
function swapTokensForExactTokens(
address router,
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapTokensForExactTokens.selector, amountOut, amountInMax, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
function swapExactETHForTokens(
address router,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapExactETHForTokens.selector, amountOutMin, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
function swapTokensForExactETH(
address router,
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapTokensForExactETH.selector, amountOut, amountInMax, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
function swapExactTokensForETH(
address router,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapExactTokensForETH.selector, amountIn, amountOutMin, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
function swapETHForExactTokens(
address router,
uint amountOut,
address[] calldata path,
address to,
uint deadline
) external payable {
(bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
IUniswapV2Router01(router).swapETHForExactTokens.selector, amountOut, path, to, deadline
));
assert(success);
emit Amounts(abi.decode(returnData, (uint[])));
}
}
================================================
FILE: protocols/uniswap-v2/src/contracts/test/WETH9.sol
================================================
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//pragma solidity =0.6.6;
pragma solidity ^0.8.0;
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
// function() public payable {
// deposit();
// }
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad, "");
balanceOf[msg.sender] -= wad;
payable(address(msg.sender)).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad, "");
if (src != msg.sender && allowance[src][msg.sender] != /*uint(-1)*/type(uint256).max) {
require(allowance[src][msg.sender] >= wad, "");
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
*/
================================================
FILE: protocols/uniswap-v2/src/interfaces/IERC20.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
================================================
FILE: protocols/uniswap-v2/src/interfaces/IUniswapV2Callee.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
================================================
FILE: protocols/uniswap-v2/src/interfaces/IUniswapV2ERC20.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
================================================
FILE: protocols/uniswap-v2/src/interfaces/IUniswapV2Factory.sol
================================================
//pragma solidity >=0.5.0;
pragma solidity ^0.8.0;
interface IUniswapV2Factory {
//event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
================================================
FILE: protocols/uniswap-v2/src/interfaces/IUniswapV2Pair.sol
================================================
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
================================================
FILE: protocols/uniswap-v2/src/libraries/AddressStringUtil.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
library AddressStringUtil {
// converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
function toAsciiString(address addr, uint256 len) internal pure returns (string memory) {
require(len % 2 == 0 && len > 0 && len <= 40, 'AddressStringUtil: INVALID_LEN');
bytes memory s = new bytes(len);
uint256 addrNum = uint256(uint160(addr));
for (uint256 i = 0; i < len / 2; i++) {
// shift right and truncate all but the least significant byte to extract the byte at position 19-i
uint8 b = uint8(addrNum >> (8 * (19 - i)));
// first hex character is the most significant 4 bits
uint8 hi = b >> 4;
// second hex character is the least significant 4 bits
uint8 lo = b - (hi << 4);
s[2 * i] = char(hi);
s[2 * i + 1] = char(lo);
}
return string(s);
}
// hi and lo are only 4 bits and between 0 and 16
// this method converts those values to the unicode/ascii code point for the hex representation
// uses upper case for the characters
function char(uint8 b) private pure returns (bytes1 c) {
if (b < 10) {
return bytes1(b + 0x30);
} else {
return bytes1(b + 0x37);
}
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/Babylonian.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/BitMath.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath: ZERO');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/FixedPoint.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
import './FullMath.sol';
import './Babylonian.sol';
import './BitMath.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint: MUL_OVERFLOW');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint: MULI_OVERFLOW');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= /*uint112(-1)*/ type(uint112).max, 'FixedPoint: MULUQ_OVERFLOW_UPPER');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= /*uint224(-1)*/ type(uint224).max, 'FixedPoint: MULUQ_OVERFLOW_SUM');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint: DIV_BY_ZERO_DIVUQ');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= /*uint144(-1)*/ type(uint144).max) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= /*uint224(-1)*/ type(uint224).max, 'FixedPoint: DIVUQ_OVERFLOW');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= /*uint224(-1)*/ type(uint224).max, 'FixedPoint: DIVUQ_OVERFLOW');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// lossy
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint: DIV_BY_ZERO_FRACTION');
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x > 1, 'FixedPoint: DIV_BY_ZERO_RECIPROCAL_OR_OVERFLOW');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= /*uint144(-1)*/ type(uint144).max) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/FullMath.sol
================================================
// SPDX-License-Identifier: CC-BY-4.0
//pragma solidity >=0.4.0;
pragma solidity ^0.8.0;
// USING the EXPENSIVE VERSION OF THIS LIBRARY MENTIONED IN THIS ARTICLE
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
/*function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}*/
function fullMul (uint x, uint y) public pure returns (uint l, uint h) {
uint xl = uint128 (x); uint xh = x >> 128;
uint yl = uint128 (y); uint yh = y >> 128;
uint xlyl = xl * yl; uint xlyh = xl * yh;
uint xhyl = xh * yl; uint xhyh = xh * yh;
uint ll = uint128 (xlyl);
uint lh = (xlyl >> 128) + uint128 (xlyh) + uint128 (xhyl);
uint hl = uint128 (xhyh) + (xlyh >> 128) + (xhyl >> 128);
uint hh = (xhyh >> 128);
l = ll + (lh << 128);
h = (lh >> 128) + hl + (hh << 128);
}
/* function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}*/
function fullDiv (uint l, uint h, uint z) public pure returns (uint r) {
require (h < z);
uint zShift = mostSignificantBit (z);
uint shiftedZ = z;
if (zShift <= 127) zShift = 0;
else {
zShift -= 127;
shiftedZ = (shiftedZ - 1 >> zShift) + 1;
}
while (h > 0) {
uint lShift = mostSignificantBit (h) + 1;
uint hShift = 256 - lShift;
uint e = ((h << hShift) + (l >> lShift)) / shiftedZ;
if (lShift > zShift) e <<= (lShift - zShift);
else e >>= (zShift - lShift);
r += e;
(uint tl, uint th) = fullMul (e, z);
h -= th;
if (tl > l) h -= 1;
l -= tl;
}
r += l / z;
}
function mostSignificantBit (uint x) public pure returns (uint r) {
require (x > 0);
if (x >= 2**128) { x >>= 128; r += 128; }
if (x >= 2**64) { x >>= 64; r += 64; }
if (x >= 2**32) { x >>= 32; r += 32; }
if (x >= 2**16) { x >>= 16; r += 16; }
if (x >= 2**8) { x >>= 8; r += 8; }
if (x >= 2**4) { x >>= 4; r += 4; }
if (x >= 2**2) { x >>= 2; r += 2; }
if (x >= 2**1) { x >>= 1; r += 1; }
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/Math.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/PairNamer.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import './SafeERC20Namer.sol';
// produces names for pairs of tokens using Uniswap's naming scheme
library PairNamer {
string private constant TOKEN_SYMBOL_PREFIX = ' ';
string private constant TOKEN_SEPARATOR = ':';
// produces a pair descriptor in the format of `${prefix}${name0}:${name1}${suffix}`
function pairName(
address token0,
address token1,
string memory prefix,
string memory suffix
) internal view returns (string memory) {
return
string(
abi.encodePacked(
prefix,
SafeERC20Namer.tokenName(token0),
TOKEN_SEPARATOR,
SafeERC20Namer.tokenName(token1),
suffix
)
);
}
// produces a pair symbol in the format of `${symbol0}:${symbol1}${suffix}`
function pairSymbol(
address token0,
address token1,
string memory suffix
) internal view returns (string memory) {
return
string(
abi.encodePacked(
TOKEN_SYMBOL_PREFIX,
SafeERC20Namer.tokenSymbol(token0),
TOKEN_SEPARATOR,
SafeERC20Namer.tokenSymbol(token1),
suffix
)
);
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/SafeERC20Namer.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import './AddressStringUtil.sol';
// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32
// this library will always produce a string symbol to represent the token
library SafeERC20Namer {
function bytes32ToString(bytes32 x) private pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint256 charCount = 0;
for (uint256 j = 0; j < 32; j++) {
bytes1 char = x[j];
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
// assumes the data is in position 2
function parseStringData(bytes memory b) private pure returns (string memory) {
uint256 charCount = 0;
// first parse the charCount out of the data
for (uint256 i = 32; i < 64; i++) {
charCount <<= 8;
charCount += uint8(b[i]);
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 i = 0; i < charCount; i++) {
bytesStringTrimmed[i] = b[i + 64];
}
return string(bytesStringTrimmed);
}
// uses a heuristic to produce a token name from the address
// the heuristic returns the full hex of the address string in upper case
function addressToName(address token) private pure returns (string memory) {
return AddressStringUtil.toAsciiString(token, 40);
}
// uses a heuristic to produce a token symbol from the address
// the heuristic returns the first 6 hex of the address string in upper case
function addressToSymbol(address token) private pure returns (string memory) {
return AddressStringUtil.toAsciiString(token, 6);
}
// calls an external view token contract method that returns a symbol or name, and parses the output into a string
function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));
// if not implemented, or returns empty data, return empty string
if (!success || data.length == 0) {
return '';
}
// bytes32 data always has length 32
if (data.length == 32) {
bytes32 decoded = abi.decode(data, (bytes32));
return bytes32ToString(decoded);
} else if (data.length > 64) {
return abi.decode(data, (string));
}
return '';
}
// attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address
function tokenSymbol(address token) internal view returns (string memory) {
// 0x95d89b41 = bytes4(keccak256("symbol()"))
string memory symbol = callAndParseStringReturn(token, 0x95d89b41);
if (bytes(symbol).length == 0) {
// fallback to 6 uppercase hex of address
return addressToSymbol(token);
}
return symbol;
}
// attempts to extract the token name. if it does not implement name, returns a name derived from the address
function tokenName(address token) internal view returns (string memory) {
// 0x06fdde03 = bytes4(keccak256("name()"))
string memory name = callAndParseStringReturn(token, 0x06fdde03);
if (bytes(name).length == 0) {
// fallback to full hex of address
return addressToName(token);
}
return name;
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/SafeMath.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/TransferHelper.sol
================================================
// SPDX-License-Identifier: GPL-3.0-or-later
//pragma solidity >=0.6.0;
pragma solidity ^0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
================================================
FILE: protocols/uniswap-v2/src/libraries/UQ112x112.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
================================================
FILE: protocols/uniswap-v2/src/test/ERC20.sol
================================================
//pragma solidity =0.5.16;
pragma solidity ^0.8.0;
import '../UniswapV2ERC20.sol';
contract ERC20 is UniswapV2ERC20 {
constructor(uint _totalSupply) /*public*/ {
_mint(msg.sender, _totalSupply);
}
}
================================================
FILE: protocols/uniswap-v2/src/test/core.t.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.0;
// Test Helpers, Mock Tokens
import "forge-std/Test.sol";
import "./MockWETH.sol";
import {DeflatingERC20} from "@uniPer/test/DeflatingERC20.sol";
import {MockToken} from "./MockToken.sol";
// Pair factory and Pair
import "@uniCore/UniswapV2Factory.sol";
import "@uniCore/UniswapV2Pair.sol";
// Routerss
import "@uniPer/UniswapV2Router02.sol";
contract TestCore is Test {
uint256 MAX = type(uint256).max;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// Mock Tokens
MockToken usdc;
MockToken usdt;
DeflatingERC20 feeToken;
MockWETH weth;
// Pair factory and Pair
UniswapV2Pair testStablePair;
UniswapV2Factory testFactory;
UniswapV2Pair testWethPair;
UniswapV2Pair testFeeWethPair;
UniswapV2Pair testFeePair;
// Routers
//UniswapV2Router01 testRouter01;
UniswapV2Router02 testRouter02;
function setUp() public {
vm.label(address(this), "THE_FUZZANATOR");
// Deploy tokens
usdc = new MockToken("USDC", "USDC", 18);
vm.label(address(usdc), "USDC");
usdt = new MockToken("USDT", "USDT", 6);
vm.label(address(usdt), "USDT");
feeToken = new DeflatingERC20(0);
vm.label(address(feeToken), "FEE_TOKEN");
weth = new MockWETH();
vm.label(address(weth), "WETH");
// Deploy factory and Pairs
testFactory = new UniswapV2Factory(address(this));
vm.label(address(testFactory), "FACTORY");
testStablePair = UniswapV2Pair(testFactory.createPair(address(usdc), address(usdt)));
vm.label(address(testStablePair), "STABLE_PAIR");
testWethPair = UniswapV2Pair(testFactory.createPair(address(usdc), address(weth)));
vm.label(address(testWethPair), "WETH_PAIR");
testFeeWethPair = UniswapV2Pair(testFactory.createPair(address(weth), address(feeToken)));
vm.label(address(testFeeWethPair), "FEEWETH_PAIR");
testFeePair = UniswapV2Pair(testFactory.createPair(address(feeToken), address(usdc)));
vm.label(address(testFeeWethPair), "FEE_PAIR");
// Deploy Router
testRouter02 = new UniswapV2Router02(address(testFactory), address(weth));
vm.label(address(testRouter02), "ROUTER");
// Approve Router
usdc.approve(address(testRouter02), MAX);
usdt.approve(address(testRouter02), MAX);
feeToken.approve(address(testRouter02), MAX);
weth.approve(address(testRouter02), MAX);
}
/* INVARIANT: Adding liquidity to a pair should:
* Increase reserves
* Increase address to balance
* Increase totalSupply
* Increase K
*/
function testFuzz_AddLiq(uint amount1, uint amount2) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
if(!setStable) {
_init(_amount1, _amount2);
}
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertGt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertGt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertGt(kAfter, kBefore, "K CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Adding ETH liquidity to a pair should:
* Increase reserves
* Increase address to balance
* Increase totalSupply
* Increase K
*/
function testFuzz_ETHAddLiq(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETH) {
_initETH(_amount);
}
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertGt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertGt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertGt(kAfter, kBefore, "K CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Keep reserves the same
* Keep the address to balance the same
* Keep totalSupply the same
* Keep K the same
*/
function testFuzz_RemoveLiq(uint amount1, uint amount2) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
if(!setStable) {
_init(_amount1, _amount2);
}
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidity(address(usdc), address(usdt), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing ETH liquidity from a pair should:
* Keep reserves the same
* Keep the address to balance the same
* Keep totalSupply the same
* Keep K the same
*/
function testFuzz_ETHRemoveLiq(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETH) {
_initETH(_amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidityETH(address(usdc), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqWithPermit(uint248 privKey, uint amount1, uint amount2, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermit) {
_initPermit(owner, _amount1, _amount2);
vm.startPrank(owner);
usdc.approve(address(testRouter02), _amount1);
usdt.approve(address(testRouter02), _amount2);
}
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(owner));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityWithPermit(address(usdc), address(usdt), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityWithPermit(address(usdc), address(usdt), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqETHWithPermit(uint248 privKey, uint amount, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermitETHFee) {
_initPermitETH(owner, _amount);
vm.startPrank(owner);
weth.approve(address(testRouter02), _amount);
usdc.approve(address(testRouter02), _amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermit(address(usdc), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermit(address(usdc), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqETHSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETHFee) {
_initETHFee(_amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(feeToken), _amount, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testFeePair.getReserves();
(uint totalSupplyBefore) = testFeePair.totalSupply();
(uint userBalBefore) = testFeePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidityETHSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testFeePair.getReserves();
(uint totalSupplyAfter) = testFeePair.totalSupply();
(uint userBalAfter) = testFeePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqETHWithPermitSupportingFeeOnTransferTokens(uint248 privKey, uint amount, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermitETHFee) {
_initPermitETHFee(owner, _amount);
vm.startPrank(owner);
weth.approve(address(testRouter02), _amount);
feeToken.approve(address(testRouter02), _amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(feeToken), _amount, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: swapExactTokensForTokens within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(usdt));
uint kBefore = reserveABefore * reserveBBefore;
if(!setStable) {
_init(_amount, _amount);
// For some reserves
try usdt.mint(address(testStablePair), 100000) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(testStablePair), 100000) {} catch {/*assert(false)*/} // overflow
testStablePair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(usdt);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForTokens(_amount, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(usdt));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactETHForTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(usdc);
uint userBalBefore1 = _amount;
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactETHForTokens{value: 1 ether}(0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = weth.balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapTokensForExactETH(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = _amount;
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapTokensForExactETH(MAX, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForETH(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = _amount;
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactTokensForETH(MAX, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapETHForExactTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(usdc);
uint userBalBefore1 = _amount;
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactETHForTokens{value: 1 ether}(0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = weth.balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setFee) {
_initFee(_amount, _amount);
// For some reserves
try feeToken.mint(address(testFeePair), 100000) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(testFeePair), 100000) {} catch {/*assert(false)*/} // overflow
testFeePair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(feeToken);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactETHForTokensSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(weth), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setETHFee) {
_initETHFee(_amount);
// For some reserves
try feeToken.mint(address(testFeeWethPair), 100000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testFeeWethPair), 100);
testFeeWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(feeToken);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactETHForTokensSupportingFeeOnTransferTokens{value: _amount}( 0, path, address(this), MAX) {
// POSTCONDTION:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken)); uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForETHSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(weth), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setETHFee) {
_initETHFee(_amount);
// For some reserves
try feeToken.mint(address(testFeeWethPair), 100000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testFeeWethPair), 100);
testFeeWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(feeToken);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForETHSupportingFeeOnTransferTokens(_amount, 0, path, address(this), MAX) {
// POSTCONDTION:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken)); uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzying framework
// This is also a guarante bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
// Helper functions to mint tokens when necessary
bool setStable;
function _init(uint256 amount1, uint256 amount2) internal {
try usdt.mint(address(this), amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(this), amount1) {} catch {/*assert(false)*/} // overflow
setStable = true;
}
bool setPermit;
function _initPermit(address owner, uint256 amount1, uint256 amount2) internal {
try usdt.mint(owner, amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(owner, amount1) {} catch {/*assert(false)*/} // overflow
setPermit = true;
}
bool setPermitETHFee;
function _initPermitETHFee(address owner, uint256 amount) internal {
vm.deal(owner, amount);
try feeToken.mint(owner, amount) {} catch {/*assert(false)*/} // overflow
setPermitETHFee = true;
}
bool setPermitETH;
function _initPermitETH(address owner, uint256 amount) internal {
vm.deal(owner, amount);
try feeToken.mint(owner, amount) {} catch {/*assert(false)*/} // overflow
setPermitETH = true;
}
bool setFee;
function _initFee(uint256 amount1, uint256 amount2) internal {
try feeToken.mint(address(this), amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(this), amount1) {} catch {/*assert(false)*/} // overflow
setFee = true;
}
bool setETHFee;
function _initETHFee(uint256 amount) internal {
vm.deal(address(this), amount);
try feeToken.mint(address(this), amount) {} catch {/*assert(false)*/} // overflow
setETHFee = true;
}
bool setETH;
function _initETH(uint256 amount) internal {
vm.deal(address(this), amount);
try usdc.mint(address(this), amount) {} catch {/*assert(false)*/} // overflow
setETH = true;
}
// Helper if any pair code is change
function testGetInitCode() public {
bytes memory bytecode = type(UniswapV2Pair).creationCode;
emit log_bytes32(keccak256(abi.encodePacked(bytecode)));
}
}
================================================
FILE: protocols/uniswap-v2/test/core.t.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.0;
// Test Helpers, Mock Tokens
import "forge-std/Test.sol";
import {MockWETH} from "./mocks/MockWETH.sol";
import {DeflatingERC20} from "@uniPer/test/DeflatingERC20.sol";
import {MockToken} from "./mocks/MockToken.sol";
// Pair factory and Pair
import "@uniCore/UniswapV2Factory.sol";
import "@uniCore/UniswapV2Pair.sol";
// Routers
import "@uniPer/UniswapV2Router02.sol";
contract TestCore is Test {
uint256 MAX = type(uint256).max;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// Mock Tokens
MockToken usdc;
MockToken usdt;
DeflatingERC20 feeToken;
MockWETH weth;
// Pair factory and Pair
UniswapV2Pair testStablePair;
UniswapV2Factory testFactory;
UniswapV2Pair testWethPair;
UniswapV2Pair testFeeWethPair;
UniswapV2Pair testFeePair;
// Routers
//UniswapV2Router01 testRouter01;
UniswapV2Router02 testRouter02;
function setUp() public {
vm.label(address(this), "THE_FUZZANATOR");
// Deploy tokens
usdc = new MockToken("USDC", "USDC", 18);
vm.label(address(usdc), "USDC");
usdt = new MockToken("USDT", "USDT", 6);
vm.label(address(usdt), "USDT");
feeToken = new DeflatingERC20(0);
vm.label(address(feeToken), "FEE_TOKEN");
weth = new MockWETH();
vm.label(address(weth), "WETH");
// Deploy factory and Pairs
testFactory = new UniswapV2Factory(address(this));
vm.label(address(testFactory), "FACTORY");
testStablePair = UniswapV2Pair(testFactory.createPair(address(usdc), address(usdt)));
vm.label(address(testStablePair), "STABLE_PAIR");
testWethPair = UniswapV2Pair(testFactory.createPair(address(usdc), address(weth)));
vm.label(address(testWethPair), "WETH_PAIR");
testFeeWethPair = UniswapV2Pair(testFactory.createPair(address(weth), address(feeToken)));
vm.label(address(testFeeWethPair), "FEEWETH_PAIR");
testFeePair = UniswapV2Pair(testFactory.createPair(address(feeToken), address(usdc)));
vm.label(address(testFeeWethPair), "FEE_PAIR");
// Deploy Router
testRouter02 = new UniswapV2Router02(address(testFactory), address(weth));
vm.label(address(testRouter02), "ROUTER");
// Approve Router
usdc.approve(address(testRouter02), MAX);
usdt.approve(address(testRouter02), MAX);
feeToken.approve(address(testRouter02), MAX);
weth.approve(address(testRouter02), MAX);
}
/* INVARIANT: Adding liquidity to a pair should:
* Increase reserves
* Increase address to balance
* Increase totalSupply
* Increase K
*/
function testFuzz_AddLiq(uint amount1, uint amount2) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
if(!setStable) {
_init(_amount1, _amount2);
}
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertGt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertGt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertGt(kAfter, kBefore, "K CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Adding ETH liquidity to a pair should:
* Increase reserves
* Increase address to balance
* Increase totalSupply
* Increase K
*/
function testFuzz_ETHAddLiq(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETH) {
_initETH(_amount);
}
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertGt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertGt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertGt(kAfter, kBefore, "K CHECK");
assertGt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertGt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Keep reserves the same
* Keep the address to balance the same
* Keep totalSupply the same
* Keep K the same
*/
function testFuzz_RemoveLiq(uint amount1, uint amount2) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
if(!setStable) {
_init(_amount1, _amount2);
}
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidity(address(usdc), address(usdt), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing ETH liquidity from a pair should:
* Keep reserves the same
* Keep the address to balance the same
* Keep totalSupply the same
* Keep K the same
*/
function testFuzz_ETHRemoveLiq(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETH) {
_initETH(_amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidityETH(address(usdc), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqWithPermit(uint248 privKey, uint amount1, uint amount2, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount1 = this._between(amount1, (10**3), MAX);
uint _amount2 = this._between(amount2, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermit) {
_initPermit(owner, _amount1, _amount2);
vm.startPrank(owner);
usdc.approve(address(testRouter02), _amount1);
usdt.approve(address(testRouter02), _amount2);
}
try testRouter02.addLiquidity(address(usdc), address(usdt), _amount1, _amount2, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testStablePair.getReserves();
(uint totalSupplyBefore) = testStablePair.totalSupply();
(uint userBalBefore) = testStablePair.balanceOf(address(owner));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityWithPermit(address(usdc), address(usdt), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityWithPermit(address(usdc), address(usdt), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testStablePair.getReserves();
(uint totalSupplyAfter) = testStablePair.totalSupply();
(uint userBalAfter) = testStablePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqETHWithPermit(uint248 privKey, uint amount, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermitETHFee) {
_initPermitETH(owner, _amount);
vm.startPrank(owner);
weth.approve(address(testRouter02), _amount);
usdc.approve(address(testRouter02), _amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(usdc), _amount, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermit(address(usdc), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermit(address(usdc), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiqETHSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
if(!setETHFee) {
_initETHFee(_amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(feeToken), _amount, 0, 0, address(this), MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testFeePair.getReserves();
(uint totalSupplyBefore) = testFeePair.totalSupply();
(uint userBalBefore) = testFeePair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.removeLiquidityETHSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, address(this), MAX) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testFeePair.getReserves();
(uint totalSupplyAfter) = testFeePair.totalSupply();
(uint userBalAfter) = testFeePair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Removing liquidity from a pair should:
* Decrease reserves
* Decrease address to balance
* Decrease totalSupply
* Decrease K
*/
function testFuzz_removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(uint248 privKey, uint amount, bool approveMax, uint deadline) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint256 privateKey = privKey;
if (deadline < block.timestamp) deadline = block.timestamp;
if (privateKey == 0) privateKey = 1;
address owner = vm.addr(privateKey);
if(!setPermitETHFee) {
_initPermitETHFee(owner, _amount);
vm.startPrank(owner);
weth.approve(address(testRouter02), _amount);
feeToken.approve(address(testRouter02), _amount);
}
try testRouter02.addLiquidityETH{value: _amount}(address(feeToken), _amount, 0, 0, owner, MAX) returns(uint, uint, uint liquidity) {
(uint reserveABefore, uint reserveBBefore, ) = testWethPair.getReserves();
(uint totalSupplyBefore) = testWethPair.totalSupply();
(uint userBalBefore) = testWethPair.balanceOf(address(this));
uint kBefore = reserveABefore * reserveBBefore;
if (approveMax) {
liquidity = type(uint256).max;
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
} else {
(uint8 v, bytes32 r, bytes32 s) = vm.sign(
privateKey,
keccak256(
abi.encodePacked(
"\x19\x01",
testStablePair.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, address(testRouter02), liquidity, 0, deadline))
)
)
);
// ACTION:
try testRouter02.removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(address(feeToken), liquidity, 0, 0, owner, MAX, approveMax, v, r, s) {
// POSTCONDTION:
(uint reserveAAfter, uint reserveBAfter, ) = testWethPair.getReserves();
(uint totalSupplyAfter) = testWethPair.totalSupply();
(uint userBalAfter) = testWethPair.balanceOf(address(this));
uint kAfter = reserveAAfter * reserveBAfter;
assertLt(reserveAAfter, reserveABefore, "RESERVE TOKEN A CHECK");
assertLt(reserveBAfter, reserveBBefore, "RESERVE TOKEN B CHECK");
assertLt(kAfter, kBefore, "K CHECK");
assertLt(totalSupplyAfter, totalSupplyBefore, "TOTAL SUPPLY CHECK");
assertLt(userBalAfter, userBalBefore, "USER BAL CHECK");
} catch {/*assert(false)*/} // overflow
}
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: swapExactTokensForTokens within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(usdt));
uint kBefore = reserveABefore * reserveBBefore;
if(!setStable) {
_init(_amount, _amount);
// For some reserves
try usdt.mint(address(testStablePair), 100000) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(testStablePair), 100000) {} catch {/*assert(false)*/} // overflow
testStablePair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(usdt);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForTokens(_amount, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(usdt));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactETHForTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(usdc);
uint userBalBefore1 = _amount;
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactETHForTokens{value: 1 ether}(0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = weth.balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapTokensForExactETH(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = _amount;
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapTokensForExactETH(MAX, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForETH(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = _amount;
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactTokensForETH(MAX, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapETHForExactTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
if(!setETH) {
_initETH(_amount);
// For some reserves
try usdc.mint(address(testWethPair), 100000000000000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testWethPair), 100);
testWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(usdc);
uint userBalBefore1 = _amount;
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kBefore = reserveABefore * reserveBBefore;
// ACTION:
try testRouter02.swapExactETHForTokens{value: 1 ether}(0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = weth.balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(weth));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDITIONS:
uint _amount = _between(amount, 1, MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setFee) {
_initFee(_amount, _amount);
// For some reserves
try feeToken.mint(address(testFeePair), 100000) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(testFeePair), 100000) {} catch {/*assert(false)*/} // overflow
testFeePair.sync();
}
address[] memory path = new address[](2);
path[0] = address(usdc);
path[1] = address(feeToken);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, 0, path, address(this), MAX) {
//POSTCONDITIONS:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken));
uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactETHForTokensSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(weth), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setETHFee) {
_initETHFee(_amount);
// For some reserves
try feeToken.mint(address(testFeeWethPair), 100000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testFeeWethPair), 100);
testFeeWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(feeToken);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactETHForTokensSupportingFeeOnTransferTokens{value: _amount}( 0, path, address(this), MAX) {
// POSTCONDTION:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken)); uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
/* INVARIANT: Swapping within a pair should:
* Decrease balance of user for token 2
* Increase balance of user for token 1
* K should decrease or remain the same
*/
function testFuzz_swapExactTokensForETHSupportingFeeOnTransferTokens(uint amount) public {
// PRECONDTION:
uint _amount = this._between(amount, (10**3), MAX);
uint burnAmount = _amount / 100;
(uint reserveABefore, uint reserveBBefore) = UniswapV2Library.getReserves(address(testFactory), address(weth), address(feeToken));
uint kBefore = reserveABefore * reserveBBefore;
if(!setETHFee) {
_initETHFee(_amount);
// For some reserves
try feeToken.mint(address(testFeeWethPair), 100000) {} catch {/*assert(false)*/} // overflow
vm.deal(address(this), 100 ether);
weth.deposit{value: 100 ether}();
weth.transfer(address(testFeeWethPair), 100);
testFeeWethPair.sync();
}
address[] memory path = new address[](2);
path[0] = address(feeToken);
path[1] = address(weth);
uint userBalBefore1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalBefore2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
require(userBalBefore1 > 0, "NO BAL");
// ACTION:
try testRouter02.swapExactTokensForETHSupportingFeeOnTransferTokens(_amount, 0, path, address(this), MAX) {
// POSTCONDTION:
uint userBalAfter1 = UniswapV2ERC20(path[0]).balanceOf(address(this));
uint userBalAfter2 = UniswapV2ERC20(path[1]).balanceOf(address(this));
(uint reserveAAfter, uint reserveBAfter) = UniswapV2Library.getReserves(address(testFactory), address(usdc), address(feeToken)); uint kAfter = reserveAAfter * reserveBAfter;
assertGe(kAfter, kBefore, "K CHECK");
assertLt(userBalBefore2 - burnAmount, userBalAfter2, "USER BAL 2 CHECK");
assertGt(userBalBefore1, userBalAfter1, "USER BAL 1 CHECK");
} catch {/*assert(false)*/} // overflow
}
// Bounding function similar to vm.assume but is more efficient regardless of the fuzzying framework
// This is also a guarante bound of the input unlike vm.assume which can only be used for narrow checks
function _between(uint256 random, uint256 low, uint256 high) public pure returns (uint256) {
return low + random % (high-low);
}
// Helper functions to mint tokens when necessary
bool setStable;
function _init(uint256 amount1, uint256 amount2) internal {
try usdt.mint(address(this), amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(this), amount1) {} catch {/*assert(false)*/} // overflow
setStable = true;
}
bool setPermit;
function _initPermit(address owner, uint256 amount1, uint256 amount2) internal {
try usdt.mint(owner, amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(owner, amount1) {} catch {/*assert(false)*/} // overflow
setPermit = true;
}
bool setPermitETHFee;
function _initPermitETHFee(address owner, uint256 amount) internal {
vm.deal(owner, amount);
try feeToken.mint(owner, amount) {} catch {/*assert(false)*/} // overflow
setPermitETHFee = true;
}
bool setPermitETH;
function _initPermitETH(address owner, uint256 amount) internal {
vm.deal(owner, amount);
try feeToken.mint(owner, amount) {} catch {/*assert(false)*/} // overflow
setPermitETH = true;
}
bool setFee;
function _initFee(uint256 amount1, uint256 amount2) internal {
try feeToken.mint(address(this), amount2) {} catch {/*assert(false)*/} // overflow
try usdc.mint(address(this), amount1) {} catch {/*assert(false)*/} // overflow
setFee = true;
}
bool setETHFee;
function _initETHFee(uint256 amount) internal {
vm.deal(address(this), amount);
try feeToken.mint(address(this), amount) {} catch {/*assert(false)*/} // overflow
setETHFee = true;
}
bool setETH;
function _initETH(uint256 amount) internal {
vm.deal(address(this), amount);
try usdc.mint(address(this), amount) {} catch {/*assert(false)*/} // overflow
setETH = true;
}
// Helper if any pair code is change
function testGetInitCode() public {
bytes memory bytecode = type(UniswapV2Pair).creationCode;
emit log_bytes32(keccak256(abi.encodePacked(bytecode)));
}
}
================================================
FILE: protocols/uniswap-v2/test/mocks/MockToken.sol
================================================
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.0;
import "@openzeppelin/token/ERC20/ERC20.sol";
contract MockToken is ERC20 {
uint8 decimal;
constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {
decimal = decimals_;
}
function decimals() public view virtual override returns (uint8) {
return decimal;
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
}
================================================
FILE: protocols/uniswap-v2/test/mocks/MockWETH.sol
================================================
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//updated version and fallback
pragma solidity ^0.8.0;
contract MockWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
payable(address(msg.sender)).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}