// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library 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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/math/Math.sol';
import '@itb/quant-common/contracts/solidity8/ITBContract.sol';
import './aave/IAaveIncentivesController.sol';
import './aave/ILendingPool.sol';
import './aave/IProtocolDataProviderV2.sol';
/// @title BasePositionManager that implements common functions accross different Aave markets and defaults to Aave V2
/// @author IntoTheBlock Corp
/// @dev Abstract
contract BasePositionManager is ITBContract {
IAaveIncentivesController public incentives_controller;
ILendingPool public lending_pool;
IProtocolDataProviderV2 public protocol_data_provider;
event Deposit(address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed token, uint amount);
event UpdateLendingPool();
event UpdateIncentivesController();
event UpdateProtocolDataProvider();
event ClaimRewardsV3(address reward, uint amount);
event ClaimRewards(uint amount);
/// @param _executors Executor addresses
/// @param _wnative Wrapped native token address
/// @param _lending_pool Aave V2 LendingPool address
/// @param _incentives_controller Aave V2 IncentivesController address
/// @param _protocol_data_provider Aave V2 ProtocolDataProvider address
constructor(address[] memory _executors, address payable _wnative, ILendingPool _lending_pool, IAaveIncentivesController _incentives_controller, IProtocolDataProviderV2 _protocol_data_provider) ITBContract(_executors, _wnative) {
updateLendingPool(_lending_pool);
updateIncentivesController(_incentives_controller);
updateProtocolDataProvider(_protocol_data_provider);
}
/* Helpers */
/// @notice Atoken addresses for a given market
/// @param _token Underlying market
/// @return Atoken address
/// @return Stable debt address
/// @return Variable debt address
function _getAaveTokens(address _token) internal view returns (address, address, address) {
return protocol_data_provider.getReserveTokensAddresses(_token); /* aToken, stableDebtToken, variableDebtToken */
}
/// @notice Get the LTV of a given market
/// @return LTV scaled to 1e18
function _getLTV(address _token) internal virtual view returns (uint) {
uint mask = lending_pool.getConfiguration(_token);
uint ltv = (mask % 2**16) * 1e18 / 1e4;
return ltv;
}
/// @notice Supply tokens to a given market
/// @param _token Underlying market
/// @param _amount Amount to supply
function _deposit(address _token, uint _amount) internal {
_checkAllowanceAndApprove(_token, address(lending_pool), _amount);
lending_pool.deposit(_token, _amount, address(this), 0);
emit Deposit(_token, _amount);
}
/// @notice Withdraw supplied tokens from a given market
/// @param _token Underlying market
/// @param _amount Amount to withdraw
function _withdrawSupply(address _token, uint256 _amount) internal {
(address atoken, ,) = _getAaveTokens(_token);
_checkAllowanceAndApprove(atoken, address(lending_pool), _amount);
lending_pool.withdraw(_token, _amount, address(this));
emit Withdraw(_token, _amount);
}
/// @notice Borrow tokens from a given market
/// @param _token Underlying market
/// @param _amount Amount to borrow
function _borrow(address _token, uint _amount) internal {
lending_pool.borrow(_token, _amount, 2, 0, address(this));
emit Borrow(_token, _amount);
}
/// @notice Repay debt for a given market
/// @param _token Underlying market
/// @param _amount Amount to repay
function _repay(address _token, uint _amount) internal {
_checkAllowanceAndApprove(_token, address(lending_pool), _amount); // required in V2
lending_pool.repay(_token, _amount, 2, address(this));
emit Repay(_token, _amount);
}
/// @notice Repay all debt for a given market
/// @param _token Underlying market
function _repayAll(address _token) internal {
_repay(_token, type(uint).max);
}
/* Infra */
/// @notice Only owner. Update LendingPool address
/// @param _address New address
function updateLendingPool(ILendingPool _address) public onlyOwner {
lending_pool = _address;
emit UpdateLendingPool();
}
/// @notice Only owner. Update IncentivesController/RewardsController address
/// @param _address New address
function updateIncentivesController(IAaveIncentivesController _address) public onlyOwner {
incentives_controller = _address;
emit UpdateIncentivesController();
}
/// @notice Only owner. Update ProtocolDataProvider address
/// @param _address New address
function updateProtocolDataProvider(IProtocolDataProviderV2 _address) public onlyOwner {
protocol_data_provider = _address;
emit UpdateProtocolDataProvider();
}
/* Primitives */
/// @notice Only executor. Claim rewards for a given market and amount
/// @dev Will claim both supply and variable debt rewards using V2 implementation
/// @param _token Underlying market
/// @param _amount Amount of rewards to claim
/// @return Amount claimed
function claimRewards(address _token, uint _amount) external virtual onlyExecutor returns (uint) {
address[] memory tokens = new address[](2);
(address atoken, , address variable_debt_token) = _getAaveTokens(_token);
tokens[0] = atoken;
tokens[1] = variable_debt_token;
uint amount_claimed = incentives_controller.claimRewards(tokens, _amount, address(this));
emit ClaimRewards(amount_claimed);
return amount_claimed;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
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-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.10;
library DataTypesV3 {
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;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable2Step.sol";
/// @title Base contract that implements executor related functions
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract Executable is Ownable2Step {
mapping(address => bool) public executors;
event ExecutorUpdated(address indexed executor, bool enabled);
/// @param _executors Initial whitelisted executor addresses
constructor(address[] memory _executors) {
for (uint256 i = 0; i < _executors.length; i++) {
addExecutor(_executors[i]);
}
}
/// @notice Revert if call is not being made from the owner or an executor
modifier onlyExecutor() {
require(owner() == msg.sender || executors[msg.sender], "Executable: caller is not the executor");
_;
}
/// @notice Only owner. Add an executor
/// @param _executor New executor address
function addExecutor(address _executor) public onlyOwner {
emit ExecutorUpdated(_executor, true);
executors[_executor] = true;
}
/// @notice Only owner. Remove an executor
/// @param _executor Executor address to remove
function removeExecutor(address _executor) external onlyOwner {
emit ExecutorUpdated(_executor, false);
executors[_executor] = false;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
interface IAaveIncentivesController {
event RewardsAccrued(address indexed user, uint256 amount);
event RewardsClaimed(
address indexed user,
address indexed to,
uint256 amount
);
event RewardsClaimed(
address indexed user,
address indexed to,
address indexed claimer,
uint256 amount
);
event ClaimerSet(address indexed user, address indexed claimer);
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Returns the whitelisted claimer for a certain address (0x0 if not set)
* @param user The address of the user
* @return The claimer address
*/
function getClaimer(address user) external view returns (address);
/**
* @dev Configure assets for a certain rewards emission
* @param assets The assets to incentivize
* @param emissionsPerSecond The emission for each asset
*/
function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond)
external;
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param userBalance The balance of the user of the asset in the lending pool
* @param totalSupply The total supply of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 userBalance,
uint256 totalSupply
) external;
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user) external view returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
function assets(address asset) external view returns (uint104, uint104, uint40);
function claimAllRewards(address[] calldata assets, address to) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import {DataTypes} from './DataTypes.sol';
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (uint);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function setPause(bool val) external;
function paused() external view returns (bool);
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import {DataTypesV3} from './DataTypesV3.sol';
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;
}
interface IPool {
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlying asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to The address that will receive the underlying
* @param amount The amount to be withdrawn
*/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
* @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly
*/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount,
bool useATokens
);
/**
* @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the
* equivalent debt tokens
* - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens
* @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken
* balance is not enough to cover the whole debt
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @return The final amount repaid
**/
function repayWithATokens(
address asset,
uint256 amount,
uint256 interestRateMode
) external returns (uint256);
/**
* @notice Returns the data of an eMode category
* @param id The id of the category
* @return The configuration data of the category
*/
function getEModeCategoryData(uint8 id) external view returns (EModeCategory memory);
/**
* @notice Allows a user to use the protocol in eMode
* @param categoryId The id of the category
*/
function setUserEMode(uint8 categoryId) external;
/**
* @notice Returns the eMode the user is using
* @param user The address of the user
* @return The eMode id
*/
function getUserEMode(address user) external view returns (uint256);
/**
* @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User supplies 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to supply
* @param amount The amount to be supplied
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function supply(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to The address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already supplied enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode The code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 interestRateMode,
address onBehalfOf
) external returns (uint256);
/**
* @notice Allows suppliers to enable/disable a specific supplied asset as collateral
* @param asset The address of the underlying asset supplied
* @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @notice Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralBase The total collateral of the user in the base currency used by the price feed
* @return totalDebtBase The total debt of the user in the base currency used by the price feed
* @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed
* @return currentLiquidationThreshold The liquidation threshold of the user
* @return ltv The loan to value of The user
* @return healthFactor The current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralBase,
uint256 totalDebtBase,
uint256 availableBorrowsBase,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
/**
* @notice Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state and configuration data of the reserve
**/
function getReserveData(address asset) external view returns (DataTypesV3.ReserveData memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
interface IProtocolDataProviderV2 {
function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled);
function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen);
function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp);
function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import {IRewardsDistributorV3} from './IRewardsDistributorV3.sol';
/**
* @title IRewardsController
* @author Aave
* @notice Defines the basic interface for a Rewards Controller.
*/
interface IRewardsControllerV3 is IRewardsDistributorV3 {
/**
* @dev Emitted when a new address is whitelisted as claimer of rewards on behalf of a user
* @param user The address of the user
* @param claimer The address of the claimer
*/
event ClaimerSet(address indexed user, address indexed claimer);
/**
* @dev Emitted when rewards are claimed
* @param user The address of the user rewards has been claimed on behalf of
* @param reward The address of the token reward is claimed
* @param to The address of the receiver of the rewards
* @param claimer The address of the claimer
* @param amount The amount of rewards claimed
*/
event RewardsClaimed(
address indexed user,
address indexed reward,
address indexed to,
address claimer,
uint256 amount
);
/**
* @dev Emitted when a transfer strategy is installed for the reward distribution
* @param reward The address of the token reward
* @param transferStrategy The address of TransferStrategy contract
*/
event TransferStrategyInstalled(address indexed reward, address indexed transferStrategy);
/**
* @dev Emitted when the reward oracle is updated
* @param reward The address of the token reward
* @param rewardOracle The address of oracle
*/
event RewardOracleUpdated(address indexed reward, address indexed rewardOracle);
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Get the price aggregator oracle address
* @param reward The address of the reward
* @return The price oracle of the reward
*/
function getRewardOracle(address reward) external view returns (address);
/**
* @dev Returns the whitelisted claimer for a certain address (0x0 if not set)
* @param user The address of the user
* @return The claimer address
*/
function getClaimer(address user) external view returns (address);
/**
* @dev Returns the Transfer Strategy implementation contract address being used for a reward address
* @param reward The address of the reward
* @return The address of the TransferStrategy contract
*/
function getTransferStrategy(address reward) external view returns (address);
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param user The address of the user
* @param userBalance The user balance of the asset
* @param totalSupply The total supply of the asset
**/
function handleAction(
address user,
uint256 userBalance,
uint256 totalSupply
) external;
/**
* @dev Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards
* @param assets List of assets to check eligible distributions before claiming rewards
* @param amount The amount of rewards to claim
* @param to The address that will be receiving the rewards
* @param reward The address of the reward token
* @return The amount of rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to,
address reward
) external returns (uint256);
/**
* @dev Claims reward for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The
* caller must be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param amount The amount of rewards to claim
* @param user The address to check and claim rewards
* @param to The address that will be receiving the rewards
* @param reward The address of the reward token
* @return The amount of rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to,
address reward
) external returns (uint256);
/**
* @dev Claims reward for msg.sender, on all the assets of the pool, accumulating the pending rewards
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param amount The amount of rewards to claim
* @param reward The address of the reward token
* @return The amount of rewards claimed
**/
function claimRewardsToSelf(
address[] calldata assets,
uint256 amount,
address reward
) external returns (uint256);
/**
* @dev Claims all rewards for a user to the desired address, on all the assets of the pool, accumulating the pending rewards
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param to The address that will be receiving the rewards
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardList"
**/
function claimAllRewards(address[] calldata assets, address to)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
/**
* @dev Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param user The address to check and claim rewards
* @param to The address that will be receiving the rewards
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList"
**/
function claimAllRewardsOnBehalf(
address[] calldata assets,
address user,
address to
) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
/**
* @dev Claims all reward for msg.sender, on all the assets of the pool, accumulating the pending rewards
* @param assets The list of assets to check eligible distributions before claiming rewards
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList"
**/
function claimAllRewardsToSelf(address[] calldata assets)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title IRewardsDistributor
* @author Aave
* @notice Defines the basic interface for a Rewards Distributor.
*/
interface IRewardsDistributorV3 {
/**
* @dev Emitted when the configuration of the rewards of an asset is updated.
* @param asset The address of the incentivized asset
* @param reward The address of the reward token
* @param oldEmission The old emissions per second value of the reward distribution
* @param newEmission The new emissions per second value of the reward distribution
* @param oldDistributionEnd The old end timestamp of the reward distribution
* @param newDistributionEnd The new end timestamp of the reward distribution
* @param assetIndex The index of the asset distribution
*/
event AssetConfigUpdated(
address indexed asset,
address indexed reward,
uint256 oldEmission,
uint256 newEmission,
uint256 oldDistributionEnd,
uint256 newDistributionEnd,
uint256 assetIndex
);
/**
* @dev Emitted when rewards of an asset are accrued on behalf of a user.
* @param asset The address of the incentivized asset
* @param reward The address of the reward token
* @param user The address of the user that rewards are accrued on behalf of
* @param assetIndex The index of the asset distribution
* @param userIndex The index of the asset distribution on behalf of the user
* @param rewardsAccrued The amount of rewards accrued
*/
event Accrued(
address indexed asset,
address indexed reward,
address indexed user,
uint256 assetIndex,
uint256 userIndex,
uint256 rewardsAccrued
);
/**
* @dev Emitted when the emission manager address is updated.
* @param oldEmissionManager The address of the old emission manager
* @param newEmissionManager The address of the new emission manager
*/
event EmissionManagerUpdated(
address indexed oldEmissionManager,
address indexed newEmissionManager
);
/**
* @dev Sets the end date for the distribution
* @param asset The asset to incentivize
* @param reward The reward token that incentives the asset
* @param newDistributionEnd The end date of the incentivization, in unix time format
**/
function setDistributionEnd(
address asset,
address reward,
uint32 newDistributionEnd
) external;
/**
* @dev Sets the emission per second of a set of reward distributions
* @param asset The asset is being incentivized
* @param rewards List of reward addresses are being distributed
* @param newEmissionsPerSecond List of new reward emissions per second
*/
function setEmissionPerSecond(
address asset,
address[] calldata rewards,
uint88[] calldata newEmissionsPerSecond
) external;
/**
* @dev Gets the end date for the distribution
* @param asset The incentivized asset
* @param reward The reward token of the incentivized asset
* @return The timestamp with the end of the distribution, in unix time format
**/
function getDistributionEnd(address asset, address reward) external view returns (uint256);
/**
* @dev Returns the index of a user on a reward distribution
* @param user Address of the user
* @param asset The incentivized asset
* @param reward The reward token of the incentivized asset
* @return The current user asset index, not including new distributions
**/
function getUserAssetIndex(
address user,
address asset,
address reward
) external view returns (uint256);
/**
* @dev Returns the configuration of the distribution reward for a certain asset
* @param asset The incentivized asset
* @param reward The reward token of the incentivized asset
* @return The index of the asset distribution
* @return The emission per second of the reward distribution
* @return The timestamp of the last update of the index
* @return The timestamp of the distribution end
**/
function getRewardsData(address asset, address reward)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
/**
* @dev Returns the list of available reward token addresses of an incentivized asset
* @param asset The incentivized asset
* @return List of rewards addresses of the input asset
**/
function getRewardsByAsset(address asset) external view returns (address[] memory);
/**
* @dev Returns the list of available reward addresses
* @return List of rewards supported in this contract
**/
function getRewardsList() external view returns (address[] memory);
/**
* @dev Returns the accrued rewards balance of a user, not including virtually accrued rewards since last distribution.
* @param user The address of the user
* @param reward The address of the reward token
* @return Unclaimed rewards, not including new distributions
**/
function getUserAccruedRewards(address user, address reward) external view returns (uint256);
/**
* @dev Returns a single rewards balance of a user, including virtually accrued and unrealized claimable rewards.
* @param assets List of incentivized assets to check eligible distributions
* @param user The address of the user
* @param reward The address of the reward token
* @return The rewards amount
**/
function getUserRewards(
address[] calldata assets,
address user,
address reward
) external view returns (uint256);
/**
* @dev Returns a list all rewards of a user, including already accrued and unrealized claimable rewards
* @param assets List of incentivized assets to check eligible distributions
* @param user The address of the user
* @return The list of reward addresses
* @return The list of unclaimed amount of rewards
**/
function getAllUserRewards(address[] calldata assets, address user)
external
view
returns (address[] memory, uint256[] memory);
/**
* @dev Returns the decimals of an asset to calculate the distribution delta
* @param asset The address to retrieve decimals
* @return The decimals of an underlying asset
*/
function getAssetDecimals(address asset) external view returns (uint8);
/**
* @dev Returns the address of the emission manager
* @return The address of the EmissionManager
*/
function getEmissionManager() external view returns (address);
/**
* @dev Updates the address of the emission manager
* @param emissionManager The address of the new EmissionManager
*/
function setEmissionManager(address emissionManager) external;
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import './utils/Withdrawable.sol';
import './utils/IWETH.sol';
/// @title ITBContract contract that implements common owner only functions accross all strategies
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract ITBContract is Withdrawable {
using SafeERC20 for IERC20;
event ApproveToken(address indexed token, address guy, uint256 wad);
address payable immutable public WNATIVE;
/// @param _executors Executor addresses
constructor(address[] memory _executors, address payable _wnative) Executable(_executors) {
WNATIVE = _wnative;
}
/// @notice Set allowance for a given token, amount and spender
/// @param _token Token to spend
/// @param _guy Spender
/// @param _wad Max amount to spend
function _approveToken(address _token, address _guy, uint256 _wad) internal {
if (_wad != 0) {
if (IERC20(_token).allowance(address(this), _guy) >= _wad)
return;
IERC20(_token).safeApprove(_guy, 0);
}
IERC20(_token).safeApprove(_guy, _wad);
emit ApproveToken(_token, _guy, _wad);
}
/// @notice Check current allowance and, if necessary, set it to a new amount for a given token, amount and spender
/// @param _token Token to spend
/// @param _guy Spender
/// @param _amount New max amount to spend
function _checkAllowanceAndApprove(address _token, address _guy, uint256 _amount) internal {
if (IERC20(_token).allowance(address(this), _guy) < _amount)
_approveToken(_token, _guy, type(uint256).max);
}
/// @notice Only owner. Set allowance for a given token, amount and spender
/// @param _token Token to spend
/// @param _guy Spender
/// @param _wad Max amount to spend
function approveToken(address _token, address _guy, uint256 _wad) external onlyOwner {
_approveToken(_token, _guy, _wad);
}
/// @notice Only owner. Revoke allowance for a given token and spender
/// @param _token Token to spend
/// @param _guy Spender
function revokeToken(address _token, address _guy) external onlyOwner {
_approveToken(_token, _guy, 0);
}
/// @notice Only owner. Execute an arbitrary call
/// @param _to Target address
/// @param _value Value (i. e. msg.value)
/// @param _data Invocation data
function execute(address _to, uint256 _value, bytes calldata _data) external payable onlyOwner {
(bool success, bytes memory returnData) = _to.call{ value: _value }(_data);
require(success, string(returnData));
}
/// @notice Only owner. Execute multiple arbitrary calls in order
/// @param _tos Target address for each call
/// @param _values Value for each call (i. e. msg.value)
/// @param _datas Invocation data for each call
function batchExecute(address[] calldata _tos, uint256[] calldata _values, bytes[] calldata _datas) external payable onlyOwner {
require(_tos.length == _values.length && _tos.length == _datas.length, "Arguments length mismatch");
for (uint256 i = 0; i < _tos.length; i++) {
(bool success, bytes memory returnData) = _tos[i].call{ value: _values[i] }(_datas[i]);
require(success, string(returnData));
}
}
function wrapNative(uint256 _amount) public onlyExecutor {
IWETH(WNATIVE).deposit{ value: _amount }();
}
function unwrapNative(uint256 _amount) public onlyExecutor {
IWETH(WNATIVE).withdraw(_amount);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface IWETH {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function balanceOf(address) external view returns (uint256);
function allowance(address, address) external view returns (uint256);
fallback() external payable;
receive() external payable;
function deposit() external payable;
function withdraw(uint256 wad) external;
function totalSupply() external view returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(address src, address dst, uint256 wad) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^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() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @dev Contract module which provides 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} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable2Step.sol";
abstract contract Ownable2StepWithShortcut is Ownable2Step {
function transferOwnership1Step(address newOwner) public onlyOwner {
require(newOwner != address(0), "ITBOwnable: zero address");
_transferOwnership(newOwner);
}
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import './BasePositionManager.sol';
/// @title PositionManager that targets Aave V2 markets
/// @author IntoTheBlock Corp
/// @notice Assembles a leveraged position using the same market for supply and borrow in Aave V2
/// @dev Deprecated, Aave now uses V3 markets
contract PositionManager is BasePositionManager {
/// @notice Mapping of underlying market to maximum leverage factor set by owner scaled by 1e18 (2x leverage: 2e18)
mapping (address => uint) public maxLFByMarket;
event Assemble(address token, uint amount, uint leverage_factor);
event Disassemble(address token, uint amount, uint leverage_factor);
event UpdatePositionConfig();
event UpdateMaxLF();
struct PositionConfig {
address underlying_token;
uint min_withdraw_step;
uint min_borrow_step;
uint leverage_factor_mantissa;
}
PositionConfig public parameters_config;
/// @param _executors Executor addresses
/// @param _wnative Wrapped native token address
/// @param _tokens Array of supported underlying markets
/// @param _max_lfs For each supported market in _tokens, maximum leverage factor set by owner scaled by 1e18
/// @param _lending_pool Aave V2 LendingPool address
/// @param _incentives_controller Aave V2 IncentivesController address
/// @param _protocol_data_provider Aave V2 ProtocolDataProvider address
/// @param _parameters_config Configuration for assemble/disassemble without parameters
constructor(
address[] memory _executors,
address payable _wnative,
address[] memory _tokens,
uint[] memory _max_lfs,
ILendingPool _lending_pool,
IAaveIncentivesController _incentives_controller,
IProtocolDataProviderV2 _protocol_data_provider,
PositionConfig memory _parameters_config
) BasePositionManager(_executors, _wnative, _lending_pool, _incentives_controller, _protocol_data_provider) {
for (uint i = 0; i < _tokens.length; i++)
updateMaxLF(_tokens[i], _max_lfs[i]);
updatePositionConfig(_parameters_config);
}
function VERSION() external pure returns (string memory) {
return "1.0.0";
}
/// @notice Only executor. Update parameters configuration.
function updatePositionConfig(PositionConfig memory _parameters_config) public onlyExecutor {
parameters_config = _parameters_config;
emit UpdatePositionConfig();
}
/* Helpers */
/// @notice Get underlyings addresses
/// @return assets all underlying assets
function getPositionAssets() public view returns (address[] memory assets) {
assets = new address[](1);
assets[0] = parameters_config.underlying_token;
}
/// @notice Get underlyings address and amounts
/// @return assets all underlying assets
/// @return amounts amounts of all underlying assets
function getUnderlyings() public view returns (address[] memory assets, uint256[] memory amounts) {
assets = getPositionAssets();
amounts = new uint[](1);
(uint supplied, uint borrowed) = accountMarketSnapshot(parameters_config.underlying_token);
amounts[0] = supplied - borrowed;
}
/// @notice Calculate liquidity and shortfall based on borrowing power (credit) and borrowed amount (debt)
/// @param _borrowing_power Borrowing power
/// @param _borrowed Borrowed amount
/// @return Liquidity (0 if undercollateralized)
/// @return Shortfall (0 if overcollateralized)
function _calculateLiquidity(uint _borrowing_power, uint _borrowed) internal pure returns (uint, uint) {
uint liquidity = _borrowing_power > _borrowed ? _borrowing_power - _borrowed : 0;
uint shortfall = _borrowing_power < _borrowed ? _borrowed - _borrowing_power : 0;
return (liquidity, shortfall);
}
/// @notice Compares after execution leverage vs max leverage factor and reverts if above max leverage factor
modifier leverageCheck(address _token) virtual {
_;
(uint supplied, uint borrowed) = accountMarketSnapshot(_token);
if (borrowed == 0)
return;
require(supplied >= borrowed, 'Dangerous LF');
uint net = supplied - borrowed;
uint max_lf_mantissa = maxLFByMarket[_token];
require(net * max_lf_mantissa / 1e18 >= supplied, 'Dangerous LF');
}
/* Infra */
/// @notice Only owner. Set maximum leverage for a given market
/// @param _token Underlying market
/// @param _max_lf Maximum leverage factor scaled by 1e18
function updateMaxLF(address _token, uint _max_lf) public onlyOwner {
maxLFByMarket[_token] = _max_lf;
emit UpdateMaxLF();
}
/* View */
/// @notice Liquidity of the position accross all markets
/// @return Liquidity (or 0 if undercollateralized)
/// @return Shortfall (or 0 if overcollateralized)
function accountLiquidity() external view returns(uint, uint) {
(, uint borrow_eth, uint borrowing_power_eth, , ,) = lending_pool.getUserAccountData(address(this));
return _calculateLiquidity(borrowing_power_eth, borrow_eth);
}
/// @notice Liquidity of the position for a given market
/// @param _token Underlying market
/// @return Liquidity (or 0 if undercollateralized)
/// @return Shortfall (or 0 if overcollateralized)
function accountMarketLiquidity(address _token) external view returns (uint, uint) {
(uint supply_amount, uint borrow_amount) = accountMarketSnapshot(_token);
uint borrowing_power = supply_amount * _getLTV(_token) / 1e18;
return _calculateLiquidity(borrowing_power, borrow_amount);
}
/// @notice Snapshot of the position accross all markets
/// @return Total supplied measured in ETH
/// @return Total borrowed measured in ETH
function accountSnapshot() external virtual view returns(uint, uint) {
(uint supply_eth, uint borrow_eth, , , ,) = lending_pool.getUserAccountData(address(this));
return (supply_eth, borrow_eth);
}
/// @notice Snapshot of the position for a given market
/// @param _token Underlying market
/// @return Total supplied measured in _token
/// @return Total borrowed measured in _token
function accountMarketSnapshot(address _token) public view returns(uint, uint) {
(address _atoken, address _stable_token, address _variable_token) = _getAaveTokens(_token);
uint supply_amount = _balance(_atoken);
uint borrow_amount;
if (_stable_token != address(0))
borrow_amount = borrow_amount + _balance(_stable_token);
if (_variable_token != address(0))
borrow_amount = borrow_amount + _balance(_variable_token);
return (supply_amount, borrow_amount);
}
/* Primitives */
/// @notice Only executor. Supply tokens to a given market
/// @param _token Underlying market
/// @param _amount Amount to supply
function deposit(address _token, uint _amount) external virtual onlyExecutor {
_deposit(_token, _amount);
}
/// @notice Only executor. Withdraw supplied tokens from a given market
/// @param _token Underlying market
/// @param _amount Amount to withdraw
function withdrawSupply(address _token, uint _amount) external virtual onlyExecutor leverageCheck(_token) {
_withdrawSupply(_token, _amount);
}
/// @notice Only executor. Withdraw all supplied tokens from a given market
/// @param _token Underlying market
function withdrawSupplyAll(address _token) public virtual onlyExecutor leverageCheck(_token) {
_withdrawSupply(_token, type(uint).max);
}
/// @notice Only executor. Borrow tokens from a given market
/// @param _token Underlying market
/// @param _amount Amount to borrow
function borrow(address _token, uint _amount) external virtual onlyExecutor leverageCheck(_token) {
_borrow(_token, _amount);
}
/// @notice Only executor. Repay debt for a given market
/// @param _token Underlying market
/// @param _amount Amount to repay
function repay(address _token, uint _amount) external virtual onlyExecutor {
_repay(_token, _amount);
}
/// @notice Only executor. Repay all debt for a given market
/// @param _token Underlying market
function repayAll(address _token) external virtual onlyExecutor {
_repayAll(_token);
}
/* Assembling */
/// @notice Only executor. Supply tokens to the market and assemble a leveraged position. Resulting leverage cant go above maxLF set by owner
/// @dev Recursively supply-borrow-supply until desired leverage is reached or supplied amount is too small to make a difference
/// @param _token Underlying market
/// @param _amount Initial amount to supply to the market. Can be 0 to increase leverage without adding external collateral
/// @param _max_leverage_factor_mantissa Desired leverage scaled to 1e18
/// @param _min_borrow_step Minimum amount of tokens to borrow/supply on each step to avoid looping with small amounts
function increaseLeverage(address _token, uint _amount, uint _max_leverage_factor_mantissa, uint _min_borrow_step) public onlyExecutor leverageCheck(_token) {
if (_amount > 0)
_deposit(_token, _amount);
(uint supply_amount, uint borrow_amount) = accountMarketSnapshot(_token);
uint net_amount = supply_amount - borrow_amount;
uint collateral_factor_mantissa = _getLTV(_token);
/*
desired borrow based on desired leverage factor and net
S = LF * net
B = S - net
nB = nS - net
nB = nLF * net - net
*/
uint desired_borrow = net_amount * _max_leverage_factor_mantissa / 1e18 - net_amount;
while (desired_borrow > borrow_amount) {
uint max_to_borrow = desired_borrow - borrow_amount;
uint approx_borrow_limit = supply_amount * collateral_factor_mantissa / 1e18;
uint approx_current_liquidity = approx_borrow_limit - borrow_amount - 10;
uint to_borrow = Math.min(max_to_borrow, approx_current_liquidity);
if (to_borrow < _min_borrow_step)
break;
_borrow(_token, to_borrow);
_deposit(_token, to_borrow);
supply_amount = supply_amount + to_borrow;
borrow_amount = borrow_amount + to_borrow;
}
(supply_amount, borrow_amount) = accountMarketSnapshot(_token);
emit Assemble(_token, _amount, _max_leverage_factor_mantissa);
}
/// @notice Only executor. Withdraw tokens to the market and disassemble a leveraged position. Resulting leverage cant go above maxLF set by owner
/// @dev Recursively withdraw supply-repay-withdraw supply until desired leverage is reached or withdrawn amount is too small to make a difference
/// @param _token Underlying market
/// @param _amount Initial amount to repay
/// @param _min_leverage_factor_mantissa Desired leverage scaled to 1e18
/// @param _min_withdraw_step Minimum amount of tokens to withdraw/repay on each step to avoid looping with small amounts
function decreaseLeverage(address _token, uint _amount, uint _min_leverage_factor_mantissa, uint _min_withdraw_step) public virtual onlyExecutor leverageCheck(_token) {
if (_amount > 0)
_repay(_token, _amount);
(uint supply_amount, uint borrow_amount) = accountMarketSnapshot(_token);
uint net_amount = supply_amount - borrow_amount;
uint collateral_factor_mantissa = _getLTV(_token);
/*
desired borrow based on desired leverage factor and net
S = LF * net
B = S - net
nB = nS - net
nB = nLF * net - net
*/
uint desired_borrow = net_amount * _min_leverage_factor_mantissa / 1e18 - net_amount;
while (desired_borrow < borrow_amount) {
uint max_to_repay = borrow_amount - desired_borrow;
uint approx_borrow_limit = supply_amount * collateral_factor_mantissa / 1e18;
uint approx_current_liquidity = approx_borrow_limit - borrow_amount - 10;
uint to_repay = Math.min(max_to_repay, approx_current_liquidity);
if (to_repay < _min_withdraw_step)
break;
_withdrawSupply(_token, to_repay);
_repay(_token, to_repay);
supply_amount = supply_amount - to_repay;
borrow_amount = borrow_amount - to_repay;
}
}
/// @notice Only executor. Disassemble all leverage and withdraw everything from supply
/// @param _token Underlying market
function fullDisassemble(address _token) public onlyExecutor {
decreaseLeverage(_token, 0, 1e18, 0);
withdrawSupplyAll(_token);
}
/* Assemble via parameters config */
/// @notice Checks if all parameters_config used in the assembly have the correct value
modifier hasConfig() {
require(parameters_config.underlying_token != address(0));
require(parameters_config.leverage_factor_mantissa >= 1e18);
_;
}
/// @notice Only executor. assemble by configuration, use all amount available
function assemble() external onlyExecutor hasConfig {
increaseLeverage(parameters_config.underlying_token, _balance(parameters_config.underlying_token), parameters_config.leverage_factor_mantissa, parameters_config.min_borrow_step);
}
/// @notice Only executor. Disassemble by configuration
/// @param _percent Amount to disassemble and withdrawSupply expressed as a percentage. 1e18 is equivalent to 100%.
function disassemble(uint _percent) public onlyExecutor hasConfig {
(uint supply_amount, uint borrow_amount) = accountMarketSnapshot(parameters_config.underlying_token);
uint initial_net = supply_amount - borrow_amount;
uint final_net = initial_net * (1e18 - _percent) / 1e18;
uint final_lf = parameters_config.leverage_factor_mantissa;
uint final_supply = final_net * final_lf / 1e18;
uint to_withdraw = initial_net - final_net;
uint temp_supply = to_withdraw + final_supply;
uint temp_leverage_factor = 1e18 * temp_supply / initial_net;
decreaseLeverage(parameters_config.underlying_token, 0, temp_leverage_factor, parameters_config.min_withdraw_step);
if (to_withdraw != 0)
_withdrawSupply(parameters_config.underlying_token, to_withdraw);
(supply_amount, borrow_amount) = accountMarketSnapshot(parameters_config.underlying_token);
uint net = supply_amount - borrow_amount;
uint lf = net != 0 ? supply_amount / net : 0;
emit Disassemble(parameters_config.underlying_token, initial_net - net /* should be same as to_withdraw */, lf);
}
/// @notice Only executor. fullDisassemble by configuration
function fullDisassemble() external onlyExecutor hasConfig {
fullDisassemble(parameters_config.underlying_token);
}
/// @notice Only executor. Claim all rewards using underlying_token from parameters_config
/// @return rewards_addresses all rewards address
/// @return claimed_amounts all amounts claimed
function claimRewards() external virtual onlyExecutor hasConfig returns (address[] memory rewards_addresses, uint[] memory claimed_amounts) {
address[] memory tokens = new address[](2);
(address atoken, , address variable_debt_token) = _getAaveTokens(parameters_config.underlying_token);
tokens[0] = atoken;
tokens[1] = variable_debt_token;
rewards_addresses = new address[](1);
claimed_amounts = new uint[](1);
rewards_addresses[0] = incentives_controller.REWARD_TOKEN();
claimed_amounts[0] = incentives_controller.claimRewards(tokens, incentives_controller.getRewardsBalance(tokens, address(this)), address(this));
}
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import './PositionManager.sol';
import './aaveV3/IRewardsControllerV3.sol';
import './aaveV3/IPool.sol';
/// @title PositionManager that targets Aave V3 markets
/// @author IntoTheBlock Corp
/// @notice Assembles a leveraged position using the same market for supply and borrow in Aave V3
contract PositionManagerV3 is PositionManager {
/// @param _executors Executor addresses
/// @param _wnative Wrapped native token address
/// @param _tokens Array of supported underlying markets
/// @param _max_lfs For each supported market in _tokens, maximum leverage factor set by owner scaled by 1e18 (2x leverage: 2e18)
/// @param _lending_pool Aave V3 LendingPool address
/// @param _incentives_controller Aave V3 RewardsController address
/// @param _protocol_data_provider Aave V3 ProtocolDataProvider address
/// @param _position_config Configuration for assemble/disassemble without parameters
constructor(address[] memory _executors, address payable _wnative, address[] memory _tokens, uint[] memory _max_lfs, ILendingPool _lending_pool, IAaveIncentivesController _incentives_controller, IProtocolDataProviderV2 _protocol_data_provider, PositionConfig memory _position_config) PositionManager(_executors, _wnative, _tokens, _max_lfs, _lending_pool, _incentives_controller, _protocol_data_provider, _position_config) {}
/* Helpers */
/// Cast inherited Aave V2 lending_pool to V3
function _v3_pool() internal view returns (IPool) {
return IPool(address(lending_pool));
}
/// Cast inherited Aave V2 incentives_controller to RewardsControllerV3
function _rewards_controller() internal view returns (IRewardsControllerV3) {
return IRewardsControllerV3(address(incentives_controller));
}
/// @notice Get the LTV of a given market taking into account current EMode category
/// @return LTV scaled to 1e18
function _getLTV(address _token) internal override view returns (uint) {
IPool v3_pool = _v3_pool();
uint current_emode_category = v3_pool.getUserEMode(address(this));
uint ltv_1e4;
if (current_emode_category == 0) {
uint mask = lending_pool.getConfiguration(_token);
ltv_1e4 = mask % 2**16;
}
else
ltv_1e4 = v3_pool.getEModeCategoryData(uint8(current_emode_category)).ltv;
return ltv_1e4 * 1e18 / 1e4;
}
/// @notice Use supply side aTokens to repay debt incurred in the same market
/// @param _token Underlying market
/// @param _amount Amount to repay
function _repayWithATokens(address _token, uint _amount) internal {
(, uint borrow_amount) = accountMarketSnapshot(_token);
if (borrow_amount != 0)
_v3_pool().repayWithATokens(_token, _amount, 2);
}
/// @notice Claim rewards in a given token for a given market and amount
/// @dev Will claim both supply and variable debt rewards
/// @param _token Underlying market
/// @param _amount Amount of _reward_address to claim
/// @param _reward_address Reward token to claim
/// @return claimed_amount claimed
function _claim_rewards(address _token, uint _amount, address _reward_address) internal returns (uint claimed_amount) {
address[] memory tokens = new address[](2);
(address atoken, , address variable_debt_token) = _getAaveTokens(_token);
tokens[0] = atoken;
tokens[1] = variable_debt_token;
uint bal_before = _balance(_reward_address);
_rewards_controller().claimRewards(tokens, _amount, address(this), _reward_address);
uint bal_after = _balance(_reward_address);
claimed_amount = bal_after - bal_before;
emit ClaimRewardsV3(_reward_address, claimed_amount);
}
/* Infra */
/// @notice Only owner. Set EMode category and update maxLFs accordingly
/// @param _category Emode category
/// @param _tokens Array of supported underlying markets to update
/// @param _max_lfs For each supported market in _tokens, maximum leverage factor scaled by 1e18 (2x leverage: 2e18)
function setEMode(uint8 _category, address[] memory _tokens, uint[] memory _max_lfs) external onlyOwner {
_v3_pool().setUserEMode(_category);
for (uint i = 0; i < _tokens.length; i++)
updateMaxLF(_tokens[i], _max_lfs[i]);
}
/* View */
/// @notice Atoken addresses for a given market
/// @param _token Underlying market
/// @return Atoken address
/// @return Stable debt address
/// @return Variable debt address
function getAaveTokens(address _token) external view returns(address, address, address) {
return _getAaveTokens(_token);
}
/* Primites */
/// @notice Only executor. Use supply side aTokens to repay debt incurred in the same market
/// @param _amount Amount to repay
function repayWithATokens(address _token, uint _amount) external onlyExecutor {
_repayWithATokens(_token, _amount);
}
/// @notice Only executor. Use supply side aTokens to repay all debt incurred in the same market
/// @param _token Underlying market
function repayAllWithATokens(address _token) external onlyExecutor {
_repayWithATokens(_token, type(uint).max);
}
/// @notice Only executor. Withdraw tokens to the market and disassemble a leveraged position. Resulting leverage cant go above maxLF set by owner
/// @dev Repay debt using supply to reach the desired leverage
/// @param _token Underlying market
/// @param _amount Initial amount to withdraw from the market
/// @param _min_leverage_factor_mantissa Desired leverage scaled to 1e18
function decreaseLeverage(address _token, uint _amount, uint _min_leverage_factor_mantissa, uint ) public override onlyExecutor leverageCheck(_token) {
if (_amount > 0)
_deposit(_token, _amount);
if (_min_leverage_factor_mantissa == 1e18) {
_repayWithATokens(_token, type(uint).max);
return;
}
(uint supply_amount, uint borrow_amount) = accountMarketSnapshot(_token);
uint net_amount = supply_amount - borrow_amount;
/*
desired borrow based on desired leverage factor and net
S = LF * net
B = S - net
nB = nS - net
nB = nLF * net - net
*/
uint desired_borrow = net_amount * _min_leverage_factor_mantissa / 1e18 - net_amount;
uint to_repay = borrow_amount - desired_borrow;
_repayWithATokens(_token, to_repay);
}
/* Rewards */
/// @notice Only executor. Claim rewards in the first reward token for a given market and amount
/// @dev Will claim both supply and variable debt rewards. Assumes only 1 reward token and atoken reward token = variable debt reward token
/// @param _token Underlying market
/// @param _amount Amount of _reward_address to claim
/// @return Amount claimed
function claimRewards(address _token, uint _amount) external override onlyExecutor returns (uint) {
(address atoken, , ) = _getAaveTokens(_token);
address[] memory rewards = _rewards_controller().getRewardsByAsset(atoken);
return _claim_rewards(_token, _amount, rewards[0]);
}
/// @notice Only executor. Claim rewards in a given token for a given market and amount
/// @dev Will claim both supply and variable debt rewards
/// @param _token Underlying market
/// @param _amount Amount of _reward_address to claim
/// @param _reward_address Reward token to claim
/// @return Amount claimed
function claimRewards(address _token, uint _amount, address _reward_address) external onlyExecutor returns (uint) {
return _claim_rewards(_token, _amount, _reward_address);
}
/// @notice Only executor. Claim rewards in all reward tokens for a given market and amount
/// @dev Will claim both supply and variable debt rewards. TODO: develop Harvester with multiple reward tokens support
/// @param _token Underlying market
function claimAllRewards(address _token) public onlyExecutor returns (address[] memory reward_addresses, uint[] memory claimed_amounts) {
address[] memory tokens = new address[](2);
(address atoken, , address variable_debt_token) = _getAaveTokens(_token);
tokens[0] = atoken;
tokens[1] = variable_debt_token;
return _rewards_controller().claimAllRewards(tokens, address(this));
}
/// @notice Only executor. Claim all rewards using underlying_token from parameters_config
/// @return rewards_addresses all rewards address
/// @return claimed_amounts all amounts claimed
function claimRewards() public override onlyExecutor returns (address[] memory rewards_addresses, uint[] memory claimed_amounts) {
return claimAllRewards(parameters_config.underlying_token);
}
}
/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;
import './PositionManagerV3.sol';
import '@itb/quant-common/contracts/solidity8/utils/Ownable2StepWithShortcut.sol';
contract PositionManagerV3Ownable2StepWithShortcut is PositionManagerV3, Ownable2StepWithShortcut {
constructor(address[] memory _executors, address payable _wnative, address[] memory _tokens, uint[] memory _max_lfs, ILendingPool _lending_pool, IAaveIncentivesController _incentives_controller, IProtocolDataProviderV2 _protocol_data_provider, PositionConfig memory _position_config) PositionManagerV3(_executors, _wnative, _tokens, _max_lfs, _lending_pool, _incentives_controller, _protocol_data_provider, _position_config) {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.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 Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
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'
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));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// 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 cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import './Executable.sol';
/**
Ensures that any contract that inherits from this contract is able to
withdraw funds that are accidentally received or stuck.
*/
/// @title Base contract that implements withdrawal related functions
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract Withdrawable is Executable {
using SafeERC20 for IERC20;
address constant ETHER = address(0);
event LogWithdraw(
address indexed _to,
address indexed _asset_address,
uint256 amount
);
receive() external payable {}
/// @notice ERC20 or ETH balance of this contract given a token address
/// @param _asset_address Token address or address(0) for ETH
/// @return Balance
function _balance(address _asset_address) internal view returns (uint256) {
return _asset_address == ETHER ? address(this).balance : IERC20(_asset_address).balanceOf(address(this));
}
/// @notice ERC20 balance of given account
/// @param _asset_address Token address
/// @param _account Account address
/// @return Balance
function balanceOf(address _asset_address, address _account) public view returns (uint256) {
return IERC20(_asset_address).balanceOf(_account);
}
/// @notice Send the given amount of the given token or ETH to the given receiver
/// @param _asset_address Token address or address(0) for ETH
/// @param _amount Amount to send
/// @param _to Receiver address
function _withdraw_to(address _asset_address, uint256 _amount, address payable _to) internal {
require(_to != address(0), 'Invalid address');
uint256 balance = _balance(_asset_address);
require(balance >= _amount, 'Insufficient funds');
if (_asset_address == ETHER) {
(bool success, ) = _to.call{value: _amount}(''); /* carry gas over so it works with contracts with custom fallback, we dont care about reentrancy on onlyOwner */
require(success, 'Native transfer failed.');
} else
IERC20(_asset_address).safeTransfer(_to, _amount);
emit LogWithdraw(_to, _asset_address, _amount);
}
/// @notice Only owner. Send the given amount of the given token or ETH to the caller
/// @param _asset_address Token address or address(0) for ETH
/// @param _amount Amount to send
function withdraw(address _asset_address, uint256 _amount) external onlyOwner {
_withdraw_to(_asset_address, _amount, payable(msg.sender));
}
/// @notice Only owner. Send the given amount of the given token or ETH to the given receiver
/// @param _asset_address Token address or address(0) for ETH
/// @param _amount Amount to send
/// @param _to Receiver address
function withdrawTo(address _asset_address, uint256 _amount, address payable _to) external onlyOwner {
_withdraw_to(_asset_address, _amount, _to);
}
/// @notice Only owner. Send its entire balance of the given token or ETH to the caller
/// @param _asset_address Token address or address(0) for ETH
function withdrawAll(address _asset_address) external onlyOwner {
uint256 balance = _balance(_asset_address);
_withdraw_to(_asset_address, balance, payable(msg.sender));
}
/// @notice Only owner. Send its entire balance of the given token or ETH to the given receiver
/// @param _asset_address Token address or address(0) for ETH
/// @param _to Receiver address
function withdrawAllTo(address _asset_address, address payable _to) external onlyOwner {
uint256 balance = _balance(_asset_address);
_withdraw_to(_asset_address, balance, _to);
}
}
{
"compilationTarget": {
"contracts/PositionManagerV3Ownable2StepWithShortcut.sol": "PositionManagerV3Ownable2StepWithShortcut"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 20
},
"remappings": []
}
[{"inputs":[{"internalType":"address[]","name":"_executors","type":"address[]"},{"internalType":"address payable","name":"_wnative","type":"address"},{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_max_lfs","type":"uint256[]"},{"internalType":"contract ILendingPool","name":"_lending_pool","type":"address"},{"internalType":"contract IAaveIncentivesController","name":"_incentives_controller","type":"address"},{"internalType":"contract IProtocolDataProviderV2","name":"_protocol_data_provider","type":"address"},{"components":[{"internalType":"address","name":"underlying_token","type":"address"},{"internalType":"uint256","name":"min_withdraw_step","type":"uint256"},{"internalType":"uint256","name":"min_borrow_step","type":"uint256"},{"internalType":"uint256","name":"leverage_factor_mantissa","type":"uint256"}],"internalType":"struct PositionManager.PositionConfig","name":"_position_config","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"guy","type":"address"},{"indexed":false,"internalType":"uint256","name":"wad","type":"uint256"}],"name":"ApproveToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"leverage_factor","type":"uint256"}],"name":"Assemble","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ClaimRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"reward","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ClaimRewardsV3","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"leverage_factor","type":"uint256"}],"name":"Disassemble","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"executor","type":"address"},{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"ExecutorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_to","type":"address"},{"indexed":true,"internalType":"address","name":"_asset_address","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"LogWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Repay","type":"event"},{"anonymous":false,"inputs":[],"name":"UpdateIncentivesController","type":"event"},{"anonymous":false,"inputs":[],"name":"UpdateLendingPool","type":"event"},{"anonymous":false,"inputs":[],"name":"UpdateMaxLF","type":"event"},{"anonymous":false,"inputs":[],"name":"UpdatePositionConfig","type":"event"},{"anonymous":false,"inputs":[],"name":"UpdateProtocolDataProvider","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"WNATIVE","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accountLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"accountMarketLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"accountMarketSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accountSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_executor","type":"address"}],"name":"addExecutor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_guy","type":"address"},{"internalType":"uint256","name":"_wad","type":"uint256"}],"name":"approveToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"assemble","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset_address","type":"address"},{"internalType":"address","name":"_account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tos","type":"address[]"},{"internalType":"uint256[]","name":"_values","type":"uint256[]"},{"internalType":"bytes[]","name":"_datas","type":"bytes[]"}],"name":"batchExecute","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"borrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"claimAllRewards","outputs":[{"internalType":"address[]","name":"reward_addresses","type":"address[]"},{"internalType":"uint256[]","name":"claimed_amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimRewards","outputs":[{"internalType":"address[]","name":"rewards_addresses","type":"address[]"},{"internalType":"uint256[]","name":"claimed_amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_reward_address","type":"address"}],"name":"claimRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"claimRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_min_leverage_factor_mantissa","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"decreaseLeverage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_percent","type":"uint256"}],"name":"disassemble","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"execute","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"executors","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"fullDisassemble","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fullDisassemble","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getAaveTokens","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPositionAssets","outputs":[{"internalType":"address[]","name":"assets","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnderlyings","outputs":[{"internalType":"address[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"incentives_controller","outputs":[{"internalType":"contract IAaveIncentivesController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_max_leverage_factor_mantissa","type":"uint256"},{"internalType":"uint256","name":"_min_borrow_step","type":"uint256"}],"name":"increaseLeverage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lending_pool","outputs":[{"internalType":"contract ILendingPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxLFByMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"parameters_config","outputs":[{"internalType":"address","name":"underlying_token","type":"address"},{"internalType":"uint256","name":"min_withdraw_step","type":"uint256"},{"internalType":"uint256","name":"min_borrow_step","type":"uint256"},{"internalType":"uint256","name":"leverage_factor_mantissa","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocol_data_provider","outputs":[{"internalType":"contract IProtocolDataProviderV2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_executor","type":"address"}],"name":"removeExecutor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"repay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"repayAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"repayAllWithATokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"repayWithATokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_guy","type":"address"}],"name":"revokeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"_category","type":"uint8"},{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_max_lfs","type":"uint256[]"}],"name":"setEMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership1Step","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"unwrapNative","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IAaveIncentivesController","name":"_address","type":"address"}],"name":"updateIncentivesController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ILendingPool","name":"_address","type":"address"}],"name":"updateLendingPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_max_lf","type":"uint256"}],"name":"updateMaxLF","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"underlying_token","type":"address"},{"internalType":"uint256","name":"min_withdraw_step","type":"uint256"},{"internalType":"uint256","name":"min_borrow_step","type":"uint256"},{"internalType":"uint256","name":"leverage_factor_mantissa","type":"uint256"}],"internalType":"struct PositionManager.PositionConfig","name":"_parameters_config","type":"tuple"}],"name":"updatePositionConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IProtocolDataProviderV2","name":"_address","type":"address"}],"name":"updateProtocolDataProvider","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset_address","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset_address","type":"address"}],"name":"withdrawAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset_address","type":"address"},{"internalType":"address payable","name":"_to","type":"address"}],"name":"withdrawAllTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdrawSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"withdrawSupplyAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset_address","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address payable","name":"_to","type":"address"}],"name":"withdrawTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"wrapNative","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]