Feature Tip: Add private address tag to any address under My Name Tag !
More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 14 from a total of 14 transactions
| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
| Tend | 24574636 | 20 days ago | IN | 0 ETH | 0.00002437 | ||||
| Deposit | 24574594 | 20 days ago | IN | 0 ETH | 0.00000535 | ||||
| Set Allowed | 24574582 | 20 days ago | IN | 0 ETH | 0.00000145 | ||||
| Set Allowed | 24574548 | 20 days ago | IN | 0 ETH | 0.0000016 | ||||
| Set Pending Mana... | 24574546 | 20 days ago | IN | 0 ETH | 0.00000102 | ||||
| Set Emergency Ad... | 24574544 | 20 days ago | IN | 0 ETH | 0.00000109 | ||||
| Set Performance ... | 24574541 | 20 days ago | IN | 0 ETH | 0.00000103 | ||||
| Set Max Gas Pric... | 24574534 | 20 days ago | IN | 0 ETH | 0.00000111 | ||||
| Set Profit Max U... | 24574515 | 20 days ago | IN | 0 ETH | 0.00000129 | ||||
| Set Performance ... | 24574514 | 20 days ago | IN | 0 ETH | 0.00000105 | ||||
| Set Performance ... | 24574512 | 20 days ago | IN | 0 ETH | 0.00000112 | ||||
| Set Pending Mana... | 24574511 | 20 days ago | IN | 0 ETH | 0.0000017 | ||||
| Set Emergency Ad... | 24574510 | 20 days ago | IN | 0 ETH | 0.00000158 | ||||
| Set Keeper | 24574508 | 20 days ago | IN | 0 ETH | 0.00000107 |
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
Contract Name:
AaveLooper
Compiler Version
v0.8.23+commit.f704f362
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BaseLooper} from "../BaseLooper.sol";
import {IPool} from "../interfaces/aave/IPool.sol";
import {IPoolDataProvider} from "../interfaces/aave/IPoolDataProvider.sol";
import {IPoolAddressesProvider} from "../interfaces/aave/IPoolAddressesProvider.sol";
import {IAaveOracle} from "../interfaces/aave/IAaveOracle.sol";
import {IRewardsController} from "../interfaces/aave/IRewardsController.sol";
import {IAToken} from "../interfaces/aave/IAToken.sol";
import {IMorpho} from "../interfaces/morpho/IMorpho.sol";
import {IMorphoFlashLoanCallback} from "../interfaces/morpho/IMorphoFlashLoanCallback.sol";
import {AuctionSwapper} from "@periphery/swappers/AuctionSwapper.sol";
/**
* @title AaveLooper
* @notice Aave V3 specific looper implementation.
* Exchange conversion logic is inherited from BaseLooper.
*/
contract AaveLooper is BaseLooper, IMorphoFlashLoanCallback, AuctionSwapper {
using SafeERC20 for ERC20;
/// @notice Interest rate mode: 2 = variable rate
uint256 internal constant VARIABLE_RATE_MODE = 2;
/// @notice Referral code (0 for no referral)
uint16 internal constant REFERRAL_CODE = 0;
/// @notice Morpho flashloan provider
IMorpho public immutable MORPHO;
/// @notice Aave V3 Pool
address public immutable POOL;
/// @notice Aave V3 Data Provider
IPoolDataProvider public immutable DATA_PROVIDER;
/// @notice Aave V3 Oracle
IAaveOracle public immutable AAVE_ORACLE;
/// @notice Aave V3 Rewards Controller
IRewardsController public immutable REWARDS_CONTROLLER;
/// @notice aToken address for collateral
address public immutable A_TOKEN;
/// @notice Variable debt token address for the asset (borrow token)
address public immutable VARIABLE_DEBT_TOKEN;
/// @notice Cached decimals for collateral token
uint256 internal immutable COLLATERAL_DECIMALS;
/// @notice Cached decimals for asset token
uint256 internal immutable ASSET_DECIMALS;
/// @notice E-Mode category ID (0 = no eMode)
uint8 public immutable E_MODE_CATEGORY_ID;
/// @notice Flashloan reentrancy guard
bool internal isFlashloanActive;
constructor(
address _asset,
string memory _name,
address _collateralToken,
address _addressesProvider,
address _morpho,
uint8 _eModeCategoryId,
address _exchange,
address _governance
) BaseLooper(_asset, _name, _collateralToken, _governance, _exchange) {
MORPHO = IMorpho(_morpho);
POOL = IPoolAddressesProvider(_addressesProvider).getPool();
DATA_PROVIDER = IPoolDataProvider(
IPoolAddressesProvider(_addressesProvider).getPoolDataProvider()
);
AAVE_ORACLE = IAaveOracle(
IPoolAddressesProvider(_addressesProvider).getPriceOracle()
);
// Get aToken address for collateral
(address _aToken, , ) = DATA_PROVIDER.getReserveTokensAddresses(
_collateralToken
);
A_TOKEN = _aToken;
// Get rewards controller from the aToken
REWARDS_CONTROLLER = IRewardsController(
IAToken(_aToken).getIncentivesController()
);
// Get aToken and variable debt token for the asset (borrow token)
(, , address _variableDebtToken) = DATA_PROVIDER
.getReserveTokensAddresses(_asset);
VARIABLE_DEBT_TOKEN = _variableDebtToken;
// Cache decimals to avoid repeated external calls
COLLATERAL_DECIMALS = ERC20(_collateralToken).decimals();
ASSET_DECIMALS = ERC20(_asset).decimals();
// Set E-Mode category for better capital efficiency on correlated assets
E_MODE_CATEGORY_ID = _eModeCategoryId;
if (_eModeCategoryId != 0) {
IPool(POOL).setUserEMode(_eModeCategoryId);
}
// Approve pool for asset and collateral
ERC20(_asset).forceApprove(POOL, type(uint256).max);
ERC20(_collateralToken).forceApprove(POOL, type(uint256).max);
// Approve Morpho for flashloan repayment
ERC20(_asset).forceApprove(_morpho, type(uint256).max);
}
/*//////////////////////////////////////////////////////////////
FLASHLOAN IMPLEMENTATION
//////////////////////////////////////////////////////////////*/
/// @notice Execute flashloan through Morpho
function _executeFlashloan(
address token,
uint256 amount,
bytes memory data
) internal override {
isFlashloanActive = true;
MORPHO.flashLoan(token, amount, data);
isFlashloanActive = false;
}
/// @notice Morpho flashloan callback - CRITICAL SECURITY FUNCTION
/// @dev Only callable by Morpho during flashLoan execution
function onMorphoFlashLoan(
uint256 assets,
bytes calldata data
) external override {
require(msg.sender == address(MORPHO), "!morpho");
require(isFlashloanActive, "!flashloan active");
_onFlashloanReceived(assets, data);
}
/// @notice Max available flashloan from Morpho
function maxFlashloan() public view override returns (uint256) {
return asset.balanceOf(address(MORPHO));
}
/*//////////////////////////////////////////////////////////////
ORACLE IMPLEMENTATION
//////////////////////////////////////////////////////////////*/
/// @notice Get oracle price (loan token value per 1 collateral token, 1e36 scale)
/// @dev Aave oracle returns prices in BASE_CURRENCY_UNIT (usually USD with 8 decimals)
/// We need to return collateral/asset price ratio in 1e36 scale
function _getCollateralPrice()
internal
view
virtual
override
returns (uint256)
{
uint256 collateralPrice = AAVE_ORACLE.getAssetPrice(collateralToken);
uint256 assetPrice = AAVE_ORACLE.getAssetPrice(address(asset));
if (assetPrice == 0) return 0;
// Both prices are in same denomination (USD), compute ratio
// Adjust for decimal differences between collateral and asset
// price = (collateralPrice * 10^assetDecimals * ORACLE_PRICE_SCALE) /
// (assetPrice * 10^collateralDecimals)
return
(collateralPrice * (10 ** ASSET_DECIMALS) * ORACLE_PRICE_SCALE) /
(assetPrice * (10 ** COLLATERAL_DECIMALS));
}
/*//////////////////////////////////////////////////////////////
AAVE PROTOCOL OPERATIONS
//////////////////////////////////////////////////////////////*/
function _supplyCollateral(uint256 amount) internal override {
if (amount == 0) return;
IPool(POOL).supply(
collateralToken,
amount,
address(this),
REFERRAL_CODE
);
// Enable as collateral (idempotent - safe to call multiple times)
IPool(POOL).setUserUseReserveAsCollateral(collateralToken, true);
}
function _withdrawCollateral(uint256 amount) internal override {
if (amount == 0) return;
IPool(POOL).withdraw(collateralToken, amount, address(this));
}
function _borrow(uint256 amount) internal virtual override {
if (amount == 0) return;
IPool(POOL).borrow(
address(asset),
amount,
VARIABLE_RATE_MODE,
REFERRAL_CODE,
address(this)
);
}
function _repay(uint256 amount) internal virtual override {
if (amount == 0) return;
IPool(POOL).repay(
address(asset),
amount,
VARIABLE_RATE_MODE,
address(this)
);
}
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
function _isSupplyPaused() internal view virtual override returns (bool) {
return DATA_PROVIDER.getPaused(collateralToken);
}
function _isBorrowPaused() internal view virtual override returns (bool) {
bool isPaused = DATA_PROVIDER.getPaused(address(asset));
if (isPaused) return true;
// Also check if borrowing is enabled and not frozen
(, , , , , , bool borrowingEnabled, , , bool isFrozen) = DATA_PROVIDER
.getReserveConfigurationData(address(asset));
return isFrozen || !borrowingEnabled;
}
function _isLiquidatable() internal view virtual override returns (bool) {
(, , , , , uint256 healthFactor) = IPool(POOL).getUserAccountData(
address(this)
);
// Health factor < 1e18 means liquidatable
return healthFactor < 1e18 && healthFactor > 0;
}
function _maxCollateralDeposit()
internal
view
virtual
override
returns (uint256)
{
(, uint256 supplyCap) = DATA_PROVIDER.getReserveCaps(collateralToken);
if (supplyCap == 0) return type(uint256).max;
uint256 currentSupply = DATA_PROVIDER.getATokenTotalSupply(
collateralToken
);
uint256 supplyCapInTokens = supplyCap * (10 ** COLLATERAL_DECIMALS);
return
supplyCapInTokens > currentSupply
? supplyCapInTokens - currentSupply
: 0;
}
function _maxBorrowAmount()
internal
view
virtual
override
returns (uint256)
{
uint256 virtualLiquidity = IPool(POOL).getVirtualUnderlyingBalance(
address(asset)
);
(uint256 borrowCap, ) = DATA_PROVIDER.getReserveCaps(address(asset));
if (borrowCap == 0) {
// No cap, bounded by virtual liquidity.
return virtualLiquidity;
}
uint256 currentDebt = DATA_PROVIDER.getTotalDebt(address(asset));
uint256 borrowCapInTokens = borrowCap * (10 ** ASSET_DECIMALS);
uint256 borrowCapRemaining = borrowCapInTokens > currentDebt
? borrowCapInTokens - currentDebt
: 0;
return
borrowCapRemaining < virtualLiquidity
? borrowCapRemaining
: virtualLiquidity;
}
function getLiquidateCollateralFactor()
public
view
virtual
override
returns (uint256)
{
(, , uint256 liquidationThreshold, , , , , , , ) = DATA_PROVIDER
.getReserveConfigurationData(collateralToken);
// Aave returns in basis points (10000 = 100%), convert to WAD
return liquidationThreshold * 1e14; // 10000 * 1e14 = 1e18
}
function balanceOfCollateral()
public
view
virtual
override
returns (uint256)
{
return ERC20(A_TOKEN).balanceOf(address(this));
}
function balanceOfDebt() public view virtual override returns (uint256) {
return ERC20(VARIABLE_DEBT_TOKEN).balanceOf(address(this));
}
/*//////////////////////////////////////////////////////////////
REWARDS
//////////////////////////////////////////////////////////////*/
/// @notice Claim all rewards from Aave incentives controller
function _claimAndSellRewards() internal virtual override {
address[] memory assets = new address[](2);
assets[0] = A_TOKEN;
assets[1] = VARIABLE_DEBT_TOKEN;
// Claim all rewards to this contract
REWARDS_CONTROLLER.claimAllRewardsToSelf(assets);
}
function setAuction(address _auction) external onlyManagement {
_setAuction(_auction);
}
function setUseAuction(bool _useAuction) external onlyManagement {
_setUseAuction(_useAuction);
}
function kickAuction(
address _token
) external override onlyKeepers returns (uint256) {
return _kickAuction(_token);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}// 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: GPL-3.0
pragma solidity ^0.8.18;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BaseHealthCheck, ERC20} from "@periphery/Bases/HealthCheck/BaseHealthCheck.sol";
import {IExchange} from "./interfaces/IExchange.sol";
/**
* @title BaseLooper
* @notice Shared leverage-looping logic using flashloans exclusively.
* Uses a fixed leverage ratio system with flashloan-based operations.
* Since asset == borrowToken, pricing uses a single oracle for collateral/asset conversion.
* Inheritors implement protocol specific hooks for flashloans, supplying collateral,
* borrowing, repaying, and oracle access.
*/
abstract contract BaseLooper is BaseHealthCheck {
using SafeERC20 for ERC20;
modifier onlyGovernance() {
require(msg.sender == GOVERNANCE, "!governance");
_;
}
/// @notice Accrue interest before state changing functions
modifier accrue() {
_accrueInterest();
_;
}
uint256 internal constant WAD = 1e18;
uint256 internal constant ORACLE_PRICE_SCALE = 1e36;
/// @notice Flashloan operation types
enum FlashLoanOperation {
LEVERAGE, // Deposit flow: increase leverage
DELEVERAGE // Withdraw flow: decrease leverage
}
/// @notice Data passed through flashloan callback
struct FlashLoanData {
FlashLoanOperation operation;
uint256 amount; // Amount to deploy or free (in asset terms)
}
/// @notice Governance address allowed to update exchange configuration.
address public immutable GOVERNANCE;
/// @notice Slippage tolerance (in basis points) for swaps.
uint64 public slippage;
/// @notice Exchange address
address public exchange;
/// @notice The timestamp of the last tend.
uint256 public lastTend;
/// @notice The amount to discount collateral by in reports in basis points.
uint256 public reportBuffer;
/// @notice The minimum interval between tends.
uint256 public minTendInterval;
/// @notice The maximum amount of asset that can be deposited
uint256 public depositLimit;
/// @notice Maximum amount of asset to swap in a single tend
uint256 public maxAmountToSwap;
/// @notice Buffer tolerance in WAD (e.g., 0.5e18 = +/- 0.5x triggers tend)
/// @dev Bounds are [targetLeverageRatio - buffer, targetLeverageRatio + buffer]
uint256 public leverageBuffer;
/// @notice Maximum leverage ratio in WAD (e.g., 10e18 = 10x leverage)
/// Will trigger a tend if the current leverage ratio exceeds this value.
uint256 public maxLeverageRatio;
/// @notice Target leverage ratio in WAD (e.g., 3e18 = 3x leverage)
/// @dev leverage = collateralValue / (collateralValue - debtValue) = 1 / (1 - LTV)
uint256 public targetLeverageRatio;
/// The max the base fee (in gwei) will be for a tend.
uint256 public maxGasPriceToTend;
/// Lower limit on flashloan size.
uint256 public minAmountToBorrow;
/// The token posted as collateral in the loop.
address public immutable collateralToken;
mapping(address => bool) public allowed;
constructor(
address _asset,
string memory _name,
address _collateralToken,
address _governance,
address _exchange
) BaseHealthCheck(_asset, _name) {
require(_governance != address(0), "!governance");
collateralToken = _collateralToken;
GOVERNANCE = _governance;
depositLimit = type(uint256).max;
// Allow self so we can use availableDepositLimit() to get the max deposit amount.
allowed[address(this)] = true;
// Leverage ratio defaults: 3x target, 0.5x buffer
targetLeverageRatio = 3e18;
leverageBuffer = 0.25e18;
maxLeverageRatio = 4e18;
minTendInterval = 2 hours;
maxAmountToSwap = type(uint256).max;
maxGasPriceToTend = 200 * 1e9;
slippage = 30;
_setLossLimitRatio(10);
_setProfitLimitRatio(1_000);
if (_exchange != address(0)) {
_setExchange(_exchange);
}
}
function version() public pure virtual returns (string memory) {
return "1.0.1";
}
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
/// @notice Set the maximum total assets the strategy can accept.
/// @dev This gates new deposits via `availableDepositLimit`; it does not force an unwind if current assets already exceed the new cap.
/// @param _depositLimit New deposit limit in asset units.
function setDepositLimit(uint256 _depositLimit) external onlyManagement {
depositLimit = _depositLimit;
}
/// @notice Allow or disallow an address for privileged strategy interactions.
/// @dev `availableDepositLimit` returns 0 for addresses not allowlisted, so disabling an address blocks fresh deposits from that caller.
/// @param _address Address to update.
/// @param _allowed Whether the address is allowed.
function setAllowed(
address _address,
bool _allowed
) external onlyManagement {
allowed[_address] = _allowed;
}
/// @notice Configure leverage targeting and safety bounds.
/// @dev Setting target to 0 disables leverage targeting and requires buffer = 0;
/// max leverage is also constrained below protocol liquidation threshold.
/// @param _targetLeverageRatio Target leverage ratio in WAD (1e18 = 1x).
/// @param _leverageBuffer Allowed deviation from target leverage in WAD.
/// @param _maxLeverageRatio Hard max leverage ratio in WAD.
function setLeverageParams(
uint256 _targetLeverageRatio,
uint256 _leverageBuffer,
uint256 _maxLeverageRatio
) external onlyManagement {
_setLeverageParams(
_targetLeverageRatio,
_leverageBuffer,
_maxLeverageRatio
);
}
function _setLeverageParams(
uint256 _targetLeverageRatio,
uint256 _leverageBuffer,
uint256 _maxLeverageRatio
) internal virtual {
if (_targetLeverageRatio == 0) {
require(_leverageBuffer == 0, "buffer must be 0 if target is 0");
} else {
require(_targetLeverageRatio >= WAD, "leverage < 1x");
require(_leverageBuffer >= 0.01e18, "buffer too small");
require(_targetLeverageRatio > _leverageBuffer, "target < buffer");
}
require(
_maxLeverageRatio >= _targetLeverageRatio + _leverageBuffer,
"max leverage < target + buffer"
);
// Ensure max leverage doesn't exceed LLTV
uint256 maxLTV = WAD - (WAD * WAD) / _maxLeverageRatio;
require(maxLTV < getLiquidateCollateralFactor(), "exceeds LLTV");
targetLeverageRatio = _targetLeverageRatio;
leverageBuffer = _leverageBuffer;
maxLeverageRatio = _maxLeverageRatio;
}
/// @notice Set the maximum base fee accepted for keeper tending.
/// @dev This only affects `_tendTrigger` keepers; it does not block management/emergency operations.
/// @param _maxGasPriceToTend Max acceptable `block.basefee`.
function setMaxGasPriceToTend(
uint256 _maxGasPriceToTend
) external onlyManagement {
maxGasPriceToTend = _maxGasPriceToTend;
}
/// @notice Set swap slippage tolerance used for min amount out checks.
/// @dev Applied to both asset->collateral and collateral->asset swaps; value is in BPS and must be strictly less than `MAX_BPS`.
/// @param _slippage Slippage in basis points.
function setSlippage(uint256 _slippage) external onlyManagement {
require(_slippage < MAX_BPS, "slippage");
slippage = uint64(_slippage);
}
/// @notice Set the report buffer used when accounting for assets.
/// @dev `estimatedTotalAssets` discounts collateral value by this BPS amount,
/// so increasing it makes reported assets more conservative.
/// @param _reportBuffer Buffer in basis points.
function setReportBuffer(uint256 _reportBuffer) external onlyManagement {
require(_reportBuffer < MAX_BPS, "buffer");
reportBuffer = _reportBuffer;
}
/// @notice Set the minimum debt amount required to execute borrow/deleverage ops.
/// @dev If set too high, small rebalance operations are skipped and leverage can drift until a larger adjustment is possible.
/// @param _minAmountToBorrow Minimum amount in asset units.
function setMinAmountToBorrow(
uint256 _minAmountToBorrow
) external onlyManagement {
minAmountToBorrow = _minAmountToBorrow;
}
/// @notice Set the minimum interval between automated tend operations.
/// @dev This throttles routine keeper tending after checks pass;
/// it does not bypass hard risk checks like liquidation/max leverage triggers.
/// @param _minTendInterval Minimum delay in seconds.
function setMinTendInterval(
uint256 _minTendInterval
) external onlyManagement {
minTendInterval = _minTendInterval;
}
/// @notice Set the max asset amount that can be swapped in one rebalance path.
/// @dev Caps `_amount + flashloanAmount` during lever-up;
/// lower values reduce execution size but can leave idle assets and under-target leverage.
/// @param _maxAmountToSwap Maximum swap amount in asset units.
function setMaxAmountToSwap(
uint256 _maxAmountToSwap
) external onlyManagement {
maxAmountToSwap = _maxAmountToSwap;
}
/// @notice Set the exchange contract used for asset/collateral swaps.
/// @dev Resets token approvals on the old exchange and grants max approvals to the new one;
/// new exchange must support expected swap paths.
/// @param _exchange New exchange address.
function setExchange(address _exchange) external onlyGovernance {
_setExchange(_exchange);
}
function _setExchange(address _exchange) internal virtual {
require(_exchange != address(0), "!exchange");
address oldExchange = exchange;
if (oldExchange != address(0)) {
asset.forceApprove(oldExchange, 0);
ERC20(collateralToken).forceApprove(oldExchange, 0);
}
exchange = _exchange;
asset.forceApprove(_exchange, type(uint256).max);
ERC20(collateralToken).forceApprove(_exchange, type(uint256).max);
}
/*//////////////////////////////////////////////////////////////
NEEDED TO BE OVERRIDDEN BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/// @notice Deploy funds into the leveraged position
/// @dev Override to customize deployment behavior. Default is no-op (funds deployed via _harvestAndReport).
/// Called by TokenizedStrategy when deposits are made.
/// @param _amount The amount of asset to deploy
function _deployFunds(uint256 _amount) internal virtual override accrue {}
/// @notice Free funds from the leveraged position for withdrawal
/// @dev Override to customize withdrawal behavior. Default deleverages the position.
/// Called by TokenizedStrategy when withdrawals are requested.
/// @param _amount The amount of asset to free
function _freeFunds(uint256 _amount) internal virtual override accrue {
_withdrawFunds(_amount);
}
/// @notice Harvest rewards and report total assets
/// @dev Override to customize harvesting behavior. Default claims rewards, levers up idle assets,
/// and reports total assets. Called during strategy reports.
/// @return _totalAssets The total assets held by the strategy
function _harvestAndReport()
internal
virtual
override
accrue
returns (uint256 _totalAssets)
{
_claimAndSellRewards();
_lever(
Math.min(balanceOfAsset(), availableDepositLimit(address(this)))
);
_totalAssets = estimatedTotalAssets();
}
/// @notice Calculate the estimated total assets of the strategy
/// @dev Override to customize asset calculation. Default returns loose assets + collateral value - debt.
/// @return The estimated total assets in asset token terms
function estimatedTotalAssets() public view virtual returns (uint256) {
// Collateral value discounted by the report buffer.
uint256 collateralValue = (_collateralToAsset(
balanceOfCollateral() + balanceOfCollateralToken()
) * (MAX_BPS - reportBuffer)) / MAX_BPS;
return balanceOfAsset() + collateralValue - balanceOfDebt();
}
/*//////////////////////////////////////////////////////////////
OPTIONAL TO OVERRIDE BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/// @notice Calculate the maximum amount that can be deposited by an address
/// @dev Override to customize deposit limits. Default checks allowlist, pause states,
/// deposit limit, collateral capacity, and borrow capacity.
/// @param _owner The address attempting to deposit
/// @return The maximum amount that can be deposited
function availableDepositLimit(
address _owner
) public view virtual override returns (uint256) {
if (!allowed[_owner]) return 0;
if (_isSupplyPaused() || _isBorrowPaused()) return 0;
if (targetLeverageRatio <= WAD) return 0;
uint256 _depositLimit = depositLimit;
if (_depositLimit == type(uint256).max) {
return type(uint256).max;
}
uint256 totalAssets = TokenizedStrategy.totalAssets();
return _depositLimit > totalAssets ? _depositLimit - totalAssets : 0;
}
/// @notice Calculate the maximum amount that can be withdrawn by an address
/// @dev Override to customize withdraw limits. Default returns max uint256 if flashloan covers debt,
/// otherwise calculates based on flashloan availability and target leverage.
/// The owner parameter is unused in default implementation.
/// @return The maximum amount that can be withdrawn
function availableWithdrawLimit(
address /*_owner*/
) public view virtual override returns (uint256) {
uint256 currentDebt = balanceOfDebt();
uint256 flashloanAvailable = maxFlashloan();
if (flashloanAvailable >= currentDebt) return type(uint256).max;
// If target leverage ratio is 1 or 0 and we cant repay the debt, we cant withdraw yet.
if (targetLeverageRatio <= WAD) return 0;
// Limited by flashloan: calculate max withdrawable
// When debtToRepay is capped at maxFlashloan:
// targetDebt = currentDebt - maxFlashloan
// targetEquity = targetDebt * WAD / (L - WAD)
// maxWithdraw = currentEquity - targetEquity
uint256 targetDebt = currentDebt - flashloanAvailable;
uint256 targetEquity = (targetDebt * WAD) / (targetLeverageRatio - WAD);
(uint256 collateralValue, ) = position();
uint256 currentEquity = collateralValue - currentDebt;
return currentEquity > targetEquity ? currentEquity - targetEquity : 0;
}
/// @notice Rebalance the position to maintain target leverage
/// @dev Override to customize rebalancing behavior. Default levers up with idle assets and updates lastTend.
/// Called by keepers when _tendTrigger returns true.
/// @param _totalIdle The total idle assets available for deployment
function _tend(uint256 _totalIdle) internal virtual override accrue {
_lever(_totalIdle);
lastTend = block.timestamp;
}
/// @notice Check if the position needs rebalancing
/// @dev Override to customize tend trigger logic. Default checks liquidation risk, leverage bounds,
/// idle assets, min tend interval, and gas price.
/// @return True if a tend operation should be triggered
function _tendTrigger() internal view virtual override returns (bool) {
if (_isLiquidatable()) return true;
if (TokenizedStrategy.totalAssets() == 0) return false;
if (_isSupplyPaused() || _isBorrowPaused()) return false;
uint256 currentLeverage = getCurrentLeverageRatio();
if (currentLeverage > maxLeverageRatio) {
return true;
}
if (block.timestamp - lastTend < minTendInterval) {
return false;
}
uint256 _targetLeverageRatio = targetLeverageRatio;
if (_targetLeverageRatio == 0) {
return currentLeverage > 0 && _isBaseFeeAcceptable();
}
// If we are over the upper bound
if (currentLeverage > _targetLeverageRatio + leverageBuffer) {
uint256 _minAmountToBorrow = minAmountToBorrow;
// Over-leveraged: can repay with idle assets OR delever via flashloan
if (
balanceOfAsset() > _minAmountToBorrow ||
maxFlashloan() > _minAmountToBorrow
) {
return _isBaseFeeAcceptable();
}
return false;
}
// We don't auto tend when under the lower bound
return false;
}
/*//////////////////////////////////////////////////////////////
FLASHLOAN OPERATIONS
//////////////////////////////////////////////////////////////*/
/// @notice Adjust position to target leverage ratio
/// @dev Handles three cases: lever up, delever, or just deploy _amount
function _lever(uint256 _amount) internal virtual {
(uint256 currentCollateralValue, uint256 currentDebt) = position();
uint256 currentEquity = currentCollateralValue - currentDebt + _amount;
(, uint256 targetDebt) = getTargetPosition(currentEquity);
if (targetDebt > currentDebt) {
// CASE 1: Need MORE debt → leverage up via flashloan
uint256 flashloanAmount = Math.min(
targetDebt - currentDebt,
maxFlashloan()
);
// Cap total swap if maxAmountToSwap is set or collateral capacity is reached
uint256 maxCollateralInAsset = _collateralToAsset(
_maxCollateralDeposit()
);
uint256 _maxAmountToSwap = maxCollateralInAsset == type(uint256).max
? maxAmountToSwap
: Math.min(
maxAmountToSwap,
(maxCollateralInAsset * (MAX_BPS - slippage)) / MAX_BPS
);
if (_maxAmountToSwap != type(uint256).max) {
uint256 totalSwap = _amount + flashloanAmount;
if (totalSwap > _maxAmountToSwap) {
if (_amount >= _maxAmountToSwap) {
// _amount alone exceeds max, just swap max and supply
_supplyCollateral(
_convertAssetToCollateral(_maxAmountToSwap)
);
return;
}
// Reduce flashloan to stay within limit
flashloanAmount = _maxAmountToSwap - _amount;
}
}
if (flashloanAmount <= minAmountToBorrow) {
// Too small for flashloan, just repay debt with available assets
_repay(Math.min(_amount, balanceOfDebt()));
return;
}
bytes memory data = abi.encode(
FlashLoanData({
operation: FlashLoanOperation.LEVERAGE,
amount: _amount
})
);
_executeFlashloan(address(asset), flashloanAmount, data);
} else if (currentDebt > targetDebt) {
// CASE 2: Need LESS debt → deleverage
uint256 debtToRepay = currentDebt - targetDebt;
if (_amount >= debtToRepay) {
// _amount covers the debt repayment, just repay and supply the rest
_repay(debtToRepay);
_amount -= debtToRepay;
if (_amount > 0) {
_convertAssetToCollateral(
Math.min(_amount, maxAmountToSwap)
);
// Cap remainder by collateral capacity
_supplyCollateral(
Math.min(
balanceOfCollateralToken(),
_maxCollateralDeposit()
)
);
}
return;
}
// First repay what is loose.
_repay(_amount);
debtToRepay -= _amount;
// Cap flashloan by available liquidity
debtToRepay = Math.min(debtToRepay, maxFlashloan());
if (debtToRepay == 0) return;
// Flashloan to repay debt, withdraw collateral to cover
uint256 collateralToWithdraw = (_assetToCollateral(debtToRepay) *
(MAX_BPS + slippage)) / MAX_BPS;
bytes memory data = abi.encode(
FlashLoanData({
operation: FlashLoanOperation.DELEVERAGE,
amount: collateralToWithdraw
})
);
_executeFlashloan(address(asset), debtToRepay, data);
} else {
// CASE 3: At target debt → just deploy _amount if any
_convertAssetToCollateral(Math.min(_amount, maxAmountToSwap));
_supplyCollateral(
Math.min(balanceOfCollateralToken(), _maxCollateralDeposit())
);
}
}
/// @notice Will withdraw funds from the strategy to cover the amount needed keeping the position at target leverage ratio using a flashloan
function _withdrawFunds(uint256 _amountNeeded) internal virtual {
(uint256 valueOfCollateral, uint256 currentDebt) = position();
if (currentDebt == 0) {
// No debt, just withdraw collateral
uint256 toWithdraw = _assetToCollateral(_amountNeeded);
_withdrawCollateral(Math.min(toWithdraw, balanceOfCollateral()));
_convertCollateralToAsset(
Math.min(toWithdraw, balanceOfCollateralToken())
);
return;
}
uint256 equity = valueOfCollateral - currentDebt;
uint256 targetEquity = equity > _amountNeeded
? equity - _amountNeeded
: 0;
(, uint256 targetDebt) = getTargetPosition(targetEquity);
if (targetDebt > currentDebt) {
// No debt to repay, just withdraw collateral
uint256 toWithdraw = _assetToCollateral(_amountNeeded);
_withdrawCollateral(Math.min(toWithdraw, balanceOfCollateral()));
_convertCollateralToAsset(toWithdraw);
return;
}
uint256 debtToRepay = currentDebt - targetDebt;
// Cap flashloan by available liquidity
debtToRepay = Math.min(debtToRepay, maxFlashloan());
if (debtToRepay == 0) return;
uint256 collateralToWithdraw = debtToRepay == currentDebt
? balanceOfCollateral()
: _assetToCollateral(debtToRepay + _amountNeeded);
bytes memory data = abi.encode(
FlashLoanData({
operation: FlashLoanOperation.DELEVERAGE,
amount: collateralToWithdraw
})
);
_executeFlashloan(address(asset), debtToRepay, data);
}
/// @notice Called by protocol-specific flashloan callback
function _onFlashloanReceived(
uint256 assets,
bytes memory data
) internal virtual {
FlashLoanData memory params = abi.decode(data, (FlashLoanData));
if (params.operation == FlashLoanOperation.LEVERAGE) {
_executeLeverageCallback(assets, params);
} else if (params.operation == FlashLoanOperation.DELEVERAGE) {
_executeDeleverageCallback(assets, params);
} else {
revert("invalid operation");
}
}
function _executeLeverageCallback(
uint256 flashloanAmount,
FlashLoanData memory params
) internal virtual {
// Total asset to convert = deposit + flashloan
uint256 totalToConvert = params.amount + flashloanAmount;
// Convert all asset to collateral
uint256 collateralReceived = _convertAssetToCollateral(totalToConvert);
// Supply collateral
_supplyCollateral(collateralReceived);
// Borrow to repay flashloan
_borrow(flashloanAmount);
// Sanity check
require(
getCurrentLeverageRatio() < maxLeverageRatio,
"leverage too high"
);
}
function _executeDeleverageCallback(
uint256 flashloanAmount,
FlashLoanData memory params
) internal virtual {
uint256 initialLeverage = getCurrentLeverageRatio();
// Use flashloaned amount to repay debt
_repay(Math.min(flashloanAmount, balanceOfDebt()));
uint256 collateralToWithdraw = Math.min(
params.amount,
balanceOfCollateral()
);
// Withdraw
_withdrawCollateral(collateralToWithdraw);
// Convert collateral back to asset
_convertCollateralToAsset(collateralToWithdraw);
// Sanity check
uint256 finalLeverage = getCurrentLeverageRatio();
// Make sure the leverage is within the bounds, or at least improved.
require(
finalLeverage < maxLeverageRatio || finalLeverage < initialLeverage,
"leverage too high"
);
}
function _convertCollateralToAsset(
uint256 amount
) internal virtual returns (uint256) {
return _convertCollateralToAsset(amount, _getAmountOut(amount, false));
}
function _convertAssetToCollateral(
uint256 amount
) internal virtual returns (uint256) {
return _convertAssetToCollateral(amount, _getAmountOut(amount, true));
}
function _convertAssetToCollateral(
uint256 amount,
uint256 amountOutMin
) internal virtual returns (uint256) {
if (amount == 0) return 0;
uint256 amountOut = IExchange(exchange).exchange(
address(asset),
collateralToken,
amount,
amountOutMin
);
require(amountOut >= amountOutMin, "!amountOut");
return amountOut;
}
function _convertCollateralToAsset(
uint256 amount,
uint256 amountOutMin
) internal virtual returns (uint256) {
if (amount == 0) return 0;
uint256 amountOut = IExchange(exchange).exchange(
collateralToken,
address(asset),
amount,
amountOutMin
);
require(amountOut >= amountOutMin, "!amountOut");
return amountOut;
}
/*//////////////////////////////////////////////////////////////
ABSTRACT - PROTOCOL SPECIFIC
//////////////////////////////////////////////////////////////*/
/// @notice Accrue interest before state changing functions
function _accrueInterest() internal virtual {
// No-op by default
}
/// @notice Execute a flashloan through the protocol
function _executeFlashloan(
address token,
uint256 amount,
bytes memory data
) internal virtual;
/// @notice Max available flashloan from protocol
function maxFlashloan() public view virtual returns (uint256);
/// @notice Get oracle price (loan token value per 1 collateral token, ORACLE_PRICE_SCALE)
/// @dev Must return raw oracle price in 1e36 scale for precision in conversions
function _getCollateralPrice() internal view virtual returns (uint256);
/// @notice Supply collateral (with asset->collateral conversion)
function _supplyCollateral(uint256 amount) internal virtual;
/// @notice Withdraw collateral (with collateral->asset conversion)
/// @dev Must implement protocol-specific collateral withdrawal logic.
/// @param amount The amount of collateral to withdraw
function _withdrawCollateral(uint256 amount) internal virtual;
/// @notice Borrow assets from the lending protocol
/// @dev Must implement protocol-specific borrow logic.
/// @param amount The amount of asset to borrow
function _borrow(uint256 amount) internal virtual;
/// @notice Repay borrowed assets to the lending protocol
/// @dev Must implement protocol-specific repay logic. Should handle partial repayments gracefully.
/// @param amount The amount of asset to repay
function _repay(uint256 amount) internal virtual;
/// @notice Check if collateral supply is paused on the lending protocol
/// @dev Must implement protocol-specific pause check.
/// @return True if supplying collateral is currently paused
function _isSupplyPaused() internal view virtual returns (bool);
/// @notice Check if borrowing is paused on the lending protocol
/// @dev Must implement protocol-specific pause check.
/// @return True if borrowing is currently paused
function _isBorrowPaused() internal view virtual returns (bool);
/// @notice Check if the position is at risk of liquidation
/// @dev Must implement protocol-specific liquidation check. Used by _tendTrigger for emergency rebalancing.
/// @return True if the position can be liquidated
function _isLiquidatable() internal view virtual returns (bool);
/// @notice Get the maximum amount of collateral that can be deposited
/// @dev Must implement protocol-specific capacity check. Return type(uint256).max if unlimited.
/// @return The maximum collateral amount that can be deposited
function _maxCollateralDeposit() internal view virtual returns (uint256);
/// @notice Get the maximum amount that can be borrowed
/// @dev Must implement protocol-specific borrow capacity check.
/// @return The maximum amount that can be borrowed in asset terms
function _maxBorrowAmount() internal view virtual returns (uint256);
/// @notice Get the liquidation loan-to-value threshold (LLTV)
/// @dev Must implement protocol-specific LLTV retrieval. Used to validate leverage params.
/// @return The liquidation threshold in WAD (e.g., 0.9e18 = 90% LLTV)
function getLiquidateCollateralFactor()
public
view
virtual
returns (uint256);
/// @notice Get the current collateral balance in the lending protocol
/// @dev Must implement protocol-specific collateral balance retrieval.
/// @return The amount of collateral supplied to the protocol
function balanceOfCollateral() public view virtual returns (uint256);
/// @notice Get the current debt balance owed to the lending protocol
/// @dev Must implement protocol-specific debt balance retrieval.
/// @return The amount of debt owed in asset terms
function balanceOfDebt() public view virtual returns (uint256);
/// @notice Claim and sell any protocol rewards
/// @dev Must implement reward claiming and selling logic. Can be no-op if no rewards.
function _claimAndSellRewards() internal virtual;
/*//////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Get the loose asset balance held by the strategy
/// @dev Override if asset is held in a different form or location.
/// @return The amount of asset tokens held by this contract
function balanceOfAsset() public view virtual returns (uint256) {
return asset.balanceOf(address(this));
}
/// @notice Get the loose collateral token balance held by the strategy
/// @dev Override if collateral tokens are held in a different form or location.
/// @return The amount of collateral tokens held by this contract (not supplied to protocol)
function balanceOfCollateralToken() public view virtual returns (uint256) {
return ERC20(collateralToken).balanceOf(address(this));
}
/// @notice Get collateral value in asset terms
/// @dev price is in ORACLE_PRICE_SCALE (1e36), so we divide by 1e36
function _collateralToAsset(
uint256 collateralAmount
) internal view virtual returns (uint256) {
if (collateralAmount == 0 || collateralAmount == type(uint256).max)
return collateralAmount;
return (collateralAmount * _getCollateralPrice()) / ORACLE_PRICE_SCALE;
}
/// @notice Get collateral amount for asset value
/// @dev price is in ORACLE_PRICE_SCALE (1e36), so we multiply by 1e36
function _assetToCollateral(
uint256 assetAmount
) internal view virtual returns (uint256) {
if (assetAmount == 0 || assetAmount == type(uint256).max)
return assetAmount;
uint256 price = _getCollateralPrice();
return (assetAmount * ORACLE_PRICE_SCALE) / price;
}
/// @notice Get current leverage ratio
function getCurrentLeverageRatio() public view virtual returns (uint256) {
(uint256 collateralValue, uint256 debt) = position();
if (collateralValue == 0) return 0;
if (debt >= collateralValue) return type(uint256).max;
return (collateralValue * WAD) / (collateralValue - debt);
}
/// @notice Get current LTV
function getCurrentLTV() external view virtual returns (uint256) {
(uint256 collateralValue, uint256 debt) = position();
return collateralValue > 0 ? (debt * WAD) / collateralValue : 0;
}
/// @notice Get the current position details
/// @dev Override to customize position calculation.
/// @return collateralValue The value of collateral in asset terms
/// @return debt The current debt amount
function position()
public
view
virtual
returns (uint256 collateralValue, uint256 debt)
{
uint256 collateral = balanceOfCollateral();
collateralValue = _collateralToAsset(collateral);
debt = balanceOfDebt();
}
/// @notice Calculate the target position for a given equity amount
/// @dev Used to determine how much collateral and debt to have at target leverage.
/// @param _equity The equity (collateral - debt) to base calculations on
/// @return collateral The target collateral amount
/// @return debt The target debt amount
function getTargetPosition(
uint256 _equity
) public view virtual returns (uint256 collateral, uint256 debt) {
uint256 targetCollateral = (_equity * targetLeverageRatio) / WAD;
uint256 targetDebt = targetCollateral > _equity
? targetCollateral - _equity
: 0;
return (targetCollateral, targetDebt);
}
/// @notice Get amount out with slippage
function _getAmountOut(
uint256 amount,
bool assetToCollateral
) internal view virtual returns (uint256) {
if (amount == 0) return 0;
uint256 converted = assetToCollateral
? _assetToCollateral(amount)
: _collateralToAsset(amount);
return (converted * (MAX_BPS - slippage)) / MAX_BPS;
}
/// @notice Check if the current base fee is acceptable for tending
/// @dev Override to customize gas price checks or disable them entirely.
/// @return True if the base fee is at or below maxGasPriceToTend
function _isBaseFeeAcceptable() internal view virtual returns (bool) {
return block.basefee <= maxGasPriceToTend;
}
/*//////////////////////////////////////////////////////////////
MANAGEMENT FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Emergency full position close via flashloan
function manualFullUnwind() external accrue onlyEmergencyAuthorized {
_withdrawFunds(TokenizedStrategy.totalAssets());
}
/// @notice Manual: supply collateral
function manualSupplyCollateral(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_supplyCollateral(Math.min(amount, balanceOfCollateralToken()));
}
/// @notice Manual: withdraw collateral
function manualWithdrawCollateral(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_withdrawCollateral(Math.min(amount, balanceOfCollateral()));
}
/// @notice Manual: borrow from protocol
function manualBorrow(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_borrow(amount);
}
/// @notice Manual: repay debt
function manualRepay(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_repay(Math.min(amount, balanceOfAsset()));
}
function convertCollateralToAsset(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_convertCollateralToAsset(Math.min(amount, balanceOfCollateralToken()));
}
function convertAssetToCollateral(
uint256 amount
) external accrue onlyEmergencyAuthorized {
_convertAssetToCollateral(Math.min(amount, balanceOfAsset()));
}
/*//////////////////////////////////////////////////////////////
EMERGENCY
//////////////////////////////////////////////////////////////*/
/// @notice Emergency withdraw funds from the leveraged position
/// @dev Override to customize emergency withdrawal behavior. Default attempts full unwind via deleverage.
/// Called during emergency shutdown.
/// @param _amount The amount of asset to attempt to withdraw
function _emergencyWithdraw(
uint256 _amount
) internal virtual override accrue {
// Try full unwind first
if (balanceOfDebt() > 0) {
_withdrawFunds(Math.min(_amount, TokenizedStrategy.totalAssets()));
} else if (_amount > 0) {
_amount = Math.min(_amount, balanceOfCollateral());
_withdrawCollateral(_amount);
_convertCollateralToAsset(_amount);
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
interface IPool {
/**
* @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* @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
* @param referralCode Code used to register the integrator originating the operation
*/
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
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn (use type(uint256).max to withdraw the full balance)
* @param to The address that will receive the underlying asset
* @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
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation
* @param onBehalfOf The address that will receive the debt (must be the msg.sender if debt is non-zero)
*/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve
* @param asset The address of the borrowed underlying asset
* @param amount The amount to repay (use type(uint256).max to repay the full debt)
* @param interestRateMode The interest rate mode: 1 for Stable, 2 for Variable
* @param onBehalfOf The address of the user whose debt is being repaid
* @return The final amount repaid
*/
function repay(
address asset,
uint256 amount,
uint256 interestRateMode,
address onBehalfOf
) external returns (uint256);
/**
* @notice Allows smartcontracts to access the liquidity of the pool within one transaction.
* Can either be repaid in full (interestRateMode = 0) or opened as debt (1 stable / 2 variable).
* @param receiverAddress The address of the contract receiving the funds
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts of the assets being flash-borrowed
* @param interestRateModes The interest rate modes for each asset:
* 0 = no debt (must repay amount + premium),
* 1 = stable debt, 2 = variable debt
* @param onBehalfOf The address that will receive the debt if a debt mode is used
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation
*/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata interestRateModes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* @param receiverAddress The address of the contract receiving the funds
* @param asset The address of the asset being flash-borrowed
* @param amount The amount of the asset being flash-borrowed
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation
*/
function flashLoanSimple(
address receiverAddress,
address asset,
uint256 amount,
bytes calldata params,
uint16 referralCode
) 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
* @return totalDebtBase The total debt of the user in the base currency
* @return availableBorrowsBase The borrowing power left of the user in the base currency
* @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 Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral True to enable, false to disable
*/
function setUserUseReserveAsCollateral(
address asset,
bool useAsCollateral
) external;
/**
* @notice Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
*/
function getReserveData(
address asset
)
external
view
returns (
uint256 configuration,
uint128 liquidityIndex,
uint128 currentLiquidityRate,
uint128 variableBorrowIndex,
uint128 currentVariableBorrowRate,
uint128 currentStableBorrowRate,
uint40 lastUpdateTimestamp,
uint16 id,
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress,
uint128 accruedToTreasury,
uint128 unbacked,
uint128 isolationModeTotalDebt
);
/**
* @notice Returns the reserve virtual underlying balance.
* @param asset The address of the underlying asset of the reserve
* @return The virtual underlying balance
*/
function getVirtualUnderlyingBalance(
address asset
) external view returns (uint256);
/**
* @notice Returns the total fee on flash loans
* @return The total fee on flash loans (in bps, e.g., 5 = 0.05%)
*/
function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);
/**
* @notice Allows a user to use the protocol in eMode
* @param categoryId The id of the category (0 to exit eMode)
*/
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);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
/**
* @title IPoolDataProvider
* @notice Defines the basic interface for a PoolDataProvider
*/
interface IPoolDataProvider {
/**
* @notice Returns the user data in a reserve
* @param asset The address of the underlying asset of the reserve
* @param user The address of the user
* @return currentATokenBalance The current AToken balance of the user
* @return currentStableDebt The current stable debt of the user
* @return currentVariableDebt The current variable debt of the user
* @return principalStableDebt The principal stable debt of the user
* @return scaledVariableDebt The scaled variable debt of the user
* @return stableBorrowRate The stable borrow rate of the user
* @return liquidityRate The liquidity rate of the reserve
* @return stableRateLastUpdated The timestamp of the last stable rate update
* @return usageAsCollateralEnabled True if the user is using the asset as collateral
*/
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
);
/**
* @notice Returns the configuration data of the reserve
* @param asset The address of the underlying asset of the reserve
* @return decimals The decimals of the asset
* @return ltv The LTV of the asset (in basis points, e.g., 8000 = 80%)
* @return liquidationThreshold The liquidation threshold (in basis points)
* @return liquidationBonus The liquidation bonus (in basis points)
* @return reserveFactor The reserve factor
* @return usageAsCollateralEnabled True if the asset can be used as collateral
* @return borrowingEnabled True if borrowing is enabled
* @return stableBorrowRateEnabled True if stable borrow rate is enabled
* @return isActive True if the reserve is active
* @return isFrozen True if the reserve is frozen
*/
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
);
/**
* @notice Returns the caps parameters of the reserve
* @param asset The address of the underlying asset of the reserve
* @return borrowCap The borrow cap of the reserve (in whole tokens, 0 = no cap)
* @return supplyCap The supply cap of the reserve (in whole tokens, 0 = no cap)
*/
function getReserveCaps(
address asset
) external view returns (uint256 borrowCap, uint256 supplyCap);
/**
* @notice Returns whether the reserve is paused
* @param asset The address of the underlying asset
* @return isPaused True if the reserve is paused
*/
function getPaused(address asset) external view returns (bool isPaused);
/**
* @notice Returns the total supply of aTokens for a given asset
* @param asset The address of the underlying asset of the reserve
* @return The total supply of the aToken
*/
function getATokenTotalSupply(
address asset
) external view returns (uint256);
/**
* @notice Returns the total debt for a given asset
* @param asset The address of the underlying asset of the reserve
* @return The total debt (stable + variable)
*/
function getTotalDebt(address asset) external view returns (uint256);
/**
* @notice Returns the token addresses of the reserve
* @param asset The address of the underlying asset of the reserve
* @return aTokenAddress The AToken address of the reserve
* @return stableDebtTokenAddress The stable debt token address
* @return variableDebtTokenAddress The variable debt token address
*/
function getReserveTokensAddresses(
address asset
)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
/**
* @title IPoolAddressesProvider
* @notice Defines the basic interface for a Pool Addresses Provider.
*/
interface IPoolAddressesProvider {
/**
* @notice Returns the address of the Pool proxy.
* @return The Pool proxy address
*/
function getPool() external view returns (address);
/**
* @notice Returns the address of the PoolDataProvider proxy.
* @return The PoolDataProvider proxy address
*/
function getPoolDataProvider() external view returns (address);
/**
* @notice Returns the address of the price oracle.
* @return The address of the PriceOracle
*/
function getPriceOracle() external view returns (address);
/**
* @notice Returns the address of the ACL manager.
* @return The address of the ACLManager
*/
function getACLManager() external view returns (address);
/**
* @notice Returns the address of the ACL admin.
* @return The address of the ACL admin
*/
function getACLAdmin() external view returns (address);
/**
* @notice Returns the id of the Aave market.
* @return The id of the Aave market
*/
function getMarketId() external view returns (string memory);
/**
* @notice Returns an address by its identifier.
* @dev The returned address might be an EOA or a contract
* @param id The id of the address
* @return The address
*/
function getAddress(bytes32 id) external view returns (address);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
/**
* @title IAaveOracle
* @notice Defines the basic interface for the Aave Oracle
*/
interface IAaveOracle {
/**
* @notice Returns the asset price in the base currency
* @param asset The address of the asset
* @return The price of the asset (scaled by BASE_CURRENCY_UNIT)
*/
function getAssetPrice(address asset) external view returns (uint256);
/**
* @notice Returns a list of prices from a list of assets addresses
* @param assets The list of assets addresses
* @return The prices of the given assets
*/
function getAssetsPrices(
address[] calldata assets
) external view returns (uint256[] memory);
/**
* @notice Returns the address of the source for an asset address
* @param asset The address of the asset
* @return The address of the source
*/
function getSourceOfAsset(address asset) external view returns (address);
/**
* @notice Returns the address of the fallback oracle
* @return The address of the fallback oracle
*/
function getFallbackOracle() external view returns (address);
/**
* @notice Returns the base currency address
* @dev Address 0x0 is reserved for USD as base currency.
* @return The base currency address
*/
function BASE_CURRENCY() external view returns (address);
/**
* @notice Returns the base currency unit (e.g., 1e8 for USD)
* @return The base currency unit
*/
function BASE_CURRENCY_UNIT() external view returns (uint256);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
/**
* @title IRewardsController
* @notice Defines the basic interface for a Rewards Controller.
*/
interface IRewardsController {
/**
* @notice Claims all rewards for a user to the desired address, on all the assets of the pool
* @param assets The list of assets to check eligible distributions (aTokens or variableDebtTokens)
* @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
*/
function claimAllRewards(
address[] calldata assets,
address to
)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
/**
* @notice Claims all rewards for a user to msg.sender, on all the assets of the pool
* @param assets The list of assets to check eligible distributions
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward
*/
function claimAllRewardsToSelf(
address[] calldata assets
)
external
returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
/**
* @notice Returns the list of available reward token addresses for the given asset
* @param asset The address of the incentivized asset
* @return The list of rewards addresses
*/
function getRewardsByAsset(
address asset
) external view returns (address[] memory);
/**
* @notice Returns all the pending rewards for a user given a list of assets
* @param assets The list of assets to check eligible distributions
* @param user The address of the user
* @return rewardsList List of addresses of the reward tokens
* @return unclaimedAmounts List that contains the unclaimed amount per reward
*/
function getAllUserRewards(
address[] calldata assets,
address user
)
external
view
returns (
address[] memory rewardsList,
uint256[] memory unclaimedAmounts
);
/**
* @notice Returns the data for a specific reward token
* @param asset The address of the incentivized asset
* @param reward The address of the reward token
* @return index The reward index
* @return emissionPerSecond The emission per second
* @return lastUpdateTimestamp The last update timestamp
* @return distributionEnd The distribution end timestamp
*/
function getRewardsData(
address asset,
address reward
)
external
view
returns (
uint256 index,
uint256 emissionPerSecond,
uint256 lastUpdateTimestamp,
uint256 distributionEnd
);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
/**
* @title IAToken
* @notice Minimal interface for Aave V3 aToken to get incentives controller
*/
interface IAToken {
/**
* @notice Returns the address of the Incentives Controller contract
* @return The address of the Incentives Controller
*/
function getIncentivesController() external view returns (address);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
type Id is bytes32;
struct MarketParams {
address loanToken;
address collateralToken;
address oracle;
address irm;
uint256 lltv;
}
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
uint256 supplyShares;
uint128 borrowShares;
uint128 collateral;
}
/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
uint128 totalSupplyAssets;
uint128 totalSupplyShares;
uint128 totalBorrowAssets;
uint128 totalBorrowShares;
uint128 lastUpdate;
uint128 fee;
}
struct Authorization {
address authorizer;
address authorized;
bool isAuthorized;
uint256 nonce;
uint256 deadline;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
function DOMAIN_SEPARATOR() external view returns (bytes32);
function owner() external view returns (address);
function feeRecipient() external view returns (address);
function isIrmEnabled(address irm) external view returns (bool);
function isLltvEnabled(uint256 lltv) external view returns (bool);
function isAuthorized(
address authorizer,
address authorized
) external view returns (bool);
function nonce(address authorizer) external view returns (uint256);
function setOwner(address newOwner) external;
function enableIrm(address irm) external;
function enableLltv(uint256 lltv) external;
function setFee(MarketParams memory marketParams, uint256 newFee) external;
function setFeeRecipient(address newFeeRecipient) external;
function createMarket(MarketParams memory marketParams) external;
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
function supplyCollateral(
MarketParams memory marketParams,
uint256 assets,
address onBehalf,
bytes memory data
) external;
function withdrawCollateral(
MarketParams memory marketParams,
uint256 assets,
address onBehalf,
address receiver
) external;
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
function flashLoan(
address token,
uint256 assets,
bytes calldata data
) external;
function setAuthorization(
address authorized,
bool newIsAuthorized
) external;
function setAuthorizationWithSig(
Authorization calldata authorization,
Signature calldata signature
) external;
function accrueInterest(MarketParams memory marketParams) external;
function extSloads(
bytes32[] memory slots
) external view returns (bytes32[] memory);
}
interface IMorphoStaticTyping is IMorphoBase {
function position(
Id id,
address user
)
external
view
returns (
uint256 supplyShares,
uint128 borrowShares,
uint128 collateral
);
function market(
Id id
)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
function idToMarketParams(
Id id
)
external
view
returns (
address loanToken,
address collateralToken,
address oracle,
address irm,
uint256 lltv
);
}
interface IMorpho is IMorphoBase {
function position(
Id id,
address user
) external view returns (Position memory p);
function market(Id id) external view returns (Market memory m);
function idToMarketParams(
Id id
) external view returns (MarketParams memory);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title IMorphoFlashLoanCallback
/// @notice Interface that contracts must implement to use Morpho's flashLoan callback.
interface IMorphoFlashLoanCallback {
/// @notice Callback called when a flash loan occurs.
/// @dev The callback is called only if data is not empty.
/// @param assets The amount of assets that was flash loaned.
/// @param data Arbitrary data passed to the flashLoan function.
function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AuctionFactory, Auction} from "../Auctions/AuctionFactory.sol";
import {BaseSwapper} from "./BaseSwapper.sol";
/**
* @title AuctionSwapper
* @author yearn.fi
* @dev Helper contract for a strategy to use dutch auctions for token sales.
*
* This contract is meant to be inherited by a V3 strategy in order
* to easily integrate dutch auctions into a contract for token swaps.
*
* AUCTION SETUP:
* - The strategist needs to implement a way to call `_setAuction()`
* to set the auction contract address for token sales
* - `useAuction` defaults to false but is automatically set to true
* when a non-zero auction address is set via `_setAuction()`
* - Auctions can be manually enabled/disabled using `_setUseAuction()`
*
* PERMISSIONLESS OPERATIONS:
* - `kickAuction()` is public and permissionless - anyone can trigger
* auctions when conditions are met (sufficient balance, auctions enabled)
* - This allows for automated auction triggering by bots or external systems
*
* AUCTION TRIGGER INTEGRATION:
* - Implements `auctionTrigger()` for integration with CommonAuctionTrigger
* - Returns encoded calldata for `kickAuction()` when conditions are met
* - Provides smart logic to prevent duplicate auctions and handle edge cases
*
* HOOKS:
* - The contract can act as a `hook` contract for the auction with the
* ability to override functions to implement custom hooks
* - If hooks are not desired, call `setHookFlags()` on the auction contract
* to avoid unnecessary gas for unused functions
*/
contract AuctionSwapper is BaseSwapper {
using SafeERC20 for ERC20;
event AuctionSet(address indexed auction);
event UseAuctionSet(bool indexed useAuction);
/// @notice Address of the specific Auction contract this strategy uses for token sales.
address public auction;
/// @notice Whether to use auctions for token swaps.
/// @dev Defaults to false but automatically set to true when setting a non-zero auction address.
/// Can be manually controlled via _setUseAuction() for fine-grained control.
bool public useAuction;
/*//////////////////////////////////////////////////////////////
AUCTION STARTING AND STOPPING
//////////////////////////////////////////////////////////////*/
/// @notice Set the auction contract to use.
/// @dev Automatically enables auctions (useAuction = true) when setting a non-zero address.
/// @param _auction The auction contract address. Must have this contract as receiver.
function _setAuction(address _auction) internal virtual {
if (_auction != address(0)) {
require(
Auction(_auction).receiver() == address(this),
"wrong receiver"
);
// Automatically enable auctions when setting a non-zero auction address
if (!useAuction) {
useAuction = true;
emit UseAuctionSet(true);
}
}
auction = _auction;
emit AuctionSet(_auction);
}
/// @notice Manually enable or disable auction usage.
/// @dev Can be used to override the auto-enable behavior or temporarily disable auctions.
/// @param _useAuction Whether to use auctions for token swaps.
function _setUseAuction(bool _useAuction) internal virtual {
useAuction = _useAuction;
emit UseAuctionSet(_useAuction);
}
/**
* @notice Return how much of a token could currently be kicked into auction.
* @dev Includes both contract balance and tokens already in the auction contract.
* @param _token The token that could be sold in auction.
* @return The total amount of `_token` available for auction (0 if auctions disabled).
*/
function kickable(address _token) public view virtual returns (uint256) {
if (!useAuction) return 0;
address _auction = auction;
if (_auction == address(0)) return 0;
if (
Auction(_auction).isActive(_token) &&
Auction(_auction).available(_token) > 0
) {
return 0;
}
return
ERC20(_token).balanceOf(address(this)) +
ERC20(_token).balanceOf(_auction);
}
/**
* @notice Kick an auction for a given token (PERMISSIONLESS).
* @dev Anyone can call this function to trigger auctions when conditions are met.
* Useful for automated systems, bots, or manual triggering.
* @param _from The token to be sold in the auction.
* @return The amount of tokens that were kicked into the auction.
*/
function kickAuction(address _from) external virtual returns (uint256) {
return _kickAuction(_from);
}
/**
* @dev Internal function to kick an auction for a given token.
* @param _from The token that was being sold.
*/
function _kickAuction(address _from) internal virtual returns (uint256) {
require(useAuction, "useAuction is false");
address _auction = auction;
if (Auction(_auction).isActive(_from)) {
if (Auction(_auction).available(_from) > 0) {
return 0;
}
Auction(_auction).settle(_from);
}
uint256 _balance = ERC20(_from).balanceOf(address(this));
if (_balance > 0) {
ERC20(_from).safeTransfer(_auction, _balance);
}
return Auction(_auction).kick(_from);
}
/*//////////////////////////////////////////////////////////////
AUCTION TRIGGER INTERFACE
//////////////////////////////////////////////////////////////*/
/**
* @notice Default auction trigger implementation for CommonAuctionTrigger integration.
* @dev Returns whether an auction should be kicked and the encoded calldata to do so.
* This enables automated auction triggering through external trigger systems.
* @param _from The token that could be sold in an auction.
* @return shouldKick True if an auction should be kicked for this token.
* @return data Encoded calldata for `kickAuction(_from)` if shouldKick is true,
* otherwise a descriptive error message explaining why not.
*/
function auctionTrigger(
address _from
) external view virtual returns (bool shouldKick, bytes memory data) {
address _auction = auction;
if (_auction == address(0)) {
return (false, bytes("No auction set"));
}
if (!useAuction) {
return (false, bytes("Auctions disabled"));
}
uint256 kickableAmount = kickable(_from);
if (kickableAmount != 0 && kickableAmount >= minAmountToSell) {
return (true, abi.encodeCall(this.kickAuction, (_from)));
}
return (false, bytes("not enough kickable"));
}
}// 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 v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
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].
*
* CAUTION: See Security Considerations above.
*/
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: 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: 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: AGPL-3.0
pragma solidity >=0.8.18;
import {BaseStrategy, ERC20} from "@tokenized-strategy/BaseStrategy.sol";
/**
* @title Base Health Check
* @author Yearn.finance
* @notice This contract can be inherited by any Yearn
* V3 strategy wishing to implement a health check during
* the `report` function in order to prevent any unexpected
* behavior from being permanently recorded as well as the
* `checkHealth` modifier.
*
* A strategist simply needs to inherit this contract. Set
* the limit ratios to the desired amounts and then
* override `_harvestAndReport()` just as they otherwise
* would. If the profit or loss that would be recorded is
* outside the acceptable bounds the tx will revert.
*
* The healthcheck does not prevent a strategy from reporting
* losses, but rather can make sure manual intervention is
* needed before reporting an unexpected loss or profit.
*/
abstract contract BaseHealthCheck is BaseStrategy {
// Can be used to determine if a healthcheck should be called.
// Defaults to true;
bool public doHealthCheck = true;
uint256 internal constant MAX_BPS = 10_000;
// Default profit limit to 100%.
uint16 private _profitLimitRatio = uint16(MAX_BPS);
// Defaults loss limit to 0.
uint16 private _lossLimitRatio;
constructor(
address _asset,
string memory _name
) BaseStrategy(_asset, _name) {}
/**
* @notice Returns the current profit limit ratio.
* @dev Use a getter function to keep the variable private.
* @return . The current profit limit ratio.
*/
function profitLimitRatio() public view returns (uint256) {
return _profitLimitRatio;
}
/**
* @notice Returns the current loss limit ratio.
* @dev Use a getter function to keep the variable private.
* @return . The current loss limit ratio.
*/
function lossLimitRatio() public view returns (uint256) {
return _lossLimitRatio;
}
/**
* @notice Set the `profitLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio The mew profit limit ratio.
*/
function setProfitLimitRatio(
uint256 _newProfitLimitRatio
) external onlyManagement {
_setProfitLimitRatio(_newProfitLimitRatio);
}
/**
* @dev Internally set the profit limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newProfitLimitRatio The mew profit limit ratio.
*/
function _setProfitLimitRatio(uint256 _newProfitLimitRatio) internal {
require(_newProfitLimitRatio > 0, "!zero profit");
require(_newProfitLimitRatio <= type(uint16).max, "!too high");
_profitLimitRatio = uint16(_newProfitLimitRatio);
}
/**
* @notice Set the `lossLimitRatio`.
* @dev Denominated in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio The new loss limit ratio.
*/
function setLossLimitRatio(
uint256 _newLossLimitRatio
) external onlyManagement {
_setLossLimitRatio(_newLossLimitRatio);
}
/**
* @dev Internally set the loss limit ratio. Denominated
* in basis points. I.E. 1_000 == 10%.
* @param _newLossLimitRatio The new loss limit ratio.
*/
function _setLossLimitRatio(uint256 _newLossLimitRatio) internal {
require(_newLossLimitRatio < MAX_BPS, "!loss limit");
_lossLimitRatio = uint16(_newLossLimitRatio);
}
/**
* @notice Turns the healthcheck on and off.
* @dev If turned off the next report will auto turn it back on.
* @param _doHealthCheck Bool if healthCheck should be done.
*/
function setDoHealthCheck(bool _doHealthCheck) public onlyManagement {
doHealthCheck = _doHealthCheck;
}
/**
* @notice OVerrides the default {harvestAndReport} to include a healthcheck.
* @return _totalAssets New totalAssets post report.
*/
function harvestAndReport()
external
override
onlySelf
returns (uint256 _totalAssets)
{
// Let the strategy report.
_totalAssets = _harvestAndReport();
// Run the healthcheck on the amount returned.
_executeHealthCheck(_totalAssets);
}
/**
* @dev To be called during a report to make sure the profit
* or loss being recorded is within the acceptable bound.
*
* @param _newTotalAssets The amount that will be reported.
*/
function _executeHealthCheck(uint256 _newTotalAssets) internal virtual {
if (!doHealthCheck) {
doHealthCheck = true;
return;
}
// Get the current total assets from the implementation.
uint256 currentTotalAssets = TokenizedStrategy.totalAssets();
if (_newTotalAssets > currentTotalAssets) {
require(
((_newTotalAssets - currentTotalAssets) <=
(currentTotalAssets * uint256(_profitLimitRatio)) /
MAX_BPS),
"healthCheck"
);
} else if (currentTotalAssets > _newTotalAssets) {
require(
(currentTotalAssets - _newTotalAssets <=
((currentTotalAssets * uint256(_lossLimitRatio)) /
MAX_BPS)),
"healthCheck"
);
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
interface IExchange {
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function exchange(
address from,
address to,
uint256 amountIn,
uint256 amountOutMin
) external returns (uint256 amountOut);
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Auction} from "./Auction.sol";
import {ClonableCreate2} from "../utils/ClonableCreate2.sol";
/// @title AuctionFactory
/// @notice Deploy a new Auction.
contract AuctionFactory is ClonableCreate2 {
event DeployedNewAuction(address indexed auction, address indexed want);
/// @notice The amount to start the auction with.
uint256 public constant DEFAULT_STARTING_PRICE = 1_000_000;
/// @notice Full array of all auctions deployed through this factory.
address[] public auctions;
constructor() {
// Deploy the original
original = address(new Auction());
}
function version() external pure returns (string memory) {
return "1.0.4";
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(address _want) external returns (address) {
return
_createNewAuction(
_want,
msg.sender,
msg.sender,
DEFAULT_STARTING_PRICE,
bytes32(0)
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _receiver Address that will receive the funds in the auction.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _receiver
) external returns (address) {
return
_createNewAuction(
_want,
_receiver,
msg.sender,
DEFAULT_STARTING_PRICE,
bytes32(0)
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _receiver Address that will receive the funds in the auction.
* @param _governance Address allowed to enable and disable auctions.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _receiver,
address _governance
) external returns (address) {
return
_createNewAuction(
_want,
_receiver,
_governance,
DEFAULT_STARTING_PRICE,
bytes32(0)
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _receiver Address that will receive the funds in the auction.
* @param _governance Address allowed to enable and disable auctions.
* @param _startingPrice Starting price for the auction (no decimals).
* NOTE: The starting price should be without decimals (1k == 1_000).
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _receiver,
address _governance,
uint256 _startingPrice
) external returns (address) {
return
_createNewAuction(
_want,
_receiver,
_governance,
_startingPrice,
bytes32(0)
);
}
/**
* @notice Creates a new auction contract.
* @param _want Address of the token users will bid with.
* @param _receiver Address that will receive the funds in the auction.
* @param _governance Address allowed to enable and disable auctions.
* @param _startingPrice Starting price for the auction (no decimals).
* @param _salt The salt to use for deterministic deployment.
* @return _newAuction Address of the newly created auction contract.
*/
function createNewAuction(
address _want,
address _receiver,
address _governance,
uint256 _startingPrice,
bytes32 _salt
) external returns (address) {
return
_createNewAuction(
_want,
_receiver,
_governance,
_startingPrice,
_salt
);
}
/**
* @dev Deploys and initializes a new Auction
*/
function _createNewAuction(
address _want,
address _receiver,
address _governance,
uint256 _startingPrice,
bytes32 _salt
) internal returns (address _newAuction) {
if (_salt == bytes32(0)) {
// If none set, generate unique salt. msg.sender gets encoded in getSalt()
_salt = keccak256(abi.encodePacked(_want, _receiver, _governance));
}
_newAuction = _cloneCreate2(_salt);
Auction(_newAuction).initialize(
_want,
_receiver,
_governance,
_startingPrice
);
auctions.push(_newAuction);
emit DeployedNewAuction(_newAuction, _want);
}
/**
* @notice Get the full list of auctions deployed through this factory.
*/
function getAllAuctions() external view returns (address[] memory) {
return auctions;
}
/**
* @notice Get the total number of auctions deployed through this factory.
*/
function numberOfAuctions() external view returns (uint256) {
return auctions.length;
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
/**
* @title BaseSwapper
* @author yearn.fi
* @dev Base contract for all swapper contracts except TradeFactorySwapper.
* Contains the common minAmountToSell variable that most swappers need.
*/
contract BaseSwapper {
/// @notice Minimum amount of tokens to sell in a swap.
uint256 public minAmountToSell;
/**
* @dev Set the minimum amount to sell in a swap.
* @param _minAmountToSell Minimum amount of tokens needed to execute a swap.
*/
function _setMinAmountToSell(uint256 _minAmountToSell) internal virtual {
minAmountToSell = _minAmountToSell;
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// TokenizedStrategy interface used for internal view delegateCalls.
import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol";
/**
* @title YearnV3 Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to
* seamlessly integrate with the `TokenizedStrategy` implementation contract
* allowing anyone to easily build a fully permissionless ERC-4626 compliant
* Vault by inheriting this contract and overriding three simple functions.
* It utilizes an immutable proxy pattern that allows the BaseStrategy
* to remain simple and small. All standard logic is held within the
* `TokenizedStrategy` and is reused over any n strategies all using the
* `fallback` function to delegatecall the implementation so that strategists
* can only be concerned with writing their strategy specific code.
*
* This contract should be inherited and the three main abstract methods
* `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt
* the Strategy to the particular needs it has to generate yield. There are
* other optional methods that can be implemented to further customize
* the strategy if desired.
*
* All default storage for the strategy is controlled and updated by the
* `TokenizedStrategy`. The implementation holds a storage struct that
* contains all needed global variables in a manual storage slot. This
* means strategists can feel free to implement their own custom storage
* variables as they need with no concern of collisions. All global variables
* can be viewed within the Strategy by a simple call using the
* `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();.
*/
abstract contract BaseStrategy {
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @dev Used on TokenizedStrategy callback functions to make sure it is post
* a delegateCall from this address to the TokenizedStrategy.
*/
modifier onlySelf() {
_onlySelf();
_;
}
/**
* @dev Use to assure that the call is coming from the strategies management.
*/
modifier onlyManagement() {
TokenizedStrategy.requireManagement(msg.sender);
_;
}
/**
* @dev Use to assure that the call is coming from either the strategies
* management or the keeper.
*/
modifier onlyKeepers() {
TokenizedStrategy.requireKeeperOrManagement(msg.sender);
_;
}
/**
* @dev Use to assure that the call is coming from either the strategies
* management or the emergency admin.
*/
modifier onlyEmergencyAuthorized() {
TokenizedStrategy.requireEmergencyAuthorized(msg.sender);
_;
}
/**
* @dev Require that the msg.sender is this address.
*/
function _onlySelf() internal view {
require(msg.sender == address(this), "!self");
}
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/**
* @dev This is the address of the TokenizedStrategy implementation
* contract that will be used by all strategies to handle the
* accounting, logic, storage etc.
*
* Any external calls to the that don't hit one of the functions
* defined in this base or the strategy will end up being forwarded
* through the fallback function, which will delegateCall this address.
*
* This address should be the same for every strategy, never be adjusted
* and always be checked before any integration with the Strategy.
*/
address public constant tokenizedStrategyAddress =
0xD377919FA87120584B21279a491F82D5265A139c;
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/**
* @dev Underlying asset the Strategy is earning yield on.
* Stored here for cheap retrievals within the strategy.
*/
ERC20 internal immutable asset;
/**
* @dev This variable is set to address(this) during initialization of each strategy.
*
* This can be used to retrieve storage data within the strategy
* contract as if it were a linked library.
*
* i.e. uint256 totalAssets = TokenizedStrategy.totalAssets()
*
* Using address(this) will mean any calls using this variable will lead
* to a call to itself. Which will hit the fallback function and
* delegateCall that to the actual TokenizedStrategy.
*/
ITokenizedStrategy internal immutable TokenizedStrategy;
/**
* @notice Used to initialize the strategy on deployment.
*
* This will set the `TokenizedStrategy` variable for easy
* internal view calls to the implementation. As well as
* initializing the default storage variables based on the
* parameters and using the deployer for the permissioned roles.
*
* @param _asset Address of the underlying asset.
* @param _name Name the strategy will use.
*/
constructor(address _asset, string memory _name) {
asset = ERC20(_asset);
// Set instance of the implementation for internal use.
TokenizedStrategy = ITokenizedStrategy(address(this));
// Initialize the strategy's storage variables.
_delegateCall(
abi.encodeCall(
ITokenizedStrategy.initialize,
(_asset, _name, msg.sender, msg.sender, msg.sender)
)
);
// Store the tokenizedStrategyAddress at the standard implementation
// address storage slot so etherscan picks up the interface. This gets
// stored on initialization and never updated.
assembly {
sstore(
// keccak256('eip1967.proxy.implementation' - 1)
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
tokenizedStrategyAddress
)
}
}
/*//////////////////////////////////////////////////////////////
NEEDED TO BE OVERRIDDEN BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/**
* @dev Can deploy up to '_amount' of 'asset' in the yield source.
*
* This function is called at the end of a {deposit} or {mint}
* call. Meaning that unless a whitelist is implemented it will
* be entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* @param _amount The amount of 'asset' that the strategy can attempt
* to deposit in the yield source.
*/
function _deployFunds(uint256 _amount) internal virtual;
/**
* @dev Should attempt to free the '_amount' of 'asset'.
*
* NOTE: The amount of 'asset' that is already loose has already
* been accounted for.
*
* This function is called during {withdraw} and {redeem} calls.
* Meaning that unless a whitelist is implemented it will be
* entirely permissionless and thus can be sandwiched or otherwise
* manipulated.
*
* Should not rely on asset.balanceOf(address(this)) calls other than
* for diff accounting purposes.
*
* Any difference between `_amount` and what is actually freed will be
* counted as a loss and passed on to the withdrawer. This means
* care should be taken in times of illiquidity. It may be better to revert
* if withdraws are simply illiquid so not to realize incorrect losses.
*
* @param _amount, The amount of 'asset' to be freed.
*/
function _freeFunds(uint256 _amount) internal virtual;
/**
* @dev Internal function to harvest all rewards, redeploy any idle
* funds and return an accurate accounting of all funds currently
* held by the Strategy.
*
* This should do any needed harvesting, rewards selling, accrual,
* redepositing etc. to get the most accurate view of current assets.
*
* NOTE: All applicable assets including loose assets should be
* accounted for in this function.
*
* Care should be taken when relying on oracles or swap values rather
* than actual amounts as all Strategy profit/loss accounting will
* be done based on this returned value.
*
* This can still be called post a shutdown, a strategist can check
* `TokenizedStrategy.isShutdown()` to decide if funds should be
* redeployed or simply realize any profits/losses.
*
* @return _totalAssets A trusted and accurate account for the total
* amount of 'asset' the strategy currently holds including idle funds.
*/
function _harvestAndReport()
internal
virtual
returns (uint256 _totalAssets);
/*//////////////////////////////////////////////////////////////
OPTIONAL TO OVERRIDE BY STRATEGIST
//////////////////////////////////////////////////////////////*/
/**
* @dev Optional function for strategist to override that can
* be called in between reports.
*
* If '_tend' is used tendTrigger() will also need to be overridden.
*
* This call can only be called by a permissioned role so may be
* through protected relays.
*
* This can be used to harvest and compound rewards, deposit idle funds,
* perform needed position maintenance or anything else that doesn't need
* a full report for.
*
* EX: A strategy that can not deposit funds without getting
* sandwiched can use the tend when a certain threshold
* of idle to totalAssets has been reached.
*
* This will have no effect on PPS of the strategy till report() is called.
*
* @param _totalIdle The current amount of idle funds that are available to deploy.
*/
function _tend(uint256 _totalIdle) internal virtual {}
/**
* @dev Optional trigger to override if tend() will be used by the strategy.
* This must be implemented if the strategy hopes to invoke _tend().
*
* @return . Should return true if tend() should be called by keeper or false if not.
*/
function _tendTrigger() internal view virtual returns (bool) {
return false;
}
/**
* @notice Returns if tend() should be called by a keeper.
*
* @return . Should return true if tend() should be called by keeper or false if not.
* @return . Calldata for the tend call.
*/
function tendTrigger() external view virtual returns (bool, bytes memory) {
return (
// Return the status of the tend trigger.
_tendTrigger(),
// And the needed calldata either way.
abi.encodeWithSelector(ITokenizedStrategy.tend.selector)
);
}
/**
* @notice Gets the max amount of `asset` that an address can deposit.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any deposit or mints to enforce
* any limits desired by the strategist. This can be used for either a
* traditional deposit limit or for implementing a whitelist etc.
*
* EX:
* if(isAllowed[_owner]) return super.availableDepositLimit(_owner);
*
* This does not need to take into account any conversion rates
* from shares to assets. But should know that any non max uint256
* amounts may be converted to shares. So it is recommended to keep
* custom amounts low enough as not to cause overflow when multiplied
* by `totalSupply`.
*
* @param . The address that is depositing into the strategy.
* @return . The available amount the `_owner` can deposit in terms of `asset`
*/
function availableDepositLimit(
address /*_owner*/
) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @notice Gets the max amount of `asset` that can be withdrawn.
* @dev Defaults to an unlimited amount for any address. But can
* be overridden by strategists.
*
* This function will be called before any withdraw or redeem to enforce
* any limits desired by the strategist. This can be used for illiquid
* or sandwichable strategies. It should never be lower than `totalIdle`.
*
* EX:
* return TokenIzedStrategy.totalIdle();
*
* This does not need to take into account the `_owner`'s share balance
* or conversion rates from shares to assets.
*
* @param . The address that is withdrawing from the strategy.
* @return . The available amount that can be withdrawn in terms of `asset`
*/
function availableWithdrawLimit(
address /*_owner*/
) public view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @dev Optional function for a strategist to override that will
* allow management to manually withdraw deployed funds from the
* yield source if a strategy is shutdown.
*
* This should attempt to free `_amount`, noting that `_amount` may
* be more than is currently deployed.
*
* NOTE: This will not realize any profits or losses. A separate
* {report} will be needed in order to record any profit/loss. If
* a report may need to be called after a shutdown it is important
* to check if the strategy is shutdown during {_harvestAndReport}
* so that it does not simply re-deploy all funds that had been freed.
*
* EX:
* if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {
* depositFunds...
* }
*
* @param _amount The amount of asset to attempt to free.
*/
function _emergencyWithdraw(uint256 _amount) internal virtual {}
/*//////////////////////////////////////////////////////////////
TokenizedStrategy HOOKS
//////////////////////////////////////////////////////////////*/
/**
* @notice Can deploy up to '_amount' of 'asset' in yield source.
* @dev Callback for the TokenizedStrategy to call during a {deposit}
* or {mint} to tell the strategy it can deploy funds.
*
* Since this can only be called after a {deposit} or {mint}
* delegateCall to the TokenizedStrategy msg.sender == address(this).
*
* Unless a whitelist is implemented this will be entirely permissionless
* and thus can be sandwiched or otherwise manipulated.
*
* @param _amount The amount of 'asset' that the strategy can
* attempt to deposit in the yield source.
*/
function deployFunds(uint256 _amount) external virtual onlySelf {
_deployFunds(_amount);
}
/**
* @notice Should attempt to free the '_amount' of 'asset'.
* @dev Callback for the TokenizedStrategy to call during a withdraw
* or redeem to free the needed funds to service the withdraw.
*
* This can only be called after a 'withdraw' or 'redeem' delegateCall
* to the TokenizedStrategy so msg.sender == address(this).
*
* @param _amount The amount of 'asset' that the strategy should attempt to free up.
*/
function freeFunds(uint256 _amount) external virtual onlySelf {
_freeFunds(_amount);
}
/**
* @notice Returns the accurate amount of all funds currently
* held by the Strategy.
* @dev Callback for the TokenizedStrategy to call during a report to
* get an accurate accounting of assets the strategy controls.
*
* This can only be called after a report() delegateCall to the
* TokenizedStrategy so msg.sender == address(this).
*
* @return . A trusted and accurate account for the total amount
* of 'asset' the strategy currently holds including idle funds.
*/
function harvestAndReport() external virtual onlySelf returns (uint256) {
return _harvestAndReport();
}
/**
* @notice Will call the internal '_tend' when a keeper tends the strategy.
* @dev Callback for the TokenizedStrategy to initiate a _tend call in the strategy.
*
* This can only be called after a tend() delegateCall to the TokenizedStrategy
* so msg.sender == address(this).
*
* We name the function `tendThis` so that `tend` calls are forwarded to
* the TokenizedStrategy.
* @param _totalIdle The amount of current idle funds that can be
* deployed during the tend
*/
function tendThis(uint256 _totalIdle) external virtual onlySelf {
_tend(_totalIdle);
}
/**
* @notice Will call the internal '_emergencyWithdraw' function.
* @dev Callback for the TokenizedStrategy during an emergency withdraw.
*
* This can only be called after a emergencyWithdraw() delegateCall to
* the TokenizedStrategy so msg.sender == address(this).
*
* We name the function `shutdownWithdraw` so that `emergencyWithdraw`
* calls are forwarded to the TokenizedStrategy.
*
* @param _amount The amount of asset to attempt to free.
*/
function shutdownWithdraw(uint256 _amount) external virtual onlySelf {
_emergencyWithdraw(_amount);
}
/**
* @dev Function used to delegate call the TokenizedStrategy with
* certain `_calldata` and return any return values.
*
* This is used to setup the initial storage of the strategy, and
* can be used by strategist to forward any other call to the
* TokenizedStrategy implementation.
*
* @param _calldata The abi encoded calldata to use in delegatecall.
* @return . The return value if the call was successful in bytes.
*/
function _delegateCall(
bytes memory _calldata
) internal returns (bytes memory) {
// Delegate call the tokenized strategy with provided calldata.
(bool success, bytes memory result) = tokenizedStrategyAddress
.delegatecall(_calldata);
// If the call reverted. Return the error.
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
// Return the result.
return result;
}
/**
* @dev Execute a function on the TokenizedStrategy and return any value.
*
* This fallback function will be executed when any of the standard functions
* defined in the TokenizedStrategy are called since they wont be defined in
* this contract.
*
* It will delegatecall the TokenizedStrategy implementation with the exact
* calldata and return any relevant values.
*
*/
fallback() external {
// load our target address
address _tokenizedStrategyAddress = tokenizedStrategyAddress;
// Execute external function using delegatecall and return any value.
assembly {
// Copy function selector and any arguments.
calldatacopy(0, 0, calldatasize())
// Execute function delegatecall.
let result := delegatecall(
gas(),
_tokenizedStrategyAddress,
0,
calldatasize(),
0,
0
)
// Get any return value
returndatacopy(0, 0, returndatasize())
// Return any return value or error back to the caller
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Maths} from "../libraries/Maths.sol";
import {ITaker} from "../interfaces/ITaker.sol";
import {GPv2Order} from "../libraries/GPv2Order.sol";
import {Governance2Step} from "../utils/Governance2Step.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
interface ICowSettlement {
function domainSeparator() external view returns (bytes32);
}
/**
* @title Auction
* @author yearn.fi
* @notice General use dutch auction contract for token sales.
*/
contract Auction is Governance2Step, ReentrancyGuard {
using GPv2Order for GPv2Order.Data;
using SafeERC20 for ERC20;
/// @notice Emitted when a new auction is enabled
event AuctionEnabled(address indexed from, address indexed to);
/// @notice Emitted when an auction is disabled.
event AuctionDisabled(address indexed from, address indexed to);
/// @notice Emitted when auction has been kicked.
event AuctionKicked(address indexed from, uint256 available);
/// @notice Emitted when the receiver is updated.
event UpdatedReceiver(address indexed receiver);
/// @notice Emitted when the minimum price is updated.
event UpdatedMinimumPrice(uint256 indexed minimumPrice);
/// @notice Emitted when the starting price is updated.
event UpdatedStartingPrice(uint256 indexed startingPrice);
/// @notice Emitted when the step decay rate is updated.
event UpdatedStepDecayRate(uint256 indexed stepDecayRate);
/// @notice Emitted when the step duration is updated.
event UpdatedStepDuration(uint256 indexed stepDuration);
/// @notice Emitted when the auction is settled.
event AuctionSettled(address indexed from);
/// @notice Emitted when the auction is swept.
event AuctionSwept(address indexed token, address indexed to);
/// @dev Store address and scaler in one slot.
struct TokenInfo {
address tokenAddress;
uint96 scaler;
}
/// @notice Store all the auction specific information.
struct AuctionInfo {
uint64 kicked;
uint64 scaler;
uint128 initialAvailable;
}
uint256 internal constant WAD = 1e18;
address internal constant COW_SETTLEMENT =
0x9008D19f58AAbD9eD0D60971565AA8510560ab41;
address internal constant VAULT_RELAYER =
0xC92E8bdf79f0507f65a392b0ab4667716BFE0110;
/// @notice The time that each auction lasts.
uint256 internal constant AUCTION_LENGTH = 1 days;
/// @notice Struct to hold the info for `want`.
TokenInfo internal wantInfo;
/// @notice Whether only governance can kick auctions.
/// @dev Default is false.
bool public governanceOnlyKick;
/// @notice The address that will receive the funds in the auction.
address public receiver;
/// @notice The minimum price for the auction, scaled to 1e18.
/// @dev If the price per auction goes below this, the auction is considered inactive.
/// @dev Default is 0 (i.e. no minimum).
uint256 public minimumPrice;
/// @notice The amount to start the auction at.
/// @dev This is an unscaled "lot size" essentially to start the pricing in "want".
/// The kicked amount of _from is divided by this to get the per auction initial price.
uint256 public startingPrice;
/// @notice The time period for each price step in seconds.
uint256 public stepDuration;
/// @notice The decay rate per step in basis points (e.g., 50 for 0.5% decrease per step).
uint256 public stepDecayRate;
/// @notice Mapping from `from` token to its struct.
mapping(address => AuctionInfo) public auctions;
/// @notice Array of all the enabled auction for this contract.
address[] public enabledAuctions;
constructor() Governance2Step(msg.sender) {}
/**
* @notice Initializes the Auction contract with initial parameters.
* @param _want Address this auction is selling to.
* @param _receiver Address that will receive the funds from the auction.
* @param _governance Address of the contract governance.
* @param _startingPrice Starting price for each auction.
*/
function initialize(
address _want,
address _receiver,
address _governance,
uint256 _startingPrice
) public virtual {
require(stepDecayRate == 0, "initialized");
require(_want != address(0), "ZERO ADDRESS");
require(_startingPrice != 0, "starting price");
require(_receiver != address(0), "receiver");
// Cannot have more than 18 decimals.
uint256 decimals = ERC20(_want).decimals();
require(decimals <= 18, "unsupported decimals");
// Set variables
wantInfo = TokenInfo({
tokenAddress: _want,
scaler: uint96(WAD / 10 ** decimals)
});
receiver = _receiver;
governance = _governance;
emit GovernanceTransferred(address(0), _governance);
startingPrice = _startingPrice;
emit UpdatedStartingPrice(_startingPrice);
// Default to 50bps every 60 seconds
stepDuration = 60;
emit UpdatedStepDuration(stepDuration);
stepDecayRate = 50; // 50 basis points = 0.5% decay per step
emit UpdatedStepDecayRate(stepDecayRate);
}
/*//////////////////////////////////////////////////////////////
VIEW METHODS
//////////////////////////////////////////////////////////////*/
function version() external pure returns (string memory) {
return "1.0.4";
}
/**
* @notice Get the address of this auctions want token.
* @return . The want token.
*/
function want() public view virtual returns (address) {
return wantInfo.tokenAddress;
}
function auctionLength() public view virtual returns (uint256) {
return AUCTION_LENGTH;
}
/**
* @notice Get the available amount for the auction.
* @param _from The address of the token to be auctioned.
* @return . The available amount for the auction.
*/
function available(address _from) public view virtual returns (uint256) {
if (!isActive(_from)) return 0;
return
Maths.min(
auctions[_from].initialAvailable,
ERC20(_from).balanceOf(address(this))
);
}
/**
* @notice Get the kicked timestamp for the auction.
* @param _from The address of the token to be auctioned.
* @return . The kicked timestamp for the auction.
*/
function kicked(address _from) external view virtual returns (uint256) {
return auctions[_from].kicked;
}
/**
* @notice Check if the auction is active.
* @param _from The address of the token to be auctioned.
* @return . Whether the auction is active.
*/
function isActive(address _from) public view virtual returns (bool) {
return price(_from, block.timestamp) > 0;
}
/**
* @notice Get all the enabled auctions.
*/
function getAllEnabledAuctions()
external
view
virtual
returns (address[] memory)
{
return enabledAuctions;
}
/**
* @notice Get the pending amount available for the next auction.
* @dev Defaults to the auctions balance of the from token if no hook.
* @param _from The address of the token to be auctioned.
* @return uint256 The amount that can be kicked into the auction.
*/
function kickable(address _from) external view virtual returns (uint256) {
// If not enough time has passed then `kickable` is 0.
if (isActive(_from)) return 0;
// Use the full balance of this contract.
return ERC20(_from).balanceOf(address(this));
}
/**
* @notice Gets the amount of `want` needed to buy the available amount of `from`.
* @param _from The address of the token to be auctioned.
* @return . The amount of `want` needed to fulfill the take amount.
*/
function getAmountNeeded(
address _from
) external view virtual returns (uint256) {
return
_getAmountNeeded(
auctions[_from],
available(_from),
block.timestamp
);
}
/**
* @notice Gets the amount of `want` needed to buy a specific amount of `from`.
* @param _from The address of the token to be auctioned.
* @param _amountToTake The amount of `from` to take in the auction.
* @return . The amount of `want` needed to fulfill the take amount.
*/
function getAmountNeeded(
address _from,
uint256 _amountToTake
) external view virtual returns (uint256) {
return
_getAmountNeeded(auctions[_from], _amountToTake, block.timestamp);
}
/**
* @notice Gets the amount of `want` needed to buy a specific amount of `from` at a specific timestamp.
* @param _from The address of the token to be auctioned.
* @param _amountToTake The amount `from` to take in the auction.
* @param _timestamp The specific timestamp for calculating the amount needed.
* @return . The amount of `want` needed to fulfill the take amount.
*/
function getAmountNeeded(
address _from,
uint256 _amountToTake,
uint256 _timestamp
) external view virtual returns (uint256) {
return _getAmountNeeded(auctions[_from], _amountToTake, _timestamp);
}
/**
* @dev Return the amount of `want` needed to buy `_amountToTake`.
*/
function _getAmountNeeded(
AuctionInfo memory _auction,
uint256 _amountToTake,
uint256 _timestamp
) internal view virtual returns (uint256) {
return
// Scale _amountToTake to 1e18
(_amountToTake *
_auction.scaler *
// Price is always 1e18
_price(
_auction.kicked,
_auction.initialAvailable * _auction.scaler,
_timestamp
)) /
1e18 /
// Scale back down to want.
wantInfo.scaler;
}
/**
* @notice Gets the price of the auction at the current timestamp.
* @param _from The address of the token to be auctioned.
* @return . The price of the auction.
*/
function price(address _from) external view virtual returns (uint256) {
return price(_from, block.timestamp);
}
/**
* @notice Gets the price of the auction at a specific timestamp.
* @param _from The address of the token to be auctioned.
* @param _timestamp The specific timestamp for calculating the price.
* @return . The price of the auction.
*/
function price(
address _from,
uint256 _timestamp
) public view virtual returns (uint256) {
// Get unscaled price and scale it down.
return
_price(
auctions[_from].kicked,
auctions[_from].initialAvailable * auctions[_from].scaler,
_timestamp
) / wantInfo.scaler;
}
/**
* @dev Internal function to calculate the scaled price based on auction parameters.
* @param _kicked The timestamp the auction was kicked.
* @param _available The initial available amount scaled 1e18.
* @param _timestamp The specific timestamp for calculating the price.
* @return . The calculated price scaled to 1e18.
*/
function _price(
uint256 _kicked,
uint256 _available,
uint256 _timestamp
) internal view virtual returns (uint256) {
if (_available == 0) return 0;
uint256 secondsElapsed = _timestamp - _kicked;
if (secondsElapsed > AUCTION_LENGTH) return 0;
// Calculate the number of price steps that have passed
uint256 steps = secondsElapsed / stepDuration;
// Convert basis points to ray multiplier (e.g., 50 bps = 0.995 * 1e27)
// rayMultiplier = 1e27 - (basisPoints * 1e23)
uint256 rayMultiplier = 1e27 - (stepDecayRate * 1e23);
// Calculate the decay multiplier using the configurable decay rate per step
uint256 decayMultiplier = Maths.rpow(rayMultiplier, steps);
// Calculate initial price per token
uint256 initialPrice = Maths.wdiv(startingPrice * 1e18, _available);
// Apply the decay to get the current price
uint256 currentPrice = Maths.rmul(initialPrice, decayMultiplier);
// Return price `0` if below the minimum price
return currentPrice < minimumPrice ? 0 : currentPrice;
}
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Enables a new auction.
* @param _from The address of the token to be auctioned.
*/
function enable(address _from) external virtual onlyGovernance {
address _want = want();
require(_from != address(0) && _from != _want, "ZERO ADDRESS");
require(auctions[_from].scaler == 0, "already enabled");
// Cannot have more than 18 decimals.
uint256 decimals = ERC20(_from).decimals();
require(decimals <= 18, "unsupported decimals");
// Store all needed info.
auctions[_from].scaler = uint64(WAD / 10 ** decimals);
ERC20(_from).forceApprove(VAULT_RELAYER, type(uint256).max);
// Add to the array.
enabledAuctions.push(_from);
emit AuctionEnabled(_from, _want);
}
/**
* @notice Disables an existing auction.
* @dev Only callable by governance.
* @param _from The address of the token being sold.
*/
function disable(address _from) external virtual {
disable(_from, 0);
}
/**
* @notice Disables an existing auction.
* @dev Only callable by governance.
* @param _from The address of the token being sold.
* @param _index The index the auctionId is at in the array.
*/
function disable(
address _from,
uint256 _index
) public virtual onlyGovernance {
// Make sure the auction was enabled.
require(auctions[_from].scaler != 0, "not enabled");
// Remove the struct.
delete auctions[_from];
ERC20(_from).forceApprove(VAULT_RELAYER, 0);
// Remove the auction ID from the array.
address[] memory _enabledAuctions = enabledAuctions;
if (_enabledAuctions[_index] != _from) {
// If the _index given is not the id find it.
for (uint256 i = 0; i < _enabledAuctions.length; ++i) {
if (_enabledAuctions[i] == _from) {
_index = i;
break;
}
}
}
// Move the id to the last spot if not there.
if (_index < _enabledAuctions.length - 1) {
_enabledAuctions[_index] = _enabledAuctions[
_enabledAuctions.length - 1
];
// Update the array.
enabledAuctions = _enabledAuctions;
}
// Pop the id off the array.
enabledAuctions.pop();
emit AuctionDisabled(_from, want());
}
function isAnActiveAuction() public view returns (bool) {
address[] memory _enabledAuctions = enabledAuctions;
for (uint256 i = 0; i < _enabledAuctions.length; ++i) {
if (isActive(_enabledAuctions[i])) {
return true;
}
}
return false;
}
/**
* @notice Sets whether only governance can kick auctions.
* @param _governanceOnlyKick The new governance only kick setting.
*/
function setGovernanceOnlyKick(
bool _governanceOnlyKick
) external virtual onlyGovernance {
governanceOnlyKick = _governanceOnlyKick;
}
/**
* @notice Sets the receiver address for the auction funds.
* @param _receiver The new receiver address.
*/
function setReceiver(address _receiver) external virtual onlyGovernance {
require(_receiver != address(0), "ZERO ADDRESS");
// Don't change the receiver when an auction is active.
require(!isAnActiveAuction(), "active auction");
receiver = _receiver;
emit UpdatedReceiver(_receiver);
}
/**
* @notice Sets the minimum price for the auction.
* @dev If the price per auction goes below this, the auction is considered inactive.
* @dev Default is 0 (i.e. no minimum).
* @param _minimumPrice The new minimum price per auction, scaled to 1e18.
*/
function setMinimumPrice(
uint256 _minimumPrice
) external virtual onlyGovernance {
// Don't change the min price when an auction is active.
require(!isAnActiveAuction(), "active auction");
minimumPrice = _minimumPrice;
emit UpdatedMinimumPrice(_minimumPrice);
}
/**
* @notice Sets the starting price for the auction.
* @dev This is an unscaled "lot size" essentially to start the pricing in "want".
* The kicked amount of _from is divided by this to get the per auction initial price.
* @param _startingPrice The new starting price for the auction.
*/
function setStartingPrice(
uint256 _startingPrice
) external virtual onlyGovernance {
require(_startingPrice != 0, "starting price");
// Don't change the price when an auction is active.
require(!isAnActiveAuction(), "active auction");
startingPrice = _startingPrice;
emit UpdatedStartingPrice(_startingPrice);
}
/**
* @notice Sets the step decay rate for the auction.
* @dev The decay rate is in basis points (e.g., 50 for 0.5% decay per step).
* @param _stepDecayRate The new decay rate per step in basis points (max 10000 = 100%).
*/
function setStepDecayRate(
uint256 _stepDecayRate
) external virtual onlyGovernance {
require(
_stepDecayRate > 0 && _stepDecayRate < 10_000,
"invalid decay rate"
);
// Don't change the decay rate when an auction is active.
require(!isAnActiveAuction(), "active auction");
stepDecayRate = _stepDecayRate;
emit UpdatedStepDecayRate(_stepDecayRate);
}
/**
* @notice Sets the step duration for the auction.
* @param _stepDuration The new step duration in seconds.
*/
function setStepDuration(
uint256 _stepDuration
) external virtual onlyGovernance {
require(
_stepDuration != 0 && _stepDuration < AUCTION_LENGTH,
"invalid step duration"
);
require(!isAnActiveAuction(), "active auction");
stepDuration = _stepDuration;
emit UpdatedStepDuration(_stepDuration);
}
/*//////////////////////////////////////////////////////////////
PARTICIPATE IN AUCTION
//////////////////////////////////////////////////////////////*/
/**
* @notice Kicks off an auction, updating its status and making funds available for bidding.
* @param _from The address of the token to be auctioned.
* @return _available The available amount for bidding on in the auction.
*/
function kick(
address _from
) external virtual nonReentrant returns (uint256 _available) {
return _kick(_from);
}
function _kick(
address _from
) internal virtual returns (uint256 _available) {
if (governanceOnlyKick) _checkGovernance();
require(auctions[_from].scaler != 0, "not enabled");
require(!isActive(_from), "too soon");
// Just use current balance.
_available = ERC20(_from).balanceOf(address(this));
require(_available != 0, "nothing to kick");
// Update the auctions status.
auctions[_from].kicked = uint64(block.timestamp);
auctions[_from].initialAvailable = uint128(_available);
emit AuctionKicked(_from, _available);
}
/**
* @notice Take the token being sold in a live auction.
* @dev Defaults to taking the full amount and sending to the msg sender.
* @param _from The address of the token to be auctioned.
* @return . The amount of fromToken taken in the auction.
*/
function take(address _from) external virtual returns (uint256) {
return _take(_from, type(uint256).max, msg.sender, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction with a specified maximum amount.
* @dev Will send the funds to the msg sender.
* @param _from The address of the token to be auctioned.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @return . The amount of fromToken taken in the auction.
*/
function take(
address _from,
uint256 _maxAmount
) external virtual returns (uint256) {
return _take(_from, _maxAmount, msg.sender, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction.
* @param _from The address of the token to be auctioned.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @param _takerReceiver The address that will receive the fromToken.
* @return _amountTaken The amount of fromToken taken in the auction.
*/
function take(
address _from,
uint256 _maxAmount,
address _takerReceiver
) external virtual returns (uint256) {
return _take(_from, _maxAmount, _takerReceiver, new bytes(0));
}
/**
* @notice Take the token being sold in a live auction.
* @param _from The address of the token to be auctioned.
* @param _maxAmount The maximum amount of fromToken to take in the auction.
* @param _takerReceiver The address that will receive the fromToken.
* @param _data The data signify the callback should be used and sent with it.
* @return _amountTaken The amount of fromToken taken in the auction.
*/
function take(
address _from,
uint256 _maxAmount,
address _takerReceiver,
bytes calldata _data
) external virtual returns (uint256) {
return _take(_from, _maxAmount, _takerReceiver, _data);
}
/// @dev Implements the take of the auction.
function _take(
address _from,
uint256 _maxAmount,
address _takerReceiver,
bytes memory _data
) internal virtual nonReentrant returns (uint256 _amountTaken) {
AuctionInfo memory auction = auctions[_from];
// Max amount that can be taken.
uint256 _available = Maths.min(
auction.initialAvailable,
ERC20(_from).balanceOf(address(this))
);
_amountTaken = _available > _maxAmount ? _maxAmount : _available;
// Get the amount needed. Returns 0 if auction not active.
uint256 needed = _getAmountNeeded(
auction,
_amountTaken,
block.timestamp
);
require(needed != 0, "zero needed");
// Send `from`.
ERC20(_from).safeTransfer(_takerReceiver, _amountTaken);
// If the caller has specified data.
if (_data.length != 0) {
// Do the callback.
ITaker(_takerReceiver).auctionTakeCallback(
_from,
msg.sender,
_amountTaken,
needed,
_data
);
}
// Cache the want address.
address _want = want();
// Pull `want`.
ERC20(_want).safeTransferFrom(msg.sender, receiver, needed);
// If the full amount is taken, end the auction.
if (_amountTaken == _available) {
auctions[_from].kicked = uint64(0);
emit AuctionSettled(_from);
}
}
/// @dev Validates a COW order signature.
function isValidSignature(
bytes32 _hash,
bytes calldata signature
) external view returns (bytes4) {
// Make sure `_take` has not already been entered.
require(!_reentrancyGuardEntered(), "ReentrancyGuard: reentrant call");
// Decode the signature to get the order.
GPv2Order.Data memory order = abi.decode(signature, (GPv2Order.Data));
AuctionInfo memory auction = auctions[address(order.sellToken)];
// Get the current amount needed for the auction.
uint256 paymentAmount = _getAmountNeeded(
auction,
order.sellAmount,
block.timestamp
);
// Verify the order details.
// Retreive domain seperator each time for chains it is not deployed on yet
require(
_hash ==
order.hash(ICowSettlement(COW_SETTLEMENT).domainSeparator()),
"bad order"
);
require(paymentAmount != 0, "zero amount");
require(available(address(order.sellToken)) != 0, "zero available");
require(order.feeAmount == 0, "fee");
require(order.partiallyFillable, "partial fill");
require(order.validTo < auction.kicked + AUCTION_LENGTH, "expired");
require(order.appData == bytes32(0), "app data");
require(order.buyAmount >= paymentAmount, "bad price");
require(address(order.buyToken) == want(), "bad token");
require(order.receiver == receiver, "bad receiver");
require(order.sellAmount <= auction.initialAvailable, "bad amount");
require(
order.sellTokenBalance == keccak256("erc20"),
"bad sell token balance"
);
require(
order.buyTokenBalance == keccak256("erc20"),
"bad buy token balance"
);
// If all checks pass, return the magic value
return this.isValidSignature.selector;
}
/**
* @notice Forces the auction to be kicked.
* @dev Only callable by governance in replace of sweep settle and kick.
* @param _from The address of the token to be auctioned.
*/
function forceKick(address _from) external onlyGovernance {
auctions[_from].kicked = uint64(0);
_kick(_from);
}
/**
* @notice Allows the auction to be stopped if the full amount is taken.
* @param _from The address of the token to be auctioned.
*/
function settle(address _from) external virtual {
require(isActive(_from), "!active");
require(ERC20(_from).balanceOf(address(this)) == 0, "!empty");
auctions[_from].kicked = uint64(0);
emit AuctionSettled(_from);
}
function sweep(address _token) external virtual onlyGovernance {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
emit AuctionSwept(_token, msg.sender);
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Clonable} from "./Clonable.sol";
contract ClonableCreate2 is Clonable {
/**
* @notice Clone the contracts default `original` contract using CREATE2.
* @param salt The salt to use for deterministic deployment.
* @return Address of the new Minimal Proxy clone.
*/
function _cloneCreate2(bytes32 salt) internal virtual returns (address) {
return _cloneCreate2(original, salt);
}
/**
* @notice Clone any `_original` contract using CREATE2.
* @param _original The address of the contract to clone.
* @param salt The salt to use for deterministic deployment.
* @return _newContract Address of the new Minimal Proxy clone.
*/
function _cloneCreate2(
address _original,
bytes32 salt
) internal virtual returns (address _newContract) {
// Hash the salt with msg.sender to protect deployments for specific callers
bytes32 finalSalt = getSalt(salt, msg.sender);
address predicted = computeCreate2Address(_original, salt, msg.sender);
bytes20 addressBytes = bytes20(_original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
_newContract := create2(0, clone_code, 0x37, finalSalt)
}
require(
_newContract != address(0) && _newContract == predicted,
"ClonableCreate2: create2 failed"
);
}
/**
* @notice Compute the address where a clone would be deployed using CREATE2.
* @param salt The salt to use for address computation.
* @return The address where the clone would be deployed.
*/
function computeCreate2Address(
bytes32 salt
) external view virtual returns (address) {
return computeCreate2Address(original, salt, msg.sender);
}
/**
* @notice Compute the address where a clone would be deployed using CREATE2.
* @param _original The address of the contract to clone.
* @param salt The salt to use for address computation.
* @return predicted address where the clone would be deployed.
*/
function computeCreate2Address(
address _original,
bytes32 salt
) external view virtual returns (address predicted) {
return computeCreate2Address(_original, salt, msg.sender);
}
/**
* @notice Compute the address where a clone would be deployed using CREATE2.
* @param _original The address of the contract to clone.
* @param salt The salt to use for address computation.
* @return predicted The address where the clone would be deployed.
*/
function computeCreate2Address(
address _original,
bytes32 salt,
address deployer
) public view virtual returns (address predicted) {
// Hash the salt with msg.sender to match deployment behavior
bytes32 finalSalt = getSalt(salt, deployer);
bytes20 addressBytes = bytes20(_original);
assembly {
let ptr := mload(0x40)
// Store the prefix
mstore(
ptr,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// Store the address
mstore(add(ptr, 0x14), addressBytes)
// Store the suffix
mstore(
add(ptr, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// Compute init code hash
let initCodeHash := keccak256(ptr, 0x37)
// Compute the CREATE2 address
// 0xff ++ address(this) ++ salt ++ initCodeHash
mstore(ptr, 0xff)
mstore8(ptr, 0xff)
mstore(add(ptr, 0x01), shl(96, address()))
mstore(add(ptr, 0x15), finalSalt)
mstore(add(ptr, 0x35), initCodeHash)
predicted := keccak256(ptr, 0x55)
}
}
/**
* @dev Internal function to compute the final salt by hashing with msg.sender.
* This ensures that different callers get different deployment addresses
* even when using the same salt value.
* @param salt The user-provided salt.
* @return The final salt to use for CREATE2.
*/
function getSalt(
bytes32 salt,
address deployer
) public view virtual returns (bytes32) {
return keccak256(abi.encodePacked(salt, deployer));
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
// Interface that implements the 4626 standard and the implementation functions
interface ITokenizedStrategy is IERC4626, IERC20Permit {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event StrategyShutdown();
event NewTokenizedStrategy(
address indexed strategy,
address indexed asset,
string apiVersion
);
event Reported(
uint256 profit,
uint256 loss,
uint256 protocolFees,
uint256 performanceFees
);
event UpdatePerformanceFeeRecipient(
address indexed newPerformanceFeeRecipient
);
event UpdateKeeper(address indexed newKeeper);
event UpdatePerformanceFee(uint16 newPerformanceFee);
event UpdateManagement(address indexed newManagement);
event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);
event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime);
event UpdatePendingManagement(address indexed newPendingManagement);
/*//////////////////////////////////////////////////////////////
INITIALIZATION
//////////////////////////////////////////////////////////////*/
function initialize(
address _asset,
string memory _name,
address _management,
address _performanceFeeRecipient,
address _keeper
) external;
/*//////////////////////////////////////////////////////////////
NON-STANDARD 4626 OPTIONS
//////////////////////////////////////////////////////////////*/
function withdraw(
uint256 assets,
address receiver,
address owner,
uint256 maxLoss
) external returns (uint256);
function redeem(
uint256 shares,
address receiver,
address owner,
uint256 maxLoss
) external returns (uint256);
function maxWithdraw(
address owner,
uint256 /*maxLoss*/
) external view returns (uint256);
function maxRedeem(
address owner,
uint256 /*maxLoss*/
) external view returns (uint256);
/*//////////////////////////////////////////////////////////////
MODIFIER HELPERS
//////////////////////////////////////////////////////////////*/
function requireManagement(address _sender) external view;
function requireKeeperOrManagement(address _sender) external view;
function requireEmergencyAuthorized(address _sender) external view;
/*//////////////////////////////////////////////////////////////
KEEPERS FUNCTIONS
//////////////////////////////////////////////////////////////*/
function tend() external;
function report() external returns (uint256 _profit, uint256 _loss);
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
function MAX_FEE() external view returns (uint16);
function FACTORY() external view returns (address);
/*//////////////////////////////////////////////////////////////
GETTERS
//////////////////////////////////////////////////////////////*/
function apiVersion() external view returns (string memory);
function pricePerShare() external view returns (uint256);
function management() external view returns (address);
function pendingManagement() external view returns (address);
function keeper() external view returns (address);
function emergencyAdmin() external view returns (address);
function performanceFee() external view returns (uint16);
function performanceFeeRecipient() external view returns (address);
function fullProfitUnlockDate() external view returns (uint256);
function profitUnlockingRate() external view returns (uint256);
function profitMaxUnlockTime() external view returns (uint256);
function lastReport() external view returns (uint256);
function isShutdown() external view returns (bool);
function unlockedShares() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
SETTERS
//////////////////////////////////////////////////////////////*/
function setPendingManagement(address) external;
function acceptManagement() external;
function setKeeper(address _keeper) external;
function setEmergencyAdmin(address _emergencyAdmin) external;
function setPerformanceFee(uint16 _performanceFee) external;
function setPerformanceFeeRecipient(
address _performanceFeeRecipient
) external;
function setProfitMaxUnlockTime(uint256 _profitMaxUnlockTime) external;
function setName(string calldata _newName) external;
function shutdownStrategy() external;
function emergencyWithdraw(uint256 _amount) external;
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.18;
// Math library from https://github.com/ajna-finance/ajna-core/blob/master/src/libraries/internal/Maths.sol
/**
@title Maths library
@notice Internal library containing common maths.
*/
library Maths {
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + WAD / 2) / WAD;
}
function floorWmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y) / WAD;
}
function ceilWmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + WAD - 1) / WAD;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD + y / 2) / y;
}
function floorWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD) / y;
}
function ceilWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * WAD + y - 1) / y;
}
function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256) {
return (x + y - 1) / y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
function wad(uint256 x) internal pure returns (uint256) {
return x * WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256) {
return (x * y + RAY / 2) / RAY;
}
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
/*************************/
/*** Integer Functions ***/
/*************************/
function maxInt(int256 x, int256 y) internal pure returns (int256) {
return x >= y ? x : y;
}
function minInt(int256 x, int256 y) internal pure returns (int256) {
return x <= y ? x : y;
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
interface ITaker {
function auctionTakeCallback(
address _from,
address _sender,
uint256 _amountTaken,
uint256 _amountNeeded,
bytes calldata _data
) external;
}// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title Gnosis Protocol v2 Order Library
/// @author Gnosis Developers
library GPv2Order {
/// @dev The complete data for a Gnosis Protocol order. This struct contains
/// all order parameters that are signed for submitting to GP.
struct Data {
ERC20 sellToken;
ERC20 buyToken;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
bytes32 kind;
bool partiallyFillable;
bytes32 sellTokenBalance;
bytes32 buyTokenBalance;
}
/// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256(
/// "Order(" +
/// "address sellToken," +
/// "address buyToken," +
/// "address receiver," +
/// "uint256 sellAmount," +
/// "uint256 buyAmount," +
/// "uint32 validTo," +
/// "bytes32 appData," +
/// "uint256 feeAmount," +
/// "string kind," +
/// "bool partiallyFillable" +
/// "string sellTokenBalance" +
/// "string buyTokenBalance" +
/// ")"
/// )
/// ```
bytes32 internal constant TYPE_HASH =
hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489";
/// @dev The marker value for a sell order for computing the order struct
/// hash. This allows the EIP-712 compatible wallets to display a
/// descriptive string for the order kind (instead of 0 or 1).
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("sell")
/// ```
bytes32 internal constant KIND_SELL =
hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775";
/// @dev The OrderKind marker value for a buy order for computing the order
/// struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("buy")
/// ```
bytes32 internal constant KIND_BUY =
hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc";
/// @dev The TokenBalance marker value for using direct ERC20 balances for
/// computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("erc20")
/// ```
bytes32 internal constant BALANCE_ERC20 =
hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9";
/// @dev The TokenBalance marker value for using Balancer Vault external
/// balances (in order to re-use Vault ERC20 approvals) for computing the
/// order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("external")
/// ```
bytes32 internal constant BALANCE_EXTERNAL =
hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632";
/// @dev The TokenBalance marker value for using Balancer Vault internal
/// balances for computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("internal")
/// ```
bytes32 internal constant BALANCE_INTERNAL =
hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce";
/// @dev Marker address used to indicate that the receiver of the trade
/// proceeds should the owner of the order.
///
/// This is chosen to be `address(0)` for gas efficiency as it is expected
/// to be the most common case.
address internal constant RECEIVER_SAME_AS_OWNER = address(0);
/// @dev The byte length of an order unique identifier.
uint256 internal constant UID_LENGTH = 56;
/// @dev Returns the actual receiver for an order. This function checks
/// whether or not the [`receiver`] field uses the marker value to indicate
/// it is the same as the order owner.
///
/// @return receiver The actual receiver of trade proceeds.
function actualReceiver(
Data memory order,
address owner
) internal pure returns (address receiver) {
if (order.receiver == RECEIVER_SAME_AS_OWNER) {
receiver = owner;
} else {
receiver = order.receiver;
}
}
/// @dev Return the EIP-712 signing hash for the specified order.
///
/// @param order The order to compute the EIP-712 signing hash for.
/// @param domainSeparator The EIP-712 domain separator to use.
/// @return orderDigest The 32 byte EIP-712 struct hash.
function hash(
Data memory order,
bytes32 domainSeparator
) internal pure returns (bytes32 orderDigest) {
bytes32 structHash;
// NOTE: Compute the EIP-712 order struct hash in place. As suggested
// in the EIP proposal, noting that the order struct has 10 fields, and
// including the type hash `(12 + 1) * 32 = 416` bytes to hash.
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata>
// solhint-disable-next-line no-inline-assembly
assembly {
let dataStart := sub(order, 32)
let temp := mload(dataStart)
mstore(dataStart, TYPE_HASH)
structHash := keccak256(dataStart, 416)
mstore(dataStart, temp)
}
// NOTE: Now that we have the struct hash, compute the EIP-712 signing
// hash using scratch memory past the free memory pointer. The signing
// hash is computed from `"\x19\x01" || domainSeparator || structHash`.
// <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory>
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification>
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, "\x19\x01")
mstore(add(freeMemoryPointer, 2), domainSeparator)
mstore(add(freeMemoryPointer, 34), structHash)
orderDigest := keccak256(freeMemoryPointer, 66)
}
}
/// @dev Packs order UID parameters into the specified memory location. The
/// result is equivalent to `abi.encodePacked(...)` with the difference that
/// it allows re-using the memory for packing the order UID.
///
/// This function reverts if the order UID buffer is not the correct size.
///
/// @param orderUid The buffer pack the order UID parameters into.
/// @param orderDigest The EIP-712 struct digest derived from the order
/// parameters.
/// @param owner The address of the user who owns this order.
/// @param validTo The epoch time at which the order will stop being valid.
function packOrderUidParams(
bytes memory orderUid,
bytes32 orderDigest,
address owner,
uint32 validTo
) internal pure {
require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow");
// NOTE: Write the order UID to the allocated memory buffer. The order
// parameters are written to memory in **reverse order** as memory
// operations write 32-bytes at a time and we want to use a packed
// encoding. This means, for example, that after writing the value of
// `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32`
// will **overwrite** bytes `20:32`. This is desirable as addresses are
// only 20 bytes and `20:32` should be `0`s:
//
// | 1111111111222222222233333333334444444444555555
// byte | 01234567890123456789012345678901234567890123456789012345
// -------+---------------------------------------------------------
// field | [.........orderDigest..........][......owner.......][vT]
// -------+---------------------------------------------------------
// mstore | [000000000000000000000000000.vT]
// | [00000000000.......owner.......]
// | [.........orderDigest..........]
//
// Additionally, since Solidity `bytes memory` are length prefixed,
// 32 needs to be added to all the offsets.
//
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(orderUid, 56), validTo)
mstore(add(orderUid, 52), owner)
mstore(add(orderUid, 32), orderDigest)
}
}
/// @dev Extracts specific order information from the standardized unique
/// order id of the protocol.
///
/// @param orderUid The unique identifier used to represent an order in
/// the protocol. This uid is the packed concatenation of the order digest,
/// the validTo order parameter and the address of the user who created the
/// order. It is used by the user to interface with the contract directly,
/// and not by calls that are triggered by the solvers.
/// @return orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @return owner The address of the user who owns this order.
/// @return validTo The epoch time at which the order will stop being valid.
function extractOrderUidParams(
bytes calldata orderUid
)
internal
pure
returns (bytes32 orderDigest, address owner, uint32 validTo)
{
require(orderUid.length == UID_LENGTH, "GPv2: invalid uid");
// Use assembly to efficiently decode packed calldata.
// solhint-disable-next-line no-inline-assembly
assembly {
orderDigest := calldataload(orderUid.offset)
owner := shr(96, calldataload(add(orderUid.offset, 32)))
validTo := shr(224, calldataload(add(orderUid.offset, 52)))
}
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
import {Governance} from "./Governance.sol";
contract Governance2Step is Governance {
/// @notice Emitted when the pending governance address is set.
event UpdatePendingGovernance(address indexed newPendingGovernance);
/// @notice Address that is set to take over governance.
address public pendingGovernance;
constructor(address _governance) Governance(_governance) {}
/**
* @notice Sets a new address as the `pendingGovernance` of the contract.
* @dev Throws if the caller is not current governance.
* @param _newGovernance The new governance address.
*/
function transferGovernance(
address _newGovernance
) external virtual override onlyGovernance {
require(_newGovernance != address(0), "ZERO ADDRESS");
pendingGovernance = _newGovernance;
emit UpdatePendingGovernance(_newGovernance);
}
/**
* @notice Allows the `pendingGovernance` to accept the role.
*/
function acceptGovernance() external virtual {
require(msg.sender == pendingGovernance, "!pending governance");
emit GovernanceTransferred(governance, msg.sender);
governance = msg.sender;
pendingGovernance = address(0);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
contract Clonable {
/// @notice Set to the address to auto clone from.
address public original;
/**
* @notice Clone the contracts default `original` contract.
* @return Address of the new Minimal Proxy clone.
*/
function _clone() internal virtual returns (address) {
return _clone(original);
}
/**
* @notice Clone any `_original` contract.
* @return _newContract Address of the new Minimal Proxy clone.
*/
function _clone(
address _original
) internal virtual returns (address _newContract) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(_original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
_newContract := create(0, clone_code, 0x37)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* _Available since v4.7._
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;
contract Governance {
/// @notice Emitted when the governance address is updated.
event GovernanceTransferred(
address indexed previousGovernance,
address indexed newGovernance
);
modifier onlyGovernance() {
_checkGovernance();
_;
}
/// @notice Checks if the msg sender is the governance.
function _checkGovernance() internal view virtual {
require(governance == msg.sender, "!governance");
}
/// @notice Address that can set the default base fee and provider
address public governance;
constructor(address _governance) {
governance = _governance;
emit GovernanceTransferred(address(0), _governance);
}
/**
* @notice Sets a new address as the governance of the contract.
* @dev Throws if the caller is not current governance.
* @param _newGovernance The new governance address.
*/
function transferGovernance(
address _newGovernance
) external virtual onlyGovernance {
require(_newGovernance != address(0), "ZERO ADDRESS");
address oldGovernance = governance;
governance = _newGovernance;
emit GovernanceTransferred(oldGovernance, _newGovernance);
}
}{
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/",
"forge-std/=lib/forge-std/src/",
"@tokenized-strategy/=lib/tokenized-strategy/src/",
"@periphery/=lib/tokenized-strategy-periphery/src/",
"ds-test/=lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"tokenized-strategy-periphery/=lib/tokenized-strategy-periphery/",
"tokenized-strategy/=lib/tokenized-strategy/",
"yearn-vaults-v3/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "shanghai",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"address","name":"_collateralToken","type":"address"},{"internalType":"address","name":"_addressesProvider","type":"address"},{"internalType":"address","name":"_morpho","type":"address"},{"internalType":"uint8","name":"_eModeCategoryId","type":"uint8"},{"internalType":"address","name":"_exchange","type":"address"},{"internalType":"address","name":"_governance","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"auction","type":"address"}],"name":"AuctionSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bool","name":"useAuction","type":"bool"}],"name":"UseAuctionSet","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"AAVE_ORACLE","outputs":[{"internalType":"contract IAaveOracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"A_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DATA_PROVIDER","outputs":[{"internalType":"contract IPoolDataProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"E_MODE_CATEGORY_ID","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GOVERNANCE","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MORPHO","outputs":[{"internalType":"contract IMorpho","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARDS_CONTROLLER","outputs":[{"internalType":"contract IRewardsController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VARIABLE_DEBT_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"allowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"auction","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"}],"name":"auctionTrigger","outputs":[{"internalType":"bool","name":"shouldKick","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"availableDepositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"availableWithdrawLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfAsset","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfCollateralToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"convertAssetToCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"convertCollateralToAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deployFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doHealthCheck","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"estimatedTotalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exchange","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"freeFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCurrentLTV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidateCollateralFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_equity","type":"uint256"}],"name":"getTargetPosition","outputs":[{"internalType":"uint256","name":"collateral","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"harvestAndReport","outputs":[{"internalType":"uint256","name":"_totalAssets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"kickAuction","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"kickable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTend","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"leverageBuffer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lossLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manualFullUnwind","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualSupplyCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualWithdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maxAmountToSwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxFlashloan","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxGasPriceToTend","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minAmountToBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minAmountToSell","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minTendInterval","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onMorphoFlashLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"position","outputs":[{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"profitLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reportBuffer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"bool","name":"_allowed","type":"bool"}],"name":"setAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_auction","type":"address"}],"name":"setAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_depositLimit","type":"uint256"}],"name":"setDepositLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_doHealthCheck","type":"bool"}],"name":"setDoHealthCheck","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_exchange","type":"address"}],"name":"setExchange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_targetLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"_leverageBuffer","type":"uint256"},{"internalType":"uint256","name":"_maxLeverageRatio","type":"uint256"}],"name":"setLeverageParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newLossLimitRatio","type":"uint256"}],"name":"setLossLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxAmountToSwap","type":"uint256"}],"name":"setMaxAmountToSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxGasPriceToTend","type":"uint256"}],"name":"setMaxGasPriceToTend","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minAmountToBorrow","type":"uint256"}],"name":"setMinAmountToBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minTendInterval","type":"uint256"}],"name":"setMinTendInterval","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newProfitLimitRatio","type":"uint256"}],"name":"setProfitLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_reportBuffer","type":"uint256"}],"name":"setReportBuffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_slippage","type":"uint256"}],"name":"setSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_useAuction","type":"bool"}],"name":"setUseAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"shutdownWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slippage","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"targetLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_totalIdle","type":"uint256"}],"name":"tendThis","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tendTrigger","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenizedStrategyAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"useAuction","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"}]Contract Creation Code
6102406040525f805462ffffff19166227100117905534801562000021575f80fd5b506040516200607238038062006072833981016040819052620000449162000d76565b6001600160a01b0388166080523060a052604051889088908890849086908590859082908290620000bb9062000087908490849033908190819060240162000ed9565b60408051601f198184030181529190526020810180516001600160e01b03908116634b839d7360e11b17909152620006b616565b505073d377919fa87120584b21279a491f82d5265a139c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc555050506001600160a01b038216620001415760405162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b60448201526064015b60405180910390fd5b6001600160a01b0380841660e052821660c0525f196005819055305f908152600c60205260408120805460ff191660011790556729a2241af62c00006009556703782dace9d90000600755673782dace9d900000600855611c20600455600691909155642e90edd000600a9081558154651e0000000000600160281b600160681b031990911617909155620001d69062000745565b620001e36103e8620007a7565b6001600160a01b03811615620001fe57620001fe8162000844565b5050505050836001600160a01b0316610100816001600160a01b031681525050846001600160a01b031663026b1d5f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200025b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000281919062000f1b565b6001600160a01b0316610120816001600160a01b031681525050846001600160a01b031663e860accb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620002d8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002fe919062000f1b565b6001600160a01b0316610140816001600160a01b031681525050846001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000355573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200037b919062000f1b565b6001600160a01b0390811661016052610140516040516334924edb60e21b815288831660048201525f92919091169063d2493b6c90602401606060405180830381865afa158015620003cf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620003f5919062000f37565b50509050806001600160a01b03166101a0816001600160a01b031681525050806001600160a01b03166375d264136040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000451573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000477919062000f1b565b6001600160a01b0390811661018052610140516040516334924edb60e21b81528b831660048201525f92919091169063d2493b6c90602401606060405180830381865afa158015620004cb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620004f1919062000f37565b92505050806001600160a01b03166101c0816001600160a01b031681525050876001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200054d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000573919062000f7e565b60ff166101e08181525050896001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015620005bb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620005e1919062000f7e565b60ff908116610200528516610220819052156200065757610120516040516328530a4760e01b815260ff871660048201526001600160a01b03909116906328530a47906024015f604051808303815f87803b1580156200063f575f80fd5b505af115801562000652573d5f803e3d5ffd5b505050505b6101205162000673906001600160a01b038c16905f196200091d565b610120516200068f906001600160a01b038a16905f196200091d565b620006a66001600160a01b038b16875f196200091d565b5050505050505050505062000fec565b60605f8073d377919fa87120584b21279a491f82d5265a139c6001600160a01b031684604051620006e8919062000f9a565b5f60405180830381855af49150503d805f811462000722576040519150601f19603f3d011682016040523d82523d5f602084013e62000727565b606091505b5091509150816200073e576040513d805f833e8082fd5b9392505050565b6127108110620007865760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b604482015260640162000138565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b5f8111620007e75760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b604482015260640162000138565b61ffff811115620008275760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b604482015260640162000138565b5f805461ffff9092166101000262ffff0019909216919091179055565b6001600160a01b038116620008885760405162461bcd60e51b81526020600482015260096024820152682165786368616e676560b81b604482015260640162000138565b6001546001600160a01b03168015620008cd57608051620008b4906001600160a01b0316825f6200091d565b60e051620008cd906001600160a01b0316825f6200091d565b600180546001600160a01b0319166001600160a01b0384811691909117909155608051620008ff9116835f196200091d565b60e05162000919906001600160a01b0316835f196200091d565b5050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b17909152620009779085908390620009f216565b620009ec576040516001600160a01b03841660248201525f6044820152620009e090859063095ea7b360e01b9060640160408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b039384161790529062000a9c16565b620009ec848262000a9c565b50505050565b5f805f846001600160a01b03168460405162000a0f919062000f9a565b5f604051808303815f865af19150503d805f811462000a4a576040519150601f19603f3d011682016040523d82523d5f602084013e62000a4f565b606091505b509150915081801562000a7d57508051158062000a7d57508080602001905181019062000a7d919062000fb7565b801562000a9357506001600160a01b0385163b15155b95945050505050565b6040805180820190915260208082527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564908201525f9062000aea906001600160a01b03851690849062000b73565b905080515f148062000b0d57508080602001905181019062000b0d919062000fb7565b62000b6e5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840162000138565b505050565b606062000b8384845f8562000b8b565b949350505050565b60608247101562000bee5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840162000138565b5f80866001600160a01b0316858760405162000c0b919062000f9a565b5f6040518083038185875af1925050503d805f811462000c47576040519150601f19603f3d011682016040523d82523d5f602084013e62000c4c565b606091505b50909250905062000c608783838762000c6b565b979650505050505050565b6060831562000cde5782515f0362000cd6576001600160a01b0385163b62000cd65760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640162000138565b508162000b83565b62000b83838381511562000cf55781518083602001fd5b8060405162461bcd60e51b815260040162000138919062000fd8565b80516001600160a01b038116811462000d28575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b5f5b8381101562000d5d57818101518382015260200162000d43565b50505f910152565b805160ff8116811462000d28575f80fd5b5f805f805f805f80610100898b03121562000d8f575f80fd5b62000d9a8962000d11565b60208a01519098506001600160401b038082111562000db7575f80fd5b818b0191508b601f83011262000dcb575f80fd5b81518181111562000de05762000de062000d2d565b604051601f8201601f19908116603f0116810190838211818310171562000e0b5762000e0b62000d2d565b816040528281528e602084870101111562000e24575f80fd5b62000e3783602083016020880162000d41565b809b50505050505062000e4d60408a0162000d11565b955062000e5d60608a0162000d11565b945062000e6d60808a0162000d11565b935062000e7d60a08a0162000d65565b925062000e8d60c08a0162000d11565b915062000e9d60e08a0162000d11565b90509295985092959890939650565b5f815180845262000ec581602086016020860162000d41565b601f01601f19169290920160200192915050565b5f60018060a01b03808816835260a0602084015262000efc60a084018862000eac565b9581166040840152938416606083015250911660809091015292915050565b5f6020828403121562000f2c575f80fd5b6200073e8262000d11565b5f805f6060848603121562000f4a575f80fd5b62000f558462000d11565b925062000f656020850162000d11565b915062000f756040850162000d11565b90509250925092565b5f6020828403121562000f8f575f80fd5b6200073e8262000d65565b5f825162000fad81846020870162000d41565b9190910192915050565b5f6020828403121562000fc8575f80fd5b815180151581146200073e575f80fd5b602081525f6200073e602083018462000eac565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e0516102005161022051614dda620012985f395f6105f601525f61380401525f81816137bf015261438501525f818161056301528181610f5c0152613b4601525f81816108b4015281816115460152613af301525f81816109860152613b9d01525f81816104fd01528181613693015261374001525f818161095f0152818161162f015281816123d5015281816124830152818161253f01528181614257015261431201525f81816107ca0152818161278d01528181612d3001528181612f2b015281816132bc015281816133570152613f1b01525f818161063701528181610d2301528181611ec1015261416c01525f818161090101528181611603015281816117f2015281816123ab01528181612758015281816129f901528181612a7b015281816132810152818161332801528181613667015281816138cb015281816140b60152818161422b01526142e801525f818161053c015261158801525f8181610b7c01528181610c1e01528181610c9d01528181610ff9015281816110f8015281816113c6015281816114800152818161171b0152818161183e015281816118b90152818161191c015281816119b601528181611a3201528181611ab901528181611b4501528181611bcb01528181611c4601528181611cc201528181611d9801528181611e1401528181611fa301528181612083015281816121050152818161219d0152818161260f0152818161280e01526133a001525f81816117a401528181611eeb0152818161245701528181612513015281816129c501528181612a4601528181612c0901528181612cf401528181612ee901528181613713015281816138f301528181613d5a01528181613eae015261408e0152614dda5ff3fe608060405234801561000f575f80fd5b5060043610610452575f3560e01c80637535d2461161023f578063bdc8144b11610139578063d6968601116100c1578063f0fa55a911610085578063f0fa55a914610a48578063fc7f71b614610a5b578063fd9f5f7514610a6e578063fde813a814610a81578063ff831b0514610a9457610452565b8063d696860114610a14578063e862114914610a27578063ea9c840714610a2f578063ecf7085814610a37578063efbb5cb014610a4057610452565b8063cfaec0da11610108578063cfaec0da146109a8578063d19a3bb8146109bb578063d2f7265a146109d6578063d472a43b146109e9578063d63a8e11146109f257610452565b8063bdc8144b1461093f578063c31443bb14610952578063c396cbf41461095a578063cd086d451461098157610452565b8063950b3d73116101c7578063ac00ff261161018b578063ac00ff26146108d6578063afeb4965146108e9578063b2016bd4146108fc578063b6a1650614610923578063b8c6f5791461092c57610452565b8063950b3d731461086357806398cdabc9146108765780639b90fb16146108895780639d7fb70c1461089c5780639ef0159f146108af57610452565b80637d9699321161020e5780637d9699321461080f5780637d9f6db5146108215780638298a4be1461083457806384d78a38146108475780638ca6dd4d1461085b57610452565b80637535d246146107c5578063757a291f146107ec578063797bf343146107ff5780637baf6f771461080757610452565b80633e032a3b1161035057806354fd4d50116102d85780636718835f1161029c5780636718835f1461077257806367b1f5df1461078e5780636be36a1d146107a15780636c7a0c91146107a957806372b10dd5146107bc57610452565b806354fd4d501461071f578063580e0d81146107465780635d265d3f146107595780635ef76292146107615780636687500e1461076a57610452565b80634a5d09431161031f5780634a5d0943146106cd5780634aca9482146106dd5780635009dd1d146106f0578063503160d91461070357806352a25a721461071657610452565b80633e032a3b1461066c5780634697f05d1461069f57806346aa2f12146106b257806349317f1d146106c557610452565b806318144367116103de5780633259356e116103a25780633259356e146105d057806335faba33146105f1578063392f7a701461062a5780633acb5624146106325780633d6cb5751461065957610452565b8063181443671461058557806320aa49ae1461058e5780632b0015e6146105a15780632cd68034146105b457806331f57072146105bd57610452565b80630ea44a56116104255780630ea44a56146104e657806313070d00146104ef57806313f8bf67146104f85780631462783414610537578063179474b51461055e57610452565b806304bd4629146104875780630870e180146104ad57806309218e91146104c05780630b3883fc146104dd575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e808015610481573d5ff35b3d5ffd5b005b61049a610495366004614673565b610aa7565b6040519081526020015b60405180910390f35b6104856104bb36600461468e565b610b67565b6104c8610be2565b604080519283526020830191909152016104a4565b61049a60065481565b61049a60095481565b61049a60035481565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016104a4565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b61049a600d5481565b61048561059c3660046146b2565b610c09565b6104856105af36600461468e565b610c88565b61049a60025481565b6104856105cb3660046146cd565b610d18565b6105e36105de366004614673565b610e10565b6040516104a492919061478f565b6106187f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016104a4565b61049a610f45565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b61048561066736600461468e565b610fd3565b5f5461068690600160281b900467ffffffffffffffff1681565b60405167ffffffffffffffff90911681526020016104a4565b6104856106ad3660046147a9565b610fe4565b61049a6106c0366004614673565b611081565b61049a611197565b5f54610100900461ffff1661049a565b61049a6106eb366004614673565b6111b6565b6104856106fe36600461468e565b6113b1565b61048561071136600461468e565b611463565b61049a60045481565b6040805180820182526005815264312e302e3160d81b602082015290516104a491906147e0565b61048561075436600461468e565b61146b565b6105e36114f2565b61049a60085481565b61049a61152f565b5f5461077e9060ff1681565b60405190151581526020016104a4565b61048561079c366004614673565b61157d565b61049a6115ec565b6104c86107b736600461468e565b6116bc565b61049a600b5481565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b6104856107fa36600461468e565b611706565b61049a61178d565b61049a6117db565b5f546301000000900461ffff1661049a565b600e5461051f906001600160a01b031681565b61048561084236600461468e565b611829565b600e5461077e90600160a01b900460ff1681565b6104856118a4565b61048561087136600461468e565b6119a1565b61048561088436600461468e565b611a1d565b61048561089736600461468e565b611aa4565b6104856108aa36600461468e565b611b1f565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b6104856108e43660046146b2565b611b30565b6104856108f736600461468e565b611bb6565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b61049a600a5481565b61048561093a366004614673565b611c31565b61048561094d36600461468e565b611cad565b61049a611d28565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b61051f7f000000000000000000000000000000000000000000000000000000000000000081565b6104856109b636600461468e565b611d83565b61051f73d377919fa87120584b21279a491f82d5265a139c81565b60015461051f906001600160a01b031681565b61049a60075481565b61077e610a00366004614673565b600c6020525f908152604090205460ff1681565b610485610a2236600461468e565b611dff565b61049a611e7b565b61049a611eaa565b61049a60055481565b61049a611f1c565b610485610a5636600461468e565b611f8e565b61049a610a69366004614673565b61206c565b610485610a7c36600461468e565b6120f0565b610485610a8f36600461468e565b612177565b610485610aa23660046147f2565b612188565b5f80610ab1610f45565b90505f610abc611eaa565b9050818110610acf57505f199392505050565b670de0b6b3a764000060095411610ae957505f9392505050565b5f610af4828461482f565b90505f670de0b6b3a7640000600954610b0d919061482f565b610b1f670de0b6b3a764000084614842565b610b299190614859565b90505f610b34610be2565b5090505f610b42868361482f565b9050828111610b51575f610b5b565b610b5b838261482f565b98975050505050505050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610bc4575f80fd5b505afa158015610bd6573d5f803e3d5ffd5b505050600b9190915550565b5f805f610bed61152f565b9050610bf881612206565b9250610c02610f45565b9150509091565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610c66575f80fd5b505afa158015610c78573d5f803e3d5ffd5b50505050610c8581612249565b50565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015610ce5575f80fd5b505afa158015610cf7573d5f803e3d5ffd5b50505050610d14610d0f82610d0a6117db565b612291565b6122a6565b5050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610d7f5760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b600e54600160a81b900460ff16610dcc5760405162461bcd60e51b815260206004820152601160248201527021666c6173686c6f616e2061637469766560781b6044820152606401610d76565b610e0b8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506122ba92505050565b505050565b600e545f906060906001600160a01b031680610e58575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600e54600160a01b900460ff16610e9e575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610ea8856111b6565b90508015801590610ebb5750600d548110155b15610f0d575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a08231906024015b602060405180830381865afa158015610faa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fce9190614878565b905090565b610fdb612354565b610c858161238b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611041575f80fd5b505afa158015611053573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600c60205260409020805460ff1916911515919091179055565b6001600160a01b0381165f908152600c602052604081205460ff166110a757505f919050565b6110af612394565b806110bd57506110bd612440565b156110c957505f919050565b670de0b6b3a7640000600954116110e157505f919050565b600554600181016110f557505f1992915050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611152573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111769190614878565b9050808211611185575f61118f565b61118f818361482f565b949350505050565b5f6111a0612354565b6111a86125c7565b90506111b3816125f4565b90565b600e545f90600160a01b900460ff166111d057505f919050565b600e546001600160a01b0316806111e957505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa15801561122d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611251919061488f565b80156112c557506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa15801561129f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c39190614878565b115b156112d257505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa158015611316573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061133a9190614878565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa15801561137c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113a09190614878565b6113aa91906148aa565b9392505050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b15801561140e575f80fd5b505afa158015611420573d5f803e3d5ffd5b50505050612710811061145e5760405162461bcd60e51b8152602060048201526006602482015265313ab33332b960d11b6044820152606401610d76565b600355565b610c85612354565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b1580156114c8575f80fd5b505afa1580156114da573d5f803e3d5ffd5b50505050610c856114ed82610d0a61152f565b612737565b5f60606114fd6127f8565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401610f8f565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146115e35760405162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b6044820152606401610d76565b610c8581612964565b604051633e15014160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f00000000000000000000000000000000000000000000000000000000000000001690633e1501419060240161014060405180830381865afa158015611675573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061169991906148bd565b505050505050509250505080655af3107a40006116b69190614842565b91505090565b5f805f670de0b6b3a7640000600954856116d69190614842565b6116e09190614859565b90505f8482116116f0575f6116fa565b6116fa858361482f565b91959194509092505050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611763575f80fd5b505afa158015611775573d5f803e3d5ffd5b50505050610d1461178882610d0a61178d565b612aa3565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401610f8f565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401610f8f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611886575f80fd5b505afa158015611898573d5f803e3d5ffd5b50505060069190915550565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611901575f80fd5b505afa158015611913573d5f803e3d5ffd5b5050505061199f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190614878565b612ab8565b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156119fe575f80fd5b505afa158015611a10573d5f803e3d5ffd5b50505050610c8581612c3a565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611a7a575f80fd5b505afa158015611a8c573d5f803e3d5ffd5b50505050610c85611a9f82610d0a61178d565b612cd3565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b01575f80fd5b505afa158015611b13573d5f803e3d5ffd5b505050600a9190915550565b611b27612354565b610c8581612d5f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b8d575f80fd5b505afa158015611b9f573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c13575f80fd5b505afa158015611c25573d5f803e3d5ffd5b50505060049190915550565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c8e575f80fd5b505afa158015611ca0573d5f803e3d5ffd5b50505050610c8581612d6f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611d0a575f80fd5b505afa158015611d1c573d5f803e3d5ffd5b50505060059190915550565b5f805f611d33610be2565b91509150815f03611d46575f9250505090565b818110611d56575f199250505090565b611d60818361482f565b611d72670de0b6b3a764000084614842565b611d7c9190614859565b9250505090565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611de0575f80fd5b505afa158015611df2573d5f803e3d5ffd5b50505050610c8581612ec8565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611e5c575f80fd5b505afa158015611e6e573d5f803e3d5ffd5b50505050610c8581612f7f565b5f805f611e86610be2565b915091505f8211611e97575f611d7c565b81611d72670de0b6b3a764000083614842565b6040516370a0823160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f0000000000000000000000000000000000000000000000000000000000000000909116906370a0823190602401610f8f565b5f80612710600354612710611f31919061482f565b611f53611f3c6117db565b611f4461152f565b611f4e91906148aa565b612206565b611f5d9190614842565b611f679190614859565b9050611f71610f45565b81611f7a61178d565b611f8491906148aa565b6116b6919061482f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611feb575f80fd5b505afa158015611ffd573d5f803e3d5ffd5b50505050612710811061203d5760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610d76565b5f805467ffffffffffffffff909216600160281b026cffffffffffffffff000000000019909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063d43fdcf7906024015f6040518083038186803b1580156120cb575f80fd5b505afa1580156120dd573d5f803e3d5ffd5b505050506120ea82612fdf565b92915050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b15801561214d575f80fd5b505afa15801561215f573d5f803e3d5ffd5b50505050610c8561217282610d0a6117db565b613260565b61217f612354565b610c8581613388565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156121e5575f80fd5b505afa1580156121f7573d5f803e3d5ffd5b50505050610e0b838383613444565b5f81158061221457505f1982145b1561221d575090565b6ec097ce7bc90715b34b9f1000000000612235613650565b61223f9084614842565b6120ea9190614859565b600e805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f81831061229f57816113aa565b5090919050565b5f6120ea826122b5845f61383e565b6138a2565b5f818060200190518101906122cf91906149a3565b90505f815160018111156122e5576122e56149fc565b036122f457610e0b83826139b4565b600181516001811115612309576123096149fc565b0361231857610e0b8382613a37565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610d76565b33301461199f5760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610d76565b610c8581612ab8565b604051632d57664160e21b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f00000000000000000000000000000000000000000000000000000000000000009091169063b55d990490602401602060405180830381865afa15801561241c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fce919061488f565b604051632d57664160e21b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f0000000000000000000000000000000000000000000000000000000000000000169063b55d990490602401602060405180830381865afa1580156124c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124ec919061488f565b905080156124fc57600191505090565b604051633e15014160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f00000000000000000000000000000000000000000000000000000000000000001690633e1501419060240161014060405180830381865afa158015612585573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125a991906148bd565b99505050975050505050505080806125bf575081155b935050505090565b5f6125d0613ad1565b6125ec6125e76125de61178d565b610d0a30611081565b613c16565b610fce611f1c565b5f5460ff1661260c57505f805460ff19166001179055565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612669573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061268d9190614878565b905080821115612700575f54612710906126b090610100900461ffff1683614842565b6126ba9190614859565b6126c4828461482f565b1115610d145760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610d76565b81811115610d14575f5461271090612723906301000000900461ffff1683614842565b61272d9190614859565b6126c4838361482f565b805f036127415750565b604051631a4ca37b60e21b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152602482018390523060448301527f000000000000000000000000000000000000000000000000000000000000000016906369328dec906064015b6020604051808303815f875af11580156127d4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d149190614878565b5f612801613efa565b1561280c5750600190565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612868573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061288c9190614878565b5f0361289757505f90565b61289f612394565b806128ad57506128ad612440565b156128b757505f90565b5f6128c0611d28565b90506008548111156128d457600191505090565b6004546002546128e4904261482f565b10156128f1575f91505090565b6009545f819003612911575f82118015611d7c5750600a54481115611d7c565b60075461291e90826148aa565b82111561295c57600b548061293161178d565b1180612943575080612941611eaa565b115b1561295357600a544811156125bf565b5f935050505090565b5f9250505090565b6001600160a01b0381166129a65760405162461bcd60e51b81526020600482015260096024820152682165786368616e676560b81b6044820152606401610d76565b6001546001600160a01b03168015612a20576129ec6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016825f613fa4565b612a206001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016825f613fa4565b600180546001600160a01b0319166001600160a01b0384811691909117909155612a6e907f000000000000000000000000000000000000000000000000000000000000000016835f19613fa4565b610d146001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016835f19613fa4565b5f6120ea82612ab384600161383e565b614065565b5f80612ac2610be2565b91509150805f03612afe575f612ad7846140fc565b9050612ae86114ed82610d0a61152f565b612af7610d0f82610d0a6117db565b5050505050565b5f612b09828461482f565b90505f848211612b19575f612b23565b612b23858361482f565b90505f612b2f826116bc565b91505083811115612b68575f612b44876140fc565b9050612b556114ed82610d0a61152f565b612b5e816122a6565b5050505050505050565b5f612b73828661482f565b9050612b8181610d0a611eaa565b9050805f03612b935750505050505050565b5f858214612bb257612bad612ba889846148aa565b6140fc565b612bba565b612bba61152f565b90505f6040518060400160405280600180811115612bda57612bda6149fc565b815260200183815250604051602001612bf39190614a10565b6040516020818303038152906040529050612c2f7f00000000000000000000000000000000000000000000000000000000000000008483614142565b505050505050505050565b5f8111612c785760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610d76565b61ffff811115612cb65760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610d76565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f03612cdd5750565b60405163573ade8160e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015260248201839052600260448301523060648301527f0000000000000000000000000000000000000000000000000000000000000000169063573ade81906084016127b8565b612d6881613c16565b5042600255565b6001600160a01b03811615612e7f57306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612dc4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612de89190614a47565b6001600160a01b031614612e2f5760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610d76565b600e54600160a01b900460ff16612e7f57600e805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600e80546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612ed25750565b60405163a415bcad60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015260248201839052600260448301525f60648301523060848301527f0000000000000000000000000000000000000000000000000000000000000000169063a415bcad9060a4015b5f604051808303815f87803b158015612f6d575f80fd5b505af1158015612af7573d5f803e3d5ffd5b6127108110612fbe5760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610d76565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b600e545f90600160a01b900460ff166130305760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610d76565b600e54604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa15801561307a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061309e919061488f565b15613173576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa1580156130ea573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061310e9190614878565b111561311c57505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b15801561315c575f80fd5b505af115801561316e573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa1580156131b7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131db9190614878565b905080156131f7576131f76001600160a01b03851683836141e4565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af115801561323c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118f9190614878565b805f0361326a5750565b60405163617ba03760e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152602482018390523060448301525f60648301527f0000000000000000000000000000000000000000000000000000000000000000169063617ba037906084015f604051808303815f87803b1580156132fd575f80fd5b505af115801561330f573d5f803e3d5ffd5b5050604051635a3b74b960e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152600160248301527f0000000000000000000000000000000000000000000000000000000000000000169250635a3b74b99150604401612f56565b5f613391610f45565b111561341e57610c8561199a827f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133fa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0a9190614878565b8015610c855761343081610d0a61152f565b905061343b81612737565b610d14816122a6565b825f0361349e5781156134995760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610d76565b613571565b670de0b6b3a76400008310156134e65760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610d76565b662386f26fc100008210156135305760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610d76565b8183116135715760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610d76565b61357b82846148aa565b8110156135ca5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610d76565b5f816135de670de0b6b3a764000080614842565b6135e89190614859565b6135fa90670de0b6b3a764000061482f565b90506136046115ec565b81106136415760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610d76565b50600992909255600755600855565b60405163b3596f0760e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f0000000000000000000000000000000000000000000000000000000000000000169063b3596f0790602401602060405180830381865afa1580156136d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136fc9190614878565b60405163b3596f0760e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301529192505f917f0000000000000000000000000000000000000000000000000000000000000000169063b3596f0790602401602060405180830381865afa158015613785573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137a99190614878565b9050805f036137ba575f9250505090565b6137e57f0000000000000000000000000000000000000000000000000000000000000000600a614b42565b6137ef9082614842565b6ec097ce7bc90715b34b9f100000000061382a7f0000000000000000000000000000000000000000000000000000000000000000600a614b42565b6138349085614842565b611d729190614842565b5f825f0361384d57505f6120ea565b5f826138615761385c84612206565b61386a565b61386a846140fc565b5f549091506127109061388e90600160281b900467ffffffffffffffff168261482f565b6138989083614842565b61118f9190614859565b5f825f036138b157505f6120ea565b600154604051630ed2fc9560e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f00000000000000000000000000000000000000000000000000000000000000008116602483015260448201869052606482018590525f921690630ed2fc95906084015b6020604051808303815f875af1158015613951573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139759190614878565b9050828110156113aa5760405162461bcd60e51b815260206004820152600a60248201526908585b5bdd5b9d13dd5d60b21b6044820152606401610d76565b5f8282602001516139c591906148aa565b90505f6139d182612aa3565b90506139dc81613260565b6139e584612ec8565b6008546139f0611d28565b10613a315760405162461bcd60e51b81526020600482015260116024820152700d8caeccae4c2ceca40e8dede40d0d2ced607b1b6044820152606401610d76565b50505050565b5f613a40611d28565b9050613a51611a9f84610d0a610f45565b5f613a628360200151610d0a61152f565b9050613a6d81612737565b613a76816122a6565b505f613a80611d28565b9050600854811080613a9157508281105b612af75760405162461bcd60e51b81526020600482015260116024820152700d8caeccae4c2ceca40e8dede40d0d2ced607b1b6044820152606401610d76565b6040805160028082526060820183525f926020830190803683370190505090507f0000000000000000000000000000000000000000000000000000000000000000815f81518110613b2457613b24614b4d565b60200260200101906001600160a01b031690816001600160a01b0316815250507f000000000000000000000000000000000000000000000000000000000000000081600181518110613b7857613b78614b4d565b6001600160a01b039283166020918202929092010152604051635fc87b1d60e11b81527f00000000000000000000000000000000000000000000000000000000000000009091169063bf90f63a90613bd4908490600401614b61565b5f604051808303815f875af1158015613bef573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610e0b9190810190614c3c565b5f80613c20610be2565b90925090505f83613c31838561482f565b613c3b91906148aa565b90505f613c47826116bc565b91505082811115613d89575f613c68613c60858461482f565b610d0a611eaa565b90505f613c76611f4e614214565b90505f5f198214613cc3576006545f54613cbe919061271090613caa90600160281b900467ffffffffffffffff168261482f565b613cb49086614842565b610d0a9190614859565b613cc7565b6006545b90505f198114613d08575f613cdc848a6148aa565b905081811115613d0657818910613cf957612c2f61217283612aa3565b613d03898361482f565b93505b505b600b548311613d2057612b5e611a9f89610d0a610f45565b6040805180820182525f80825260208083018c905292519092613d44929101614a10565b6040516020818303038152906040529050613d807f00000000000000000000000000000000000000000000000000000000000000008583614142565b50505050612af7565b80831115613edc575f613d9c828561482f565b9050808610613dee57613dae81612cd3565b613db8818761482f565b95508515613de657613dcf61178887600654612291565b50613de6612172613dde6117db565b610d0a614214565b505050505050565b613df786612cd3565b613e01868261482f565b9050613e0f81610d0a611eaa565b9050805f03613e2057505050505050565b5f805461271090613e4290600160281b900467ffffffffffffffff16826148aa565b613e4b846140fc565b613e559190614842565b613e5f9190614859565b90505f6040518060400160405280600180811115613e7f57613e7f6149fc565b815260200183815250604051602001613e989190614a10565b6040516020818303038152906040529050613ed47f00000000000000000000000000000000000000000000000000000000000000008483614142565b505050612af7565b613eeb61178886600654612291565b50612af7612172613dde6117db565b604051632fe4a15f60e21b81523060048201525f9081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063bf92857c9060240160c060405180830381865afa158015613f60573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f849190614cfb565b95505050505050670de0b6b3a7640000811080156116b657501515919050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052613ff584826143ce565b613a31576040516001600160a01b03841660248201525f604482015261405b90859063095ea7b360e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261446f565b613a31848261446f565b5f825f0361407457505f6120ea565b600154604051630ed2fc9560e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f00000000000000000000000000000000000000000000000000000000000000008116602483015260448201869052606482018590525f921690630ed2fc9590608401613935565b5f81158061410a57505f1982145b15614113575090565b5f61411c613650565b9050806141386ec097ce7bc90715b34b9f100000000085614842565b6113aa9190614859565b600e805460ff60a81b1916600160a81b17905560405163701195a160e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e0232b42906141a590869086908690600401614d41565b5f604051808303815f87803b1580156141bc575f80fd5b505af11580156141ce573d5f803e3d5ffd5b5050600e805460ff60a81b191690555050505050565b6040516001600160a01b038316602482015260448101829052610e0b90849063a9059cbb60e01b90606401614024565b6040516308df7cab60e31b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f000000000000000000000000000000000000000000000000000000000000000016906346fbe558906024016040805180830381865afa15801561429b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142bf9190614d67565b915050805f036142d1575f1991505090565b6040516351460e2560e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f0000000000000000000000000000000000000000000000000000000000000000909116906351460e2590602401602060405180830381865afa158015614359573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061437d9190614878565b90505f6143ab7f0000000000000000000000000000000000000000000000000000000000000000600a614b42565b6143b59084614842565b90508181116143c4575f6125bf565b6125bf828261482f565b5f805f846001600160a01b0316846040516143e99190614d89565b5f604051808303815f865af19150503d805f8114614422576040519150601f19603f3d011682016040523d82523d5f602084013e614427565b606091505b5091509150818015614451575080511580614451575080806020019051810190614451919061488f565b801561446657506001600160a01b0385163b15155b95945050505050565b5f6144c3826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166145429092919063ffffffff16565b905080515f14806144e35750808060200190518101906144e3919061488f565b610e0b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d76565b606061118f84845f85855f80866001600160a01b031685876040516145679190614d89565b5f6040518083038185875af1925050503d805f81146145a1576040519150601f19603f3d011682016040523d82523d5f602084013e6145a6565b606091505b50915091506145b7878383876145c2565b979650505050505050565b606083156146305782515f03614629576001600160a01b0385163b6146295760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d76565b508161118f565b61118f83838151156146455781518083602001fd5b8060405162461bcd60e51b8152600401610d7691906147e0565b6001600160a01b0381168114610c85575f80fd5b5f60208284031215614683575f80fd5b81356113aa8161465f565b5f6020828403121561469e575f80fd5b5035919050565b8015158114610c85575f80fd5b5f602082840312156146c2575f80fd5b81356113aa816146a5565b5f805f604084860312156146df575f80fd5b83359250602084013567ffffffffffffffff808211156146fd575f80fd5b818601915086601f830112614710575f80fd5b81358181111561471e575f80fd5b87602082850101111561472f575f80fd5b6020830194508093505050509250925092565b5f5b8381101561475c578181015183820152602001614744565b50505f910152565b5f815180845261477b816020860160208601614742565b601f01601f19169290920160200192915050565b8215158152604060208201525f61118f6040830184614764565b5f80604083850312156147ba575f80fd5b82356147c58161465f565b915060208301356147d5816146a5565b809150509250929050565b602081525f6113aa6020830184614764565b5f805f60608486031215614804575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b818103818111156120ea576120ea61481b565b80820281158282048414176120ea576120ea61481b565b5f8261487357634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215614888575f80fd5b5051919050565b5f6020828403121561489f575f80fd5b81516113aa816146a5565b808201808211156120ea576120ea61481b565b5f805f805f805f805f806101408b8d0312156148d7575f80fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151614905816146a5565b60c08c0151909550614916816146a5565b60e08c0151909450614927816146a5565b6101008c0151909350614939816146a5565b6101208c015190925061494b816146a5565b809150509295989b9194979a5092959850565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561499b5761499b61495e565b604052919050565b5f604082840312156149b3575f80fd5b6040516040810181811067ffffffffffffffff821117156149d6576149d661495e565b6040528251600281106149e7575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b8151604082019060028110614a3357634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f60208284031215614a57575f80fd5b81516113aa8161465f565b600181815b80851115614a9c57815f1904821115614a8257614a8261481b565b80851615614a8f57918102915b93841c9390800290614a67565b509250929050565b5f82614ab2575060016120ea565b81614abe57505f6120ea565b8160018114614ad45760028114614ade57614afa565b60019150506120ea565b60ff841115614aef57614aef61481b565b50506001821b6120ea565b5060208310610133831016604e8410600b8410161715614b1d575081810a6120ea565b614b278383614a62565b805f1904821115614b3a57614b3a61481b565b029392505050565b5f6113aa8383614aa4565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f9190848201906040850190845b81811015614ba15783516001600160a01b031683529284019291840191600101614b7c565b50909695505050505050565b5f67ffffffffffffffff821115614bc657614bc661495e565b5060051b60200190565b5f82601f830112614bdf575f80fd5b81516020614bf4614bef83614bad565b614972565b8083825260208201915060208460051b870101935086841115614c15575f80fd5b602086015b84811015614c315780518352918301918301614c1a565b509695505050505050565b5f8060408385031215614c4d575f80fd5b825167ffffffffffffffff80821115614c64575f80fd5b818501915085601f830112614c77575f80fd5b81516020614c87614bef83614bad565b82815260059290921b84018101918181019089841115614ca5575f80fd5b948201945b83861015614ccc578551614cbd8161465f565b82529482019490820190614caa565b91880151919650909350505080821115614ce4575f80fd5b50614cf185828601614bd0565b9150509250929050565b5f805f805f8060c08789031215614d10575f80fd5b865195506020870151945060408701519350606087015192506080870151915060a087015190509295509295509295565b60018060a01b0384168152826020820152606060408201525f6144666060830184614764565b5f8060408385031215614d78575f80fd5b505080516020909101519092909150565b5f8251614d9a818460208701614742565b919091019291505056fea264697066735822122032a1468284d6f0df42e46ea99e089a0c9fda2097de9ddc6866b9c60b99e13b1b64736f6c634300081700330000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c59900000000000000000000000000000000000000000000000000000000000001000000000000000000000000008236a87084f8b84306f72007f36f2618a56344940000000000000000000000002f39d218133afab8f2b819b1066c7e434ad94e9e000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb0000000000000000000000000000000000000000000000000000000000000004000000000000000000000000a94fbdb1ec4e12358e9581b9829bec57115fad9700000000000000000000000088ba032be87d5ef1fbe87336b7090767f367bf7300000000000000000000000000000000000000000000000000000000000000156c4254432f574254432041617665204c6f6f7065720000000000000000000000
Deployed Bytecode
0x608060405234801561000f575f80fd5b5060043610610452575f3560e01c80637535d2461161023f578063bdc8144b11610139578063d6968601116100c1578063f0fa55a911610085578063f0fa55a914610a48578063fc7f71b614610a5b578063fd9f5f7514610a6e578063fde813a814610a81578063ff831b0514610a9457610452565b8063d696860114610a14578063e862114914610a27578063ea9c840714610a2f578063ecf7085814610a37578063efbb5cb014610a4057610452565b8063cfaec0da11610108578063cfaec0da146109a8578063d19a3bb8146109bb578063d2f7265a146109d6578063d472a43b146109e9578063d63a8e11146109f257610452565b8063bdc8144b1461093f578063c31443bb14610952578063c396cbf41461095a578063cd086d451461098157610452565b8063950b3d73116101c7578063ac00ff261161018b578063ac00ff26146108d6578063afeb4965146108e9578063b2016bd4146108fc578063b6a1650614610923578063b8c6f5791461092c57610452565b8063950b3d731461086357806398cdabc9146108765780639b90fb16146108895780639d7fb70c1461089c5780639ef0159f146108af57610452565b80637d9699321161020e5780637d9699321461080f5780637d9f6db5146108215780638298a4be1461083457806384d78a38146108475780638ca6dd4d1461085b57610452565b80637535d246146107c5578063757a291f146107ec578063797bf343146107ff5780637baf6f771461080757610452565b80633e032a3b1161035057806354fd4d50116102d85780636718835f1161029c5780636718835f1461077257806367b1f5df1461078e5780636be36a1d146107a15780636c7a0c91146107a957806372b10dd5146107bc57610452565b806354fd4d501461071f578063580e0d81146107465780635d265d3f146107595780635ef76292146107615780636687500e1461076a57610452565b80634a5d09431161031f5780634a5d0943146106cd5780634aca9482146106dd5780635009dd1d146106f0578063503160d91461070357806352a25a721461071657610452565b80633e032a3b1461066c5780634697f05d1461069f57806346aa2f12146106b257806349317f1d146106c557610452565b806318144367116103de5780633259356e116103a25780633259356e146105d057806335faba33146105f1578063392f7a701461062a5780633acb5624146106325780633d6cb5751461065957610452565b8063181443671461058557806320aa49ae1461058e5780632b0015e6146105a15780632cd68034146105b457806331f57072146105bd57610452565b80630ea44a56116104255780630ea44a56146104e657806313070d00146104ef57806313f8bf67146104f85780631462783414610537578063179474b51461055e57610452565b806304bd4629146104875780630870e180146104ad57806309218e91146104c05780630b3883fc146104dd575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e808015610481573d5ff35b3d5ffd5b005b61049a610495366004614673565b610aa7565b6040519081526020015b60405180910390f35b6104856104bb36600461468e565b610b67565b6104c8610be2565b604080519283526020830191909152016104a4565b61049a60065481565b61049a60095481565b61049a60035481565b61051f7f00000000000000000000000054586be62e3c3580375ae3723c145253060ca0c281565b6040516001600160a01b0390911681526020016104a4565b61051f7f00000000000000000000000088ba032be87d5ef1fbe87336b7090767f367bf7381565b61051f7f00000000000000000000000040aabef1aa8f0eec637e0e7d92fbffb2f26a8b7b81565b61049a600d5481565b61048561059c3660046146b2565b610c09565b6104856105af36600461468e565b610c88565b61049a60025481565b6104856105cb3660046146cd565b610d18565b6105e36105de366004614673565b610e10565b6040516104a492919061478f565b6106187f000000000000000000000000000000000000000000000000000000000000000481565b60405160ff90911681526020016104a4565b61049a610f45565b61051f7f000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb81565b61048561066736600461468e565b610fd3565b5f5461068690600160281b900467ffffffffffffffff1681565b60405167ffffffffffffffff90911681526020016104a4565b6104856106ad3660046147a9565b610fe4565b61049a6106c0366004614673565b611081565b61049a611197565b5f54610100900461ffff1661049a565b61049a6106eb366004614673565b6111b6565b6104856106fe36600461468e565b6113b1565b61048561071136600461468e565b611463565b61049a60045481565b6040805180820182526005815264312e302e3160d81b602082015290516104a491906147e0565b61048561075436600461468e565b61146b565b6105e36114f2565b61049a60085481565b61049a61152f565b5f5461077e9060ff1681565b60405190151581526020016104a4565b61048561079c366004614673565b61157d565b61049a6115ec565b6104c86107b736600461468e565b6116bc565b61049a600b5481565b61051f7f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e281565b6104856107fa36600461468e565b611706565b61049a61178d565b61049a6117db565b5f546301000000900461ffff1661049a565b600e5461051f906001600160a01b031681565b61048561084236600461468e565b611829565b600e5461077e90600160a01b900460ff1681565b6104856118a4565b61048561087136600461468e565b6119a1565b61048561088436600461468e565b611a1d565b61048561089736600461468e565b611aa4565b6104856108aa36600461468e565b611b1f565b61051f7f00000000000000000000000065906988adee75306021c417a1a345804023960281565b6104856108e43660046146b2565b611b30565b6104856108f736600461468e565b611bb6565b61051f7f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449481565b61049a600a5481565b61048561093a366004614673565b611c31565b61048561094d36600461468e565b611cad565b61049a611d28565b61051f7f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd81565b61051f7f0000000000000000000000008164cc65827dcfe994ab23944cbc90e0aa80bfcb81565b6104856109b636600461468e565b611d83565b61051f73d377919fa87120584b21279a491f82d5265a139c81565b60015461051f906001600160a01b031681565b61049a60075481565b61077e610a00366004614673565b600c6020525f908152604090205460ff1681565b610485610a2236600461468e565b611dff565b61049a611e7b565b61049a611eaa565b61049a60055481565b61049a611f1c565b610485610a5636600461468e565b611f8e565b61049a610a69366004614673565b61206c565b610485610a7c36600461468e565b6120f0565b610485610a8f36600461468e565b612177565b610485610aa23660046147f2565b612188565b5f80610ab1610f45565b90505f610abc611eaa565b9050818110610acf57505f199392505050565b670de0b6b3a764000060095411610ae957505f9392505050565b5f610af4828461482f565b90505f670de0b6b3a7640000600954610b0d919061482f565b610b1f670de0b6b3a764000084614842565b610b299190614859565b90505f610b34610be2565b5090505f610b42868361482f565b9050828111610b51575f610b5b565b610b5b838261482f565b98975050505050505050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610bc4575f80fd5b505afa158015610bd6573d5f803e3d5ffd5b505050600b9190915550565b5f805f610bed61152f565b9050610bf881612206565b9250610c02610f45565b9150509091565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610c66575f80fd5b505afa158015610c78573d5f803e3d5ffd5b50505050610c8581612249565b50565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b158015610ce5575f80fd5b505afa158015610cf7573d5f803e3d5ffd5b50505050610d14610d0f82610d0a6117db565b612291565b6122a6565b5050565b336001600160a01b037f000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb1614610d7f5760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b600e54600160a81b900460ff16610dcc5760405162461bcd60e51b815260206004820152601160248201527021666c6173686c6f616e2061637469766560781b6044820152606401610d76565b610e0b8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506122ba92505050565b505050565b600e545f906060906001600160a01b031680610e58575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600e54600160a01b900460ff16610e9e575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610ea8856111b6565b90508015801590610ebb5750600d548110155b15610f0d575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000040aabef1aa8f0eec637e0e7d92fbffb2f26a8b7b6001600160a01b0316906370a08231906024015b602060405180830381865afa158015610faa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fce9190614878565b905090565b610fdb612354565b610c858161238b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611041575f80fd5b505afa158015611053573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600c60205260409020805460ff1916911515919091179055565b6001600160a01b0381165f908152600c602052604081205460ff166110a757505f919050565b6110af612394565b806110bd57506110bd612440565b156110c957505f919050565b670de0b6b3a7640000600954116110e157505f919050565b600554600181016110f557505f1992915050565b5f7f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611152573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111769190614878565b9050808211611185575f61118f565b61118f818361482f565b949350505050565b5f6111a0612354565b6111a86125c7565b90506111b3816125f4565b90565b600e545f90600160a01b900460ff166111d057505f919050565b600e546001600160a01b0316806111e957505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa15801561122d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611251919061488f565b80156112c557506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa15801561129f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c39190614878565b115b156112d257505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa158015611316573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061133a9190614878565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa15801561137c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113a09190614878565b6113aa91906148aa565b9392505050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b15801561140e575f80fd5b505afa158015611420573d5f803e3d5ffd5b50505050612710811061145e5760405162461bcd60e51b8152602060048201526006602482015265313ab33332b960d11b6044820152606401610d76565b600355565b610c85612354565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b1580156114c8575f80fd5b505afa1580156114da573d5f803e3d5ffd5b50505050610c856114ed82610d0a61152f565b612737565b5f60606114fd6127f8565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000065906988adee75306021c417a1a34580402396026001600160a01b0316906370a0823190602401610f8f565b336001600160a01b037f00000000000000000000000088ba032be87d5ef1fbe87336b7090767f367bf7316146115e35760405162461bcd60e51b815260206004820152600b60248201526a21676f7665726e616e636560a81b6044820152606401610d76565b610c8581612964565b604051633e15014160e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301525f9182917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd1690633e1501419060240161014060405180830381865afa158015611675573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061169991906148bd565b505050505050509250505080655af3107a40006116b69190614842565b91505090565b5f805f670de0b6b3a7640000600954856116d69190614842565b6116e09190614859565b90505f8482116116f0575f6116fa565b6116fa858361482f565b91959194509092505050565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611763575f80fd5b505afa158015611775573d5f803e3d5ffd5b50505050610d1461178882610d0a61178d565b612aa3565b6040516370a0823160e01b81523060048201525f907f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5996001600160a01b0316906370a0823190602401610f8f565b6040516370a0823160e01b81523060048201525f907f0000000000000000000000008236a87084f8b84306f72007f36f2618a56344946001600160a01b0316906370a0823190602401610f8f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611886575f80fd5b505afa158015611898573d5f803e3d5ffd5b50505060069190915550565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611901575f80fd5b505afa158015611913573d5f803e3d5ffd5b5050505061199f7f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190614878565b612ab8565b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b1580156119fe575f80fd5b505afa158015611a10573d5f803e3d5ffd5b50505050610c8581612c3a565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611a7a575f80fd5b505afa158015611a8c573d5f803e3d5ffd5b50505050610c85611a9f82610d0a61178d565b612cd3565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b01575f80fd5b505afa158015611b13573d5f803e3d5ffd5b505050600a9190915550565b611b27612354565b610c8581612d5f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b8d575f80fd5b505afa158015611b9f573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c13575f80fd5b505afa158015611c25573d5f803e3d5ffd5b50505060049190915550565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c8e575f80fd5b505afa158015611ca0573d5f803e3d5ffd5b50505050610c8581612d6f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611d0a575f80fd5b505afa158015611d1c573d5f803e3d5ffd5b50505060059190915550565b5f805f611d33610be2565b91509150815f03611d46575f9250505090565b818110611d56575f199250505090565b611d60818361482f565b611d72670de0b6b3a764000084614842565b611d7c9190614859565b9250505090565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611de0575f80fd5b505afa158015611df2573d5f803e3d5ffd5b50505050610c8581612ec8565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611e5c575f80fd5b505afa158015611e6e573d5f803e3d5ffd5b50505050610c8581612f7f565b5f805f611e86610be2565b915091505f8211611e97575f611d7c565b81611d72670de0b6b3a764000083614842565b6040516370a0823160e01b81526001600160a01b037f000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb811660048301525f917f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599909116906370a0823190602401610f8f565b5f80612710600354612710611f31919061482f565b611f53611f3c6117db565b611f4461152f565b611f4e91906148aa565b612206565b611f5d9190614842565b611f679190614859565b9050611f71610f45565b81611f7a61178d565b611f8491906148aa565b6116b6919061482f565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611feb575f80fd5b505afa158015611ffd573d5f803e3d5ffd5b50505050612710811061203d5760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610d76565b5f805467ffffffffffffffff909216600160281b026cffffffffffffffff000000000019909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03169063d43fdcf7906024015f6040518083038186803b1580156120cb575f80fd5b505afa1580156120dd573d5f803e3d5ffd5b505050506120ea82612fdf565b92915050565b6040516320b8029160e21b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906382e00a44906024015f6040518083038186803b15801561214d575f80fd5b505afa15801561215f573d5f803e3d5ffd5b50505050610c8561217282610d0a6117db565b613260565b61217f612354565b610c8581613388565b6040516348e4a64960e01b81523360048201527f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b0316906348e4a649906024015f6040518083038186803b1580156121e5575f80fd5b505afa1580156121f7573d5f803e3d5ffd5b50505050610e0b838383613444565b5f81158061221457505f1982145b1561221d575090565b6ec097ce7bc90715b34b9f1000000000612235613650565b61223f9084614842565b6120ea9190614859565b600e805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f81831061229f57816113aa565b5090919050565b5f6120ea826122b5845f61383e565b6138a2565b5f818060200190518101906122cf91906149a3565b90505f815160018111156122e5576122e56149fc565b036122f457610e0b83826139b4565b600181516001811115612309576123096149fc565b0361231857610e0b8382613a37565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610d76565b33301461199f5760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610d76565b610c8581612ab8565b604051632d57664160e21b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301525f917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd9091169063b55d990490602401602060405180830381865afa15801561241c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fce919061488f565b604051632d57664160e21b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599811660048301525f9182917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd169063b55d990490602401602060405180830381865afa1580156124c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124ec919061488f565b905080156124fc57600191505090565b604051633e15014160e01b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599811660048301525f9182917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd1690633e1501419060240161014060405180830381865afa158015612585573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125a991906148bd565b99505050975050505050505080806125bf575081155b935050505090565b5f6125d0613ad1565b6125ec6125e76125de61178d565b610d0a30611081565b613c16565b610fce611f1c565b5f5460ff1661260c57505f805460ff19166001179055565b5f7f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612669573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061268d9190614878565b905080821115612700575f54612710906126b090610100900461ffff1683614842565b6126ba9190614859565b6126c4828461482f565b1115610d145760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610d76565b81811115610d14575f5461271090612723906301000000900461ffff1683614842565b61272d9190614859565b6126c4838361482f565b805f036127415750565b604051631a4ca37b60e21b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449481166004830152602482018390523060448301527f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e216906369328dec906064015b6020604051808303815f875af11580156127d4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d149190614878565b5f612801613efa565b1561280c5750600190565b7f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612868573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061288c9190614878565b5f0361289757505f90565b61289f612394565b806128ad57506128ad612440565b156128b757505f90565b5f6128c0611d28565b90506008548111156128d457600191505090565b6004546002546128e4904261482f565b10156128f1575f91505090565b6009545f819003612911575f82118015611d7c5750600a54481115611d7c565b60075461291e90826148aa565b82111561295c57600b548061293161178d565b1180612943575080612941611eaa565b115b1561295357600a544811156125bf565b5f935050505090565b5f9250505090565b6001600160a01b0381166129a65760405162461bcd60e51b81526020600482015260096024820152682165786368616e676560b81b6044820152606401610d76565b6001546001600160a01b03168015612a20576129ec6001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c59916825f613fa4565b612a206001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449416825f613fa4565b600180546001600160a01b0319166001600160a01b0384811691909117909155612a6e907f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c59916835f19613fa4565b610d146001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449416835f19613fa4565b5f6120ea82612ab384600161383e565b614065565b5f80612ac2610be2565b91509150805f03612afe575f612ad7846140fc565b9050612ae86114ed82610d0a61152f565b612af7610d0f82610d0a6117db565b5050505050565b5f612b09828461482f565b90505f848211612b19575f612b23565b612b23858361482f565b90505f612b2f826116bc565b91505083811115612b68575f612b44876140fc565b9050612b556114ed82610d0a61152f565b612b5e816122a6565b5050505050505050565b5f612b73828661482f565b9050612b8181610d0a611eaa565b9050805f03612b935750505050505050565b5f858214612bb257612bad612ba889846148aa565b6140fc565b612bba565b612bba61152f565b90505f6040518060400160405280600180811115612bda57612bda6149fc565b815260200183815250604051602001612bf39190614a10565b6040516020818303038152906040529050612c2f7f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998483614142565b505050505050505050565b5f8111612c785760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610d76565b61ffff811115612cb65760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610d76565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f03612cdd5750565b60405163573ade8160e01b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998116600483015260248201839052600260448301523060648301527f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169063573ade81906084016127b8565b612d6881613c16565b5042600255565b6001600160a01b03811615612e7f57306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612dc4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612de89190614a47565b6001600160a01b031614612e2f5760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610d76565b600e54600160a01b900460ff16612e7f57600e805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600e80546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612ed25750565b60405163a415bcad60e01b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998116600483015260248201839052600260448301525f60648301523060848301527f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169063a415bcad9060a4015b5f604051808303815f87803b158015612f6d575f80fd5b505af1158015612af7573d5f803e3d5ffd5b6127108110612fbe5760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610d76565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b600e545f90600160a01b900460ff166130305760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610d76565b600e54604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa15801561307a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061309e919061488f565b15613173576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa1580156130ea573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061310e9190614878565b111561311c57505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b15801561315c575f80fd5b505af115801561316e573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa1580156131b7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131db9190614878565b905080156131f7576131f76001600160a01b03851683836141e4565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af115801561323c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118f9190614878565b805f0361326a5750565b60405163617ba03760e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449481166004830152602482018390523060448301525f60648301527f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169063617ba037906084015f604051808303815f87803b1580156132fd575f80fd5b505af115801561330f573d5f803e3d5ffd5b5050604051635a3b74b960e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a563449481166004830152600160248301527f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169250635a3b74b99150604401612f56565b5f613391610f45565b111561341e57610c8561199a827f00000000000000000000000078ae4b8e034ba8a3dc0260cf3d448f0b6aa4b80d6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133fa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0a9190614878565b8015610c855761343081610d0a61152f565b905061343b81612737565b610d14816122a6565b825f0361349e5781156134995760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610d76565b613571565b670de0b6b3a76400008310156134e65760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610d76565b662386f26fc100008210156135305760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610d76565b8183116135715760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610d76565b61357b82846148aa565b8110156135ca5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610d76565b5f816135de670de0b6b3a764000080614842565b6135e89190614859565b6135fa90670de0b6b3a764000061482f565b90506136046115ec565b81106136415760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610d76565b50600992909255600755600855565b60405163b3596f0760e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301525f9182917f00000000000000000000000054586be62e3c3580375ae3723c145253060ca0c2169063b3596f0790602401602060405180830381865afa1580156136d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136fc9190614878565b60405163b3596f0760e01b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599811660048301529192505f917f00000000000000000000000054586be62e3c3580375ae3723c145253060ca0c2169063b3596f0790602401602060405180830381865afa158015613785573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137a99190614878565b9050805f036137ba575f9250505090565b6137e57f0000000000000000000000000000000000000000000000000000000000000008600a614b42565b6137ef9082614842565b6ec097ce7bc90715b34b9f100000000061382a7f0000000000000000000000000000000000000000000000000000000000000008600a614b42565b6138349085614842565b611d729190614842565b5f825f0361384d57505f6120ea565b5f826138615761385c84612206565b61386a565b61386a846140fc565b5f549091506127109061388e90600160281b900467ffffffffffffffff168261482f565b6138989083614842565b61118f9190614859565b5f825f036138b157505f6120ea565b600154604051630ed2fc9560e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301527f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998116602483015260448201869052606482018590525f921690630ed2fc95906084015b6020604051808303815f875af1158015613951573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139759190614878565b9050828110156113aa5760405162461bcd60e51b815260206004820152600a60248201526908585b5bdd5b9d13dd5d60b21b6044820152606401610d76565b5f8282602001516139c591906148aa565b90505f6139d182612aa3565b90506139dc81613260565b6139e584612ec8565b6008546139f0611d28565b10613a315760405162461bcd60e51b81526020600482015260116024820152700d8caeccae4c2ceca40e8dede40d0d2ced607b1b6044820152606401610d76565b50505050565b5f613a40611d28565b9050613a51611a9f84610d0a610f45565b5f613a628360200151610d0a61152f565b9050613a6d81612737565b613a76816122a6565b505f613a80611d28565b9050600854811080613a9157508281105b612af75760405162461bcd60e51b81526020600482015260116024820152700d8caeccae4c2ceca40e8dede40d0d2ced607b1b6044820152606401610d76565b6040805160028082526060820183525f926020830190803683370190505090507f00000000000000000000000065906988adee75306021c417a1a3458040239602815f81518110613b2457613b24614b4d565b60200260200101906001600160a01b031690816001600160a01b0316815250507f00000000000000000000000040aabef1aa8f0eec637e0e7d92fbffb2f26a8b7b81600181518110613b7857613b78614b4d565b6001600160a01b039283166020918202929092010152604051635fc87b1d60e11b81527f0000000000000000000000008164cc65827dcfe994ab23944cbc90e0aa80bfcb9091169063bf90f63a90613bd4908490600401614b61565b5f604051808303815f875af1158015613bef573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610e0b9190810190614c3c565b5f80613c20610be2565b90925090505f83613c31838561482f565b613c3b91906148aa565b90505f613c47826116bc565b91505082811115613d89575f613c68613c60858461482f565b610d0a611eaa565b90505f613c76611f4e614214565b90505f5f198214613cc3576006545f54613cbe919061271090613caa90600160281b900467ffffffffffffffff168261482f565b613cb49086614842565b610d0a9190614859565b613cc7565b6006545b90505f198114613d08575f613cdc848a6148aa565b905081811115613d0657818910613cf957612c2f61217283612aa3565b613d03898361482f565b93505b505b600b548311613d2057612b5e611a9f89610d0a610f45565b6040805180820182525f80825260208083018c905292519092613d44929101614a10565b6040516020818303038152906040529050613d807f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998583614142565b50505050612af7565b80831115613edc575f613d9c828561482f565b9050808610613dee57613dae81612cd3565b613db8818761482f565b95508515613de657613dcf61178887600654612291565b50613de6612172613dde6117db565b610d0a614214565b505050505050565b613df786612cd3565b613e01868261482f565b9050613e0f81610d0a611eaa565b9050805f03613e2057505050505050565b5f805461271090613e4290600160281b900467ffffffffffffffff16826148aa565b613e4b846140fc565b613e559190614842565b613e5f9190614859565b90505f6040518060400160405280600180811115613e7f57613e7f6149fc565b815260200183815250604051602001613e989190614a10565b6040516020818303038152906040529050613ed47f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c5998483614142565b505050612af7565b613eeb61178886600654612291565b50612af7612172613dde6117db565b604051632fe4a15f60e21b81523060048201525f9081906001600160a01b037f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169063bf92857c9060240160c060405180830381865afa158015613f60573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f849190614cfb565b95505050505050670de0b6b3a7640000811080156116b657501515919050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052613ff584826143ce565b613a31576040516001600160a01b03841660248201525f604482015261405b90859063095ea7b360e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261446f565b613a31848261446f565b5f825f0361407457505f6120ea565b600154604051630ed2fc9560e01b81526001600160a01b037f0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599811660048301527f0000000000000000000000008236a87084f8b84306f72007f36f2618a56344948116602483015260448201869052606482018590525f921690630ed2fc9590608401613935565b5f81158061410a57505f1982145b15614113575090565b5f61411c613650565b9050806141386ec097ce7bc90715b34b9f100000000085614842565b6113aa9190614859565b600e805460ff60a81b1916600160a81b17905560405163701195a160e11b81526001600160a01b037f000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb169063e0232b42906141a590869086908690600401614d41565b5f604051808303815f87803b1580156141bc575f80fd5b505af11580156141ce573d5f803e3d5ffd5b5050600e805460ff60a81b191690555050505050565b6040516001600160a01b038316602482015260448101829052610e0b90849063a9059cbb60e01b90606401614024565b6040516308df7cab60e31b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301525f9182917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd16906346fbe558906024016040805180830381865afa15801561429b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142bf9190614d67565b915050805f036142d1575f1991505090565b6040516351460e2560e01b81526001600160a01b037f0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494811660048301525f917f0000000000000000000000000a16f2fcc0d44fae41cc54e079281d84a363becd909116906351460e2590602401602060405180830381865afa158015614359573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061437d9190614878565b90505f6143ab7f0000000000000000000000000000000000000000000000000000000000000008600a614b42565b6143b59084614842565b90508181116143c4575f6125bf565b6125bf828261482f565b5f805f846001600160a01b0316846040516143e99190614d89565b5f604051808303815f865af19150503d805f8114614422576040519150601f19603f3d011682016040523d82523d5f602084013e614427565b606091505b5091509150818015614451575080511580614451575080806020019051810190614451919061488f565b801561446657506001600160a01b0385163b15155b95945050505050565b5f6144c3826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166145429092919063ffffffff16565b905080515f14806144e35750808060200190518101906144e3919061488f565b610e0b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d76565b606061118f84845f85855f80866001600160a01b031685876040516145679190614d89565b5f6040518083038185875af1925050503d805f81146145a1576040519150601f19603f3d011682016040523d82523d5f602084013e6145a6565b606091505b50915091506145b7878383876145c2565b979650505050505050565b606083156146305782515f03614629576001600160a01b0385163b6146295760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d76565b508161118f565b61118f83838151156146455781518083602001fd5b8060405162461bcd60e51b8152600401610d7691906147e0565b6001600160a01b0381168114610c85575f80fd5b5f60208284031215614683575f80fd5b81356113aa8161465f565b5f6020828403121561469e575f80fd5b5035919050565b8015158114610c85575f80fd5b5f602082840312156146c2575f80fd5b81356113aa816146a5565b5f805f604084860312156146df575f80fd5b83359250602084013567ffffffffffffffff808211156146fd575f80fd5b818601915086601f830112614710575f80fd5b81358181111561471e575f80fd5b87602082850101111561472f575f80fd5b6020830194508093505050509250925092565b5f5b8381101561475c578181015183820152602001614744565b50505f910152565b5f815180845261477b816020860160208601614742565b601f01601f19169290920160200192915050565b8215158152604060208201525f61118f6040830184614764565b5f80604083850312156147ba575f80fd5b82356147c58161465f565b915060208301356147d5816146a5565b809150509250929050565b602081525f6113aa6020830184614764565b5f805f60608486031215614804575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b818103818111156120ea576120ea61481b565b80820281158282048414176120ea576120ea61481b565b5f8261487357634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215614888575f80fd5b5051919050565b5f6020828403121561489f575f80fd5b81516113aa816146a5565b808201808211156120ea576120ea61481b565b5f805f805f805f805f806101408b8d0312156148d7575f80fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151614905816146a5565b60c08c0151909550614916816146a5565b60e08c0151909450614927816146a5565b6101008c0151909350614939816146a5565b6101208c015190925061494b816146a5565b809150509295989b9194979a5092959850565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561499b5761499b61495e565b604052919050565b5f604082840312156149b3575f80fd5b6040516040810181811067ffffffffffffffff821117156149d6576149d661495e565b6040528251600281106149e7575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b8151604082019060028110614a3357634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f60208284031215614a57575f80fd5b81516113aa8161465f565b600181815b80851115614a9c57815f1904821115614a8257614a8261481b565b80851615614a8f57918102915b93841c9390800290614a67565b509250929050565b5f82614ab2575060016120ea565b81614abe57505f6120ea565b8160018114614ad45760028114614ade57614afa565b60019150506120ea565b60ff841115614aef57614aef61481b565b50506001821b6120ea565b5060208310610133831016604e8410600b8410161715614b1d575081810a6120ea565b614b278383614a62565b805f1904821115614b3a57614b3a61481b565b029392505050565b5f6113aa8383614aa4565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f9190848201906040850190845b81811015614ba15783516001600160a01b031683529284019291840191600101614b7c565b50909695505050505050565b5f67ffffffffffffffff821115614bc657614bc661495e565b5060051b60200190565b5f82601f830112614bdf575f80fd5b81516020614bf4614bef83614bad565b614972565b8083825260208201915060208460051b870101935086841115614c15575f80fd5b602086015b84811015614c315780518352918301918301614c1a565b509695505050505050565b5f8060408385031215614c4d575f80fd5b825167ffffffffffffffff80821115614c64575f80fd5b818501915085601f830112614c77575f80fd5b81516020614c87614bef83614bad565b82815260059290921b84018101918181019089841115614ca5575f80fd5b948201945b83861015614ccc578551614cbd8161465f565b82529482019490820190614caa565b91880151919650909350505080821115614ce4575f80fd5b50614cf185828601614bd0565b9150509250929050565b5f805f805f8060c08789031215614d10575f80fd5b865195506020870151945060408701519350606087015192506080870151915060a087015190509295509295509295565b60018060a01b0384168152826020820152606060408201525f6144666060830184614764565b5f8060408385031215614d78575f80fd5b505080516020909101519092909150565b5f8251614d9a818460208701614742565b919091019291505056fea264697066735822122032a1468284d6f0df42e46ea99e089a0c9fda2097de9ddc6866b9c60b99e13b1b64736f6c63430008170033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c59900000000000000000000000000000000000000000000000000000000000001000000000000000000000000008236a87084f8b84306f72007f36f2618a56344940000000000000000000000002f39d218133afab8f2b819b1066c7e434ad94e9e000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb0000000000000000000000000000000000000000000000000000000000000004000000000000000000000000a94fbdb1ec4e12358e9581b9829bec57115fad9700000000000000000000000088ba032be87d5ef1fbe87336b7090767f367bf7300000000000000000000000000000000000000000000000000000000000000156c4254432f574254432041617665204c6f6f7065720000000000000000000000
-----Decoded View---------------
Arg [0] : _asset (address): 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599
Arg [1] : _name (string): lBTC/WBTC Aave Looper
Arg [2] : _collateralToken (address): 0x8236a87084f8B84306f72007F36F2618A5634494
Arg [3] : _addressesProvider (address): 0x2f39d218133AFaB8F2B819B1066c7E434Ad94E9e
Arg [4] : _morpho (address): 0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb
Arg [5] : _eModeCategoryId (uint8): 4
Arg [6] : _exchange (address): 0xa94fBdB1Ec4E12358e9581B9829bEc57115Fad97
Arg [7] : _governance (address): 0x88Ba032be87d5EF1fbE87336B7090767F367BF73
-----Encoded View---------------
10 Constructor Arguments found :
Arg [0] : 0000000000000000000000002260fac5e5542a773aa44fbcfedf7c193bc2c599
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000100
Arg [2] : 0000000000000000000000008236a87084f8b84306f72007f36f2618a5634494
Arg [3] : 0000000000000000000000002f39d218133afab8f2b819b1066c7e434ad94e9e
Arg [4] : 000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000004
Arg [6] : 000000000000000000000000a94fbdb1ec4e12358e9581b9829bec57115fad97
Arg [7] : 00000000000000000000000088ba032be87d5ef1fbe87336b7090767f367bf73
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000015
Arg [9] : 6c4254432f574254432041617665204c6f6f7065720000000000000000000000
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 33 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.