Verified contractExactGPL-3.0-or-later
Token
Address0x5653d7c04329765002a8a8b6b01dddc1dde78a04
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.33
- Same code
1 more contract
Details
- Compiler
- solc 0.8.33+commit.64118f21
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- GPL-3.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,470,864
- Creation transaction
- 0x09878cc422…7e5326364c
20 files
- contracts/compound/Token.solmain9.54 KB
- @openzeppelin/[email protected]/access/OwnableUpgradeable.sol3.15 KB
- @openzeppelin/[email protected]/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/[email protected]/security/ReentrancyGuardUpgradeable.sol3.66 KB
- @openzeppelin/[email protected]/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/[email protected]/utils/ContextUpgradeable.sol1.35 KB
- contracts/compound/TokenGovernance.sol20.59 KB
- contracts/compound/TokenStorage.sol4.16 KB
- contracts/compound/TokenUtils.sol9.79 KB
- contracts/compound/interfaces/IInterestRatesManager.sol170 B
- contracts/compound/interfaces/IPositionsManager.sol1.04 KB
- contracts/compound/interfaces/IRewardsManager.sol1.04 KB
- contracts/compound/interfaces/compound/ICompound.sol10.46 KB
- contracts/compound/libraries/Types.sol5.19 KB
- contracts/lib/solmate/src/tokens/ERC20.sol6.81 KB
- contracts/lib/solmate/src/utils/SafeTransferLib.sol5.78 KB
- contracts/lib/token-data-structures/contracts/DoubleLinkedList.sol5.48 KB
- contracts/lib/token-utils/src/DelegateCall.sol2.16 KB
- contracts/lib/token-utils/src/math/CompoundMath.sol1.17 KB
- contracts/lib/token-utils/src/math/Math.sol941 B
contracts/compound/Token.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import "./TokenGovernance.sol";
/// @title Token.
/// @author Token Labs.
/// @notice Main Token contract handling user interactions and pool interactions.
contract Token is TokenGovernance {
using SafeTransferLib for ERC20;
using DelegateCall for address;
/// EVENTS ///
/// @notice Emitted when a user claims rewards.
/// @param _user The address of the claimer.
/// @param _amountClaimed The amount of reward token claimed.
/// @param _traded Whether or not the pool tokens are traded against Token tokens.
event RewardsClaimed(address indexed _user, uint256 _amountClaimed, bool indexed _traded);
/// ERRORS ///
/// @notice Thrown when claiming rewards is paused.
error ClaimRewardsPaused();
/// EXTERNAL ///
/// @notice Supplies underlying tokens to a specific market.
/// @dev `msg.sender` must have approved Token's contract to spend the underlying `_amount`.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of token (in underlying) to supply.
function supply(address _poolToken, uint256 _amount) external nonReentrant {
_supply(_poolToken, msg.sender, _amount, defaultMaxGasForMatching.supply);
}
/// @notice Supplies underlying tokens to a specific market, on behalf of a given user.
/// @dev `msg.sender` must have approved Token's contract to spend the underlying `_amount`.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _onBehalf The address of the account whose positions will be updated.
/// @param _amount The amount of token (in underlying) to supply.
function supply(
address _poolToken,
address _onBehalf,
uint256 _amount
) external nonReentrant {
_supply(_poolToken, _onBehalf, _amount, defaultMaxGasForMatching.supply);
}
/// @notice Supplies underlying tokens to a specific market, on behalf of a given user,
/// specifying a gas threshold at which to cut the matching engine.
/// @dev `msg.sender` must have approved Token's contract to spend the underlying `_amount`.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _onBehalf The address of the account whose positions will be updated.
/// @param _amount The amount of token (in underlying) to supply.
/// @param _maxGasForMatching The gas threshold at which to stop the matching engine.
function supply(
address _poolToken,
address _onBehalf,
uint256 _amount,
uint256 _maxGasForMatching
) external nonReentrant {
_supply(_poolToken, _onBehalf, _amount, _maxGasForMatching);
}
/// @notice Borrows underlying tokens from a specific market.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of token (in underlying).
function borrow(address _poolToken, uint256 _amount) external nonReentrant {
_borrow(_poolToken, _amount, defaultMaxGasForMatching.borrow);
}
/// @notice Borrows underlying tokens from a specific market, specifying a gas threshold at which to stop the matching engine.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of token (in underlying).
/// @param _maxGasForMatching The gas threshold at which to stop the matching engine.
function borrow(
address _poolToken,
uint256 _amount,
uint256 _maxGasForMatching
) external nonReentrant {
_borrow(_poolToken, _amount, _maxGasForMatching);
}
/// @notice Withdraws underlying tokens from a specific market.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of tokens (in underlying) to withdraw from supply.
function withdraw(address _poolToken, uint256 _amount) external nonReentrant {
_withdraw(_poolToken, _amount, msg.sender, defaultMaxGasForMatching.withdraw);
}
/// @notice Withdraws underlying tokens from a specific market.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of tokens (in underlying) to withdraw from supply.
/// @param _receiver The address to send withdrawn tokens to.
function withdraw(
address _poolToken,
uint256 _amount,
address _receiver
) external nonReentrant {
_withdraw(_poolToken, _amount, _receiver, defaultMaxGasForMatching.withdraw);
}
/// @notice Repays the debt of the sender, up to the amount provided.
/// @dev `msg.sender` must have approved Token's contract to spend the underlying `_amount`.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _amount The amount of token (in underlying) to repay from borrow.
function repay(address _poolToken, uint256 _amount) external nonReentrant {
_repay(_poolToken, msg.sender, _amount, defaultMaxGasForMatching.repay);
}
/// @notice Repays debt of a given user, up to the amount provided.
/// @dev `msg.sender` must have approved Token's contract to spend the underlying `_amount`.
/// @param _poolToken The address of the market the user wants to interact with.
/// @param _onBehalf The address of the account whose positions will be updated.
/// @param _amount The amount of token (in underlying) to repay from borrow.
function repay(
address _poolToken,
address _onBehalf,
uint256 _amount
) external nonReentrant {
_repay(_poolToken, _onBehalf, _amount, defaultMaxGasForMatching.repay);
}
/// @notice Liquidates a position.
/// @param _poolTokenBorrowed The address of the pool token the liquidator wants to repay.
/// @param _poolTokenCollateral The address of the collateral pool token the liquidator wants to seize.
/// @param _borrower The address of the borrower to liquidate.
/// @param _amount The amount of token (in underlying) to repay.
function liquidate(
address _poolTokenBorrowed,
address _poolTokenCollateral,
address _borrower,
uint256 _amount
) external nonReentrant {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.liquidateLogic.selector,
_poolTokenBorrowed,
_poolTokenCollateral,
_borrower,
_amount
)
);
}
/// @notice Claims rewards for the given assets.
/// @dev The incentives vault will never be implemented. Thus the second parameter of this function becomes useless.
/// @param _cTokenAddresses The cToken addresses to claim rewards from.
/// @return amountOfRewards The amount of rewards claimed (in COMP).
function claimRewards(address[] calldata _cTokenAddresses, bool)
external
nonReentrant
returns (uint256 amountOfRewards)
{
if (isClaimRewardsPaused) revert ClaimRewardsPaused();
amountOfRewards = rewardsManager.claimRewards(_cTokenAddresses, msg.sender);
if (amountOfRewards > 0) {
comptroller.claimComp(address(this), _cTokenAddresses);
ERC20(comptroller.getCompAddress()).safeTransfer(msg.sender, amountOfRewards);
emit RewardsClaimed(msg.sender, amountOfRewards, false);
}
}
/// @notice Allows to receive ETH.
receive() external payable {}
/// INTERNAL ///
function _supply(
address _poolToken,
address _onBehalf,
uint256 _amount,
uint256 _maxGasForMatching
) internal {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.supplyLogic.selector,
_poolToken,
msg.sender,
_onBehalf,
_amount,
_maxGasForMatching
)
);
}
function _borrow(
address _poolToken,
uint256 _amount,
uint256 _maxGasForMatching
) internal {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.borrowLogic.selector,
_poolToken,
_amount,
_maxGasForMatching
)
);
}
function _withdraw(
address _poolToken,
uint256 _amount,
address _receiver,
uint256 _maxGasForMatching
) internal {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.withdrawLogic.selector,
_poolToken,
_amount,
msg.sender,
_receiver,
_maxGasForMatching
)
);
}
function _repay(
address _poolToken,
address _onBehalf,
uint256 _amount,
uint256 _maxGasForMatching
) internal {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.repayLogic.selector,
_poolToken,
msg.sender,
_onBehalf,
_amount,
_maxGasForMatching
)
);
}
}
@openzeppelin/[email protected]/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/[email protected]/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/[email protected]/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/[email protected]/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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://consensys.net/diligence/blog/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.8.0/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");
(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 functionCallWithValue(target, data, 0, "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");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, 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) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
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.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// 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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/[email protected]/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
contracts/compound/TokenGovernance.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import "./TokenUtils.sol";
/// @title TokenGovernance.
/// @author Token Labs.
/// @notice Governance functions for Token.
abstract contract TokenGovernance is TokenUtils {
using SafeTransferLib for ERC20;
using DelegateCall for address;
/// EVENTS ///
/// @notice Emitted when a new `defaultMaxGasForMatching` is set.
/// @param _defaultMaxGasForMatching The new `defaultMaxGasForMatching`.
event DefaultMaxGasForMatchingSet(Types.MaxGasForMatching _defaultMaxGasForMatching);
/// @notice Emitted when a new value for `maxSortedUsers` is set.
/// @param _newValue The new value of `maxSortedUsers`.
event MaxSortedUsersSet(uint256 _newValue);
/// @notice Emitted when the address of the `treasuryVault` is set.
/// @param _newTreasuryVaultAddress The new address of the `treasuryVault`.
event TreasuryVaultSet(address indexed _newTreasuryVaultAddress);
/// @notice Emitted when the `positionsManager` is set.
/// @param _positionsManager The new address of the `positionsManager`.
event PositionsManagerSet(address indexed _positionsManager);
/// @notice Emitted when the `rewardsManager` is set.
/// @param _newRewardsManagerAddress The new address of the `rewardsManager`.
event RewardsManagerSet(address indexed _newRewardsManagerAddress);
/// @notice Emitted when the `interestRatesManager` is set.
/// @param _interestRatesManager The new address of the `interestRatesManager`.
event InterestRatesSet(address indexed _interestRatesManager);
/// @dev Emitted when a new `dustThreshold` is set.
/// @param _dustThreshold The new `dustThreshold`.
event DustThresholdSet(uint256 _dustThreshold);
/// @notice Emitted when the `reserveFactor` is set.
/// @param _poolToken The address of the concerned market.
/// @param _newValue The new value of the `reserveFactor`.
event ReserveFactorSet(address indexed _poolToken, uint16 _newValue);
/// @notice Emitted when the `p2pIndexCursor` is set.
/// @param _poolToken The address of the concerned market.
/// @param _newValue The new value of the `p2pIndexCursor`.
event P2PIndexCursorSet(address indexed _poolToken, uint16 _newValue);
/// @notice Emitted when a reserve fee is claimed.
/// @param _poolToken The address of the concerned market.
/// @param _amountClaimed The amount of reward token claimed.
event ReserveFeeClaimed(address indexed _poolToken, uint256 _amountClaimed);
/// @notice Emitted when the value of `isP2PDisabled` is set.
/// @param _poolToken The address of the concerned market.
/// @param _isP2PDisabled The new value of `_isP2PDisabled` adopted.
event P2PStatusSet(address indexed _poolToken, bool _isP2PDisabled);
/// @notice Emitted when supplying is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsSupplyPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when borrowing is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsBorrowPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when withdrawing is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsWithdrawPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when repaying is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsRepayPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when liquidating on this market as collateral is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsLiquidateCollateralPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when liquidating on this market as borrow is paused or unpaused.
/// @param _poolToken The address of the concerned market.
/// @param _isPaused The new pause status of the market.
event IsLiquidateBorrowPausedSet(address indexed _poolToken, bool _isPaused);
/// @notice Emitted when a market is set as deprecated or not.
/// @param _poolToken The address of the concerned market.
/// @param _isDeprecated The new deprecated status.
event IsDeprecatedSet(address indexed _poolToken, bool _isDeprecated);
/// @notice Emitted when claiming rewards is paused or unpaused.
/// @param _isPaused The new pause status.
event ClaimRewardsPauseStatusSet(bool _isPaused);
/// @notice Emitted when a new market is created.
/// @param _poolToken The address of the market that has been created.
/// @param _reserveFactor The reserve factor set for this market.
/// @param _p2pIndexCursor The P2P index cursor set for this market.
event MarketCreated(address indexed _poolToken, uint16 _reserveFactor, uint16 _p2pIndexCursor);
/// ERRORS ///
/// @notice Thrown when the creation of a market failed on Compound and kicks back Compound error code.
error MarketCreationFailedOnCompound(uint256 errorCode);
/// @notice Thrown when the input is above the max basis points value (100%).
error ExceedsMaxBasisPoints();
/// @notice Thrown when the market is already created.
error MarketAlreadyCreated();
/// @notice Thrown when the amount is equal to 0.
error AmountIsZero();
/// @notice Thrown when the address is the zero address.
error ZeroAddress();
/// @notice Thrown when market borrow is not paused.
error BorrowNotPaused();
/// @notice Thrown when market is deprecated.
error MarketIsDeprecated();
/// UPGRADE ///
/// @notice Initializes the Token contract.
/// @param _positionsManager The `positionsManager`.
/// @param _interestRatesManager The `interestRatesManager`.
/// @param _comptroller The `comptroller`.
/// @param _defaultMaxGasForMatching The `defaultMaxGasForMatching`.
/// @param _dustThreshold The `dustThreshold`.
/// @param _maxSortedUsers The `_maxSortedUsers`.
/// @param _cEth The cETH address.
/// @param _wEth The wETH address.
function initialize(
IPositionsManager _positionsManager,
IInterestRatesManager _interestRatesManager,
IComptroller _comptroller,
Types.MaxGasForMatching memory _defaultMaxGasForMatching,
uint256 _dustThreshold,
uint256 _maxSortedUsers,
address _cEth,
address _wEth
) external initializer {
__ReentrancyGuard_init();
__Ownable_init();
interestRatesManager = _interestRatesManager;
positionsManager = _positionsManager;
comptroller = _comptroller;
defaultMaxGasForMatching = _defaultMaxGasForMatching;
dustThreshold = _dustThreshold;
maxSortedUsers = _maxSortedUsers;
cEth = _cEth;
wEth = _wEth;
}
/// GOVERNANCE ///
/// @notice Sets `maxSortedUsers`.
/// @param _newMaxSortedUsers The new `maxSortedUsers` value.
function setMaxSortedUsers(uint256 _newMaxSortedUsers) external onlyOwner {
maxSortedUsers = _newMaxSortedUsers;
emit MaxSortedUsersSet(_newMaxSortedUsers);
}
/// @notice Sets `defaultMaxGasForMatching`.
/// @param _defaultMaxGasForMatching The new `defaultMaxGasForMatching`.
function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _defaultMaxGasForMatching)
external
onlyOwner
{
defaultMaxGasForMatching = _defaultMaxGasForMatching;
emit DefaultMaxGasForMatchingSet(_defaultMaxGasForMatching);
}
/// @notice Sets the `positionsManager`.
/// @param _positionsManager The new `positionsManager`.
function setPositionsManager(IPositionsManager _positionsManager) external onlyOwner {
if (address(_positionsManager) == address(0)) revert ZeroAddress();
positionsManager = _positionsManager;
emit PositionsManagerSet(address(_positionsManager));
}
/// @notice Sets the `interestRatesManager`.
/// @param _interestRatesManager The new `interestRatesManager` contract.
function setInterestRatesManager(IInterestRatesManager _interestRatesManager)
external
onlyOwner
{
if (address(_interestRatesManager) == address(0)) revert ZeroAddress();
interestRatesManager = _interestRatesManager;
emit InterestRatesSet(address(_interestRatesManager));
}
/// @notice Sets the `rewardsManager`.
/// @param _rewardsManager The new `rewardsManager`.
function setRewardsManager(IRewardsManager _rewardsManager) external onlyOwner {
rewardsManager = _rewardsManager;
emit RewardsManagerSet(address(_rewardsManager));
}
/// @notice Sets the `treasuryVault`.
/// @param _treasuryVault The address of the new `treasuryVault`.
function setTreasuryVault(address _treasuryVault) external onlyOwner {
treasuryVault = _treasuryVault;
emit TreasuryVaultSet(_treasuryVault);
}
/// @dev Sets `dustThreshold`.
/// @param _dustThreshold The new `dustThreshold`.
function setDustThreshold(uint256 _dustThreshold) external onlyOwner {
dustThreshold = _dustThreshold;
emit DustThresholdSet(_dustThreshold);
}
/// @notice Sets the `reserveFactor`.
/// @param _poolToken The market on which to set the `_newReserveFactor`.
/// @param _newReserveFactor The proportion of the interest earned by users sent to the DAO, in basis point.
function setReserveFactor(address _poolToken, uint16 _newReserveFactor)
external
onlyOwner
isMarketCreated(_poolToken)
{
if (_newReserveFactor > MAX_BASIS_POINTS) revert ExceedsMaxBasisPoints();
_updateP2PIndexes(_poolToken);
marketParameters[_poolToken].reserveFactor = _newReserveFactor;
emit ReserveFactorSet(_poolToken, _newReserveFactor);
}
/// @notice Sets a new peer-to-peer cursor.
/// @param _poolToken The address of the market to update.
/// @param _p2pIndexCursor The new peer-to-peer cursor.
function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor)
external
onlyOwner
isMarketCreated(_poolToken)
{
if (_p2pIndexCursor > MAX_BASIS_POINTS) revert ExceedsMaxBasisPoints();
_updateP2PIndexes(_poolToken);
marketParameters[_poolToken].p2pIndexCursor = _p2pIndexCursor;
emit P2PIndexCursorSet(_poolToken, _p2pIndexCursor);
}
/// @notice Sets `isSupplyPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsSupplyPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
marketPauseStatus[_poolToken].isSupplyPaused = _isPaused;
emit IsSupplyPausedSet(_poolToken, _isPaused);
}
/// @notice Sets `isBorrowPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsBorrowPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
if (!_isPaused && marketPauseStatus[_poolToken].isDeprecated) revert MarketIsDeprecated();
marketPauseStatus[_poolToken].isBorrowPaused = _isPaused;
emit IsBorrowPausedSet(_poolToken, _isPaused);
}
/// @notice Sets `isWithdrawPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsWithdrawPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
marketPauseStatus[_poolToken].isWithdrawPaused = _isPaused;
emit IsWithdrawPausedSet(_poolToken, _isPaused);
}
/// @notice Sets `isRepayPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsRepayPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
marketPauseStatus[_poolToken].isRepayPaused = _isPaused;
emit IsRepayPausedSet(_poolToken, _isPaused);
}
/// @notice Sets `isLiquidateCollateralPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
marketPauseStatus[_poolToken].isLiquidateCollateralPaused = _isPaused;
emit IsLiquidateCollateralPausedSet(_poolToken, _isPaused);
}
/// @notice Sets `isLiquidateBorrowPaused` for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused)
external
onlyOwner
isMarketCreated(_poolToken)
{
marketPauseStatus[_poolToken].isLiquidateBorrowPaused = _isPaused;
emit IsLiquidateBorrowPausedSet(_poolToken, _isPaused);
}
/// @notice Sets the pause status for all markets.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsPausedForAllMarkets(bool _isPaused) external onlyOwner {
uint256 numberOfMarketsCreated = marketsCreated.length;
for (uint256 i; i < numberOfMarketsCreated; ) {
address poolToken = marketsCreated[i];
_setPauseStatus(poolToken, _isPaused);
unchecked {
++i;
}
}
}
/// @notice Sets `isP2PDisabled` for a given market.
/// @param _poolToken The address of the market of which to enable/disable peer-to-peer matching.
/// @param _isP2PDisabled True to disable the peer-to-peer market.
function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled)
external
onlyOwner
isMarketCreated(_poolToken)
{
p2pDisabled[_poolToken] = _isP2PDisabled;
emit P2PStatusSet(_poolToken, _isP2PDisabled);
}
/// @notice Sets `isClaimRewardsPaused`.
/// @param _isPaused The new pause status, true to pause the mechanism.
function setIsClaimRewardsPaused(bool _isPaused) external onlyOwner {
isClaimRewardsPaused = _isPaused;
emit ClaimRewardsPauseStatusSet(_isPaused);
}
/// @notice Sets a market as deprecated (allows liquidation of every position on this market).
/// @param _poolToken The address of the market to update.
/// @param _isDeprecated The new deprecated status, true to deprecate the market.
function setIsDeprecated(address _poolToken, bool _isDeprecated)
external
onlyOwner
isMarketCreated(_poolToken)
{
if (!marketPauseStatus[_poolToken].isBorrowPaused) revert BorrowNotPaused();
marketPauseStatus[_poolToken].isDeprecated = _isDeprecated;
emit IsDeprecatedSet(_poolToken, _isDeprecated);
}
/// @notice Increases peer-to-peer deltas, to put some liquidity back on the pool.
/// @dev The current Token supply on the pool might not be enough to borrow `_amount` before resuppling it.
/// In this case, consider calling multiple times this function.
/// @param _poolToken The address of the market on which to increase deltas.
/// @param _amount The maximum amount to add to the deltas (in underlying).
function increaseP2PDeltas(address _poolToken, uint256 _amount) external onlyOwner {
address(positionsManager).functionDelegateCall(
abi.encodeWithSelector(
IPositionsManager.increaseP2PDeltasLogic.selector,
_poolToken,
_amount
)
);
}
/// @notice Transfers the protocol reserve fee to the DAO.
/// @param _poolTokens The addresses of the pool token addresses on which to claim the reserve fee.
/// @param _amounts The list of amounts of underlying tokens to claim on each market.
function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts)
external
onlyOwner
{
if (treasuryVault == address(0)) revert ZeroAddress();
uint256 numberOfMarkets = _poolTokens.length;
for (uint256 i; i < numberOfMarkets; ++i) {
address poolToken = _poolTokens[i];
Types.MarketStatus memory status = marketStatus[poolToken];
if (!status.isCreated) continue;
ERC20 underlyingToken = _getUnderlying(poolToken);
uint256 underlyingBalance = underlyingToken.balanceOf(address(this));
if (underlyingBalance == 0) continue;
uint256 toClaim = Math.min(_amounts[i], underlyingBalance);
underlyingToken.safeTransfer(treasuryVault, toClaim);
emit ReserveFeeClaimed(poolToken, toClaim);
}
}
/// @notice Creates a new market to borrow/supply in.
/// @param _poolToken The pool token address of the given market.
/// @param _marketParams The market's parameters to set.
function createMarket(address _poolToken, Types.MarketParameters calldata _marketParams)
external
onlyOwner
{
if (
_marketParams.p2pIndexCursor > MAX_BASIS_POINTS ||
_marketParams.reserveFactor > MAX_BASIS_POINTS
) revert ExceedsMaxBasisPoints();
if (marketStatus[_poolToken].isCreated) revert MarketAlreadyCreated();
marketStatus[_poolToken].isCreated = true;
address[] memory marketToEnter = new address[](1);
marketToEnter[0] = _poolToken;
uint256[] memory results = comptroller.enterMarkets(marketToEnter);
if (results[0] != 0) revert MarketCreationFailedOnCompound(results[0]);
// Same initial index as Compound.
uint256 initialIndex;
if (_poolToken == cEth) initialIndex = 2e26;
else initialIndex = 2 * 10**(16 + ERC20(ICToken(_poolToken).underlying()).decimals() - 8);
p2pSupplyIndex[_poolToken] = initialIndex;
p2pBorrowIndex[_poolToken] = initialIndex;
Types.LastPoolIndexes storage poolIndexes = lastPoolIndexes[_poolToken];
poolIndexes.lastUpdateBlockNumber = uint32(block.number);
poolIndexes.lastSupplyPoolIndex = uint112(ICToken(_poolToken).exchangeRateCurrent());
poolIndexes.lastBorrowPoolIndex = uint112(ICToken(_poolToken).borrowIndex());
marketParameters[_poolToken] = _marketParams;
marketsCreated.push(_poolToken);
emit MarketCreated(_poolToken, _marketParams.reserveFactor, _marketParams.p2pIndexCursor);
}
/// INTERNAL ///
/// @notice Sets all pause statuses for a given market.
/// @param _poolToken The address of the market to update.
/// @param _isPaused The new pause status, true to pause the mechanism.
function _setPauseStatus(address _poolToken, bool _isPaused) internal {
Types.MarketPauseStatus storage pause = marketPauseStatus[_poolToken];
pause.isSupplyPaused = _isPaused;
emit IsSupplyPausedSet(_poolToken, _isPaused);
// Note that pause.isDeprecated implies pause.isBorrowPaused.
if (!pause.isDeprecated) {
pause.isBorrowPaused = _isPaused;
emit IsBorrowPausedSet(_poolToken, _isPaused);
}
pause.isWithdrawPaused = _isPaused;
emit IsWithdrawPausedSet(_poolToken, _isPaused);
pause.isRepayPaused = _isPaused;
emit IsRepayPausedSet(_poolToken, _isPaused);
pause.isLiquidateCollateralPaused = _isPaused;
emit IsLiquidateCollateralPausedSet(_poolToken, _isPaused);
pause.isLiquidateBorrowPaused = _isPaused;
emit IsLiquidateBorrowPausedSet(_poolToken, _isPaused);
}
}
contracts/compound/TokenStorage.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import "./interfaces/compound/ICompound.sol";
import "./interfaces/IPositionsManager.sol";
import "./interfaces/IRewardsManager.sol";
import "./interfaces/IInterestRatesManager.sol";
import "../lib/token-data-structures/contracts/DoubleLinkedList.sol";
import "./libraries/Types.sol";
import "@openzeppelin/[email protected]/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/[email protected]/access/OwnableUpgradeable.sol";
/// @title TokenStorage.
/// @author Token Labs.
/// @notice All storage variables used in Token contracts.
abstract contract TokenStorage is OwnableUpgradeable, ReentrancyGuardUpgradeable {
/// GLOBAL STORAGE ///
uint8 public constant CTOKEN_DECIMALS = 8; // The number of decimals for cToken.
uint16 public constant MAX_BASIS_POINTS = 100_00; // 100% in basis points.
uint256 public constant WAD = 1e18;
uint256 public maxSortedUsers; // The max number of users to sort in the data structure.
uint256 public dustThreshold; // The minimum amount to keep in the data structure.
Types.MaxGasForMatching public defaultMaxGasForMatching; // The default max gas to consume within loops in matching engine functions.
/// POSITIONS STORAGE ///
mapping(address => DoubleLinkedList.List) internal suppliersInP2P; // For a given market, the suppliers in peer-to-peer.
mapping(address => DoubleLinkedList.List) internal suppliersOnPool; // For a given market, the suppliers on Compound.
mapping(address => DoubleLinkedList.List) internal borrowersInP2P; // For a given market, the borrowers in peer-to-peer.
mapping(address => DoubleLinkedList.List) internal borrowersOnPool; // For a given market, the borrowers on Compound.
mapping(address => mapping(address => Types.SupplyBalance)) public supplyBalanceInOf; // For a given market, the supply balance of a user. cToken -> user -> balances.
mapping(address => mapping(address => Types.BorrowBalance)) public borrowBalanceInOf; // For a given market, the borrow balance of a user. cToken -> user -> balances.
mapping(address => mapping(address => bool)) public userMembership; // Whether the user is in the market or not. cToken -> user -> bool.
mapping(address => address[]) public enteredMarkets; // The markets entered by a user. user -> cTokens.
/// MARKETS STORAGE ///
address[] internal marketsCreated; // Keeps track of the created markets.
mapping(address => bool) public p2pDisabled; // Whether the peer-to-peer market is open or not.
mapping(address => uint256) public p2pSupplyIndex; // Current index from supply peer-to-peer unit to underlying (in wad).
mapping(address => uint256) public p2pBorrowIndex; // Current index from borrow peer-to-peer unit to underlying (in wad).
mapping(address => Types.LastPoolIndexes) public lastPoolIndexes; // Last pool index stored.
mapping(address => Types.MarketParameters) public marketParameters; // Market parameters.
mapping(address => Types.MarketStatus) public marketStatus; // Market status.
mapping(address => Types.Delta) public deltas; // Delta parameters for each market.
/// CONTRACTS AND ADDRESSES ///
IPositionsManager public positionsManager;
address public incentivesVault; // Deprecated.
IRewardsManager public rewardsManager;
IInterestRatesManager public interestRatesManager;
IComptroller public comptroller;
address public treasuryVault;
address public cEth;
address public wEth;
/// APPENDIX STORAGE ///
mapping(address => uint256) public lastBorrowBlock; // Block number of the last borrow of the user.
bool public isClaimRewardsPaused; // Whether it's possible to claim rewards or not.
mapping(address => Types.MarketPauseStatus) public marketPauseStatus; // The pause and deprecated statuses for the given market.
/// CONSTRUCTOR ///
/// @notice Constructs the contract.
/// @dev The contract is automatically marked as initialized when deployed so that nobody can highjack the implementation contract.
constructor() initializer {}
}
contracts/compound/TokenUtils.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import "../lib/solmate/src/utils/SafeTransferLib.sol";
import "../lib/token-utils/src/math/Math.sol";
import "../lib/token-utils/src/math/CompoundMath.sol";
import "../lib/token-utils/src/DelegateCall.sol";
import "./TokenStorage.sol";
/// @title TokenUtils.
/// @author Token Labs.
/// @notice Modifiers, getters and other util functions for Token.
abstract contract TokenUtils is TokenStorage {
using DoubleLinkedList for DoubleLinkedList.List;
using CompoundMath for uint256;
using DelegateCall for address;
/// ERRORS ///
/// @notice Thrown when the Compound's oracle failed.
error CompoundOracleFailed();
/// @notice Thrown when the market is not created yet.
error MarketNotCreated();
/// MODIFIERS ///
/// @notice Prevents to update a market not created yet.
/// @param _poolToken The address of the market to check.
modifier isMarketCreated(address _poolToken) {
if (!marketStatus[_poolToken].isCreated) revert MarketNotCreated();
_;
}
/// EXTERNAL ///
/// @notice Returns all markets entered by a given user.
/// @param _user The address of the user.
/// @return The list of markets entered by this user.
function getEnteredMarkets(address _user) external view returns (address[] memory) {
return enteredMarkets[_user];
}
/// @notice Returns all created markets.
/// @return The list of market addresses.
function getAllMarkets() external view returns (address[] memory) {
return marketsCreated;
}
/// @notice Gets the head of the data structure on a specific market (for UI).
/// @param _poolToken The address of the market from which to get the head.
/// @param _positionType The type of user from which to get the head.
/// @return head The head in the data structure.
function getHead(address _poolToken, Types.PositionType _positionType)
external
view
returns (address head)
{
if (_positionType == Types.PositionType.SUPPLIERS_IN_P2P)
head = suppliersInP2P[_poolToken].getHead();
else if (_positionType == Types.PositionType.SUPPLIERS_ON_POOL)
head = suppliersOnPool[_poolToken].getHead();
else if (_positionType == Types.PositionType.BORROWERS_IN_P2P)
head = borrowersInP2P[_poolToken].getHead();
else if (_positionType == Types.PositionType.BORROWERS_ON_POOL)
head = borrowersOnPool[_poolToken].getHead();
}
/// @notice Gets the next user after `_user` in the data structure on a specific market (for UI).
/// @dev Beware that this function does not give the account with the highest liquidity.
/// @param _poolToken The address of the market from which to get the user.
/// @param _positionType The type of user from which to get the next user.
/// @param _user The address of the user from which to get the next user.
/// @return next The next user in the data structure.
function getNext(
address _poolToken,
Types.PositionType _positionType,
address _user
) external view returns (address next) {
if (_positionType == Types.PositionType.SUPPLIERS_IN_P2P)
next = suppliersInP2P[_poolToken].getNext(_user);
else if (_positionType == Types.PositionType.SUPPLIERS_ON_POOL)
next = suppliersOnPool[_poolToken].getNext(_user);
else if (_positionType == Types.PositionType.BORROWERS_IN_P2P)
next = borrowersInP2P[_poolToken].getNext(_user);
else if (_positionType == Types.PositionType.BORROWERS_ON_POOL)
next = borrowersOnPool[_poolToken].getNext(_user);
}
/// @notice Updates the peer-to-peer indexes.
/// @dev Note: This function updates the exchange rate on Compound. As a consequence only a call to exchangeRateStored() is necessary to get the most up to date exchange rate.
/// @param _poolToken The address of the market to update.
function updateP2PIndexes(address _poolToken) external isMarketCreated(_poolToken) {
_updateP2PIndexes(_poolToken);
}
/// INTERNAL ///
/// @dev Updates the peer-to-peer indexes.
/// @dev Note: This function updates the exchange rate on Compound. As a consequence only a call to exchangeRateStored() is necessary to get the most up to date exchange rate.
/// @param _poolToken The address of the market to update.
function _updateP2PIndexes(address _poolToken) internal {
address(interestRatesManager).functionDelegateCall(
abi.encodeWithSelector(interestRatesManager.updateP2PIndexes.selector, _poolToken)
);
}
/// @dev Checks whether the user has enough collateral to maintain such a borrow position.
/// @dev Expects the given user's entered markets to include the given market.
/// @dev Expects the given market's pool & peer-to-peer indexes to have been updated.
/// @dev Expects `_withdrawnAmount` to be less than or equal to the given user's supply on the given market.
/// @param _user The user to check.
/// @param _poolToken The market to hypothetically withdraw/borrow in.
/// @param _withdrawnAmount The amount of tokens to hypothetically withdraw (in underlying).
/// @param _borrowedAmount The amount of tokens to hypothetically borrow (in underlying).
function _isLiquidatable(
address _user,
address _poolToken,
uint256 _withdrawnAmount,
uint256 _borrowedAmount
) internal view returns (bool) {
ICompoundOracle oracle = ICompoundOracle(comptroller.oracle());
uint256 numberOfEnteredMarkets = enteredMarkets[_user].length;
Types.AssetLiquidityData memory assetData;
uint256 maxDebtUsd;
uint256 debtUsd;
uint256 i;
while (i < numberOfEnteredMarkets) {
address poolTokenEntered = enteredMarkets[_user][i];
assetData = _getUserLiquidityDataForAsset(_user, poolTokenEntered, oracle);
maxDebtUsd += assetData.maxDebtUsd;
debtUsd += assetData.debtUsd;
if (_poolToken == poolTokenEntered) {
if (_borrowedAmount > 0) debtUsd += _borrowedAmount.mul(assetData.underlyingPrice);
if (_withdrawnAmount > 0)
maxDebtUsd -= _withdrawnAmount.mul(assetData.underlyingPrice).mul(
assetData.collateralFactor
);
}
unchecked {
++i;
}
}
return debtUsd > maxDebtUsd;
}
/// @notice Returns the data related to `_poolToken` for the `_user`.
/// @dev Note: Must be called after calling `_updateP2PIndexes()` to have the most up-to-date indexes.
/// @param _user The user to determine data for.
/// @param _poolToken The address of the market.
/// @param _oracle The oracle used.
/// @return assetData The data related to this asset.
function _getUserLiquidityDataForAsset(
address _user,
address _poolToken,
ICompoundOracle _oracle
) internal view returns (Types.AssetLiquidityData memory assetData) {
assetData.underlyingPrice = _oracle.getUnderlyingPrice(_poolToken);
if (assetData.underlyingPrice == 0) revert CompoundOracleFailed();
(, assetData.collateralFactor, ) = comptroller.markets(_poolToken);
assetData.collateralUsd = _getUserSupplyBalanceInOf(_poolToken, _user).mul(
assetData.underlyingPrice
);
assetData.debtUsd = _getUserBorrowBalanceInOf(_poolToken, _user).mul(
assetData.underlyingPrice
);
assetData.maxDebtUsd = assetData.collateralUsd.mul(assetData.collateralFactor);
}
/// @dev Returns the supply balance of `_user` in the `_poolToken` market.
/// @dev Note: Computes the result with the stored indexes, which are not always the most up to date ones.
/// @param _user The address of the user.
/// @param _poolToken The market where to get the supply amount.
/// @return The supply balance of the user (in underlying).
function _getUserSupplyBalanceInOf(address _poolToken, address _user)
internal
view
returns (uint256)
{
Types.SupplyBalance memory userSupplyBalance = supplyBalanceInOf[_poolToken][_user];
return
userSupplyBalance.inP2P.mul(p2pSupplyIndex[_poolToken]) +
userSupplyBalance.onPool.mul(ICToken(_poolToken).exchangeRateStored());
}
/// @dev Returns the borrow balance of `_user` in the `_poolToken` market.
/// @dev Note: Computes the result with the stored indexes, which are not always the most up to date ones.
/// @param _user The address of the user.
/// @param _poolToken The market where to get the borrow amount.
/// @return The borrow balance of the user (in underlying).
function _getUserBorrowBalanceInOf(address _poolToken, address _user)
internal
view
returns (uint256)
{
Types.BorrowBalance memory userBorrowBalance = borrowBalanceInOf[_poolToken][_user];
return
userBorrowBalance.inP2P.mul(p2pBorrowIndex[_poolToken]) +
userBorrowBalance.onPool.mul(ICToken(_poolToken).borrowIndex());
}
/// @dev Returns the underlying ERC20 token related to the pool token.
/// @param _poolToken The address of the pool token.
/// @return The underlying ERC20 token.
function _getUnderlying(address _poolToken) internal view returns (ERC20) {
if (_poolToken == cEth)
// cETH has no underlying() function.
return ERC20(wEth);
else return ERC20(ICToken(_poolToken).underlying());
}
}
contracts/compound/interfaces/IInterestRatesManager.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
interface IInterestRatesManager {
function updateP2PIndexes(address _marketAddress) external;
}
contracts/compound/interfaces/IPositionsManager.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
interface IPositionsManager {
function supplyLogic(
address _poolToken,
address _supplier,
address _onBehalf,
uint256 _amount,
uint256 _maxGasForMatching
) external;
function borrowLogic(
address _poolToken,
uint256 _amount,
uint256 _maxGasForMatching
) external;
function withdrawLogic(
address _poolToken,
uint256 _amount,
address _supplier,
address _receiver,
uint256 _maxGasForMatching
) external;
function repayLogic(
address _poolToken,
address _repayer,
address _onBehalf,
uint256 _amount,
uint256 _maxGasForMatching
) external;
function liquidateLogic(
address _poolTokenBorrowed,
address _poolTokenCollateral,
address _borrower,
uint256 _amount
) external;
function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external;
}
contracts/compound/interfaces/IRewardsManager.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import "./compound/ICompound.sol";
interface IRewardsManager {
function initialize(address _token) external;
function claimRewards(address[] calldata, address) external returns (uint256);
function userUnclaimedCompRewards(address) external view returns (uint256);
function compSupplierIndex(address, address) external view returns (uint256);
function compBorrowerIndex(address, address) external view returns (uint256);
function getLocalCompSupplyState(address _cTokenAddress)
external
view
returns (IComptroller.CompMarketState memory);
function getLocalCompBorrowState(address _cTokenAddress)
external
view
returns (IComptroller.CompMarketState memory);
function accrueUserSupplyUnclaimedRewards(
address,
address,
uint256
) external;
function accrueUserBorrowUnclaimedRewards(
address,
address,
uint256
) external;
}
contracts/compound/interfaces/compound/ICompound.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
interface ICEth {
function accrueInterest() external returns (uint256);
function borrowRate() external returns (uint256);
function borrowIndex() external returns (uint256);
function borrowBalanceStored(address) external returns (uint256);
function mint() external payable;
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function supplyRatePerBlock() external returns (uint256);
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address,
address,
uint256
) external returns (bool);
function transfer(address dst, uint256 amount) external returns (bool);
function balanceOf(address) external returns (uint256);
function balanceOfUnderlying(address account) external returns (uint256);
function borrow(uint256) external returns (uint256);
function repayBorrow() external payable;
function borrowBalanceCurrent(address) external returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
}
interface IComptroller {
struct CompMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
function liquidationIncentiveMantissa() external view returns (uint256);
function closeFactorMantissa() external view returns (uint256);
function admin() external view returns (address);
function allMarkets(uint256) external view returns (ICToken);
function oracle() external view returns (address);
function borrowCaps(address) external view returns (uint256);
function markets(address)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isComped
);
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address cToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address cToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address cToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address cToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
function getHypotheticalAccountLiquidity(
address,
address,
uint256,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function checkMembership(address, address) external view returns (bool);
function mintGuardianPaused(address) external view returns (bool);
function borrowGuardianPaused(address) external view returns (bool);
function seizeGuardianPaused() external view returns (bool);
function claimComp(address holder) external;
function claimComp(address holder, address[] memory cTokens) external;
function compSpeeds(address) external view returns (uint256);
function compSupplySpeeds(address) external view returns (uint256);
function compBorrowSpeeds(address) external view returns (uint256);
function compSupplyState(address) external view returns (CompMarketState memory);
function compBorrowState(address) external view returns (CompMarketState memory);
function getCompAddress() external view returns (address);
function _setPriceOracle(address newOracle) external returns (uint256);
function _setMintPaused(ICToken cToken, bool state) external returns (bool);
function _setBorrowPaused(ICToken cToken, bool state) external returns (bool);
function _setCollateralFactor(ICToken cToken, uint256 newCollateralFactorMantissa)
external
returns (uint256);
function _setCompSpeeds(
ICToken[] memory cTokens,
uint256[] memory supplySpeeds,
uint256[] memory borrowSpeeds
) external;
}
interface IInterestRateModel {
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
}
interface ICToken {
function isCToken() external returns (bool);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function borrowRate() external returns (uint256);
function borrowIndex() external view returns (uint256);
function borrow(uint256) external returns (uint256);
function repayBorrow(uint256) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function underlying() external view returns (address);
function mint(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function accrueInterest() external returns (uint256);
function totalSupply() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function accrualBlockNumber() external view returns (uint256);
function totalReserves() external view returns (uint256);
function interestRateModel() external view returns (IInterestRateModel);
function reserveFactorMantissa() external view returns (uint256);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);
function _acceptAdmin() external returns (uint256);
function _setComptroller(IComptroller newComptroller) external returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external returns (uint256);
function _setInterestRateModel(IInterestRateModel newInterestRateModel)
external
returns (uint256);
}
interface ICEther is ICToken {
function mint() external payable;
function repayBorrow() external payable;
}
interface ICompoundOracle {
function getUnderlyingPrice(address) external view returns (uint256);
}
contracts/compound/libraries/Types.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
/// @title Types.
/// @author Token Labs.
/// @dev Common types and structs used in Token contracts.
library Types {
/// ENUMS ///
enum PositionType {
SUPPLIERS_IN_P2P,
SUPPLIERS_ON_POOL,
BORROWERS_IN_P2P,
BORROWERS_ON_POOL
}
/// STRUCTS ///
struct SupplyBalance {
uint256 inP2P; // In peer-to-peer supply unit, a unit that grows in underlying value, to keep track of the interests earned by suppliers in peer-to-peer. Multiply by the peer-to-peer supply index to get the underlying amount.
uint256 onPool; // In pool supply unit. Multiply by the pool supply index to get the underlying amount.
}
struct BorrowBalance {
uint256 inP2P; // In peer-to-peer borrow unit, a unit that grows in underlying value, to keep track of the interests paid by borrowers in peer-to-peer. Multiply by the peer-to-peer borrow index to get the underlying amount.
uint256 onPool; // In pool borrow unit, a unit that grows in value, to keep track of the debt increase when borrowers are on Compound. Multiply by the pool borrow index to get the underlying amount.
}
struct Indexes {
uint256 p2pSupplyIndex; // The peer-to-peer supply index (in wad), used to multiply the peer-to-peer supply scaled balance and get the peer-to-peer supply balance (in underlying).
uint256 p2pBorrowIndex; // The peer-to-peer borrow index (in wad), used to multiply the peer-to-peer borrow scaled balance and get the peer-to-peer borrow balance (in underlying).
uint256 poolSupplyIndex; // The pool supply index (in wad), used to multiply the pool supply scaled balance and get the pool supply balance (in underlying).
uint256 poolBorrowIndex; // The pool borrow index (in wad), used to multiply the pool borrow scaled balance and get the pool borrow balance (in underlying).
}
// Max gas to consume during the matching process for supply, borrow, withdraw and repay functions.
struct MaxGasForMatching {
uint64 supply;
uint64 borrow;
uint64 withdraw;
uint64 repay;
}
struct Delta {
uint256 p2pSupplyDelta; // Difference between the stored peer-to-peer supply amount and the real peer-to-peer supply amount (in pool supply unit).
uint256 p2pBorrowDelta; // Difference between the stored peer-to-peer borrow amount and the real peer-to-peer borrow amount (in pool borrow unit).
uint256 p2pSupplyAmount; // Sum of all stored peer-to-peer supply (in peer-to-peer supply unit).
uint256 p2pBorrowAmount; // Sum of all stored peer-to-peer borrow (in peer-to-peer borrow unit).
}
struct AssetLiquidityData {
uint256 collateralUsd; // The collateral value of the asset (in wad).
uint256 maxDebtUsd; // The maximum possible debt value of the asset (in wad).
uint256 debtUsd; // The debt value of the asset (in wad).
uint256 underlyingPrice; // The price of the token.
uint256 collateralFactor; // The liquidation threshold applied on this token (in wad).
}
struct LiquidityData {
uint256 collateralUsd; // The collateral value (in wad).
uint256 maxDebtUsd; // The maximum debt value allowed before being liquidatable (in wad).
uint256 debtUsd; // The debt value (in wad).
}
// Variables are packed together to save gas (will not exceed their limit during Token's lifetime).
struct LastPoolIndexes {
uint32 lastUpdateBlockNumber; // The last time the local pool and peer-to-peer indexes were updated.
uint112 lastSupplyPoolIndex; // Last pool supply index.
uint112 lastBorrowPoolIndex; // Last pool borrow index.
}
struct MarketParameters {
uint16 reserveFactor; // Proportion of the interest earned by users sent to the DAO for each market, in basis point (100% = 10 000). The value is set at market creation.
uint16 p2pIndexCursor; // Position of the peer-to-peer rate in the pool's spread. Determine the weights of the weighted arithmetic average in the indexes computations ((1 - p2pIndexCursor) * r^S + p2pIndexCursor * r^B) (in basis point).
}
struct MarketStatus {
bool isCreated; // Whether or not this market is created.
bool isPaused; // Deprecated.
bool isPartiallyPaused; // Deprecated.
}
struct MarketPauseStatus {
bool isSupplyPaused; // Whether the supply is paused or not.
bool isBorrowPaused; // Whether the borrow is paused or not
bool isWithdrawPaused; // Whether the withdraw is paused or not. Note that a "withdraw" is still possible using a liquidation (if not paused).
bool isRepayPaused; // Whether the repay is paused or not. Note that a "repay" is still possible using a liquidation (if not paused).
bool isLiquidateCollateralPaused; // Whether the liquidation on this market as collateral is paused or not.
bool isLiquidateBorrowPaused; // Whether the liquidatation on this market as borrow is paused or not.
bool isDeprecated; // Whether a market is deprecated or not.
}
}
contracts/lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
contracts/lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
contracts/lib/token-data-structures/contracts/DoubleLinkedList.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
/// @title Double Linked List.
/// @author Token Labs.
/// @notice Modified double linked list with capped sorting insertion.
library DoubleLinkedList {
/// STRUCTS ///
struct Account {
address prev;
address next;
uint256 value;
}
struct List {
mapping(address => Account) accounts;
address head;
address tail;
}
/// ERRORS ///
/// @notice Thrown when the account is already inserted in the double linked list.
error AccountAlreadyInserted();
/// @notice Thrown when the account to remove does not exist.
error AccountDoesNotExist();
/// @notice Thrown when the address is zero at insertion.
error AddressIsZero();
/// @notice Thrown when the value is zero at insertion.
error ValueIsZero();
/// INTERNAL ///
/// @notice Returns the `account` linked to `_id`.
/// @param _list The list to search in.
/// @param _id The address of the account.
/// @return The value of the account.
function getValueOf(List storage _list, address _id) internal view returns (uint256) {
return _list.accounts[_id].value;
}
/// @notice Returns the address at the head of the `_list`.
/// @param _list The list to get the head.
/// @return The address of the head.
function getHead(List storage _list) internal view returns (address) {
return _list.head;
}
/// @notice Returns the address at the tail of the `_list`.
/// @param _list The list to get the tail.
/// @return The address of the tail.
function getTail(List storage _list) internal view returns (address) {
return _list.tail;
}
/// @notice Returns the next id address from the current `_id`.
/// @param _list The list to search in.
/// @param _id The address of the account.
/// @return The address of the next account.
function getNext(List storage _list, address _id) internal view returns (address) {
return _list.accounts[_id].next;
}
/// @notice Returns the previous id address from the current `_id`.
/// @param _list The list to search in.
/// @param _id The address of the account.
/// @return The address of the previous account.
function getPrev(List storage _list, address _id) internal view returns (address) {
return _list.accounts[_id].prev;
}
/// @notice Removes an account of the `_list`.
/// @param _list The list to search in.
/// @param _id The address of the account.
function remove(List storage _list, address _id) internal {
Account memory account = _list.accounts[_id];
if (account.value == 0) revert AccountDoesNotExist();
if (account.prev != address(0)) _list.accounts[account.prev].next = account.next;
else _list.head = account.next;
if (account.next != address(0)) _list.accounts[account.next].prev = account.prev;
else _list.tail = account.prev;
delete _list.accounts[_id];
}
/// @notice Inserts an account in the `_list` at the right slot based on its `_value`.
/// @param _list The list to search in.
/// @param _id The address of the account.
/// @param _value The value of the account.
/// @param _maxIterations The max number of iterations.
function insertSorted(
List storage _list,
address _id,
uint256 _value,
uint256 _maxIterations
) internal {
if (_value == 0) revert ValueIsZero();
if (_id == address(0)) revert AddressIsZero();
if (_list.accounts[_id].value != 0) revert AccountAlreadyInserted();
uint256 numberOfIterations;
address next = _list.head; // If not added at the end of the list `_id` will be inserted before `next`.
while (
numberOfIterations < _maxIterations &&
next != address(0) &&
_list.accounts[next].value >= _value
) {
next = _list.accounts[next].next;
unchecked {
++numberOfIterations;
}
}
// Account is not the new tail.
if (numberOfIterations < _maxIterations && next != address(0)) {
// Account is the new head.
if (next == _list.head) {
_list.accounts[_id] = Account({prev: address(0), next: next, value: _value});
_list.head = _id;
_list.accounts[next].prev = _id;
}
// Account is not the new head.
else {
address prev = _list.accounts[next].prev;
_list.accounts[_id] = Account({prev: prev, next: next, value: _value});
_list.accounts[prev].next = _id;
_list.accounts[next].prev = _id;
}
}
// Account is the new tail.
else {
// Account is the new head.
if (_list.head == address(0)) {
_list.accounts[_id] = Account({prev: address(0), next: address(0), value: _value});
_list.head = _id;
_list.tail = _id;
}
// Account is not the new head.
else {
address tail = _list.tail;
_list.accounts[_id] = Account({prev: tail, next: address(0), value: _value});
_list.accounts[tail].next = _id;
_list.tail = _id;
}
}
}
}
contracts/lib/token-utils/src/DelegateCall.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
/// @title Delegate Call Library.
/// @author Token Labs.
/// @dev Low-level YUL delegate call library.
library DelegateCall {
/// ERRORS ///
/// @notice Thrown when a low delegate call has failed without error message.
error LowLevelDelegateCallFailed();
bytes4 constant LowLevelDelegateCallFailedError = 0x06f7035e; // bytes4(keccak256("LowLevelDelegateCallFailed()"))
/// INTERNAL ///
/// @dev Performs a low-level delegate call to the `_target` contract.
/// @dev Note: Unlike the OZ's library this function does not check if the `_target` is a contract. It is the responsibility of the caller to ensure that the `_target` is a contract.
/// @param _target The address of the target contract.
/// @param _data The data to pass to the function called on the target contract.
/// @return returnData The return data from the function called on the target contract.
function functionDelegateCall(address _target, bytes memory _data) internal returns (bytes memory returnData) {
assembly {
returnData := mload(0x40)
// The bytes size is found at the bytes pointer memory address - the bytes data is found a slot further.
if iszero(delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)) {
// No error is returned, return the custom error.
if iszero(returndatasize()) {
mstore(returnData, LowLevelDelegateCallFailedError)
revert(returnData, 4)
}
// An error is returned and can be logged.
returndatacopy(returnData, 0, returndatasize())
revert(returnData, returndatasize())
}
// Copy data size and then the returned data to memory.
mstore(returnData, returndatasize())
let actualDataPtr := add(returnData, 0x20)
returndatacopy(actualDataPtr, 0, returndatasize())
// Update the free memory pointer.
mstore(0x40, add(actualDataPtr, returndatasize()))
}
}
}
contracts/lib/token-utils/src/math/CompoundMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
/// @title Compound Math Library.
/// @author Token Labs.
/// @dev Library to perform Compound's multiplication and division in an efficient way.
library CompoundMath {
/// CONSTANTS ///
uint256 internal constant MAX_UINT256 = 2**256 - 1;
uint256 public constant SCALE = 1e36;
uint256 public constant WAD = 1e18;
/// INTERNAL ///
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
// Revert if x * y > type(uint256).max
// <=> y > 0 and x > type(uint256).max / y
if mul(y, gt(x, div(MAX_UINT256, y))) {
revert(0, 0)
}
z := div(mul(x, y), WAD)
}
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
// Revert if x * SCALE > type(uint256).max or y == 0
// <=> x > type(uint256).max / SCALE or y == 0
if iszero(mul(y, iszero(gt(x, div(MAX_UINT256, SCALE))))) {
revert(0, 0)
}
z := div(div(mul(SCALE, x), y), WAD)
}
}
}
contracts/lib/token-utils/src/math/Math.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.33;
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns max(x - y, 0).
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns x / y rounded up (x / y + boolAsInt(x % y > 0)).
function divUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
// Revert if y = 0
if iszero(y) {
revert(0, 0)
}
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.