Verified contractExactApache
FlashMintLeveragedZeroEx
Address0x58093c03b4e7804d0127a6d0a5d86dcbd5652113
- Balance
0 ETH
- Transactions
48
- Compiler
solc 0.6.10
- Same code
4 more contracts
Details
- Compiler
- solc 0.6.10+commit.00c0fcaf
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- istanbul
- License
- Apache
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,092,434
- Creation transaction
- 0xfc488516d1…4ef719cb55
20 files
- contracts/exchangeIssuance/FlashmintLeveragedZeroEx.solmain34.03 KB
- @openzeppelin/contracts/access/Ownable.sol2.25 KB
- @openzeppelin/contracts/math/SafeMath.sol7.23 KB
- @openzeppelin/contracts/math/SignedSafeMath.sol2.67 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.7 KB
- @openzeppelin/contracts/token/ERC20/SafeERC20.sol3.72 KB
- @openzeppelin/contracts/utils/Address.sol7.82 KB
- @openzeppelin/contracts/utils/Context.sol941 B
- @openzeppelin/contracts/utils/ReentrancyGuard.sol2.61 KB
- contracts/interfaces/Datatypes.sol7.34 KB
- contracts/interfaces/IAToken.sol3.71 KB
- contracts/interfaces/IController.sol1.42 KB
- contracts/interfaces/IDebtIssuanceModule.sol1.61 KB
- contracts/interfaces/IManagerIssuanceHook.sol995 B
- contracts/interfaces/IMorpho.sol5.63 KB
- contracts/interfaces/IMorphoLeverageModule.sol1.05 KB
- contracts/interfaces/IPool.sol8.44 KB
- contracts/interfaces/ISetToken.sol5.11 KB
- contracts/interfaces/IWETH.sol265 B
- contracts/lib/PreciseUnitMath.sol6.03 KB
contracts/exchangeIssuance/FlashmintLeveragedZeroEx.sol
/*
Copyright 2025 Index Cooperative
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IMorphoLeverageModule } from "../interfaces/IMorphoLeverageModule.sol";
import { IDebtIssuanceModule } from "../interfaces/IDebtIssuanceModule.sol";
import { IController } from "../interfaces/IController.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { IWETH } from "../interfaces/IWETH.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
import { IMorpho } from "../interfaces/IMorpho.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IAToken } from "../interfaces/IAToken.sol";
import {IPool} from "../interfaces/IPool.sol";
/**
* @title FlashMintLeveragedZeroEx
* @author Index Coop
*
* Contract for issuing and redeeming a leveraged Set Token
* Supports all standard (1 collateral / 1 debt token) leveraged tokens on either morpho or aave leveragemodule
* Both the collateral as well as the debt token have to be available for flashloan from morpho and be
* tradeable against each other via one of the whitelisted swap target contracts
*/
contract FlashMintLeveragedZeroEx is ReentrancyGuard, Ownable {
using Address for address payable;
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for ISetToken;
/* ============ Structs ============ */
struct LeveragedTokenData {
address collateralToken;
address collateralAToken;
uint256 collateralAmount;
address debtToken;
uint256 debtAmount;
}
struct SwapData {
address swapTarget;
bytes callData;
}
struct DecodedParams {
ISetToken setToken;
bool isAave;
uint256 setAmount;
address originalSender;
bool isIssuance;
address paymentToken;
uint256 limitAmount;
LeveragedTokenData leveragedTokenData;
SwapData collateralAndDebtSwapData;
SwapData paymentTokenSwapData;
}
struct TokenBalance {
IERC20 token;
uint256 balance;
}
/* ============ Constants ============= */
uint256 private constant MAX_UINT256 = type(uint256).max;
uint256 public constant ROUNDING_ERROR_MARGIN = 2;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/* ============ State Variables ============ */
IController public immutable setController;
IDebtIssuanceModule public immutable debtIssuanceModule;
IMorphoLeverageModule public immutable morphoLeverageModule;
IMorphoLeverageModule public immutable aaveLeverageModule;
IMorpho public immutable morpho;
IWETH public immutable weth;
IPool public immutable aavePool;
address private flashLoanBenefactor;
// TODO: Add support for multiple routers supplied by the user
mapping(address => bool) public swapTargetWhitelist;
/* ============ Events ============ */
event FlashMint(
address indexed _recipient, // The recipient address of the issued SetTokens
ISetToken indexed _setToken, // The issued SetToken
address indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens
uint256 _amountSetIssued // The amount of SetTokens received by the recipient
);
event FlashRedeem(
address indexed _recipient, // The recipient address which redeemed the SetTokens
ISetToken indexed _setToken, // The redeemed SetToken
address indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient
uint256 _amountSetRedeemed // The amount of SetTokens redeemed for output tokens
);
/* ============ Constructor ============ */
/**
* Sets various contract addresses
*
* @param _setController SetToken controller used to verify a given token is a set
* @param _debtIssuanceModule DebtIssuanceModule used to issue and redeem tokens
* @param _morphoLeverageModule MorphoLeverageModule to sync before every issuance / redemption
* @param _aaveLeverageModule AaveLeverageModule to sync before every issuance / redemption
* @param _morpho Morpho contract to call for flashloan
* @param _weth WETH contract to deposit and withdraw eth
* @param _swapTarget Address of the 0x router to use for swaps
*/
constructor(
IController _setController,
IDebtIssuanceModule _debtIssuanceModule,
IMorphoLeverageModule _morphoLeverageModule,
IMorphoLeverageModule _aaveLeverageModule,
IMorpho _morpho,
IPool _aavePool,
IWETH _weth,
address _swapTarget
)
public
{
setController = _setController;
debtIssuanceModule = _debtIssuanceModule;
morphoLeverageModule = _morphoLeverageModule;
aaveLeverageModule = _aaveLeverageModule;
morpho = _morpho;
aavePool = _aavePool;
weth = _weth;
swapTargetWhitelist[_swapTarget] = true;
}
/* ============ External Functions ============ */
/**
* Adds or removes a given swapTarget from the whitelist
* OWNER ONLY
*
* @param _swapTarget Settlement contract to add/remove from whitelist
* @param _isAllowed Boolean indicating wether given contract should be included in the whitelist
*
*/
function setSwapTargetWhitelist(address _swapTarget, bool _isAllowed) external onlyOwner {
swapTargetWhitelist[_swapTarget] = _isAllowed;
}
/**
* Withdraws stranded tokens from the contracts balance
* OWNER ONLY
*
* @param _token Token to be withdrawn from the contract balance
*
*/
function withdrawToken(IERC20 _token) external onlyOwner {
if (address(_token) == address(0)) {
msg.sender.sendValue(address(this).balance);
} else {
_token.safeTransfer(msg.sender, _token.balanceOf(address(this)));
}
}
/**
* Returns the collateral / debt token addresses and amounts for a leveraged index
*
* @param _setToken Address of the SetToken to be issued / redeemed
* @param _setAmount Amount of SetTokens to issue / redeem
* @param _isIssuance Boolean indicating if the SetToken is to be issued or redeemed
* @param _isAave Boolean indicating wether given leveraged token is based on aave leverage module (or morpho)
*
* @return Struct containing the collateral / debt token addresses and amounts
*/
function getLeveragedTokenData(
ISetToken _setToken,
uint256 _setAmount,
bool _isIssuance,
bool _isAave
)
external
returns (LeveragedTokenData memory)
{
_syncLeverageModule(_isAave, _setToken);
return _getLeveragedTokenData(_setToken, _setAmount, _isIssuance, _isAave);
}
/**
* Runs all the necessary approval functions required for a given ERC20 token.
* This function can be called when a new token is added to a SetToken during a
* rebalance.
*
* @param _token Address of the token which needs approval
*/
function approveToken(IERC20 _token) external {
_approveToken(_token);
}
/**
* Trigger redemption of set token to pay the user with Eth
*
* @param _setToken Set token to redeem
* @param _setAmount Amount to redeem
* @param _minAmountOutputToken Minimum amount of ETH to send to the user
* @param _swapDataCollateralForDebt Data (token path and fee levels) describing the swap from Collateral Token to Debt Token
* @param _swapDataOutputToken Data (token path and fee levels) describing the swap from Collateral Token to Eth
* @param _isAave Boolean indicating wether given token is based on aave or morpho leverage module
*/
function redeemExactSetForETH(
ISetToken _setToken,
uint256 _setAmount,
uint256 _minAmountOutputToken,
SwapData memory _swapDataCollateralForDebt,
SwapData memory _swapDataOutputToken,
bool _isAave
)
external
virtual
nonReentrant
returns(uint256[] memory)
{
_initiateRedemption(
_setToken,
_setAmount,
ETH_ADDRESS,
_minAmountOutputToken,
_swapDataCollateralForDebt,
_swapDataOutputToken,
_isAave
);
}
/**
* Trigger redemption of set token to pay the user with an arbitrary ERC20
*
* @param _setToken Set token to redeem
* @param _setAmount Amount to redeem
* @param _outputToken Address of the ERC20 token to send to the user
* @param _minAmountOutputToken Minimum amount of output token to send to the user
* @param _swapDataCollateralForDebt Data (token path and fee levels) describing the swap from Collateral Token to Debt Token
* @param _swapDataOutputToken Data (token path and fee levels) describing the swap from Collateral Token to Output token
* @param _isAave Boolean indicating wether given token is based on aave or morpho leverage module
*/
function redeemExactSetForERC20(
ISetToken _setToken,
uint256 _setAmount,
address _outputToken,
uint256 _minAmountOutputToken,
SwapData memory _swapDataCollateralForDebt,
SwapData memory _swapDataOutputToken,
bool _isAave
)
external
virtual
nonReentrant
returns(uint256[] memory)
{
_initiateRedemption(
_setToken,
_setAmount,
_outputToken,
_minAmountOutputToken,
_swapDataCollateralForDebt,
_swapDataOutputToken,
_isAave
);
}
/**
* Trigger issuance of set token paying with any arbitrary ERC20 token
*
* @param _setToken Set token to issue
* @param _setAmount Amount to issue
* @param _inputToken Input token to pay with
* @param _maxAmountInputToken Maximum amount of input token to spend
* @param _swapDataDebtForCollateral Data (token addresses and fee levels) to describe the swap path from Debt to collateral token
* @param _swapDataInputToken Data (token addresses and fee levels) to describe the swap path from input to collateral token
* @param _isAave Boolean indicating wether given token is based on aave or morpho leverage module
*/
function issueExactSetFromERC20(
ISetToken _setToken,
uint256 _setAmount,
address _inputToken,
uint256 _maxAmountInputToken,
SwapData memory _swapDataDebtForCollateral,
SwapData memory _swapDataInputToken,
bool _isAave
)
external
virtual
nonReentrant
returns(uint256[] memory)
{
_initiateIssuance(
_setToken,
_setAmount,
_inputToken,
_maxAmountInputToken,
_swapDataDebtForCollateral,
_swapDataInputToken,
_isAave
);
}
/**
* Trigger issuance of set token paying with Eth
*
* @param _setToken Set token to issue
* @param _setAmount Amount to issue
* @param _swapDataDebtForCollateral Data (token addresses and fee levels) to describe the swap path from Debt to collateral token
* @param _swapDataInputToken Data (token addresses and fee levels) to describe the swap path from eth to collateral token
* @param _isAave Boolean indicating wether given token is based on aave or morpho leverage module
*/
function issueExactSetFromETH(
ISetToken _setToken,
uint256 _setAmount,
SwapData memory _swapDataDebtForCollateral,
SwapData memory _swapDataInputToken,
bool _isAave
)
external
virtual
payable
nonReentrant
returns(uint256[] memory)
{
_initiateIssuance(
_setToken,
_setAmount,
ETH_ADDRESS,
msg.value,
_swapDataDebtForCollateral,
_swapDataInputToken,
_isAave
);
}
/**
* Callback function called by Morpho after flashloan has been requested
*
* @param assets Amount of tokens loaned / to be repayed
* @param data Encoded data containing the original sender and leveraged token data
*/
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external {
require(msg.sender == address(morpho));
DecodedParams memory decodedParams = abi.decode(data, (DecodedParams));
require(flashLoanBenefactor == decodedParams.originalSender, "Flashloan not initiated by this contract");
if(decodedParams.isIssuance){
_performIssuance(decodedParams);
IERC20(decodedParams.leveragedTokenData.collateralToken).approve(address(morpho), assets);
} else {
_performRedemption(decodedParams);
IERC20(decodedParams.leveragedTokenData.debtToken).approve(address(morpho), assets);
}
}
/**
* Runs all the necessary approval functions required for a list of ERC20 tokens.
*
* @param _tokens Addresses of the tokens which need approval
*/
function approveTokens(IERC20[] memory _tokens) external {
for (uint256 i = 0; i < _tokens.length; i++) {
_approveToken(_tokens[i]);
}
}
/**
* Runs all the necessary approval functions required before issuing
* or redeeming a SetToken. This function need to be called only once before the first time
* this smart contract is used on any particular SetToken.
*
* @param _setToken Address of the SetToken being initialized
* @param _isAave Boolean indicating wether leverage token is based on aave leverage module
*/
function approveSetToken(ISetToken _setToken, bool _isAave) external {
LeveragedTokenData memory leveragedTokenData = _getLeveragedTokenData(_setToken, 1 ether, true, _isAave);
if(_isAave){
_approveToken(IERC20(leveragedTokenData.collateralAToken));
_approveToken(IERC20(leveragedTokenData.debtToken));
_approveTokenToLendingPool(IERC20(leveragedTokenData.collateralToken));
_approveTokenToLendingPool(IERC20(leveragedTokenData.debtToken));
} else {
_approveToken(IERC20(leveragedTokenData.collateralToken));
_approveToken(IERC20(leveragedTokenData.debtToken));
}
}
/* ============ Internal Functions ============ */
function _getTokenBalances(address _paymentToken, LeveragedTokenData memory leveragedTokenData)
internal
returns (uint256[] memory tokenBalances)
{
bool isPaymentTokenDistinct = _paymentToken != leveragedTokenData.collateralToken && _paymentToken != leveragedTokenData.debtToken;
tokenBalances = isPaymentTokenDistinct ? new uint256[](3) : new uint256[](2);
tokenBalances[0] = IERC20(leveragedTokenData.collateralToken).balanceOf(address(this));
tokenBalances[1] = IERC20(leveragedTokenData.debtToken).balanceOf(address(this));
if (isPaymentTokenDistinct) {
if(_paymentToken == ETH_ADDRESS) {
tokenBalances[2] = address(this).balance;
} else {
tokenBalances[2] = IERC20(_paymentToken).balanceOf(address(this));
}
}
}
function _returnExcessTokenBalances(uint256[] memory balancesBefore, address _paymentToken, LeveragedTokenData memory leveragedTokenData)
internal
returns(uint256[] memory amountsReturned)
{
amountsReturned = new uint256[](balancesBefore.length);
if(balancesBefore.length > 2) {
if(_paymentToken == ETH_ADDRESS) {
uint256 paymentTokenBalance = weth.balanceOf(address(this));
if(paymentTokenBalance > balancesBefore[2]) {
amountsReturned[2] = paymentTokenBalance - balancesBefore[2];
weth.withdraw(amountsReturned[2]);
msg.sender.sendValue(amountsReturned[2]);
}
} else {
uint256 paymentTokenBalance = IERC20(_paymentToken).balanceOf(address(this));
if(paymentTokenBalance > balancesBefore[2]) {
amountsReturned[2] = paymentTokenBalance - balancesBefore[2];
IERC20(_paymentToken).safeTransfer(msg.sender, amountsReturned[2]);
}
}
}
uint256 collateralTokenBalance = IERC20(leveragedTokenData.collateralToken).balanceOf(address(this));
if(collateralTokenBalance > balancesBefore[0]) {
amountsReturned[0] = collateralTokenBalance - balancesBefore[0];
if(leveragedTokenData.collateralToken == address(weth) && _paymentToken == ETH_ADDRESS) {
weth.withdraw(amountsReturned[0]);
msg.sender.sendValue(amountsReturned[0]);
} else {
IERC20(leveragedTokenData.collateralToken).safeTransfer(msg.sender, amountsReturned[0]);
}
}
uint256 debtTokenBalance = IERC20(leveragedTokenData.debtToken).balanceOf(address(this));
if(debtTokenBalance > balancesBefore[1]) {
amountsReturned[1] = debtTokenBalance - balancesBefore[1];
if(leveragedTokenData.debtToken == address(weth) && _paymentToken == ETH_ADDRESS) {
weth.withdraw(amountsReturned[1]);
msg.sender.sendValue(amountsReturned[1]);
} else {
IERC20(leveragedTokenData.debtToken).safeTransfer(msg.sender, amountsReturned[1]);
}
}
}
/**
* Performs all the necessary steps for issuance using the collateral tokens obtained in the flashloan
*
* @param _decodedParams Struct containing token addresses / amounts to perform issuance
*/
function _performIssuance(
DecodedParams memory _decodedParams
)
internal
{
if(_decodedParams.isAave) {
// Deposit collateral token obtained from flashloan to get the respective aToken position required for issuance
_depositCollateralToken(_decodedParams.leveragedTokenData.collateralToken, _decodedParams.leveragedTokenData.collateralAmount);
}
debtIssuanceModule.issue(_decodedParams.setToken, _decodedParams.setAmount, _decodedParams.originalSender);
// Obtain necessary collateral tokens to repay flashloan
_executeSwapData(
_decodedParams.leveragedTokenData.debtToken,
_decodedParams.collateralAndDebtSwapData
);
address inputToken;
if(_decodedParams.paymentToken == ETH_ADDRESS) {
weth.deposit{value: _decodedParams.limitAmount}();
inputToken = address(weth);
} else {
inputToken = _decodedParams.paymentToken;
// Security Assumption: No one can manipulate Morpho such that this original sender is not the original sender of the transaction
// Alternatively:
IERC20(inputToken).safeTransferFrom(_decodedParams.originalSender, address(this), _decodedParams.limitAmount);
}
_executeSwapData(
inputToken,
_decodedParams.paymentTokenSwapData
);
emit FlashMint(
_decodedParams.originalSender,
_decodedParams.setToken,
_decodedParams.paymentToken,
_decodedParams.setAmount
);
}
/**
* Performs all the necessary steps for redemption using the debt tokens obtained in the flashloan
*
* @param _decodedParams Struct containing token addresses / amounts to perform redemption
*/
function _performRedemption(
DecodedParams memory _decodedParams
)
internal
{
debtIssuanceModule.redeem(_decodedParams.setToken, _decodedParams.setAmount, address(this));
if(_decodedParams.isAave) {
// Withdraw underlying collateral token from the aToken position returned by redeem step
_withdrawCollateralToken(
_decodedParams.leveragedTokenData.collateralToken,
_decodedParams.leveragedTokenData.collateralAmount - ROUNDING_ERROR_MARGIN
);
}
// Swap Collateral for Debt Tokens
_executeSwapData(
_decodedParams.leveragedTokenData.collateralToken,
_decodedParams.collateralAndDebtSwapData
);
// Swap Collateral tokens for Payment token
_executeSwapData(
_decodedParams.leveragedTokenData.collateralToken,
_decodedParams.paymentTokenSwapData
);
emit FlashRedeem(
_decodedParams.originalSender,
_decodedParams.setToken,
_decodedParams.paymentToken,
_decodedParams.setAmount
);
}
/**
* Returns the collateral / debt token addresses and amounts for a leveraged index
*
* @param _setToken Address of the SetToken to be issued / redeemed
* @param _setAmount Amount of SetTokens to issue / redeem
* @param _isIssuance Boolean indicating if the SetToken is to be issued or redeemed
* @param _isAave Boolean indicating wether given leveraged token is based on aave leverage module (or morpho)
*
* @return Struct containing the collateral / debt token addresses and amounts
*/
function _getLeveragedTokenData(
ISetToken _setToken,
uint256 _setAmount,
bool _isIssuance,
bool _isAave
)
internal
view
returns (LeveragedTokenData memory)
{
address[] memory components;
uint256[] memory equityPositions;
uint256[] memory debtPositions;
if(_isIssuance){
(components, equityPositions, debtPositions) = debtIssuanceModule.getRequiredComponentIssuanceUnits(_setToken, _setAmount);
} else {
(components, equityPositions, debtPositions) = debtIssuanceModule.getRequiredComponentRedemptionUnits(_setToken, _setAmount);
}
require(components.length == 2, "ExchangeIssuance: TOO MANY COMPONENTS");
require(debtPositions[0] == 0 || debtPositions[1] == 0, "ExchangeIssuance: TOO MANY DEBT POSITIONS");
if(equityPositions[0] > 0){
return LeveragedTokenData(
_isAave ? IAToken(components[0]).UNDERLYING_ASSET_ADDRESS() : components[0],
_isAave ? components[0] : address(0),
equityPositions[0] + ROUNDING_ERROR_MARGIN,
components[1],
debtPositions[1]
);
} else {
return LeveragedTokenData(
_isAave ? IAToken(components[1]).UNDERLYING_ASSET_ADDRESS() : components[1],
_isAave ? components[1] : address(0),
equityPositions[1] + ROUNDING_ERROR_MARGIN,
components[0],
debtPositions[0]
);
}
}
/**
* Approves max amount of given token to all exchange routers and the debt issuance module
*
* @param _token Address of the token to be approved
*/
function _approveToken(IERC20 _token) internal {
_safeApprove(_token, address(debtIssuanceModule), MAX_UINT256);
}
/**
* Approves max amount of token to lending pool
*
* @param _token Address of the token to approve
*/
function _approveTokenToLendingPool(
IERC20 _token
)
internal
{
uint256 allowance = _token.allowance(address(this), address(aavePool));
if (allowance > 0) {
_token.approve(address(aavePool), 0);
}
_token.approve(address(aavePool), MAX_UINT256);
}
/**
* Initiates a flashloan call with the correct parameters for issuing set tokens in the callback
* Borrows correct amount of collateral token and and forwards encoded memory to controll issuance in the callback.
*
* @param _setToken Address of the SetToken being initialized
* @param _setAmount Amount of the SetToken being initialized
* @param _inputToken Address of the input token to pay with
* @param _maxAmountInputToken Maximum amount of input token to pay
* @param _swapDataDebtForCollateral Data (token addresses and fee levels) to describe the swap path from Debt to collateral token
* @param _swapDataInputToken Data (token addresses and fee levels) to describe the swap path from input to collateral token
* @param _isAave Boolean indicating wether given token is based on aave or morpho leverage module
*/
function _initiateIssuance(
ISetToken _setToken,
uint256 _setAmount,
address _inputToken,
uint256 _maxAmountInputToken,
SwapData memory _swapDataDebtForCollateral,
SwapData memory _swapDataInputToken,
bool _isAave
)
internal
returns(uint256[] memory)
{
_syncLeverageModule(_isAave, _setToken);
LeveragedTokenData memory leveragedTokenData = _getLeveragedTokenData(_setToken, _setAmount, true, _isAave);
uint256[] memory tokenBalances = _getTokenBalances(_inputToken, leveragedTokenData);
bytes memory params = abi.encode(
DecodedParams(
_setToken,
_isAave,
_setAmount,
msg.sender,
true,
_inputToken,
_maxAmountInputToken,
leveragedTokenData,
_swapDataDebtForCollateral,
_swapDataInputToken
)
);
_flashloan(leveragedTokenData.collateralToken, leveragedTokenData.collateralAmount, params);
return _returnExcessTokenBalances(tokenBalances, _inputToken, leveragedTokenData);
}
/**
* Initiates a flashloan call with the correct parameters for redeeming set tokens in the callback
*
* @param _setToken Address of the SetToken to redeem
* @param _setAmount Amount of the SetToken to redeem
* @param _outputToken Address of token to return to the user
* @param _minAmountOutputToken Minimum amount of output token to receive
* @param _swapDataCollateralForDebt Data (token path and fee levels) describing the swap from Collateral Token to Debt Token
* @param _swapDataOutputToken Data (token path and fee levels) describing the swap from Collateral Token to Output token
* @param _isAave Boolean indicating wether given leverage token is based on aave leverage module
*/
function _initiateRedemption(
ISetToken _setToken,
uint256 _setAmount,
address _outputToken,
uint256 _minAmountOutputToken,
SwapData memory _swapDataCollateralForDebt,
SwapData memory _swapDataOutputToken,
bool _isAave
)
internal
returns(uint256[] memory returnedAmounts)
{
_syncLeverageModule(_isAave, _setToken);
_setToken.safeTransferFrom(msg.sender, address(this), _setAmount);
LeveragedTokenData memory leveragedTokenData = _getLeveragedTokenData(_setToken, _setAmount, false, _isAave);
uint256[] memory tokenBalances = _getTokenBalances(_outputToken, leveragedTokenData);
bytes memory params = abi.encode(
DecodedParams(
_setToken,
_isAave,
_setAmount,
msg.sender,
false,
_outputToken,
_minAmountOutputToken,
leveragedTokenData,
_swapDataCollateralForDebt,
_swapDataOutputToken
)
);
_flashloan(leveragedTokenData.debtToken, leveragedTokenData.debtAmount, params);
returnedAmounts = _returnExcessTokenBalances(tokenBalances, _outputToken, leveragedTokenData);
require(
(_outputToken == leveragedTokenData.collateralToken && returnedAmounts[0] >= _minAmountOutputToken)
||
(_outputToken == leveragedTokenData.debtToken && returnedAmounts[1] >= _minAmountOutputToken)
||
(returnedAmounts[2] >= _minAmountOutputToken),
"INSUFFICIENT OUTPUT AMOUNT"
);
}
function _syncLeverageModule(
bool _isAave,
ISetToken _setToken
)
internal {
if(_isAave) {
aaveLeverageModule.sync(_setToken);
} else {
morphoLeverageModule.sync(_setToken);
}
}
/**
* Swaps the debt tokens obtained from issuance for the collateral
*
* @param _inputToken Input token to be approved for this swap
* @param _swapData Struct containing path and fee data for swap
*
*/
function _executeSwapData(
address _inputToken,
SwapData memory _swapData
)
internal
{
if(_swapData.swapTarget != address(0)){
IERC20(_inputToken).approve(_swapData.swapTarget, IERC20(_inputToken).balanceOf(address(this)));
_fillQuote(_swapData);
}
}
/**
* Execute a 0x Swap quote
*
* @param _quote Swap quote as returned by 0x API
*
*/
function _fillQuote(
SwapData memory _quote
)
internal
{
require(swapTargetWhitelist[_quote.swapTarget], "swapTarget not whitelisted");
(bool success, bytes memory returndata) = _quote.swapTarget.call(_quote.callData);
// Forwarding errors including new custom errors
// Taken from: https://ethereum.stackexchange.com/a/111187/73805
if (!success) {
if (returndata.length == 0) revert();
assembly {
revert(add(32, returndata), mload(returndata))
}
}
}
/**
* Sets a max approval limit for an ERC20 token, provided the current allowance
* is less than the required allownce.
*
* @param _token Token to approve
* @param _spender Spender address to approve
* @param _requiredAllowance Target allowance to set
*/
function _safeApprove(
IERC20 _token,
address _spender,
uint256 _requiredAllowance
)
internal
{
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _requiredAllowance) {
_token.safeIncreaseAllowance(_spender, MAX_UINT256 - allowance);
}
}
/**
* Triggers the flashloan from the BalancerV2 Vault
*
* @param token Address of the token to loan
* @param amount Amount to loan
* @param params Encoded memory to forward to the executeOperation method
*/
function _flashloan(
address token,
uint256 amount,
bytes memory params
)
internal
{
require(flashLoanBenefactor == address(0), "Flashloan already taken");
flashLoanBenefactor = msg.sender;
morpho.flashLoan(token, amount, params);
flashLoanBenefactor = address(0);
}
/**
* Deposit collateral to aave to obtain collateralAToken for issuance
*
* @param _collateralToken Address of collateral token
* @param _depositAmount Amount to deposit
*/
function _depositCollateralToken(
address _collateralToken,
uint256 _depositAmount
) internal {
aavePool.deposit(_collateralToken, _depositAmount, address(this), 0);
}
/**
* Convert collateralAToken from set redemption to collateralToken by withdrawing underlying from Aave
*
* @param _collateralToken Address of the collateralToken to withdraw from Aave lending pool
* @param _collateralAmount Amount of collateralToken to withdraw
*/
function _withdrawCollateralToken(
address _collateralToken,
uint256 _collateralAmount
) internal {
aavePool.withdraw(_collateralToken, _collateralAmount, address(this));
}
receive() external payable {}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
@openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
@openzeppelin/contracts/math/SignedSafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
@openzeppelin/contracts/token/ERC20/SafeERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @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 GSN 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 Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 ReentrancyGuard {
// 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;
constructor () internal {
_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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
contracts/interfaces/Datatypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.10;
library DataTypes {
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
//timestamp of last update
uint40 lastUpdateTimestamp;
//the id of the reserve. Represents the position in the list of the active reserves
uint16 id;
//aToken address
address aTokenAddress;
//stableDebtToken address
address stableDebtTokenAddress;
//variableDebtToken address
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the current treasury balance, scaled
uint128 accruedToTreasury;
//the outstanding unbacked aTokens minted through the bridging feature
uint128 unbacked;
//the outstanding debt borrowed against this asset in isolation mode
uint128 isolationModeTotalDebt;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60: asset is paused
//bit 61: borrowing in isolation mode is enabled
//bit 62-63: reserved
//bit 64-79: reserve factor
//bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap
//bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap
//bit 152-167 liquidation protocol fee
//bit 168-175 eMode category
//bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
//bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
//bit 252-255 unused
uint256 data;
}
struct UserConfigurationMap {
/**
* @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
* The first bit indicates if an asset is used as collateral by the user, the second whether an
* asset is borrowed by the user.
*/
uint256 data;
}
struct EModeCategory {
// each eMode category has a custom ltv and liquidation threshold
uint16 ltv;
uint16 liquidationThreshold;
uint16 liquidationBonus;
// each eMode category may or may not have a custom oracle to override the individual assets price oracles
address priceSource;
string label;
}
enum InterestRateMode {
NONE,
STABLE,
VARIABLE
}
struct ReserveCache {
uint256 currScaledVariableDebt;
uint256 nextScaledVariableDebt;
uint256 currPrincipalStableDebt;
uint256 currAvgStableBorrowRate;
uint256 currTotalStableDebt;
uint256 nextAvgStableBorrowRate;
uint256 nextTotalStableDebt;
uint256 currLiquidityIndex;
uint256 nextLiquidityIndex;
uint256 currVariableBorrowIndex;
uint256 nextVariableBorrowIndex;
uint256 currLiquidityRate;
uint256 currVariableBorrowRate;
uint256 reserveFactor;
ReserveConfigurationMap reserveConfiguration;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
uint40 reserveLastUpdateTimestamp;
uint40 stableDebtLastUpdateTimestamp;
}
struct ExecuteLiquidationCallParams {
uint256 reservesCount;
uint256 debtToCover;
address collateralAsset;
address debtAsset;
address user;
bool receiveAToken;
address priceOracle;
uint8 userEModeCategory;
address priceOracleSentinel;
}
struct ExecuteSupplyParams {
address asset;
uint256 amount;
address onBehalfOf;
uint16 referralCode;
}
struct ExecuteBorrowParams {
address asset;
address user;
address onBehalfOf;
uint256 amount;
InterestRateMode interestRateMode;
uint16 referralCode;
bool releaseUnderlying;
uint256 maxStableRateBorrowSizePercent;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
address priceOracleSentinel;
}
struct ExecuteRepayParams {
address asset;
uint256 amount;
InterestRateMode interestRateMode;
address onBehalfOf;
bool useATokens;
}
struct ExecuteWithdrawParams {
address asset;
uint256 amount;
address to;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
}
struct ExecuteSetUserEModeParams {
uint256 reservesCount;
address oracle;
uint8 categoryId;
}
struct FinalizeTransferParams {
address asset;
address from;
address to;
uint256 amount;
uint256 balanceFromBefore;
uint256 balanceToBefore;
uint256 reservesCount;
address oracle;
uint8 fromEModeCategory;
}
struct FlashloanParams {
address receiverAddress;
address[] assets;
uint256[] amounts;
uint256[] interestRateModes;
address onBehalfOf;
bytes params;
uint16 referralCode;
uint256 flashLoanPremiumToProtocol;
uint256 flashLoanPremiumTotal;
uint256 maxStableRateBorrowSizePercent;
uint256 reservesCount;
address addressesProvider;
uint8 userEModeCategory;
bool isAuthorizedFlashBorrower;
}
struct FlashloanSimpleParams {
address receiverAddress;
address asset;
uint256 amount;
bytes params;
uint16 referralCode;
uint256 flashLoanPremiumToProtocol;
uint256 flashLoanPremiumTotal;
}
struct FlashLoanRepaymentParams {
uint256 amount;
uint256 totalPremium;
uint256 flashLoanPremiumToProtocol;
address asset;
address receiverAddress;
uint16 referralCode;
}
struct CalculateUserAccountDataParams {
UserConfigurationMap userConfig;
uint256 reservesCount;
address user;
address oracle;
uint8 userEModeCategory;
}
struct ValidateBorrowParams {
ReserveCache reserveCache;
UserConfigurationMap userConfig;
address asset;
address userAddress;
uint256 amount;
InterestRateMode interestRateMode;
uint256 maxStableLoanPercent;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
address priceOracleSentinel;
bool isolationModeActive;
address isolationModeCollateralAddress;
uint256 isolationModeDebtCeiling;
}
struct ValidateLiquidationCallParams {
ReserveCache debtReserveCache;
uint256 totalDebt;
uint256 healthFactor;
address priceOracleSentinel;
}
struct CalculateInterestRatesParams {
uint256 unbacked;
uint256 liquidityAdded;
uint256 liquidityTaken;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 averageStableBorrowRate;
uint256 reserveFactor;
address reserve;
address aToken;
}
struct InitReserveParams {
address asset;
address aTokenAddress;
address stableDebtAddress;
address variableDebtAddress;
address interestRateStrategyAddress;
uint16 reservesCount;
uint16 maxNumberReserves;
}
}
contracts/interfaces/IAToken.sol
pragma solidity 0.6.10;
interface IAToken {
event Approval(address indexed owner, address indexed spender, uint256 value);
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
event Burn(address indexed from, address indexed target, uint256 value, uint256 balanceIncrease, uint256 index);
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
event Mint(
address indexed caller, address indexed onBehalfOf, uint256 value, uint256 balanceIncrease, uint256 index
);
event Transfer(address indexed from, address indexed to, uint256 value);
function ATOKEN_REVISION() external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function EIP712_REVISION() external view returns (bytes memory);
function PERMIT_TYPEHASH() external view returns (bytes32);
function POOL() external view returns (address);
function RESERVE_TREASURY_ADDRESS() external view returns (address);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address user) external view returns (uint256);
function burn(address from, address receiverOfUnderlying, uint256 amount, uint256 index) external;
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function getIncentivesController() external view returns (address);
function getPreviousIndex(address user) external view returns (uint256);
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
function handleRepayment(address user, address onBehalfOf, uint256 amount) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function initialize(
address initializingPool,
address treasury,
address underlyingAsset,
address incentivesController,
uint8 aTokenDecimals,
string memory aTokenName,
string memory aTokenSymbol,
bytes memory params
) external;
function mint(address caller, address onBehalfOf, uint256 amount, uint256 index) external returns (bool);
function mintToTreasury(uint256 amount, uint256 index) external;
function name() external view returns (string memory);
function nonces(address owner) external view returns (uint256);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
function rescueTokens(address token, address to, uint256 amount) external;
function scaledBalanceOf(address user) external view returns (uint256);
function scaledTotalSupply() external view returns (uint256);
function setIncentivesController(address controller) external;
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transferOnLiquidation(address from, address to, uint256 value) external;
function transferUnderlyingTo(address target, uint256 amount) external;
}
contracts/interfaces/IController.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function isResource(address _resource) external view returns(bool);
function resourceId(uint256 _id) external view returns(address);
function owner() external view returns(address);
function addFactory(address _factory) external;
function addModule(address _module) external;
}
contracts/interfaces/IDebtIssuanceModule.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity >=0.6.10;
import { ISetToken } from "./ISetToken.sol";
import { IManagerIssuanceHook } from "./IManagerIssuanceHook.sol";
interface IDebtIssuanceModule {
function getRequiredComponentIssuanceUnits(
ISetToken _setToken,
uint256 _quantity
) external view returns (address[] memory, uint256[] memory, uint256[] memory);
function getRequiredComponentRedemptionUnits(
ISetToken _setToken,
uint256 _quantity
) external view returns (address[] memory, uint256[] memory, uint256[] memory);
function issue(ISetToken _setToken, uint256 _quantity, address _to) external;
function redeem(ISetToken _token, uint256 _quantity, address _to) external;
function initialize(
ISetToken _setToken,
uint256 _maxManagerFee,
uint256 _managerIssueFee,
uint256 _managerRedeemFee,
address _feeRecipient,
IManagerIssuanceHook _managerIssuanceHook
) external;
}
contracts/interfaces/IManagerIssuanceHook.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
interface IManagerIssuanceHook {
function invokePreIssueHook(ISetToken _setToken, uint256 _issueQuantity, address _sender, address _to) external;
function invokePreRedeemHook(ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to) external;
}contracts/interfaces/IMorpho.sol
// SPDX-License-bytes32entifier: UNLICENSED
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface IMorpho {
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
event AccrueInterest(bytes32 indexed id, uint256 prevBorrowRate, uint256 interest, uint256 feeShares);
event Borrow(
bytes32 indexed id,
address caller,
address indexed onBehalf,
address indexed receiver,
uint256 assets,
uint256 shares
);
event CreateMarket(bytes32 indexed id, MarketParams marketParams);
event EnableIrm(address indexed irm);
event EnableLltv(uint256 lltv);
event FlashLoan(address indexed caller, address indexed token, uint256 assets);
event IncrementNonce(address indexed caller, address indexed authorizer, uint256 usedNonce);
event Liquidate(
bytes32 indexed id,
address indexed caller,
address indexed borrower,
uint256 repaidAssets,
uint256 repaidShares,
uint256 seizedAssets,
uint256 badDebtAssets,
uint256 badDebtShares
);
event Repay(bytes32 indexed id, address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);
event SetAuthorization(
address indexed caller, address indexed authorizer, address indexed authorized, bool newIsAuthorized
);
event SetFee(bytes32 indexed id, uint256 newFee);
event SetFeeRecipient(address indexed newFeeRecipient);
event SetOwner(address indexed newOwner);
event Supply(bytes32 indexed id, address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);
event SupplyCollateral(bytes32 indexed id, address indexed caller, address indexed onBehalf, uint256 assets);
event Withdraw(
bytes32 indexed id,
address caller,
address indexed onBehalf,
address indexed receiver,
uint256 assets,
uint256 shares
);
event WithdrawCollateral(
bytes32 indexed id, address caller, address indexed onBehalf, address indexed receiver, uint256 assets
);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function accrueInterest(MarketParams memory marketParams) external;
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256, uint256);
function createMarket(MarketParams memory marketParams) external;
function enableIrm(address irm) external;
function enableLltv(uint256 lltv) external;
function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory res);
function feeRecipient() external view returns (address);
function flashLoan(address token, uint256 assets, bytes memory data) external;
function idToMarketParams(bytes32)
external
view
returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
function isAuthorized(address, address) external view returns (bool);
function isIrmEnabled(address) external view returns (bool);
function isLltvEnabled(uint256) external view returns (bool);
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
function market(bytes32)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
function nonce(address) external view returns (uint256);
function owner() external view returns (address);
function position(bytes32, address)
external
view
returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256, uint256);
function setAuthorization(address authorized, bool newIsAuthorized) external;
function setAuthorizationWithSig(Authorization memory authorization, Signature memory signature) external;
function setFee(MarketParams memory marketParams, uint256 newFee) external;
function setFeeRecipient(address newFeeRecipient) external;
function setOwner(address newOwner) external;
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256, uint256);
function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
external;
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256, uint256);
function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
external;
}
contracts/interfaces/IMorphoLeverageModule.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
import { IMorpho } from "./IMorpho.sol";
interface IMorphoLeverageModule {
function sync(
ISetToken _setToken
) external;
function lever(
ISetToken _setToken,
uint256 _borrowQuantityUnits,
uint256 _minReceiveQuantityUnits,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function delever(
ISetToken _setToken,
uint256 _redeemQuantityUnits,
uint256 _minRepayQuantityUnits,
string memory _tradeAdapterName,
bytes memory _tradeData
) external;
function marketParams(ISetToken _setToken) external view returns (IMorpho.MarketParams memory);
function getCollateralAndBorrowBalances(
ISetToken _setToken
)
external
view
returns(uint256 collateralBalance, uint256 borrowBalance, uint256 borrowSharesU256);
}
contracts/interfaces/IPool.sol
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { DataTypes } from "./Datatypes.sol";
interface IPool {
event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint8 interestRateMode,
uint256 borrowRate,
uint16 indexed referralCode
);
event FlashLoan(
address indexed target,
address initiator,
address indexed asset,
uint256 amount,
uint8 interestRateMode,
uint256 premium,
uint16 indexed referralCode
);
event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
event MintUnbacked(
address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referralCode
);
event MintedToTreasury(address indexed reserve, uint256 amountMinted);
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
event Repay(
address indexed reserve, address indexed user, address indexed repayer, uint256 amount, bool useATokens
);
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
event Supply(
address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referralCode
);
event SwapBorrowRateMode(address indexed reserve, address indexed user, uint8 interestRateMode);
event UserEModeSet(address indexed user, uint8 categoryId);
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
struct EModeCategory {
uint16 ltv;
uint16 liquidationThreshold;
uint16 liquidationBonus;
address priceSource;
string label;
}
struct ReserveConfigurationMap {
uint256 data;
}
struct ReserveData {
ReserveConfigurationMap configuration;
uint128 liquidityIndex;
uint128 currentLiquidityRate;
uint128 variableBorrowIndex;
uint128 currentVariableBorrowRate;
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
uint16 id;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
uint128 accruedToTreasury;
uint128 unbacked;
uint128 isolationModeTotalDebt;
}
struct UserConfigurationMap {
uint256 data;
}
function ADDRESSES_PROVIDER() external view returns (address);
function BRIDGE_PROTOCOL_FEE() external view returns (uint256);
function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);
function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);
function MAX_NUMBER_RESERVES() external view returns (uint16);
function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);
function POOL_REVISION() external view returns (uint256);
function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256);
function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)
external;
function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory category) external;
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
function dropReserve(address asset) external;
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external;
function flashLoan(
address receiverAddress,
address[] memory assets,
uint256[] memory amounts,
uint256[] memory interestRateModes,
address onBehalfOf,
bytes memory params,
uint16 referralCode
) external;
function flashLoanSimple(
address receiverAddress,
address asset,
uint256 amount,
bytes memory params,
uint16 referralCode
) external;
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);
function getReserveAddressById(uint16 id) external view returns (address);
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function getReserveNormalizedIncome(address asset) external view returns (uint256);
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
function getReservesList() external view returns (address[] memory);
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 availableBorrowsBase,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);
function getUserEMode(address user) external view returns (uint256);
function initReserve(
address asset,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function initialize(address provider) external;
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
function mintToTreasury(address[] memory assets) external;
function mintUnbacked(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
function rebalanceStableBorrowRate(address asset, address user) external;
function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf)
external
returns (uint256);
function repayWithATokens(address asset, uint256 amount, uint256 interestRateMode) external returns (uint256);
function repayWithPermit(
address asset,
uint256 amount,
uint256 interestRateMode,
address onBehalfOf,
uint256 deadline,
uint8 permitV,
bytes32 permitR,
bytes32 permitS
) external returns (uint256);
function rescueTokens(address token, address to, uint256 amount) external;
function resetIsolationModeTotalDebt(address asset) external;
function setConfiguration(address asset, DataTypes.ReserveConfigurationMap memory configuration) external;
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external;
function setUserEMode(uint8 categoryId) external;
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
function supplyWithPermit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode,
uint256 deadline,
uint8 permitV,
bytes32 permitR,
bytes32 permitS
) external;
function swapBorrowRateMode(address asset, uint256 interestRateMode) external;
function updateBridgeProtocolFee(uint256 protocolFee) external;
function updateFlashloanPremiums(uint128 flashLoanPremiumTotal, uint128 flashLoanPremiumToProtocol) external;
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
}
contracts/interfaces/ISetToken.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function controller() external view returns (address);
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
contracts/interfaces/IWETH.sol
// SPDX-License-Identifier: Apache License, Version 2.0
pragma solidity >=0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint) external;
}
contracts/lib/PreciseUnitMath.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "istanbul",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.